Python Question Write a function called numberoflists It is

Python Question:

Write a function called number_of_lists. It is passed a parameter x, that may or may not be a list. As in problem 6, if is x is a list it may contain other lists. The function should return the total number of lists in x. For example:

The Solution must be recursive

>>> number_of_lists(\'abc\')
0
>>> number_of_lists([ ])
1
>>> number_of_lists([[1, 2, 3]])
2
>>> number_of_lists([1,[3,1,2],[[3,6,2],[6,1,0,6]]])
5

Solution

def number_of_lists(l):
result = 0
if type(l) is list:
result += 1
for i in l:
result+= number_of_lists(i)
return result
else:
return result
print number_of_lists(\'abc\')
print number_of_lists([ ])
print number_of_lists([[1, 2, 3]])
print number_of_lists([1,[3,1,2],[[3,6,2],[6,1,0,6]]])

pastebin link: http://pastebin.com/rD4tBDpG

Python Question: Write a function called number_of_lists. It is passed a parameter x, that may or may not be a list. As in problem 6, if is x is a list it may c

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site