Python中的冰雹序列

时间:2012-08-03 20:25:50

标签: python python-2.7 sequence

length = 0
for n in range(1,101):
    print "Sequence #:", n
    while n != 1:
        print n,
        if n % 2 == 0:
           n = n / 2
           length = length + 1
        else:
            n = (n * 3) + 1
            length = length + 1
        if n == 1:
            print n
            length = length + 1
    print "The sequence above contains", length, "numbers"
    length = 0

我的问题:

上面的python代码计算数字1 - 100的hailstone序列,然后显示序列的长度。在完成所有计算后,如何显示序列最长的数字及其对应的长度?

2 个答案:

答案 0 :(得分:0)

只需保存每个输入的结果,然后查找最长的结果。

results = []
length = 0
for n in range(1,101):
    print "Sequence #:", n
    while n != 1:
        print n,
        if n % 2 == 0:
            n = n / 2
            length = length + 1
        else:
            n = (n * 3) + 1
            length = length + 1
        if n == 1:
            print n
            length = length + 1
    results.append((n,length))
    print "The sequence above contains", length, "numbers"
    length = 0
print 'Longest sequence of lenght {1} found for number {0}'.format(*max(results, key=lambda x: x[1]))

答案 1 :(得分:0)

这将跟踪最大长度和顺序,并在结尾显示它们。标有##的行是原始代码的补充。

length = 0
max_length = 0 ##

for n in range(1,101):
    print "Sequence #:", n
    seq = [] ##
    while n != 1:
        print n,
        seq.append(n)  ##
        if n % 2 == 0:
           n = n / 2
           length = length + 1
        else:
            n = (n * 3) + 1
            length = length + 1
        if n == 1:
            print n
            seq.append(n) ##
            length = length + 1
    print "The sequence above contains", length, "numbers"

    if length > max_length:  ##
        max_length = length  ##
        max_seq = seq[:]     ##

    length = 0

print 'max length: ', max_length ## same as len(max_seq)
print 'max seq: ', max_seq       ##