2011-01-19 50 views
0

我在這裏丟失了技術詞,但這裏的問題是要麼將int更改爲float,要麼將其更改爲int。解釋因子分析中的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 

的錯誤 - 試圖與功能,如int()float()但仍固定它堅持:

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

爲什麼浮動參與`factorize`函數呢? – dan04 2011-01-19 16:53:37

+0

dan04:過度使用,殺死它。現在它可以工作,但仍然對其他問題感到疑惑,更有效? – hhh 2011-01-19 17:30:52

回答

2

這種表達是立即解決問題:

float(factorize(n/candidate)) 

factorize返回一個列表,但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!子進程,10003進程10002因爲每個都會失敗,直到每個子進程都被評估並且每個子進程都會有n-1子進程時才能被評估。很好的例子,如何不分解。