I want to write a recursive function named greater_than_30(list_nums) which finds how many numbers in the given list are greater than 30.
eg:
list1 = [10, 35, 30, 50]
output - 2
Here is the function I have writter:
def greater_than_30(list_nums):
if len(list_nums) == 1:
if list_nums[0] > 30:
return 1
else:
if list_nums[0] > greater_than_30(list_nums[1:]):
return list_nums[0]
else:
return greater_than_30(list_nums[1:])
>>>a_list = [13, 21, 50, 34, 29, 33]
print(greater_than_30(a_list))
3 #output expected
50 #output gotten
CodePudding user response:
You're never actually counting it there. If you replace
if list_nums[0] > greater_than_30(list_nums[1:]):
return list_nums[0]
with
if list_nums[0] > 30:
return 1 greater_than_30(list_nums[1:])
it will work as expected.
CodePudding user response:
Even though I can't understand why you'd want to do this trivial operation recursively, here's a solution:
list1 = [13, 21, 50, 34, 29, 33]
def greater_than_30(lst):
if len(lst) == 0:
return 0
return (1 if lst[0] > 30 else 0) greater_than_30(lst[1:])
print(greater_than_30(list1))
Output:
3
CodePudding user response:
def grater_than_30(my_list, count=0):
if len(my_list) == 0:
return count
if my_list[0] > 30:
count = 1
count = grater_than_30(my_list[1:], count)
return count
list1 = [13, 21, 50, 34, 29, 33]
grater_than_30(list1)
