Same structure, it works against test cases but is marked wrong.

0
1

Can someone tell me what is wrong with my code? It makes the difference for my Certificate.

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

def same_structure(a,b):
    if is_list(a) == False and is_list(b) == False:
        return True
    if len(a) != len(b):
        return False
    q = 0
    for e in a:
        if is_list(e) != is_list(b[q]):
            return False
        if is_list(e) == True and is_list(b[q])==True:
            return same_structure(e,b[q])
        q += 1
    return True

#Here are some examples:

print same_structure(3, 7)
#>>> True

print same_structure([1, 0, 1], [2, 1, 2])
#>>> True

print same_structure([1, [0], 1], [2, 5, 3])
#>>> False

print same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['d', 'e']]]])
#>>> True

print same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['de']]]])
#>>> False

asked 22 Apr '12, 11:50

Pedro%20Gomez%20de%20Almeida%20Sanches's gravatar image

Pedro Gomez ...
2917
accept rate: 33%


One Answer:
if len(a) != len(b):

If either one of a or b is not pointing to a data structure that has no len, like an integer, this will throw an error.

if is_list(e) == True and is_list(b[q])==True:
    return same_structure(e,b[q])

This will just return the result for the first two elements that are both lists, and leave out the rest of the parent lists.

link

answered 22 Apr '12, 12:18

elssar's gravatar image

elssar
19.3k2563155

Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×15,297
×325
×172

Asked: 22 Apr '12, 11:50

Seen: 144 times

Last updated: 22 Apr '12, 12:18