简体   繁体   中英

How to use recursion to find divisible numbers in list?

I'm making a function takes a list of integers as a argument, and I want to see if there is 5 items in the list that are divisible by 2.

So for example, if I call the function "find_numbers" with this call:

  print(find_numbers([1,4,6,8,5,66,22,3]))

it should return:

   True

because the list has 5 items that are divisible by two (4,6,8,66 and 22) otherwise it should return false .

How would I go about doing this?

Thanks for the help!

Note : I need to use recursion for later in the program, I know using a loop would be easier but it will be more of a headache for me later on (Again, thank you very much).

Edit: apologies for misreading. It is now recursive even though I'm having trouble figuring out why you would need this.

You iterate through the list until you find a n numbers where modulo 2 == 0 . % is the python modulo operator.

def find_numbers(l, i=0, count=0):
  try:
    if count == 5:
      return True
    elif l[i] % 2 == 0:
      return find_numbers(l, i=i+1, count=count+1)
    else: 
      return find_numbers(l, i=i+1, count=count)
  except IndexError as e:
    return False
print(find_numbers([1, 2, 4, 6, 3, 1])) # False
print(find_numbers([1, 1, 1, 1, 1, 1])) # False
print(find_numbers([1, 2, 2, 4, 6, 1])) # False
print(find_numbers([1, 2, 2, 2, 2, 2])) # True
print(find_numbers([1])) # False

This will return True if and only if x meets the condition enough times. It will throw an error if it iterates to an index on the list where an inoperable value is located (eg a str ). It will catch the IndexError so that it can take short lists as in the last example.


Explanation: The important thing to remember here is that the final case ramifies up the call stack. So if the last call returns True | False True | False and each successive call before that can only return an error (the str input case I mentioned) or True | False | Another recursive call True | False | Another recursive call True | False | Another recursive call then we can expect the final case to be one one of those.

Another nice thing about this is that it stops when it finds the fifth match so you save iterating through the list any further, I think. Perhaps that's the reason OP wanted recursion.

Here is another approach that keeps the records of the list elements who are divisible by 2:

def divi(a, number=5, divs=[]):
    if a == []:
        return True if len(divs) == number else False
    if not a[0] % 2:
       divs.append(a[0])
    return divi(a[1:], divs)


test = [
    [1, 2, 4, 6, 3, 1],
    [1, 1, 1, 1, 1, 1],
    [1, 2, 2, 4, 6, 1],
    [1,2, 2, 2, 2, 2],
    [1]
]

for elm in test:
    divs = []
    print('{} => {} # {}'.format(elm, divi(elm, divs=divs), divs))

Output:

[1, 2, 4, 6, 3, 1] => False # [2, 4, 6]
[1, 1, 1, 1, 1, 1] => False # []
[1, 2, 2, 4, 6, 1] => False # [2, 2, 4, 6]
[1, 2, 2, 2, 2, 2] => True # [2, 2, 2, 2, 2]
[1] => False # []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM