Reputation: 69
Im trying to define a function that returns true if every item in list is less than 2 and false in else situation. The items' type can be an integer, float, str or sth different from list. I should check for the lists.
def ifeveryitems(lst):
for items in lst:
if isinstance(items,list) and len(items) <= 2:
return True and ifeveryitem(????) # '????' should be the items other than the item that has been searched #
else:
return False
Upvotes: 1
Views: 123
Reputation: 225005
Judging by your description, you don't need a recursive call at all:
def ifeveryitems(lst):
for items in lst:
if isinstance(items, list) and len(items) > 2:
return False
return True
Or, alternatively:
def ifeveryitems(lst):
return all(len(items) <= 2 for items in lst if isinstance(items, list))
Upvotes: 5
Reputation: 1911
With your problem solved, I would explain the concept of loop vs tail recursion in general instead, as tail recursion would be a useful technique in general.
Although looping and list comprehension in Python mean it is not likely that you would need tail recursion, it is good to have the idea of it.
The technique of recursively calling a function is called tail recursion. The same thing can be achieved using tail recursion and a loop, but you don't need both.
To do what you want you can use a loop:
def ifeveryitems(lst):
for items in lst:
if not isinstance(items,list) or len(items) > 2:
return False
return True
Or tail recursion:
def ifeveryitems(lst):
if isinstance(items,list) and len(lst)==0:
return True
return isinstance(lst[0],list) and len(lst[0]) <= 2 and ifeveryitems(lst[1:])
This function checks if the first item of lst
is a list and is of length 2 or less, and then check the rest of the list (lst[1:]
) using the function itself. Eventually, it would either return False by shortcutting (when isinstance(lst[0],list) and len(lst[0]) <= 2
is False) or reach the base case where the whole list is exhausted, when it would return True.
One more example: To implement len(L)
yourself.
Assuming L
would always be a list, you can implement len
using a loop:
def len(L):
i = 0
for item in L:
i += 1
return i
(Note: using a loop like this is also called accumulation)
Or tail recursion.
def len(L):
if L==[]:
return 0
return 1 + len(l[1:])
It removes the first item of the list and add 1 to the length of the rest of the list. Eventually, it would reach the point where L is exhausted and is reduced to the empty list, in which case it would just return 0.
Upvotes: 1
Reputation: 3695
You could try the following:
def ifeveryitems(lst):
return all(map(lambda x: x < 2, lst))
Upvotes: 1