2016-05-23 10 views
2

ノードとバイナリツリーのクラスを作成する必要がありますが、どちらも問題なく動作します。また、メソッドのメニューを使用する必要があります。何かを追加しようとすると追加されますが、すぐにNoneにリセットされ、addが呼び出されたときに再び開始されます。これはメニュー実装です。Pythonのバイナリツリーインプリメンテーションでエラーが発生する

if __name__ == '__main__': 

    print("Menu \n" 
     "\n" 
     "1. Add item \n" 
     "2. Get item \n" 
     "3. Print Binary Tree in Inorder Transversal \n" 
     "4. Exit \n") 

    user_input = input("Please select an action from the menu: ") 
    tree = BinaryTree() 

    if user_input == "1": 
     item = str(input("Please enter an item to add to the Binary Tree: ")) 
     bin_str = str(input("Please enter binary string to place in the Binary Tree: ")) 
     tree.add(item, bin_str) 
     tree.print_inorder() 

    elif user_input == "2": 
     get_item = input("Please enter binary string of wanted item: ") 
     get_bin_str = tree.get(get_item) 
     print(get_bin_str) 

    elif user_input == "3": 
     tree.print_inorder()) 

    elif user_input == "4": 
     sys.exit(0) 

    else: 
     print("Error: please select an action from the menu") 
+0

「なしにリセットされ、もう一度やり直す」とはどういう意味ですか? – polku

+2

あなたが表示したコードは、ループがないので、入力に関係なく一度だけ実行されます。ループを置くと仮定すると、毎回それを再初期化したくないので、メニューの外に 'tree = BinaryTree()'を移動させてください。それ以外の場合は、状態を失うことになります。 – algrebe

答えて

1

上記のコメントが示すように、あなたはtree変数を毎回リセットせずに、追加のユーザ入力を可能にするために、whileループを必要としています。

if __name__ == '__main__': 

    tree = BinaryTree() 
    while True: 

     print("Menu \n" 
      "\n" 
      "1. Add item \n" 
      "2. Get item \n" 
      "3. Print Binary Tree in Inorder Transversal \n" 
      "4. Exit \n") 

     user_input = input("Please select an action from the menu: ") 

     if user_input == "1": 
      item = str(input("Please enter an item to add to the Binary Tree: ")) 
      bin_str = str(input("Please enter binary string to place in the Binary Tree: ")) 
      tree.add(item, bin_str) 
      tree.print_inorder() 

     elif user_input == "2": 
      get_item = input("Please enter binary string of wanted item: ") 
      get_bin_str = tree.get(get_item) 
      print(get_bin_str) 

     elif user_input == "3": 
      tree.print_inorder()) 

     elif user_input == "4": 
      sys.exit(0) 

     else: 
      print("Error: please select an action from the menu") 
関連する問題