avkpol
avkpol

Reputation: 61

How can I check whether neighbor (previous and next) digits in a row differ in 1 (Python 3)

is it possible to create a code(without list comprehensions, please) that will compare whether neighbor (previous and next) digits in a row differ in 1 so if the condition is met returns the row and returns "good", if not met - "bad". Also, the difference between 9 and 0 doesn't consider as 1. Besides, I need to check whether the only one-digit number and return "one digit" then. I see for me just now it's tricky, so please help! For example:

for (12345432): 
    return "good"                                                                  
for (1793):
    return "bad"
for (7):
    return "one digit"                                                                         

`

Upvotes: 1

Views: 107

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Another solution (with check for one digit):

i = 12345432

if i < 10:
    print("One Digit")
else:
    for a, b in zip(str(i), str(i)[1:]):
        if abs(int(a) - int(b)) != 1:
            print("Bad")
            break
    else:
        print("Good")

Prints:

Good

Upvotes: 1

Related Questions