将输入添加到列表中并找到Python中相同输入的最长连续序列

3
我正在编写一个程序,用户输入数值到列表中,直到他们想要结束,并且程序将告诉用户他们输入的最长连续数字。例如,如果用户输入7、7、7、6、6、4、end,则会得到输出:你的最长连续是3。因为7连续输入了3次。
到目前为止,我的代码似乎不想结束当前运行,所以如果我输入7、7、7、6、6、6、6、5、4,它会告诉我最长的连续数字是7,就像它从输入的7开始继续计算一样。以下是我的代码:
mylist = []

run = 1

currentrun = 1

number = input('enter a number: ')
mylist.append(number)



while number != 'end' :
    number = input ('enter a number: ')
    mylist.append(number)
for i in range (len(mylist)):

    if mylist[i] == mylist[i-1] and mylist[i] == mylist[i+1] :
        currentrun = currentrun + 1
    else:
        currentrun = 0

    print (currentrun)
    if currentrun > run:
        run = currentrun

print (mylist)

print ('Your longest run was' ,run)

非常感谢您的帮助。

5个回答

3
假设您有一个列表,如[7, 7, 7, 6, 6, 6, 6, 5, 4, 6, 7],您可以使用groupby()函数来计算重复的次数,然后在末尾打印最大数。
from itertools import groupby
a = [7, 7, 7, 6, 6, 6, 6, 5, 4, 6, 7]
lst = []
for n,c in groupby(a):
   num,count = n,sum(1 for i in c)
   lst.append((num,count))

maxx = max([y for x,y in lst])
print 'Your longest run was {}'.format(maxx)

在这种情况下,它返回4,因为数字6连续重复了4次。

2
>>> from itertools import groupby
>>> input_iter = iter(lambda: input('enter a number: '), 'end')
>>> max(sum(1 for x in v) for k,v in groupby(input_iter))
enter a number: 7
enter a number: 7
enter a number: 7
enter a number: 6
enter a number: 6
enter a number: 4
enter a number: end
3

1
这是一个详细的描述,说明了你所描述的内容如何完成。在进行到一半时,我意识到它可以在 Python 16 上运行,因此具有向后兼容性!
a = None # stores the last number seen
b = 0 # stores the count of the last number
result = [0, 0] # number, count result array
for c in "7,7,7,6,6,6,6,5,4".split(','): # split string into array of
                                         # just our numbers
    c = int(c) # change the character into a bast ten int
    if c != a: # check current number against last
        a = c # if different than last, remember current number as last
        b = 1 # start over counting at one
    else: # if current number is same as last
        b = b + 1 # increment counter
        if b > result[1]: result = a, b # if counter higher than highest
                                        # previous count, store the
                                        # current number and count
print(("value: %i, count: %i" % result)) # print resulting number, count

输出:

value: 6, count 4

如果您有任何问题,请随意在评论中提出。

1
这将追踪连胜的价值。如果另一个连胜更长,它将用新的价值和长度替换上一个连胜。
我使用异常处理来处理输入。如果您输入非数字,它将忽略它并再次要求输入数字。如果您什么都不输入,它将结束输入循环。
请注意,我正在使用raw_input而不是input。
while True:
    number = raw_input('enter a number: ')
    if number == '':
      break

    try:
        number = int(number)
    except ValueError:
        print ("'" + number + "' is not a number.")
        continue

    mylist.append(number)

if len(mylist) > 0:
    #print (mylist)

    # Chain is the current run we're tracking. Longest is the longest chain we've tracked so far.
    chain = longest = 1
    # Current is the value of the chain we're tracking now. Value is the value of the longest chain we've tracked so far. We use the first value of the list.
    current = value = mylist[0]

    # Starting with the second number in the list and iterating to the end we compare values.
    for number in mylist[1:]:
        # Did we find another in our current chain?
        if number == current:
            chain += 1
        else:
            chain = 1
            current = number

        # This will require chains to exceed the previous longest chain to be chosen as the longest. Change this to >= to track the last chain (in the case of a tie).
        if chain > longest:
            longest = chain
            value = current

    print ('Your longest run was', longest)

1
你正在犯一个不好的习惯——吃掉了 ValueError - motoku
@MotokoKusanagi,你在小细节上指出了我的问题。是的,我们应该告诉用户他们输入了无效值。但是,我们还应该告诉用户如何退出循环。这是OP没有做到的,我认为答案中不需要这样做。我让OP填写UX的空白部分。添加所有必需的错误检查和用户反馈不是问题的一部分。 - tsdorsey

0

试试这个

mylist = []
while True:
    mylist.append(int(raw_input("enter number:")))
streak = 0
cur, last = 0, None
for num in mylist:
    if num == last:
        curr += 1
    else:
        streak = max(streak, cur)
        last = num
        cur = 0
print("longest run was ",streak)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接