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

2024-09-29 21:39:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: in列表forif数字even奇数偶数
3条回答

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

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)

试试这个:

def par_nepar(n):

    split = [int(i) for i in str(n)]. 

    for i in range(1,len(split)):

        if (split[i] % 2 == 0) ^ (split[i-1] % 2 == 1):
            return False

    return True

工作内容如下:

  1. 将整数转换为列表:1234->;[1,2,3,4]
  2. 迭代元素(不包括第一个)
  3. 如果两个连续数字是偶数或奇数,则取False的异或条件

测试:

>>> print(par_nepar(2749))
True

>>> print(par_nepar(2744))
False

我的解决方案很简单。只需更改一点代码,避免使用索引在cifre中循环所有数字并处理布尔标志:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    even = True
    odd = True
    output = "The number complies to the needed terms"

    for broj in cifre:
        if broj % 2 == 0 and odd:
            even = True
            odd = False
        elif broj % 2 != 0 and even:
            odd = True
            even = False
        else:
            return "The number doesn't comply to the needed terms."
    return output
n = int(input("Unesite broj n: "))
print(par_nepar(n))

产出:

Unesite broj n: 33890
The number doesn't comply to the needed terms.

Unesite broj n: 4963850
The number complies to the needed terms

相关问题 更多 >

    热门问题