user1762229
user1762229

Reputation: 71

Output formatting based on user parameters

 250 255 260 265 270 275 280 285 290 295 300 305 310 315 320
 325 330 335 340 345 350 355 360 365 370 375 380 385 390 395
 400 405 410 415 420 425 430 435 440 445 450 455 460 465 470
 475 480 485 490 495 500 505 510 515 520 525 530 535 540 545
 550 555 560 565 570 575 580 585 590 595 600 605 610 615 620
 625 630 635 640 645 650 655 660 665 670 675 680 685 690 695
 700 705 710 715 720 725 730 735 740 745 750

I am trying to create a program where you enter in a lower bound (250 in this case), and upper bound(750 in this case, a skip number (5 in this case) and also tell Python how many numbers I want per line (15 in this case) before breaking the line, can somehow help me go about with formatting this? I have Python 3.1.7. Thanks!

Basically how do I tell python to create 15 numbers per line before breaking, thanks.

Upvotes: 1

Views: 136

Answers (4)

Jon Clements
Jon Clements

Reputation: 142176

Another option to through in the mix is to use the itertools.grouper recipe:

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    from itertools import izip_longest
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Then the loop becomes:

for line in grouper(15, range(250, 755, 5), ''):
    print(' '.join(map(str, line)))

Upvotes: 1

volcano
volcano

Reputation: 3582

@ljk07

  1. xrange is better - does not create whole list at once
  2. You do not really need sys.stdout - just add comma
  3. New style formatting is better

how about a little more compact and more contemporary

for cnt,v in enumerate(range(250,755,5),1):
    print '{}{}'.format(v,' ' if cnt % 15 else '\n'),

EDIT: Missed python 3 part - print even better here

for cnt,v in enumerate(range(250,755,5),1):
    print( '{:3}'.format(v),end=' ' if cnt % 15 else '\n')

Upvotes: 1

ljk07
ljk07

Reputation: 962

Use range to create a list of your numbers from 250 to 750 in steps of 5. Loop over this using enumerate which gives the value and a counter. Check modulo 15 of the counter to determine if a line break needs to be included in the print. The counter starts at zero so look for cnt%15==14.

import sys

for cnt,v in enumerate(range(250,755,5)):
    if cnt%15==14:
        sys.stdout.write("%d\n" % v)
    else:
        sys.stdout.write("%d " % v)

Upvotes: 1

Christiaan
Christiaan

Reputation: 183

You should keep a counter and check on the modulo of the counter if you have to print a new line.

Could look something like this:

if counter % 15 == 0:
    sys.stdout.write(str("\n"))

Upvotes: 0

Related Questions