x=int(input("Enter an integer:"))
answer=None
cube_root_found=False
for i in range(0,abs(x)+1):
if i**3 == abs(x):
answer=i
cube_root_found=True
if not cube_root_found:
print(x,"is not a perfect cube")
else:
if x<0:
answer=-answer
print("Cube root of",x,"is",answer)
我无法理解为什么我们在第二行使用了answer = None和cube_root_found = False。另一个问题是我在标题中提到的: 我们如何才能使这段代码更有效率?
答案 0 :(得分:2)
我的意思是,有一个数学解决方案 - 只是立方根x
,而不是测试[0, x+1)
中的所有内容。没有理由在这种情况下循环。
x = int(input("Enter an integer: "))
result = x ** (1/3)
if result == int(result):
print("Cube root of", x, "is", result)
else:
print(x, "is not a perfect cube")
答案 1 :(得分:1)
在break
之后添加cube_root_found = True
会在找到答案而不是继续时使其短路。
x=int(input("Enter an integer:"))
answer=None
cube_root_found=False
for i in range(0,abs(x)+1):
if i**3 == abs(x):
answer=i
cube_root_found=True
break
if not cube_root_found:
print(x,"is not a perfect cube")
else:
if x<0:
answer=-answer
print("Cube root of",x,"is",answer)
答案 2 :(得分:1)
不要迭代一堆整数,只需取输入的立方根并检查它是否为整数。
这样的事情:
root = x**(1.0/3.0)
return root.is_integer()
答案 3 :(得分:0)
answer=None
cube_root_found=False
我们这样做是因为,如果x
为0,则for循环将执行0次。在这种情况下,如果没有上述代码,我们永远不会为这些变量赋值,
if not cube_root_found:
将失败并显示"NameError: name 'cube_root_found' is not defined
消息。
答案 4 :(得分:0)
Besides using break, I would suggest limiting range to abs(x)/2 - unless it's either -1, 0 or 1.
Besides, I am not sure whether Python can optimize calling abs on each cycle on the same value - most probably not, so I would pre-store abs(x)
abs_x = abs(x)
upper_limit = 2 if abs_x < 2 else abs_x / 2
for i in range(upper_limit):
if i**3 == abs_x:
......
答案 5 :(得分:0)
checking if int(n**(1./3)) == n**(1./3)
does NOT work generally, since 1/3 does not represent nicely in binary. try abs(int(n**(1./3)) == n**(1./3)) < 0.000000000001
Checking within a threshold is a normal way to check for equality in the presence of rounding errors. Note that (n+1) ** (1/3) -> n**(1/3) as n gets large, so this will give incorrect results for very very very large n.