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

Viewed 1210

I am doing some exercises and learning 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. 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].

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
5 Answers

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]
  2. iterate the elements (excluding the first)
  3. XOR condition that takes False if two consecutive digits are even or odd.

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:

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

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.

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.
Related