2016-11-03 131 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