简体   繁体   English

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

[英]How to check if consecutive digits in a number are even or odd?

I am doing some exercises and learning Python.我正在做一些练习和学习 Python。 I need to be able to check for an input number whether its consecutive digits are even or odd.我需要能够检查输入数字的连续数字是偶数还是奇数。 So, if the first number is odd, the next should be even and so on in order for the terms to comply.因此,如果第一个数字是奇数,则下一个应该是偶数,依此类推,以符合条款。 I have the following code:我有以下代码:

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))

As you can see, I am struggling with index looping.如您所见,我正在努力解决索引循环问题。 I took the input number and transformed it into a list.我把输入的数字转换成一个列表。 Created a variable for index[0] and don't really know how to loop through consecutive indexes.为 index[0] 创建了一个变量,并且真的不知道如何遍历连续的索引。 I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].我知道我可能能够使用 zip 或枚举,但我认为这不是一个真正的 Pythonic 解决方案,并且可能有一种更简单的方法来循环连续列表编号并将它们与索引 [-1] 进行比较。

Input examples:输入示例:

>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False

try this:尝试这个:

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

Works as:用作:

  1. Converts integer to list: 1234 -> [1,2,3,4]将 integer 转换为列表:1234 -> [1,2,3,4]
  2. iterate the elements (excluding the first)迭代元素(不包括第一个)
  3. XOR condition that takes False if two consecutive digits are even or odd.如果两个连续数字是偶数或奇数,则 XOR 条件为False

Tests:测试:

>>> print(par_nepar(2749))
True

>>> print(par_nepar(2744))
False

mine solution is very simple.我的解决方案非常简单。 just change a bit your code and avoiding using indexes just looping through all digits in cifre and handling boolean flags:只需更改您的代码并避免使用索引,只需遍历 cifre 中的所有数字并处理 boolean 标志:

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))

outputs:输出:

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

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

I think instead of getting an integer as input you can get a string and convert it to a list of integers我认为您可以获取一个字符串并将其转换为整数列表,而不是获取 integer 作为输入

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):
    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

Maybe you would also like this one liner.也许你也想要这一个班轮。

In a single loop, we find if the number mod 2 is the same as the (first number + the index) mod 2.在单个循环中,我们查找数字 mod 2 是否与(第一个数字 + 索引)mod 2 相同。

This works for you alternating use case.这适用于您交替用例。

par_nepar = lambda x: all([(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in enumerate(str(x))])

print(par_nepar(2749))
print(par_nepar(2744))

# Output
True
False

Or if you want with the strings you said, slightly bigger或者如果你想要你说的字符串,稍微大一点

par_nepar = lambda x: 'The number complies to the needed terms. ' if all(
    [(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in
     enumerate(str(x))]) else "The number doesn't comply to the needed terms."

#Output
The number complies to the needed terms.
The number doesn't comply to the needed terms.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM