2017-05-12 2 views
0

마지막 행은 primelist 홀수 입력을 차단 도착 생성파이썬 n의 마지막 행을 해결하는 방법 N의

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() 

전류 출력 :

을 계산하는 소수의 번호를 입력하여 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 

마지막 줄 누락 : 467 479 487 491 499 503 509

어떻게 마지막 소수점 줄을 인쇄 할 수 있습니까?

답변

0

귀하의 코드는 실제로 파이썬 2에서 작동하지만 파이썬에서 파이썬 2 3.

,이 라인은

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

당신에게 10

하지만 파이썬 3에서, 그것은 의지를 포기하지 않습니다 10.7이되어야합니다.

물론 인 경우 귀하의 상태는 elif count == (len(primeList) % 10) and row == (last_row - 1):과 전혀 일치하지 않습니다.

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

len(primeList)/10의 결과가 정수인지 확인 할 그것을 해결하려면.

더 나은 여전히, 당신은 단순히 primeList의 숫자를 10 요소 목록의 목록으로 나눠야합니다. 그런 다음 이러한 복잡한 논리를 없앨 수 있습니다. 자세한 내용은 How do you split a list into evenly sized chunks?

+0

내게 너무 감사합니다 설명해 주셔서 감사합니다. 제발 미치광이 lol을 많이 몰아 주셔서 감사합니다. –

+0

Cool. upvote 및 답변을 수락 잊지 마세요! –

관련 문제