Hesham - 1 year ago 101

Python Question

I would like to generate a list of single digits based on user input. In a circular iterative way, the list should contain the user input, the two digits before that, and the two digits after that. The order of the digits isn't important.

user_input = "1"

output = [9, 0, 1, 2, 3]

user_input = "9"

output = [7, 8, 9, 0, 1]

Using itertools.cycle I was able to get the next two digits, but I couldn't find an answer that can help me get the previous two digits. Is there a simple way to get those previous two digits?

`from itertools import cycle`

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

user_input = "139"

for i in user_input:

s = int(i)

lst = [s]

itr = cycle(numbers)

if s in itr:

#how can I get the two digits before s?

lst.append(next(itr)) #getting the next digit

lst.append(next(itr))

print(lst)

Answer Source

Could use a list comprehension and `% 10`

:

```
>>> for s in range(10):
print([i % 10 for i in range(s-2, s+3)])
[8, 9, 0, 1, 2]
[9, 0, 1, 2, 3]
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
[6, 7, 8, 9, 0]
[7, 8, 9, 0, 1]
```