Lana Kim
Lana Kim

Reputation: 23

How do I print a sequence of "1 2 3" for a length up to an input integer?

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

Answers (8)

NANDHA KUMAR
NANDHA KUMAR

Reputation: 503

you can simply write,

print(" ".join([str((i%3)+1)  for i in range(n)] ))

Upvotes: 0

Jussi Nurminen
Jussi Nurminen

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

Ehsan Rajabi
Ehsan Rajabi

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

Jamshy
Jamshy

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

theherk
theherk

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

LingangWang
LingangWang

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

K.Mat
K.Mat

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

XxJames07-
XxJames07-

Reputation: 1826

you could use modulo operation to accomplish this:

for x in range(int(input("number:"))):
    print(x%3+1,end=' ')

Upvotes: 5

Related Questions