find the largest consecutive occurrence of the same number in list without import any modules. I have this code
def reads():
lst=[] #create empty list
flag=True #create flag
N1=input("Input a number to add to list or 0 to stop: ") #read value
while flag: #check if invalid or not
if not N1.isdigit():
print("Invalid input")
N1=input("Input a number to add to list or 0 to stop: ") #re read if invalid
elif N1=="0": #stop if 0
flag=False
else:
lst.append(N1) #add to empty list if valid
N1=input("Input a number to add to list or 0 to stop: ") # re read
lst=list(map(int, lst)) #convert to integer
return lst #return
def long(lst):
newx=0 #count
x=lst[0]
max1=0 #to save the how many number dupilicted
num=lst[0] #to save which number is
for i in range(1,len(lst)):
if x==lst[i]:
newx=newx 1
else:
newx=newx 1
if max1<newx:
max1=newx
num=x
x=lst[i]
newx=0
else:
newx=0
x=lst[i]
return max1,num
def main(): # to call other functions and display the results
x=reads()
m,a=long(x)
print("List: ",x)
print("The number is: ",a)
print("The largest size of consecutive numbers: ", m)
main()
the program run perfectly but there is mistake
if I input 1 1 2 3 4 4 4 0
the list will be,
lst=[1,1,2,3,4,4,4]
and output must be
The number is: 4
The largest size of consecutive numbers: 3
but it be like that:
The number is: 1
The largest size of consecutive numbers: 2
the problem in long() function
CodePudding user response:
Try with this approach:
def long(lst):
max_count = 1
max_num = lst[0]
count = 1
for prec, num in zip(lst[:-1], lst[1:]):
if num != prec:
if count > max_count:
max_count = count:
max_num = prec
count = 1
else:
count = 1
return max_num, max_count
CodePudding user response:
cont_cnt
will continuosly count numbers in the input list, resetting the counter if a number differ from the the previous one. max_num
then selects the max. The default=(None, None)
is returned if the list is empty.
def cont_cnt(lst):
prev = object() # guaranteed not to be present in the list
for x in lst:
if x != prev:
count = 0
prev = x
count = 1
yield (count, x)
def max_num(lst):
count, number = max(cont_cnt(lst), default=(None, None))
print(f"Max: {number=}, {count=}")
max_num([1,1,2,3,4,4,4])
max_num([])