我正在尝试使用while
循环返回一系列数字,从输入值num
开始,以1结尾。例如:
>>> tray(8)
[8, 2, 1]
如果数字是偶数,我希望用num
** 0.5的整数值替换num
,如果它是奇数,它应该用整数替换num
价值num
** 1.5。
def tray(num):
'''returns a sequence of numbers including the starting
value of num and ending value of 1, replacing num with
integer value of num**0.5 if even and num**1.5 if odd'''
while num != 1:
if num %2 == 0:
num**=0.5
else:
num**=1.5
return num
我对如何确保替换是整数感到很遗憾 - 如果我尝试int(num**0.5)
它会返回“无效语法”。此外,它只返回num**0.5
的答案,我无法弄清楚如何将起始值num
以及序列返回到1.感谢任何输入。
答案 0 :(得分:0)
这些调整可以修复代码中的错误
def tray(num):
'''returns a sequence of numbers including the starting
value of num and ending value of 1, replacing num with
integer value of num**0.5 if even and num**1.5 if odd'''
seq = [ num ]
while num != 1:
if num %2 == 0:
num = int(num**0.5)
else:
num = int(num**1.5)
seq.append( num )
return seq
这里改写为发电机。
def tray(num):
'''returns a sequence of numbers including the starting
value of num and ending value of 1, replacing num with
integer value of num**0.5 if even and num**1.5 if odd'''
yield num
while num != 1:
if num %2 == 0:
num = int(num**0.5)
else:
num = int(num**1.5)
yield num
可用于创建这样的列表。
list( tray(8) )
答案 1 :(得分:0)
生成器版本:
def tray(n):
while n > 1:
expo = 1.5 if n%2 else 0.5
yield n
n = int(n**expo)
yield 1
演示:
>>> list(tray(8))
[8, 2, 1]
>>> list(tray(7))
[7, 18, 4, 2, 1]