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

标签 python python-3.x math integer python-3.6

(使用 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/

相关文章:

python - ImportError:Mac 上没有名为 bs4 的模块

python - 使用 adler32 对 Python 3 字符串进行确定性散列

python-3.x - 请求 SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] Windows

python - 在 Numpy 中编写从 i = 1 到 n, log(1 + exp(w_i)) 的和的有效方法是什么

python 3 : Can we avoid repeating an instance name when calling several of its methods?

python - 打印二叉树中从根开始的最长路径

python - 使用 PyDrive 下载特定文件夹中的所有文件

python - 如何提取存储在 mock.call 中的参数

java - 线-三角形交点检查返回错误的交点

javascript - GAS/Javascript 在汇总数字时给出错误的数字