我正在尝试编写一个带有控制台UI的程序,用户可以在其中输入序列,如果按2或3,则可以找到最长的相等整数序列和最长的";山;顺序分别
当我按1时,一切都很顺利,我可以进入列表,但当我按2时(我还没有实现3),什么都没发生
示例输入:按1、1 2 2 2 4后,然后按2
预期输出:4
实际输出:没有,程序不工作
(我希望标题是正题)
def lista_egale(lst1):
l = 0
prev_one = None
lmax = -1
for current in lst1:
if prev_one == current:
l += 1
elif l > lmax:
lmax = l
l = 0
prev_one = current
print(lmax)
def afiseaza_meniu():
print("Aplicatie cu liste")
print("1. Introduceti lista")
print("2. Verificati daca lista are o secventa maxima cu numere egale si afisati-o")
print("3. Verificati daca lista este de tip munte si afisati-o")
print("4. exit")
def ui_citire_lista(lst1):
input_string = input("Introduceti numerele ")
lst1 = input_string.split()
def ui_afisare_munte():
pass
def run():
global lst1
lst1 = []
afiseaza_meniu()
while True:
cmd = input(">>>")
if cmd == "4":
return
if cmd == "1":
ui_citire_lista(lst1)
elif cmd == "2":
lista_egale(lst1)
elif cmd == "3":
ui_afisare_munte()
else:
print("comanda invalida")
def main():
run()
#test_egale()
#test_munte()
if __name__ == "__main__":
main()
您的代码不起作用,因为ui_citire_lista
只在本地分配lst1
。您应该返回值并在run
(其中它是全局的)中捕获它
更改为ui_citire_lista
:
def ui_citire_lista():
input_string = input("Introduceti numerele ")
return input_string.split()
更改为run
:
if cmd == "1":
lst1 = ui_citire_lista()
注意。还有其他问题,但我会让你自己发现;)如果你遇到麻烦,不要犹豫,可以再次发帖
这里有一个返回输入的版本,但您必须更正lista_egle函数。
def lista_egale(lst1):
l = 0
prev_one = None
lmax = -1
for current in lst1:
if prev_one == current:
l += 1
elif l > lmax:
lmax = l
l = 0
prev_one = current
# print(lmax)
return lmax
def afiseaza_meniu():
print("Aplicatie cu liste")
print("1. Introduceti lista")
print("2. Verificati daca lista are o secventa maxima cu numere egale si afisati-o")
print("3. Verificati daca lista este de tip munte si afisati-o")
print("4. exit")
def ui_citire_lista(lst1):
input_string = input("Introduceti numerele ")
lst1 = input_string.split()
def ui_afisare_munte():
pass
def run():
global lst1
lst1 = []
afiseaza_meniu()
result = None
while True:
cmd = input(">>>")
if cmd in ['1','2','3','4']:
lst1.append(cmd)
else:
print("comanda invalida")
if cmd == "4":
print('longest sequence is', result)
return result
elif cmd == "1":
ui_citire_lista(lst1)
elif cmd == "2":
result = lista_egale(lst1)
elif cmd == "3":
ui_afisare_munte()
def main():
run()
#test_egale()
#test_munte()
if __name__ == "__main__":
main()