#Same Structure #Define a procedure, same_structure, that takes two inputs. It should output #True if the lists contain the same elements in 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. #For this procedure, you can use the is_list(p) procedure from Homework 6: 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 else: if len(a) == len(b): if is_list(a) and is_list(b): i = 0 while i< len(a): if not is_list(a[i]) and not is_list(b[i]): i = i+1 else: if is_list(a[i]) and is_list(b[i]): return same_structure(a[i:][0],b[i:][0]) else: return False return True return False return False #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
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question