#python #python-3.x #list #function
#питон #python-3.x #Список #функция
Вопрос:
найдите наибольшее последовательное вхождение одного и того же числа в списке без импорта каких-либо модулей. У меня есть этот код
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 max1lt;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()
программа работает отлично, но есть ошибка , если я введу 1 1 2 3 4 4 4 0
список, он будет,
lst=[1,1,2,3,4,4,4]
и результат должен быть
The number is: 4 The largest size of consecutive numbers: 3
но пусть будет так:
The number is: 1 The largest size of consecutive numbers: 2
проблема в функции long()
Комментарии:
1. Совет на будущее: используйте значимые имена переменных. Например:
current_count
это гораздо лучшее имя, чемnewx
. Это может показаться не важным, но это позволяет гораздо легче понять, что делает ваш код, и предотвращать ошибки.2. Не могли бы вы переформатировать код , некоторые отступы кажутся странными ?
Ответ №1:
Попробуйте использовать этот подход:
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 gt; max_count: max_count = count: max_num = prec count = 1 else: count = 1 return max_num, max_count
Комментарии:
1. Спасибо, но ошибка все та же
Ответ №2:
cont_cnt
будет непрерывно подсчитывать числа во входном списке, сбрасывая счетчик, если число отличается от предыдущего. max_num
затем выбирает максимальное значение. Значение default=(None, None)
возвращается, если список пуст.
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([])
Ответ №3:
Что происходит, так это то, что вы проверяете максимальное количество вхождений только после изменения числа (т. Е. Когда x != lst[i]). Поскольку 4-последнее значение в списке , его количество никогда не проверяется. Вы должны переместить тест между max1 и num в той части, где вы увеличиваете num. Вам также нужно увеличивать число только тогда , когда x равно lst[i], что означает, что подсчет значения должен начинаться с 1 :
def long(lst): newx=1 #count = 1 x=lst[0] max1=newx #to save the how many number dupilicted num=x #to save which number is for i in range(1,len(lst)): if x==lst[i]: # compute new value if consecutive counts newx=newx 1 # check new value of newx if max1lt;newx: max1=newx num=x else: # different values : start new counting newx=1 x=lst[i] return max1,num
Ответ №4:
Наконец я нахожу решение, нам просто нужно добавить поддельное значение в список, и результат будет отличным ! Ниже long() функция редактирования*
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): lst.append(0) #add fake value to correct the function 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 max1lt;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() print("List:" ,x) #print the list without adding 0 , the fake value**** m,a=long(x) print("The number is: ",a) print("The largest size of consecutive numbers: ", m) main()