简体   繁体   中英

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

you could use modulo operation to accomplish this:

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

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.

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]

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, eg if you want to have pattern 4 2 2 1 4 2 2 for input 7 just set

values = [4, 2, 2, 1]

you can simply write,

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

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

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=' ')

Simples way is to use modulo operation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM