0

Write a function that takes in a number and determines if the digits contain two adjacent 8s.

def double_eights(n):
    """Return true if n has two eights in a row.
    >>> double_eights(8)
    False
    >>> double_eights(88)
    True
    >>> double_eights(2882)
    True
    >>> double_eights(880088)
    True
    >>> double_eights(12345)
    False
    >>> double_eights(80808080)
    False
    """
    "*** YOUR CODE HERE ***"

I tried to call double_eights by passing n//10 as an argument. I kept encountering errors when 2882 was passed in as an argument. The double eights function returned nothing when that argument was passed in. I attached what I've tried so far.

    if n < 10:
        return False
    elif (n % 10 == 8) and ((n // 10) % 10 == n % 10):
        return True
    double_eights(n //10)

Doctests for double_eights

>>> from lab01_extra import *
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)

# Error: expected
#     True
# but got
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
BigBro666
  • 71
  • 8
  • 2
    This question has nothing to do with higher order functions. Did you mean *recursive* functions? (The two concepts have no relation really, although both are widely used in functional programming.) – Robin Zigmond Sep 04 '19 at 00:55
  • @RobinZigmond Yes, I mean recursive functinos. – BigBro666 Sep 04 '19 at 01:19

1 Answers1

1

You need to return that last recursive call, otherwise None will be returned by default on inputs that don't satisfy the conditions of the if and elif statements:

def double_eights(n):
    if n < 10:
        return False
    elif (n % 10 == 8) and ((n // 10) % 10 == 8):  #  8 instead of n % 10
        return True
    return double_eights(n // 10)

                                #  Output:
print(double_eights(8))         #  False
print(double_eights(88))        #  True
print(double_eights(2882))      #  True
print(double_eights(880088))    #  True
print(double_eights(12345))     #  False
print(double_eights(80808080))  #  False

The 8 instead of n % 10 is there because the and evaluates the second term only if the first one is True (in which case you know that n % 10 == 8 so why re-calculate it?).


note: double_eights is not a higher-order function, but it is a recursive function.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55