[英]How to solve the coding error with python?
Topic: Check adjacent odd numbers
主题:检查相邻的奇数
Problem description: Enter 5 numbers问题描述:输入5个数字
Input description: Whether the output has adjacent odd numbers.
输入说明:output是否有相邻的奇数。
Output description: If there are adjacent odd numbers, output the first group of adjacent odd numbers, otherwise, turn out NO.
Output 说明:如果有相邻的奇数,output第一组相邻的奇数,否则,转NO。
Sample Input: Sample Output: 5 6 7 8 9 NO⏎ 8 9 11 13 15 9,11⏎
Writing condition:
写作条件:
Input: Use the list(), map(), int() functions to convert the input string to a sequence of integers输入:使用 list()、map()、int() 函数将输入字符串转换为整数序列
Process: Use a loop to check for adjacent odd numbers
过程:使用循环检查相邻的奇数
Output: apply f-string
Output:应用 f 字符串
num1, num2, num3, num4, num5 = map(int,input().split())
list1= [num1, num2, num3, num4, num5]
for i in range(list1[0], list1[4]):
if i%2 != 0:
for j in range(list1[1], list1[4]):
if j%2 != 0 :
break
print(f'{i, j}')
else :
print('NO')
I used for-loop to write the code but the result is a wrong error.我用for-loop来写代码但是结果是错误的错误。 I excepted that when I input
5 6 7 8 9
and the actual result is NO
.我排除了当我输入
5 6 7 8 9
并且实际结果为NO
时。 However, my wrong result is但是,我的错误结果是
(5, 7)
NO
(7, 7)
NO
When you use range
you are creating an entirely new set of numbers.当您使用
range
时,您正在创建一组全新的数字。 You need to use the list
directly.您需要直接使用
list
。 An easy way to solve this problem is by using zip on the list
and an offset of the list
解决这个问题的一个简单方法是在
list
使用zip和list
的偏移量
This way you can compare the current number with the next number without creating more loops.这样您就可以将当前数字与下一个数字进行比较,而无需创建更多循环。
#you can apply your split results directly to the list
#no need to unpack and repack the data
data = list(map(int,input().split()))
for i,j in zip(data, data[1:]):
#you don't need explicit equality (ie. i%2!=0)
#both of these either "are" or "aren't"
if i%2 and j%2:
#the way you wrote your fstring
#you were actually printing a tuple
print(f'{i}, {j}')
break
else:
#if `break` was never reached
print('NO')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.