2016-10-11 1 views
0

숫자의 소수 분해를 찾는 코드를 작성 중입니다. 주 함수는 숫자를 통해 증가합니다. 타이밍 실험을 수행하기 위해 코드를 사용하기 때문에이 작업을 수행하고 있습니다. 나는 그다지 효율적이지 않다는 것에 신경 쓰지 않는다. 나를위한 프로젝트의 일부는 스스로를 더 효율적으로 만들 것이다. 아직 완전히 완성되지도 않았습니다.프라임 분해 프로그램에서 할당 오류 이전에 참조되는 변수는 무엇입니까?

import math 
import time 

primfac=[] 

def primcheck(n): 
    for x in xrange(2, int(n**0.5)+1): 
     if n % x == 0: 
      return False 
    return True 

def primes(n): 
    sieve = [True] * n 
    for i in xrange(3,int(n**0.5)+1,2): 
     if sieve[i]: 
      sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) 
    return [2] + [i for i in xrange(3,n,2) if sieve[i]] 


def factfind(lsp,n): #finds factors of n among primes 
    for i in lsp: 
     if n%i==0: 
      primfac.append(i) 
     else: 
      i+=1 

def simplify(lsp, n): 
    x = 1 
    for i in lsp: 
     x=i*x 
    if x != n: 
     print "needs exponent, computing" 
     for i in lsp: 
      y=n/i 
      if primcheck(y) == True: 
       lsp.append(y) 
      else: 
       lsp.append(factfind(primes,y)) 

def primfacfind(n1,n2): 
    while n1 <= n2: 
     time_start = time.clock() 
     if primcheck(n1) == True: 
      print "prime" 
      time_elapsed = time.clock() - time_start 
      print "time:", time_elapsed 
      n1+=1 
     else: 
      n = n1 
      print "starting #", n 

      factfind(primes(n),n) 
      print primfac 

      del primfac 
      primfac[:] = [] 
      simplify(primfac, n) 

      time_elapsed = time.clock() - time_start 
      print "time:", time_elapsed 

      n1+=1 

primfacfind(6,15) 

내가 코드를 실행 은,이 오류 메시지를 제공합니다 : 나는 유일한 새 부품도 다음 simplify 기능을 제외한 모든 기능을 테스트했기 때문에 이해가 안

Traceback (most recent call last): 
    File "python", line 65, in <module> 
    File "python", line 54, in primfacfind 
UnboundLocalError: local variable 'primfac' referenced before assignment 

print 이후의 행입니다.

+1

문제는 'primefacfind'의 'del primfac' 행입니다. 이것은 컴파일러가'primefac' 변수를 로컬 변수로 지정하게하지만'primefac'라는 로컬 변수가 생성되지 않았기 때문에 * Runtime 오류 *'UnboundLocalError : 로컬 변수 'primfac'가 할당 전에 참조됩니다' –

+0

그래서'primefacfind'의'else' 블록에'print primfac'이 에러를 내고있는 이유입니다. –

+0

예를 들어, 나는 여러분이 원하는 것은 대신'del primefac' 대신에'primefac.clear()'라고 생각합니다. 왜냐하면 후자는 컴파일러가'primefac'를 지역 변수로 취급하게 될 것이기 때문입니다. –

답변

1

파이썬의 함수는 global 키워드없이 함수 범위 읽기 전용으로 선언 된 변수에만 액세스 할 수 있습니다.

import math 
import time 

primfac=[] 

def primcheck(n): 
    for x in xrange(2, int(n**0.5)+1): 
     if n % x == 0: 
      return False 
    return True 

def primes(n): 
    sieve = [True] * n 
    for i in xrange(3,int(n**0.5)+1,2): 
     if sieve[i]: 
      sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) 
    return [2] + [i for i in xrange(3,n,2) if sieve[i]] 


def factfind(lsp,n): #finds factors of n among primes 
    for i in lsp: 
     if n%i==0: 
      primfac.append(i) 
     else: 
      i+=1 

def simplify(lsp, n): 
    x = 1 
    for i in lsp: 
     x=i*x 
    if x != n: 
     print "needs exponent, computing" 
     for i in lsp: 
      y=n/i 
      if primcheck(y) == True: 
       lsp.append(y) 
      else: 
       lsp.append(factfind(primes,y)) 

def primfacfind(n1,n2): 
    global primfac 
    while n1 <= n2: 
     time_start = time.clock() 
     if primcheck(n1) == True: 
      print "prime" 
      time_elapsed = time.clock() - time_start 
      print "time:", time_elapsed 
      n1+=1 
     else: 
      n = n1 
      print "starting #", n 

      factfind(primes(n),n) 
      print primfac 

      del primfac 
      primfac = [] 
      simplify(primfac, n) 

      time_elapsed = time.clock() - time_start 
      print "time:", time_elapsed 

      n1+=1 

primfacfind(6,15) 
+0

파이썬은 함수 밖의 변수를 참조 할 수 있습니다. –

+0

...하지만 글로벌 키워드가 필요합니다. 기능에 "global"키워드가 추가되었을 때 내가 게시 한 코드는 OP가 갖는 오류를 방지합니다. – Scott

+0

... 대다수의 다른 언어와는 달리, 특별한 조치없이 이러한 것을 허용합니다. https://en.wikipedia.org/wiki/Global_variable – Scott

관련 문제