在Python中使用while循环计算数字序列
我试图使用在Python中使用while循环计算数字序列,python,Python,我试图使用while循环返回一个数字序列,从输入值num开始,以1结束。例如: >>> tray(8) [8, 2, 1] 如果数字是偶数,我希望它将num替换为num**0.5的整数值,如果是奇数,则应将num替换为num**1.5的整数值 def tray(num): '''returns a sequence of numbers including the starting value of num and ending value of 1, rep
while
循环返回一个数字序列,从输入值num
开始,以1结束。例如:
>>> tray(8)
[8, 2, 1]
如果数字是偶数,我希望它将num
替换为num
**0.5的整数值,如果是奇数,则应将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的序列。感谢您的输入。这些调整修复了代码中的错误
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) )
生成器版本:
def tray(n):
while n > 1:
expo = 1.5 if n%2 else 0.5
yield n
n = int(n**expo)
yield 1
演示:
给出“无效语法”错误的确切代码是什么?建议:您可能想了解
yield
。您是否知道,当指数为1.5且输入数>=1时,您永远不会达到1?当我尝试运行模块时,弹出“无效语法”错误,并突出显示对生成器的附加调整
>>> list(tray(8))
[8, 2, 1]
>>> list(tray(7))
[7, 18, 4, 2, 1]