1

我有一个用 python 编写的脚本,用于测试我实现的排序算法。该程序的主要部分要求用户从列表中选择一种排序算法。然后他们是想从数字文件中排序还是选择随机数字列表。我已经设置好了(我认为),这样输入不在第一个选项列表中的数字只会打印“错误选择”并尝试再次获取该数字。

[编辑]在听取了答案的建议后,我将一些输入更改为原始输入。我改变了程序的结构。它现在可以完美运行,只是即使在成功后仍会打印出“Bad Choice”。

def fileOrRandom():
  return raw_input("Would you like to read from file or random list? (A or B): ")

choices = {1:SelectionSorter,2:ComparisonSorter}
print "Please enter the type of sort you would like to perform."
print "1. Selection Sort\n2. Comparison Sort"
while(True):
  try:
    choice=input("Your choice: ")
    for i in range(2):
    if(choice==i+1):
      choice2=fileOrRandom()
      if(choice2=='A'):
        fileName=raw_input("Please Enter The Name of the File to sort: ")
        sorter = choices[choice](fileName)
        sorter.timedSort(sorter.sort)
      elif(choice2=='B'):
        num = input("How many random numbers would you like to sort: ")
        sorter = choices[choice](None,num)
        sorter.timedSort(sorter.sort)
      else:
        raise Exception
    else:
      raise Exception
    break
  except Exception:
    print "Bad Choice"

我的问题是它根据预期的第一部分工作,它将返回一个不在列表中的数字的错误选择,它将获得fileorrandom(),但在选择良好的值时,它仍然打印出“糟糕的选择”应该打印出来我的结果是因为sorter.timedSort(sorter.sort)执行我的排序算法并将一堆其他的东西打印到屏幕上。我只是错过了一些简单的东西,还是有更好的方法来处理 python 程序中的这些嵌套选项?

4

1 回答 1

0

使用 raw_input()

def fileOrRandom():
  return raw_input("Would you like to read from file or random list? (A or B): ")

您的 while 循环应如下所示(修复缩进后)

while True :
    choice=raw_input("Your choice: ")
    for i in range(2):
     if choice==i+1 and fileOrRandom()=="A" :
       fileName=raw_input("Please Enter The Name of the File to sort: ")
       sorter = choices[choice](fileName)
       sorter.timedSort(sorter.sort)
     elif choice==i+1 and fileOrRandom()=="B" :
       num = raw_input("How many random numbers would you like to sort: ")
       sorter = choices[choice](None,num)
       sorter.timedSort(sorter.sort)
     elif choice in ['q','Q']: break
     else: print "Bad choice"
于 2010-01-27T04:50:46.680 回答