python - 我如何比较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):
解决方案
我不确定您为什么在eval
此处使用或将输入存储在字符串中而不是列表中...找出数字是否为奇数的标准方法是使用模运算符%
- int n 为奇数 if n % 2 != 0
。
推荐阅读
- kubernetes-helm - 如何在使用 toyaml 格式化之前通过 tpl 处理文本?
- arrays - 您可以在 C 中创建等效的打字稿记录类型吗
- reactjs - React Native 中的图像表
- go - Go 是否只允许在匿名函数中捕获函数调用一次?
- java - 在 WebFlux 中生成 UUID
- java - 为 generateProto 上的属性“$1”指定的原始源
- wordpress - DevTools 无法加载 SourceMap:无法加载内容
- java - RestAssured - 在调用 API B 的主体中使用来自 API A 的响应值
- java - Lombok - 将 @EmbeddedId 字段暴露给 @SuperBuilder
- r - 如何通过自定义函数在 r 中的 for 循环中使用向量