2016-11-03 128 views
-3
def powers(L): 
    ''' 
    (list of ints) -> bool 
    Return True if the given list of ints is a list of powers of some 
    int x of the form [x^0, x^1, x^2, x^3, ...] and False otherwise. 
    >>>powers[1, 3, 9, 27, 81] 
    True 
    ''' 
    i = 1 
    x = L[0] 
    while i < len(L): 
     if L[i] == x**(i+1): 
      i += 1 
      return True 
     else: 
      return False 

我改变了你指出的错误,但它仍然无法正常工作..你能帮我吗?虽然python上的循环

+0

为什么你使用'+ ='?当你指定new_l [i]'的新值时,你正在使用它;那应该是'='。你在比较时使用它,应该是'=='。另外,在比较值之前,你正在增加'i'。 – Barmar

+0

另一个问题,你分配给'new_l [i]',但是然后你使用'new_L [i]'。 Python区分大小写。 – Barmar

+0

你不需要数组'new_L'。只要测试'L [i] == x ** i'。 – Barmar

回答

0
def powx(l): 
    i = 0 
    x = l[1] 
    newL = [] 
    while i < len(l): 
     if x**i == l[i]: 
      newL.append(x**i) 
     else: 
      return False 

     i+=1 
    if newL == l: 
     print(newL) 
     return True 

一个= [1,2,4,9]
B = [1,3,9,27]
POWX的(a)//应该返回false
POWX(B)//应该返回[1,3,9,27]真

+0

修复您的缩进 – Barmar

+0

感谢!这真的很有帮助! @Davi Rolim – Jason

+0

谢谢!它帮助了很多! @Barmar – Jason

0

你不能在循环中返回True,因为这将结束功能,无需测试列表的其余部分。你的函数只是检查列表的第二个元素,因为它在两种情况下都会返回。

知道,一切都是数量的功率的方法是等到循环结束。如果在循环过程中它从未返回False,则所有内容都符合条件。出于某种原因,对于新程序员来说,这个一般概念似乎难以置信,因为我一直在这里看到这种错误模式。

def powers(L): 
    ''' 
    (list of ints) -> bool 
    Return True if the given list of ints is a list of powers of some 
    int x of the form [x^0, x^1, x^2, x^3, ...] and False otherwise. 
    >>>powers[1, 3, 9, 27, 81] 
    True 
    ''' 
    i = 0 
    x = L[1] 
    while i < len(L): 
     if L[i] != x**i: 
      return False 
     i += 1 
    return True 
0

显然以来您的列表中的第二个元素(而不是第一个)是x,因为它是x**1,您可以构建的x一切权力清单和比较,为您的列表。

def powers(L): 
    return [L[1]**i for i in range(len(L))] == L