Aba Pobee
Aba Pobee

Reputation: 11

Python: Condensing code into nested for loop

I need to print this code using nested for-loops. I see the pattern within my code, but am unsure how to condense it. It seems really simple, but it's not quite clicking yet for me. The result should look like this:

01234
12345
23456
34567
45678
56789

My code prints this, but no nested loops are involved and its kind of lengthy. Any help condensing it?

for i in range(0,5):
    print(i,end='')
print()
for i in range(1,6):
    print(i,end='')
print()
for i in range(2,7):
    print(i,end='')
print()
for i in range(3,8):
    print(i,end='')
print()
for i in range(4,9):
    print(i,end='')
print()
for i in range(5,10):
    print(i,end='')
print()

Upvotes: 0

Views: 454

Answers (3)

Mark
Mark

Reputation: 92461

Notice that each set of numbers you print is 1 plus the previous group. So if you make an outer loop that increases by one, you can add that to the numbers in the inner loop. There are a few ways to do this, but this should be pretty clear:

for i in range(6):
    for j in range(5):
        print(j+i, end='')
    print()

printing:

01234
12345
23456
34567
45678
56789

For a different take, consider that the inner loop is just a range starting at increasing starting numbers. You can print a range in python by spreading it out into the print function with *. This, plus sep='' allow you to print the ranges in a single for loop by creating an range than starts at the increasing indices of the loop:

rows = 6
cols = 5

for i in range(rows):
    print(*range(i, i+cols), sep='')

# prints the same thing as the code above

Upvotes: 1

ILS
ILS

Reputation: 1380

Two-tier loops can solve your problem. The outer one traverses for the start_index of each output sequence, and the inner one describes the rule how to generate each output sequence from the start_index.

So try this:

start, end = 0, 6
output_len, inner_step = 5, 1
for start_index in range(start, end):
  output_seq = ""
  for o in range(start_index, start_index+output_len, inner_step):
    output_seq += str(o)
  print(output_seq)

Edit: inner_step can be omitted, because the default step of range is 1. I wrote it to emphasize we can change it for more general rule.

Upvotes: 0

Vae Jiang
Vae Jiang

Reputation: 347

I assume this is something you want.

def pattern_creator(number_of_loops: int, start_pattern: str) -> None: 
    for loop in range(number_of_loops):
        print(''.join([str(int(x)+loop) for x in start_pattern]))

pattern_creator(number_of_loops=6, start_pattern='01234')

Upvotes: 0

Related Questions