Home > Enterprise >  Python: Condensing code into nested for loop
Python: Condensing code into nested for loop

Time:10-01

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()

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related