Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a table of numbers

I am having issues with trying to figure out where to start on generating a table that will look like this:

  2      3      5      7     11     13     17     19     23     29 
 31     37     41     43     47     53     59     61     67     71 
 73     79     83     89     97    101    103    107    109    113 
127    131    137    139    149    151    157    163    167    173 
179    181    191    193    197    199    211    223    227    229 

This is my code thus far that solves for the first 1000 primes, but I'm unsure how to get in a 10x100 table.

Code:

def is_prime(number):
    for i in range(2,number):
        if ((number % i) == 0):
            return False
    return True

def main():
    for value in range(2, 7920):
        if ( is_prime(value) ):
            print(value, end='\t')
main()
like image 298
Nite Avatar asked Mar 09 '23 12:03

Nite


2 Answers

Just keep track of how many you have printed on the current line.

def main():
    count = 0
    for value in range(2, 7920):
        if (is_prime(value)):
            print(value, end='\t')
            count += 1
            if count % 10 == 0:
                print()
like image 134
Stephen Rauch Avatar answered Mar 15 '23 10:03

Stephen Rauch


The easiest approach is to accumulate each row in a list. Whenever the list reaches ten elements, display that row in a nicely formatted way:

def is_prime(number):
    for i in range(2,number):
        if ((number % i) == 0):
            return False
    return True

def display_row(row):
    print(''.join(format(value, '7d') for value in row))

def main():
    row = []
    for value in range(2, 7920):
        if ( is_prime(value) ):
            row.append(value)
            if len(row) == 10:
                display_row(row)
                row = []
    display_row(row)

main()

The logic for display_row() says to take every value and format it as a decimal, padding with spaces as necessary to fill exactly 7 spaces and then join those together in a single string.

like image 30
Raymond Hettinger Avatar answered Mar 15 '23 10:03

Raymond Hettinger