Checking two node chains and calculate whether they have same data

Viewed 52

I have a function, which checks given two node chains and determines whether those two node chains contain same data values in same order. Function returns True if they do and returns False otherwise. I need to write this function using recursion.

Here's my attempt:

def check_chains(chain1, chain2):
    if chain1 is None or chain2 is None:
        return False
    else:
        if chain1.get_data() == chain2.get_data():
            check_chains(chain1.get_next(), chain2.get_next())
            return True
        else:
            return False

This one returns True even if node chains have different data values in them.

Below are some test cases:

1. Test case 1 (test passed)

    chain1 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    chain2 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    expected = True
    
    result = a7q8.check_chains(chain1, chain2)
    
    if result!=expected:
        print('Test failed')

2. test 2 (test failed, expected false but returned True)

    chain1 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    chain2 = N.node(5 ,N.node(10,N.node(7, N.node(1))))
    expected = True
    
    result = a7q8.check_chains(chain1, chain2)
    
    if result!=expected:
        print('Test failed')
2 Answers

Your logic was a little bit flawed in two places:

def check_chains(chain1, chain2):
    # base case for equality was missing!
    if chain1 is chain2 is None:  
        return True
    if None in (chain1, chain2):  # rewrote your condition less verbosely
        return False
    if chain1.get_data() == chain2.get_data():
        # recursive result was never used!
        return check_chains(chain1.get_next(), chain2.get_next())
    return False

I also removed some spurious else, as you return from every if-block.

def check_chains(chain1, chain2):
    if chain1 is None and chain2 is None:
        return True
    if chain1 is None or chain2 is None:
        return False
    else:
        if chain1.get_data() == chain2.get_data():
            return check_chains(chain1.get_next(), chain2.get_next())
            
        else:
            return False
Related