简体   繁体   中英

Python 3: Recursivley find if number is even

I am writing a program that must find if a number is even or not. It needs to follow this template. I can get it to find if a number is even or not recursively

The key is that you need to return a boolean value:

def isEven(num):
    if (num <= 0):
        return (num == 0)
    return isEven(num-2)

For larger numbers though this quickly exceeds the default maximum recursion depth for Python. That can be remedied by calling sys.setrecursionlimit(n) where n is the number of recursive calls you want to allow. n in turn is limited by the platform you are on.

Try this, it works for integer values with 0 <= n <= sys.getrecursionlimit()-2 :

def even(n):
    return True if n == 0 else odd(n - 1)

def odd(n):
    return False if n == 0 else even(n - 1)

It's a nice example of a pair of mutually recursive functions. Not the most efficient way to find the answer, of course - but nevertheless interesting from an academic point of view.

This template will help. You need to fill in the commented lines. The one you have in the question won't work - you aren't passing anything into isEven . This will only work if n >= 0 , otherwise it will crash your program. Easy enough to fix if you ever need to deal with negative numbers.

def isEven(n):
    if n == 0:
        # Number is even
    elif n == 1:
        # Number is odd
    else:
        # Call the function again, but with a different n

A really dumb use case for recursion, but here is my version anyway

import random

def isEven(num):
    if random.random() < 0.5:
        # let's learn about recursion!
        return isEven(num)
    else:
        # let's be sane!
        return num % 2 == 0

disclaimer: if you submitted this you'd probably tick off the teacher and come across as a smartypants.

Taking up wim's challenge to find a "different" way to do this: The prototypical recursive pattern is foo(cdr(x)) , with a base case for the empty list … so let's write it around that:

def isEven(num):
  def isEvenLength(l):
    if not l:
      return True
    return not isEvenLength(l[1:])
  return isEvenLength(range(num))

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