user3636636
user3636636

Reputation: 2499

Python recursive function: Takes even Num (n), returns odd num multiplied by 2s such that the final value is equal to n

Write a function printTwos(n) that takes in a number as argument and returns a string composed of an odd number multiplied by 2s such that the final value is equal to n. There should be equal number of 2s on both sides. Extra 2 should appear at the front of the string. Note: The value of the odd number can be 1.

My mess:

def printTwos(n):
    x = n//2
    if n <= 0:
        return 'invalid'
    elif n==1:
        return '1'
    elif x % 2 !=0:
        return '2 * %d' % x
    elif n % 5 == 0:
        return  "%s * 2" % printTwos(n/2)
    else:
        return "2 * %s * 2" % printTwos((n/2)/2)

Example result:

>>> printTwos(32)
'2 * 2 * 2 * 1 * 2 * 2' 

(This is successful in my function)

>>> printTwos(80)
'2 * 2 * 5 * 2 * 2'

(Mine returns: '2 * 5 * 2 * 2 * 2')

Any advice on fixing this would be appreciated, thanks.

Upvotes: 0

Views: 769

Answers (2)

Josip Grggurica
Josip Grggurica

Reputation: 421

First check if n is divisible by 4, if not check if it is divisible by 2 so that you can add 2 at the beginning of your string

def printTwos(n):
   if n % 4 != 0:
      if n % 2 == 0:
         # n is divisible by 2 so add two at the beginning of string
         result = printTwos(n/2)
         return "2 * " + result
      else:
         # n is odd so return it as string    
         return str(n)
   else:
      result = printTwos(n/4)
      return "2 * %s * 2" % result

print printTwos(4)
print printTwos(8)
print printTwos(32)
print printTwos(80)

Upvotes: 1

wonce
wonce

Reputation: 1921

Tip: Use the following scaffold:

if n % 4 == 0:
    #…
elif n % 2 == 0:
    #…
else:
    #…

Upvotes: 0

Related Questions