Home > Back-end >  How can I check whether neighbor (previous and next) digits in a row differ in 1 (Python 3)
How can I check whether neighbor (previous and next) digits in a row differ in 1 (Python 3)

Time:08-02

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"                                                                         

`

CodePudding user response:

You can keep (integer-) dividing the number and compare the previously seen digit and the new digit:

def good_or_bad(num):
    digit_prev = num % 10
    while num != 0:
        num, digit = divmod(num, 10)
        if abs(digit - digit_prev) > 1:
            return 'bad'
        digit_prev = digit
    return 'good'

print(good_or_bad(12345432)) # good
print(good_or_bad(1793)) # bad

CodePudding user response:

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