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

Luk*_*e D 20 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 root of ' + str(x) + ' is ' + str(ans)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法,最好是避免不得不迭代候选值?

NPE*_*NPE 33

您可以x ** (1. / 3)用来计算(浮点)立方根x.

这里的细微之处在于,对于Python 2和3中的负数,这种方式有所不同.但是,下面的代码处理:

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
Run Code Online (Sandbox Code Playgroud)

它取立方根x,将其舍入到最接近的整数,升至第三个幂,最后检查结果是否等于x.

采用绝对值的原因是使代码在Python版本中对负数正确工作(Python 2和3将负数提升为分数幂).

  • @PascalvKooten:嗯,`0.3333333333333333`仍然不等于数学三分之一,因此立方根仍然是近似的.正如我所说,而不仅仅是猜测,只需试验代码即可. (5认同)
  • @PascalvKooten:代码需要舍入到最接近的整数,并且`int()`向零舍入. (2认同)
  • 哎呀,你说得对,抱歉:) (2认同)
  • @PascalvKooten:请为这次辩论付出一些努力,不要只是随机问题轰炸其他人.:)**我的答案中的测试用例没有**没有`round()`. (2认同)
  • 它失败了`10**45`,而[基于“二进制搜索”的答案有效](http://stackoverflow.com/a/23622115/4279)。 (2认同)

Bha*_*Rao 19

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

>>> a = 8
>>> a**(1./3.)
2.0
Run Code Online (Sandbox Code Playgroud)

编辑

对于负数

>>> a = -8
>>> -(-a)**(1./3.)
-2.0
Run Code Online (Sandbox Code Playgroud)

完成所有要求的完整程序

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)
Run Code Online (Sandbox Code Playgroud)

  • 完整的程序是错误的.例如,它没有正确处理2146689000(说它不是一个完美的立方体). (3认同)

小智 7

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))
Run Code Online (Sandbox Code Playgroud)

这是负数和正数的完整答案。

>>> 
2.0
-2.0
>>> 
Run Code Online (Sandbox Code Playgroud)

或者这里是单线;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)
Run Code Online (Sandbox Code Playgroud)