首页 > 解决方案 > 我如何比较python代码中序列中的奇数?

问题描述

我需要编写一个代码来计算用户输入的一系列数字中相邻奇数对的数量。

比如说,用户输入序列 3, 4, 5, 11, 6, 17, 9, 13, 12。有三对相邻的奇数:(5, 11), (17, 9), ( 9、13)。

这是预期输入和输出的示例:

Enter the length of the sequence:

5

Enter number 1:

57

Enter number 2:

89

Enter number 3:

3

Enter number 4:

11

Enter number 5:

8

The number of pairs of adjacent odd numbers is: 3 

这是我的代码的开头(但是我不确定如何找到奇数):

n = eval(input("Enter the length of the sequence: \n"))
string = ""
c = 0
for i in range(n):

标签: python

解决方案


我不确定您为什么在eval此处使用或将输入存储在字符串中而不是列表中...找出数字是否为奇数的标准方法是使用模运算符%- int n 为奇数 if n % 2 != 0


推荐阅读