Python Pyschool主题11:问题13

Python Pyschool主题11:问题13,python,python-2.7,Python,Python 2.7,我正在pyschool学习python,在解决以下问题时遇到了一个问题 编写一个函数printTwos(n),它接受一个数字作为参数 返回由奇数乘以2s组成的字符串,以便 最终值等于n。上应有相等数量的2 双方。额外的2应该出现在字符串的前面。注: 奇数的值可以是1 例子 >>> printTwos(1) '1' >>> printTwos(2) '2 * 1' >>> printTwos(10) '2 * 5' >>> p

我正在pyschool学习python,在解决以下问题时遇到了一个问题

编写一个函数
printTwos(n)
,它接受一个数字作为参数 返回由奇数乘以2s组成的字符串,以便 最终值等于
n
。上应有相等数量的2 双方。额外的2应该出现在字符串的前面。注: 奇数的值可以是1

例子

>>> printTwos(1)
'1'
>>> printTwos(2)
'2 * 1'
>>> printTwos(10)
'2 * 5'
>>> printTwos(20)
'2 * 5 * 2'
>>> printTwos(30)
'2 * 15'
>>> printTwos(32)
'2 * 2 * 2 * 1 * 2 * 2'
>>> printTwos(80)
'2 * 2 * 5 * 2 * 2'
我相信我已经成功了

def printTwos(n):
count = 0
if n == 1:
    return '1'

if n == 2:
    return '2 * 1'
while n%2 == 0:
   n = n/2
   count +=1

if count%2 == 0:
    twos = count/2
    myoutput = ('2 * ' * twos, str(n), ' * 2' * twos)
    return ''.join(myoutput)
else:
    twos = count/2
    twofront = twos+1

    myoutput = ('2 * ' * twofront, str(n), ' * 2' * twos)
    return ''.join(myoutput)
这项工作:

def printTwos(n): 
    if(n%2==1):return str(n)
    else:
        if(n%4==0):return str('2 * ')+ printTwos(n/4) +str(' * 2')
        else: return str('2 * ')+ printTwos(n/2)

问题是什么?你试过什么?你被困在哪里了?很好。您可以通过处理奇数和负数来改进函数。@ChristianSt。非常感谢你的帮助。