我正在做一些练习,学习Python。我需要能够检查输入的数字,无论其连续数字是偶数还是奇数。因此,如果第一个数字是奇数,那么下一个数字应该是偶数,依此类推,以使条款符合要求。我有以下代码:
def par_nepar(n):
cifre = []
while n != 0:
cifre.append(n % 10)
n //= 10
cifre = cifre[::-1]
ind = cifre[0]
for broj in cifre:
if cifre[0] % 2 == 0:
# for br in range(len(cifre)):
if cifre[ind + 1] % 2 != 0:
ind = cifre[ind+1]
n = int(input("Unesite broj n: "))
print(par_nepar(n))
正如您所看到的,我正在与索引循环作斗争。我把输入的数字转换成一个列表。为索引[0]创建了一个变量,但实际上不知道如何循环遍历连续的索引。我知道我可能可以使用zip或enumerate,但我认为这不是一个真正的Python解决方案,可能有一种更简单的方法来循环连续的列表编号,并将它们与索引[-1]进行比较
输入示例:
>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
我认为你可以得到一个字符串并将其转换为整数列表,而不是得到一个整数作为输入
试试这个:
工作内容如下:
False
的异或条件李>测试:
我的解决方案很简单。只需更改一点代码,避免使用索引在cifre中循环所有数字并处理布尔标志:
产出:
相关问题 更多 >
编程相关推荐