Pyschool专题11:q13

2024-05-13 23:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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.

示例

>>> 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'

我相信我已经成功了。在

^{pr2}$

Tags: ofthenumberstringthatvaluefunctionequal
1条回答
网友
1楼 · 发布于 2024-05-13 23:17:15

这是有效的:

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)

相关问题 更多 >