2016-05-14 56 views
-3

我是Python全新的,我嘗試做一個簡單的代碼,如果用戶輸入了錯誤的產品代碼,他會得到一個「錯誤消息」,他會被提示再次輸入。但我無法讓它工作。有人可以幫忙嗎?謝謝如果用戶在Python樹中輸入錯誤選項,則返回錯誤

class Node(object): 
    def __init__(self,val,key,Number): 
     self.val = val 
     self.key = key 
     self.number = Number 
     self.left = None 
     self.right = None 

def search(value,p): 
    if(p.val == value): 
     print("You bought item:",p.val,",description:", p.key,"cost:", p.number) 
     return 1 
    else: 
     if(p.val !=None): 
      if(p.val < value): 
       search (value,p.right) 
      if(p.val > value): 
       search (value,p.left) 
     else: 
      print("You've entered a wrong option") 

root = Node(3,"Chips", "$12") 
root.left = Node(1,"Chicken", "$13") 
root.left.right = Node(2,"Potato","$14") 
root.right = Node(5,"AisKrim","$15") 
root.right.left = Node(4,"Bag","$16") 
root.right.right = Node(6,"TV","$17") 

option = int(input("Please enter code:")) 
answer = search(option,root) 

while (answer != 1): 
    print("You've entered a wrong option") 
    option = int(input("Please enter code:")) 
    answer = search(option,root) 

回答

-1

有幾個問題。首先,您需要處理在搜索中未定義p以避免發生異常的情況。

def search(value,p): 
    if p is None: 
     return None 

添加該代碼搜索功能的開始將避免搜索失敗,你達到那個不存在的節點時發生的基本的異常。

其次,遞歸代碼應該返回值。所以,你需要else子句更改爲類似:

else: 
    if(p.val !=None): 
     if(p.val < value): 
      return search (value,p.right) 
     if(p.val > value): 
      return search (value,p.left) 
    else: 
     print("You've entered a wrong option") 

注意,每次調用搜索功能返回從遞歸調用價值。

+0

好了,我沒運行的代碼與這三個行改變了我之前發佈的,它工作正常打印「你輸入了一個錯誤的選擇」爲遺失物品,併爲找到的項目的數據。 – djkrause

0

下面的工作代碼。謝謝djkrause!

class Node(object): 
    def __init__(self,val,key,Number): 
     self.val = val 
     self.key = key 
     self.number = Number 
     self.left = None 
     self.right = None 

def search(value,p): 
    if p is None: 
    return 1 

elif(p.val == value): 
    print("You bought item no:",p.val,", the description", p.key, "and the cost is:", p.number) 
else: 
    if(p.val !=None): 
     if(p.val < value): 
      return search (value,p.right) 
     if(p.val > value): 
      return search (value,p.left) 

root = Node(3,"Chips", "$12") 
root.left = Node(1,"Ayam", "$13") 
root.left.right = Node(2,"Itik","$14") 
root.right = Node(5,"AisKrim","$15") 
root.right.left = Node(4,"Kentang","$16") 
root.right.right = Node(6,"Itik","$17") 

option = int(input("Please enter code:")) 
answer = search(option,root) 

while (answer == 1): 
    print("You've entered a wrong option") 
    option = int(input("Please enter code:")) 
    answer = search(option,root)