How to use while loop to start at the right end of the list

So, I have a list of numbers that I want to increase only when the condition is met. In this case, the list contains the numbers 0-9.

What I want to do is change 9 in my list to 0, and if the next element is not 9, add it until it is = 9. In the end, it should be a list of zeros.

this is what i have so far:

def increment(self):
    i = len(self.number) - 1
    while (self.number[i] == 9):
        self.number[i] = 0
        i -= 1

It modifies the last item in the list, which is 9, 0. But I'm lost on how to check if 8 = 9, and if not, add 1 until it is. The same goes for all other numbers.

How can I iterate over from the last element of my list with a while loop?

+4
3

, self.numbers, 0: 9, 0; 1. :

def increment(self):
    for i, num in enumerate(reversed(self.numbers)):
        if num:  # that is, if num is not 0
            self.numbers[-i - 1] = 0 if num == 9 else num + 1
            break  # once one number is changed, we stop

:

class Demo:
    def __init__(self):
        self.numbers = list(range(1, 10))

    def increment(self):
        for i, num in enumerate(reversed(self.numbers)):
            if num:
                self.numbers[-i - 1] = 0 if num == 9 else num + 1
                break

demo = Demo()
for _ in range(5):
    print(demo.numbers)
    demo.increment()

[1, 2, 3, 4, 5, 6, 7, 8, 9]  # the original list
[1, 2, 3, 4, 5, 6, 7, 8, 0]
[1, 2, 3, 4, 5, 6, 7, 9, 0]
[1, 2, 3, 4, 5, 6, 7, 0, 0]
[1, 2, 3, 4, 5, 6, 8, 0, 0]
+2

, , , .

my_num = [1,2,3]
rev_num = my_num.reverse()
for num in rev_num:
    print num
+1

I think this is what you want:

def increment(self):
    i = len(self.number) - 1
    while i >= 0:
        while(self.number[i] < 9):
            self.number[i] += 1
        self.number[i] = 0
        i -= 1
+1
source

Source: https://habr.com/ru/post/1628417/


All Articles