如何使用Python查找多维数据集根?

如何使用Python查找多维数据集根?,python,python-3.x,Python,Python 3.x,以下是我发现的最好的方法: x = int(raw_input("Enter an integer: ")) for ans in range(0, abs(x) + 1): if ans ** 3 == abs(x): break if ans ** 3 != abs(x): print x, 'is not a perfect cube!' else: if x < 0: ans = -ans print 'Cube ro

以下是我发现的最好的方法:

x = int(raw_input("Enter an integer: "))
for ans in range(0, abs(x) + 1):
    if ans ** 3 == abs(x):
        break
if ans ** 3 != abs(x):
    print x, 'is not a perfect cube!'
else:
    if x < 0:
        ans = -ans
    print 'Cube root of ' + str(x) + ' is ' + str(ans)
x=int(原始输入(“输入整数”))
对于范围(0,abs(x)+1)内的ans:
如果ans**3==abs(x):
打破
如果ans**3!=abs(x):
打印x,“不是一个完美的立方体!”
其他:
如果x<0:
ans=-ans
打印“+str(x)+”的立方根是“+str(ans)

有没有更好的方法,最好是避免对候选值进行迭代的方法?

最好的方法是使用简单的数学

>>> a = 8
>>> a**(1./3.)
2.0
编辑

对于负数

>>> a = -8
>>> -(-a)**(1./3.)
-2.0
按照规定完成所有要求的程序

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)
您可以使用
x**(1./3)
计算
x
的(浮点)立方根

这里有一点微妙之处,那就是在Python2和Python3中,它对负数的作用是不同的。但是,以下代码将处理:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly
这将取
x
的立方根,将其四舍五入到最接近的整数,并提升到三次方,最后检查结果是否等于
x

采用绝对值的原因是为了使代码在Python版本中正确处理负数(Python2和Python3将负数提升为分数次幂的处理方式不同)

或者这是一条单行线

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

root_cube=lambda x:x**(1./3。)如果0,它将给出一个奇怪的输出,例如
a=-8
。矿山编号将为您提供复数输出。它是-8=-2的立方根。这里的输出:
(1.0000000000000002+1.7320508075688772j)
。这是一个复数。@BhargavRao lol为什么要用两个
-
?它把它转回来了
-8
的立方根是
-2
。但是你的方式输出是
(1.0000000000000002+1.7320508075688772j)
这个奇怪的复数,在技术上是正确的。向下投票是因为你展示了如何做数学,而不是如何找出它是否是一个完美的立方体。完整的程序有缺陷。例如,它不能正确处理2146689000(表示它不是一个完美的立方体)。@PascalvKooten:代码需要四舍五入到最接近的整数,
int()
向零四舍五入。哇,你说得对,对不起:)@PascalvKooten:请在这场辩论中投入一些精力,不要用随机问题轰炸其他人。:)如果没有
round()
@PascalvKooten:Erm,
0.3333
的话,我的答案中没有一个测试用例是有效的,它仍然不等于数学上的三分之一,因此立方根仍然是近似的。正如我所说的,与其只是猜测,不如简单地用代码进行实验。
10**45
while失败。
>>> 
2.0
-2.0
>>> 
root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)