Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out two lists with same structure in python?

Define a procedure, same_structure, that takes two inputs. It should output True if the lists have the same structure, and False otherwise. Two values, p and q have the same structure if:

Neither p or q is a list.

Both p and q are lists, they have the same number of elements, and each
element of p has the same structure as the corresponding element of q.

EDIT: To make the picture clear the following are the expected output

same_structure([1, 0, 1], [2, 1, 2])
    ---> True
same_structure([1, [0], 1], [2, 5, 3])
    ---> False
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['d', 'e']]]])
    ---> True
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['de']]]])
    ---> False 

I thought recursion would be best to solve this problem in python I have come up with the following code but its not working.

def is_list(p):
    return isinstance(p, list)

 def same_structure(a,b):
    if not is_list(a) and not is_list(b):
        return True
    elif is_list(a) and is_list(b):
        if len(a) == len(b):
            same_structure(a[1:],b[1:])
    else:
        return False
like image 953
Umesh K Avatar asked Apr 09 '12 15:04

Umesh K


People also ask

How do I search for two lists of elements in Python?

Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.

How do I compare two identical lists?

Using Counter() , we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements.

How do I compare two lists to find differences in Python?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .


1 Answers

Instead of same_structure(a[1:],b[1:]), you need to check item pair of a and b one by one

def is_list(p):
    return isinstance(p, list)

def same_structure(a, b):
    if not is_list(a) and not is_list(b):
        return True
    elif (is_list(a) and is_list(b)) and (len(a) == len(b)):
        return all(map(same_structure, a, b)) # Here
    return False
like image 162
okm Avatar answered Oct 01 '22 18:10

okm