Skip to main content
 首页 » 编程设计

python之计算相邻奇数的个数

2024年10月25日15davidwang456

我正在尝试用 Python 编写代码,要求用户输入序列中的数字个数,然后输入数字本身。最后,程序输出相邻奇数对的数量。这是一个示例输出:

输入序列长度:6
输入数字 1: 3
输入数字 2:4
输入数字 3:7
输入数字 4:9
输入数字 5:3
输入数字 6: 5
相邻奇数的对数为3

我想出了以下代码:

length = eval(input("Enter the length of the sequence: ")) 
 
for i in range(1,length+1): 
    ask = eval(input("Enter number: "+str(i)+ ": ")) 
    for m in range(0,length+1,2): 
        ask2 = ask 
 
h = ask%2 
f = ask2%2 
 
if h>0 and f>0: 
    k = (len(str(ask) + str(ask2))) 
    print(k) 
 
else: 
    pass 

虽然提示的输出是正确的,但我无法计算相邻奇数对的数量。请帮助我更正我的代码或在此基础上进行构建;这将不胜感激。您一定已经注意到,我一直在使用基本的 if 语句、循环和字符串来编写代码。如果您能坚持这一点以便我更好地理解,那就太好了。

抱歉发了这么长的帖子。

非常感谢

请您参考如下方法:

这将解决您的问题。

首先将用户给出的输入放入名为 numList 的列表中。保留一个计数变量来统计相邻奇数的个数。一个一个循环遍历numList,通过检查除以2的余数来识别奇数。(通过给定的if条件检查)然后您可以简单地打印列表中相邻奇数的数量。

length=int(input("Enter the length of the sequence: ")) 
numList=[] 
count=0 
for i in range(length): 
    num=int(input("Enter number "+str(i+1)+ ": ")) 
    numList.append(num) 
 
for x in range(len(numList)-1): 
    num1=numList[x] 
    num2=numList[x+1] 
    if((num1%2==1) and (num2%2==1)): 
        count=count+1 
    else: 
        continue 
 
print("The number of pairs of adjacent odd numbers is "+str(count)) 

如果您想在不使用列表的情况下解决这个问题,这就是答案。 您应该在接收输入时处理输入。

length=int(input("Enter the length of the sequence: ")) 
count=0 
num1=int(input("Enter number "+str(1)+ ": ")) 
for i in range(length-1): 
    num2=int(input("Enter number "+str(i+2)+ ": ")) 
    if((num1%2==1) and (num2%2==1)): 
        count=count+1 
    num1=num2 
 
 
print("The number of pairs of adjacent odd numbers is "+str(count))