gpt4 book ai didi

python - 打印所有大于其左邻居的整数

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:48 24 4
gpt4 key购买 nike

(使用 python 3)这是我的任务:

给定一个数字列表,找到并打印其所有大于其左邻居的元素。

示例输入

1 5 2 4 3

示例输出

5 4

这是我的代码:

# creates a list out of the input given as '# # # # # #...'
a = [int(s) for s in input().split()]

for i in a[1:]: #skips the first since it has no "left neighbor"
if i > a[a.index(i) - 1]: #checks if 'i' is greater than element before 'i'
print(i, end=' ')

我的问题是它适用于我所做的所有测试,除非我给它一个列表,其中 a[0] == a[-1] 那么它会忽略列表等于那个整数。

例如:

3 5 2 3 1 2 3 1 3
--> 5

我一直很难找到错误!如果这个问题没有很好地呈现,请原谅。这是我第一次问关于 stackoverflow 的问题。

最佳答案

试试这个:

for i in range(1, len(a)):
if a[i] > a[i-1]:
print(a[i], end=' ')

结果:

3 5 2 3 1 2 3 1 3
--> 5 3 2 3 3

关于python - 打印所有大于其左邻居的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971454/

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