如何检查数字中的连续数字是偶数还是奇数?

问题描述 投票:1回答:3

我正在做一些练习并学习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))

如您所见,我正在努力进行索引循环。我将输入的数字转换为列表。为index [0]创建了一个变量,实际上并不知道如何遍历连续的索引。我知道我也许可以使用zip或枚举,但是我认为这不是真正的pythonic解决方案,可能有一种更简单的方法可以遍历连续的列表编号并将它们与index [-1]比较。

输入示例1:2749。输出:数字符合所需的条件。输入示例2:2744。输出:数字不符合所需的条件。

python python-3.x list function nested-lists
3个回答
0
投票

我认为可以获取一个字符串并将其转换为整数列表,而不是获取整数作为输入

def par_nepar(n):
    s,h=0,0
    for i in range(len(n)-1):
        if n[i]%2==0 and n[i+1]%2!=0:
            s+=1
        elif n[i]%2!=0 and n[i+1]%2==0:
            h+=1
    if s==len(n)//2 or h==len(n)//2:
        print("The number complies to the needed terms")
    else:
        print("The number does not complies to the needed terms")

# list of digits in the provided input
n = list(map(lambda x: int(x),list(input("Unesite broj n: "))))
par_nepar(n)

0
投票
def par_nepar(n):
    cifre = list(str(n))
    flg = False
    if int(cifre[0]) % 2 == 0:
        flg = True
    for d in cifre[1:]:
        _flg = False
        if int(d) % 2 == 0:
            _flg = True
        if not flg^_flg:
            print("The number does not complies to the needed terms")
            return
        flg = _flg
    print("The number complies to the needed terms")
    return

0
投票

您能否指定给定数字所需的输出。您是否只想获取最后一位数字并检查它是奇数还是偶数?

© www.soinside.com 2019 - 2024. All rights reserved.