Пример рекурсивного кода
Код
def increment(lst, base):
if len(lst) == 0:
return lst
lst[-1] += 1 # increment right most digit in list
if lst[-1] >= base:
# carry forward
lst[-1] = 0 # reset right most to zero
# (1) increment without right most t
# (2) then append right most digit
lst = increment(lst[:-1], base) + lst[-1:]
return lst
Тест
print('Base 12 example')
lst = [0, 0, 0, 5, 12]
print(lst)
for i in range(10):
lst = increment(lst, 12)
print(lst)
print('Base 3 example')
lst = [0, 0, 0]
print(lst)
for i in range(10):
lst = increment(lst, 3)
print(lst)
Out
Base 12 example
[0, 0, 0, 5, 12]
[0, 0, 0, 6, 0]
[0, 0, 0, 6, 1]
[0, 0, 0, 6, 2]
[0, 0, 0, 6, 3]
[0, 0, 0, 6, 4]
[0, 0, 0, 6, 5]
[0, 0, 0, 6, 6]
[0, 0, 0, 6, 7]
[0, 0, 0, 6, 8]
[0, 0, 0, 6, 9]
Base 3 example
[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 2, 0]
[0, 2, 1]
[0, 2, 2]
[1, 0, 0]
[1, 0, 1]