-1
d=int(input("Decreasing number: "))
i=int(input("Increasing number: "))

def i_d (n,m):
    c=0
    for f in range (100,0,-n):
        for c in range (0,100,m):
            print (f,c)
        print ()    
i_d(d,i)

This is my program, it should give me two number lists, one decreasing and the other increasing.

For example:

d=60
i=40

it should print:

100 0
40  40
40  80

instead it prints:

100 0
100 40
100 80

40 0
40 40
40 80 
pault
  • 41,343
  • 15
  • 107
  • 149
  • Why did you expect the output you expected? – user2357112 Mar 12 '18 at 19:34
  • You shouldn't be using a nested loop here. Instead you want one loop that decrements f at the same time it increments c. – Garrett Gutierrez Mar 12 '18 at 19:35
  • 1
    You have a double for loop. The first one iterates over f and it will print all the values for c for each f. For your desired output, you could probably use [`zip()`](https://stackoverflow.com/questions/13704860/zip-lists-in-python) Try replacing the double loop with `for f, c in zip(range(100, 0, -n), range(0, 100, m)):` – pault Mar 12 '18 at 19:36

1 Answers1

2

You are using a nested loop, which means you are iterating over the increasing range once for each value of the decreasing range. You want a single loop using the zip function so that you iterate over each range in parallel.

for f, c in zip(range(100,0,-n), range(0, 100, m)):
    print (f, c)

To handle sequences of differing lengths, repeating the last element of the shorter sequence as necessary, use itertools.zip_longest. You'll need to track the last value of each sequence separately so that you can reuse it.

for f, c in itertools.zip_longest(range(100, 0, -n), range(0, 100, m)):
    if f is None:
        f = last_f
    elif c is None:
        c = last_c
    print(f, c)
    last_f = f
    last_c = c
chepner
  • 497,756
  • 71
  • 530
  • 681
  • thank you, is there a way to do this without using the zip function? – Alejandro Galvan Mar 12 '18 at 19:39
  • Sure, but I'm not sure what your objection to `zip` is. You could, for instance, simply use a single `while` loop in which you update `f` and `c` manually rather than iterating over two ranges. – chepner Mar 12 '18 at 19:43
  • the zip function worked, but if my counters end when the other ends, ex: i=40 and d=20 it will print all the numbers for i but it wont print all the numbers for d, it will stop when i stops. I want all the numbers for i – Alejandro Galvan Mar 12 '18 at 20:21
  • Ah, right. Do you want to just keep repeating the last element of the shorter sequence? – chepner Mar 12 '18 at 20:23