user8643068
user8643068

Reputation:

Python - For loop and Counters

I'm currently writing a program that uses a 'for' loop and the range function to process all integers from 999 down to zero. I have to code in the loop multiples of 40 on one line separated by spaces, but with only six on one line. The problem I'm having is implementing a counter to determine when six multiples have been printed.

The output should look like this:

Required Output

960 920 880 840 800 760 
720 680 640 600 560 520 
480 440 400 360 320 280 
240 200 160 120 80 40

Currently I have this:

def main():
   count = 0
   for num in range(960, 0, -40):
        print(num, end=' ') 
main()

I know this should be simple but I'm struggling to get the range to format into 6 columns. Any help would be appreciated.

Upvotes: 1

Views: 1052

Answers (6)

Quinn
Quinn

Reputation: 4504

This is a two-step task (using Python 2.7x):

1.Get all integers that are multiples of 40 into a list

2.Split above list every 6 elements, and format the output

>>> n=[str(x) for x in range(999,0,-1) if x%40 == 0]
>>> for x in [n[6*i:6*(i+1)] for i in range(len(n)/6)]:
...     print ' '.join(x)
...
960 920 880 840 800 760
720 680 640 600 560 520
480 440 400 360 320 280
240 200 160 120 80 40

Upvotes: 0

RobertB
RobertB

Reputation: 1929

It is perhaps irrational but I hate counters in loops. While overkill in this particular instance, have you thought of embedding a generator into the mix? This is a handy pattern for more complex situations:

def print_newline_after_x_iterations(my_range, x):
    i = my_range.__iter__()
    while True:
        try:
            for _ in range(x):
                yield next(i)
            print()
        except StopIteration:
            break

def main2():
    for num in print_newline_after_x_iterations(range(960, 0, -40), x=6):
        print(num, end=' ') 

Output:

>>> main2()
960 920 880 840 800 760 
720 680 640 600 560 520 
480 440 400 360 320 280 
240 200 160 120 80 40 

Or even use a co-routine based version:

def coroutine(f):
    def wrap(*args, **kwargs):
        x = f(*args, **kwargs)
        next(x)
        return x
    return wrap


@coroutine
def printer():
    while True:
        msg, end = yield
        print(str(msg), end=end)


@coroutine
def columnator(columns=6, outputer=printer):
    p = printer()
    try:
        while True:
            for _ in range(columns):
                p.send(((yield), " "))
            p.send(("", "\n"))
    except GeneratorExit as err:
        p.send(("", "\n"))


def main3():
    s = columnator(6, outputer=printer)
    for num in range(960, 0, -40):
        s.send(num)
    s.close()

Output:

>>> main3()
960 920 880 840 800 760 
720 680 640 600 560 520 
480 440 400 360 320 280 
240 200 160 120 80 40 

Upvotes: 0

VPfB
VPfB

Reputation: 17362

You could use Python's enumerate for the counter and a conditional expression to make the code more compact:

for i, number in enumerate(range(960, 0, -40), 1):
    print(number, end=' ' if i%6 else '\n')

This is Python 3 code. For Python 2 add this line to the top of the file:

from __future__ import print_function

Upvotes: 2

Raju Pitta
Raju Pitta

Reputation: 606

increment the counter in every loop and reset it to zero once it reaches six.

def main():
   counter = 0
   for number in range(960, 0, -40):
       counter += 1
       print(number, end=' ')
       if counter  == 6:
           counter = 0
           print('')
main()

Upvotes: 0

Kyle Higginson
Kyle Higginson

Reputation: 952

This should work:

def main():
   count = 0
   for num in range(960, 0, -40):
        count += 1
        if count % 6 == 0:
            print(num, end='\n')
        else:
            print(num, end=' ')
main()

Basically the same function, except we check if the count is divisible by 6, if so, print a new line for the next row.

Upvotes: 0

Juho Enala
Juho Enala

Reputation: 69

You can use the Python's modulo operator % to determinate if count is divisible by 6. This might not be the prettiest answer, but how about:

def main():
   count = 0
   for num in range(960, 0, -40):
        count += 1
        print(num, end=' ')
        if count % 6 == 0:
            print('')
main()

Upvotes: 0

Related Questions