0

ここで技術用語が欠落していますが、ここでの問題は、int を 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

int()エラー -- andなどの関数で修正しようとしましfloat()たが、それでも持続します:

TypeError: 'float' object cannot be interpreted as an integer
4

3 に答える 3

2

この式はあなたの差し迫った問題です:

float(factorize(n/candidate))

factorizeリストを返しますが、floatその引数は文字列または数値である必要があります。

(あなたのコードには他にも多くの問題がありますが、おそらく自分でそれらを発見するのが最善でしょう...)

于 2011-01-19T16:48:58.533 に答える
0

list次の行で andを返すことに注意してください。

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
于 2011-01-19T16:52:01.790 に答える
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)はかなり控えめな表現です (笑) Google から見つけたものを、素数が大きい場合の悪い結果を考えてみましょう。10003少なくとも10002!サブプロセスを10003ポーン10002します。それぞれが失敗し、各サブプロセスが評価され、各nサブプロセスがサブプロセスを持つようになるまで評価できないためn-1です。因数分解しない良い例。

于 2011-01-19T17:30:05.147 に答える