Ida No - 1 year ago 56
Python Question

# How to fix the last row of python n generated primelist getting cut off?

last row of n generated primelist gets cut off with odd input

def isPrime(m, L):
while i < n:
if n % i == 0:
return False
i = 1
return True

print()
n = int(input('Enter the number of Primes to compute: '))
primeList = []
x = 2

while len(primeList) < n:
isPrime = True
index = 0
root = int(x ** 0.5) + 1

while index < len(primeList) and primeList[index] <= root:
if x % primeList[index] == 0:
isPrime = False
break
index += 1

if isPrime:
primeList.append(x)

x += 1

print()
n = str(n)
print('The first ' + n + ' primes are: ')

count = 0
tempstring = []
last_row = len(primeList) / 10 + (1 if len(primeList) % 10 else 0)
row = 0
for i in range(0, len(primeList)):
tempstring.append(str(primeList[i]))
count += 1
if count == 10:
print(' '.join(tempstring))
count = 0
tempstring = []
row += 1
elif count == (len(primeList) % 10) and row == (last_row - 1):
print(' '.join(tempstring))
# done
print()

current output:

Enter the number of Primes to compute: 97

The first 97 primes are:
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
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463

missing the last line: 467 479 487 491 499 503 509

how do I get it to print the last line of primes?

Your code will actually work in python 2 but not in python 3.

In python 2, this line

last_row = len(primeList) / 10 + (1 if len(primeList) % 10 else 0)

will give you 10

but in python 3, it will be 10.7.

Of course, if it is 10.7, your condition elif count == (len(primeList) % 10) and row == (last_row - 1): will not match at all.

To fix it, just do

last_row = int(len(primeList) / 10) + (1 if len(primeList) % 10 else 0)

i.e. make sure the result of len(primeList) / 10 is an integer.

Better still, you should simply divide the numbers in primeList into a list of 10-element list. Then you can do away with these complicated logic. For more details see How do you split a list into evenly sized chunks?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download