Reputation: 23
for instance:
input=7 -> print : 1 2 3 1 2 3 1
input=2 -> print : 1 2
I've only been able to print the whole "1 2 3" repeated for the input integer with the code below. (input=2 -> print : 1 2 3 1 2 3)
n = int(input())
for i in range(1,n+1):
for num in range(1,4):
print(num, end="")
num += 1
Upvotes: 2
Views: 1743
Reputation: 503
you can simply write,
print(" ".join([str((i%3)+1) for i in range(n)] ))
Upvotes: 0
Reputation: 2408
There are many possible solutions. itertools
provides cycle
that cycles over desired values:
from itertools import cycle
c = cycle((range(1, 4)))
for k in range(7):
print(next(c)) # prints 1, 2, 3, 1, 2, 3, 1
The modulo trick is not difficult to understand, especially for those educated in programming. However, when writing Python I would prefer this more Pythonic solution. After all, the whole point of Python is to provide readable code and high level abstractions.
Upvotes: 2
Reputation: 46
you can use this code:
n = int(input())
out = ""
seq = "123"
j=0
for i in range(n):
if j<len(seq):
out +=str(seq[j])
j+=1
else:
j=0
out +=str(seq[j])
j+=1
print (out) # print: 12312
Upvotes: 0
Reputation: 70
Simples way is to use modulo operation:
input = int(input("enter your number:"))
for i in range(input):
print(i % 3+1, end=' ')
Upvotes: -2
Reputation: 7546
This could also be done with a generator using yield_from
.
def from_seq(seq):
while True:
yield from seq
gen = from_seq([1, 2, 3])
z = [next(gen) for _ in range(7)]
print(z)
output:
[1, 2, 3, 1, 2, 3, 1]
Upvotes: 1
Reputation: 19
A easy to understand answer:
n = int(input())
repeat_times = int(n / 3)
remainder = n % 3
store = []
if repeat_times > 0:
for i in range(0, repeat_times):
for j in range(1, 4):
store.append(j)
if remainder > 0:
for i in range(1, remainder + 1):
store.append(i)
for i in store:
print(i, end=' ')
Upvotes: -1
Reputation: 1620
You can access element in [1, 2, 3]
based on index modulo 3.
values = [1, 2, 3]
n = int(input())
for i in range(n):
index = i % len(values)
print(values[index], end=" ")
This is a good method if you want to repeat different values, e.g. if you want to have pattern 4 2 2 1 4 2 2
for input 7
just set
values = [4, 2, 2, 1]
Upvotes: 0
Reputation: 1826
you could use modulo operation to accomplish this:
for x in range(int(input("number:"))):
print(x%3+1,end=' ')
Upvotes: 5