我在这里缺少技术词,但这里的问题是将int更改为float或float to 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 :(得分:2)
这个表达式是您的直接问题:
float(factorize(n/candidate))
factorize
返回一个列表,但float
需要将其参数作为字符串或数字。
(你的代码有很多很多其他问题,但也许你最好自己发现它们......)
答案 1 :(得分: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
答案 2 :(得分: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
,因为每个子进程都会失败并且在评估每个子进程并且每个n
子进程将进行评估之前无法对其进行评估有n-1
子进程。很好的例子,如何不分解。