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

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

无法理解 Gareth 的意思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之前无法评估它。很好的例子如何不分解。nn-1

于 2011-01-19T17:30:05.147 回答