在Python中使用while循环计算数字序列

2024-04-19 15:15:35 发布

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

我尝试使用while循环返回一个数字序列,从输入值num开始,以1结束。例如:

>>> tray(8)
[8, 2, 1]

如果这个数是偶数,我希望它用整数值num**0.5替换num,如果它是奇数,它应该用整数值num**1.5替换num。你知道吗

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的序列。谢谢你的意见。你知道吗


Tags: andofifvaluedef序列数字整数
2条回答

这些调整修复了代码中的错误

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

演示:

>>> list(tray(8))
[8, 2, 1]
>>> list(tray(7))
[7, 18, 4, 2, 1]

相关问题 更多 >