gpt4 book ai didi

Python:Longest Plateau Problem:找到最长连续等值序列的长度和位置

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:11 28 4
gpt4 key购买 nike

题目是解决 Sedgewick Wayne 的 Python 书中的以下问题:

给定一个整数数组,编写一个程序,找出最长的连续等值序列的长度和位置,其中该序列前后元素的值较小。

我试过这个问题,遇到了一些问题。

这是我的代码:

import sys
import stdio

# Ask the user input for the list of integers
numList = list(sys.argv[1])

maxcount = 0
value = None
location = None

i = 1
while i < len(numList) - 1:
resList = []
count = 0
# If i > i-1, then we start taking i into the resList
if numList[i] > numList[i - 1]:
# start counting
resList += [numList[i]]
# Iterating through the rest of the numbers
j = i + 1
while j < len(numList):
# If the j element equals the i, then append it to resList
if numList[i] == numList[j]:
resList += [numList[j]]
j += 1
elif numList[i] < numList[j]:
# if j element is greater than i, break out the loop
i = j
break
else:
# if j element is smaller than i, count equals length of resList
count = len(resList)
if count > maxcount:
maxcount = count
value = resList[1]
location = i
i = j
else:
# if not greater than the previous one, increment by 1
i += 1

stdio.writeln("The longest continuous plateau is at location: " + str(location))
stdio.writeln("Length is: " + str(maxcount))
stdio.writeln("Number is: " + str(value))

结果显示:

python exercise1_4_21.py 553223334445554
The longest continuous plateau is at location: 11
Length is: 3
Number is: 5


python exercise1_4_21.py 1234567
The longest continuous plateau is at location: None
Length is: 0
Number is: None

但是不知何故,如果给定的列表的格式是一组大于前一个的连续整数,但随后这组列表结束时后面没有整数,我的程序就不会结束。 ...

exercise1_4_21.py 11112222111444
Traceback (most recent call last):
File "exercise1_4_21.py", line 32, in <module>
if numList[i] == numList[j]:
KeyboardInterrupt


exercise1_4_21.py 111222211112223333
Traceback (most recent call last):
File "exercise1_4_21.py", line 25, in <module>
if numList[i] > numList[i - 1]:
KeyboardInterrupt

不太确定逻辑错误在哪里...非常感谢您的帮助和好意!

最佳答案

您似乎使解决方案过于复杂(但正确选择了关键案例)。

它只需要单次运行列表。

def maxplat(l):
if (len(l)==0):
return 0, 0
start, leng = 0, 1
maxlen, maxstart = 0, 1
for i in range(1, len(l) + 1):
if (i == len(l)) or (l[i] < l[i-1]):
if (leng > maxlen):
maxlen, maxstart = leng, start
elif (l[i] == l[i-1]):
leng += 1
else:
start, leng = i, 1
return maxlen, maxstart

#test cases
print(maxplat([])) #empty case
print(maxplat([3])) #single element
print(maxplat([3,2,4,4,2,5,5,5,3])) #simple case
print(maxplat([3,2,4,4,2,5,5,5,6])) #up after long run
print(maxplat([3,2,4,4,2,5,5,5])) #run at the end
print(maxplat([3,3,3,3,2,4,4,2])) #run at the start

>>>
(0, 0)
(1, 0)
(3, 5)
(2, 2)
(3, 5)
(4, 0)

关于Python:Longest Plateau Problem:找到最长连续等值序列的长度和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52346223/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com