Monday, October 17, 2022

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

Issue

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"                                                                         

`


Solution

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


Answered By - Andrej Kesely
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.