2011-01-19 2 views
0

여기서 기술 단어가 누락되었지만 여기에서 문제는 int를 float 또는 float로 변경하는 것입니다.분해 문제에서 float - int 문제를 설명하십시오.

def factorize(n): 
    def isPrime(n): 
     return not [x for x in range(2,int(math.sqrt(n))) 
        if n%x == 0] 
    primes = [] 
    candidates = range(2,n+1) 
    candidate = 2 
    while not primes and candidate in candidates: 
     if n%candidate == 0 and isPrime(candidate): 

      # WHY ERROR? 
      #I have tried here to add float(), int() but cannot understand why it returns err 
      primes = primes + [float(candidate)] + float(factorize(n/candidate)) 
     candidate += 1 
    return primes 

ERR - 등 여전히 int()float()하지만 같은 기능을 수정 시도는 지속 :

float(factorize(n/candidate)) 

factorize이 목록을 반환

TypeError: 'float' object cannot be interpreted as an integer 
+0

왜 float는'factorize' 함수와 관련이 있습니까? – dan04

+0

dan04 : 그냥 지나치게 살해하십시오. 이제는 작동하지만 여전히 다른 문제에 대해 궁금해하고 있습니다. – hhh

답변

2

이 표현은 즉각적인 문제 그러나 float은 인수가 문자열 또는 숫자 여야합니다.

(코드는 많은 다른 많은 문제가 있지만 ... 자신을 위해 그들을 발견하기 위해 아마도 가장이 될 것입니다)

1

공지 사항을 당신이 list을 반환하고 그 라인 :

primes = primes + [float(candidate)] + float(factorize(n/candidate)) 

그러나 float은 목록이 아닌 숫자 또는 문자열에 사용할 수 있습니다.

올바른 해결책은 다음과 같습니다

primes = primes + [float(candidate)] + [float(x) for x in factorize(n/candidate)] 
# Converting every element to a float 
0

가레스가 many, many other problems으로 무엇을 의미하는지 이해할 수 없다, 문제는 위생입니다!

def factorize(n): 
    # now I won`t get floats 
    n=int(n) 

    def isPrime(n): 
     return not [x for x in range(2,int(math.sqrt(n))) 
        if n%x == 0] 

    primes = [] 
    candidates = range(2,n+1) 
    candidate = 2 
    while not primes and candidate in candidates: 
     if n%candidate == 0 and isPrime(candidate): 
      primes = primes + [candidate] + factorize(n/candidate) 
     candidate += 1 
    return primes 


clearString = sys.argv[1] 
obfuscated = 34532.334 
factorized = factorize(obfuscated) 

print("#OUTPUT "+factorized) 


#OUTPUT [2, 2, 89, 97] 

더 나은하지만 당신은 그것을 간단 이하의 라인은 할 수 있습니까?

def factorize(n): 
    """ returns factors to n """ 

    while(1): 
      if n == 1: 
        break 

      c = 2 

      while n % c != 0: 
        c +=1 

      yield c 
      n /= c 

print([x for x in factorize(10003)]) 

시간 비교

$ time python3.1 sieve.py 
[100003] 

real 0m0.086s 
user 0m0.080s 
sys 0m0.008s 
$ time python3.1 bad.py 
^CTraceback (most recent call last): 
    File "obfuscate128.py", line 25, in <module> 
    print(factorize(1000003)) 
    File "obfuscate128.py", line 19, in factorize 
    if n%candidate == 0 and isPrime(candidate): 
KeyboardInterrupt 

real 8m24.323s 
user 8m24.320s 
sys 0m0.016s 

at least O(n) 큰 삼가, 롤 내가 구글에서 찾을 수있는,의는 큰 소수와 가난한 결과를 살펴 보자. 10003은 적어도 10002! 개의 하위 프로세스를 나타냅니다. 10003pawns는 각각 10002이므로 실패하고 각 하위 프로세스가 평가되고 하위 프로세스 각각 n-1 개의 하위 프로세스가 계산 될 때까지 평가할 수 없습니다. 인수 분해하지 않는 좋은 예.

+0

'factorize (100003)'라고 말 했나요? –

관련 문제