Matthew Hanson
Matthew Hanson

Reputation: 331

inputting to a list and finding longest streak of the same input python

I am writing a program in which a user inputs values into a list until the want to end it and the program will tell the user the longest streak of numbers they entered. For example, is the user inputted 7,7,7,6,6,4,end the would get the output: your longest streak was 3. As 7 was entered 3 times in a row.

So far I have this and it seems to not want to ever end the current run so if i enter 7,7,7,6,6,6,6,5,4 it will tell me the longest streak is 7 like it is continuing the streak from the 7 being entered. This is what i have:

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)

Any help is greatly appreciated.

Upvotes: 3

Views: 10654

Answers (5)

tsdorsey
tsdorsey

Reputation: 618

This will track the value of streak. If another streak is longer it will replace the last streak with the new value and length.

I used exception handling for input. If you enter a non-number it will ignore it and ask for a number again. If you enter nothing it will end the input loop.

Note that I'm using raw_input instead of 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)

Upvotes: 1

jamylak
jamylak

Reputation: 133554

>>> 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

Upvotes: 2

Daniel
Daniel

Reputation: 5381

Assuming you have a list such as [7, 7, 7, 6, 6, 6, 6, 5, 4, 6, 7] you can use the groupby() function to count the number of repetitions and then print the max number at the end.

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)

In this case it returns 4 since the number six was repeated 4 consecutive times

Upvotes: 3

motoku
motoku

Reputation: 1581

This is a drawn-out version of how what you describe can be done. Half-way through I realized I was running it with Python 16, so it's backwards compatible!

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

Output:

value: 6, count 4

If you have any questions, feel free to comment them.

Upvotes: 1

user590028
user590028

Reputation: 11730

Try this

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)

Upvotes: 0

Related Questions