你如何构建递归函数?

时间:2015-10-07 19:53:47

标签: python function python-3.x recursion python-3.4

我试图创建一个递归函数,检查等级是否可以转换为浮点数,然后检查以确保等级在0到100之间。我的逻辑为什么这将起作用:< / p>

  1. 检查等级是否可以转换为浮动。
  2. 如果无法将其转换为浮点数,则用户会收到错误消息,必须输入新等级,并且gradeChecker会再次检查。
  3. 如果可以将其转换为浮动,则gradeChecker会检查它是否在0到100之间
  4. 如果等级介于0到100之间,则会将成绩附加到“作业”字典。
  5. 如果等级不在0到100之间,则用户会给出新等级,然后将其传回函数,从第1步开始重复。
  6. 你能告诉我这段代码是如何遵循这个逻辑的吗?

    def gradeChecker(grade):
        while True:
            try:
                grade = float(grade)        
                while (grade < 0) or (grade > 100):
                    print("Sorry, your grade must be between 0 and 100.")
                    grade = input("What grade did you receive on: %s? " % assignment)
                    gradeChecker(grade)
            except:
                print("Sorry, that's an invalid input. Please only use numbers and decimal points!")
                grade = input("What grade did you receive on: %s? " % assignment)
            else:
                break
        Assignments[assignment].append(grade)
    

    编辑:缩进已修复!

    供参考,以下是我用来将成绩传递给gradeChecker的全部代码。

    import collections #We import collections so we can use an ordered dictionary
    Assignments = collections.OrderedDict() #We create an ordered dictionary called 'Assignments'
    #We have to add each assignment to our dictionary individually because it's an ordered dictionary
    #You can't convert a regular dictionary, which is unordered, to an ordered dictionary
    #If you used a regular dictionary, when looping through the assignments they would be displayed at random
    Assignments['Exam 1'] = [0.2] #We add the assignment and the weight to the dictionary
    Assignments['Exam 2'] = [0.2] #We add the assignment and the weight to the dictionary
    Assignments['Exam 3'] = [0.2] #We add the assignment and the weight to the dictionary
    Assignments['Homework'] = [0.2] #We add the assignment and the weight to the dictionary
    Assignments['LQR'] = [0.1] #We add the assignment and the weight to the dictionary
    Assignments['Final'] = [0.1] #We add the assignment and the weight to the dictionary
    
    #We have to define our grade checker before it is called so that it can be used to verify users inputs
    
    def gradeChecker(grade): #Used to verify that a users grades are in-between 0 and 100
        while True:
            try:
                grade = float(grade)        
                while (grade < 0) or (grade > 100):
                    print("Sorry, your grade must be between 0 and 100.")
                    grade = input("What grade did you receive on: %s? " % assignment)
                    gradeChecker(grade)
            except:
                print("Sorry, that's an invalid input. Please only use numbers and decimal points!")
                grade = input("What grade did you receive on: %s? " % assignment)
            else:
                break
        Assignments[assignment].append(grade) #We append the grade to the assignment to be used with it's weight for the final grade calculation
    
    #INPUT
    
    for assignment in Assignments.keys(): #We loop through every assignment in our  Assignments dictionary
        grade = input("What grade did you receive on: %s? " % assignment) #We ask the user to enter their grade
        gradeChecker(grade) #We check to see if their grade is valid by passing their input through the gradeChecker function
    

2 个答案:

答案 0 :(得分:1)

这里使用递归和循环是多余的。此外,循环应该优先于正常的递归#39;像Python这样的语言(即不是Lisp),除非您正在处理像树这样的固有递归数据结构。

鉴于你从未说过为什么你需要首先使用递归,我建议使用这样的东西:

Assignments

注1 。我没有测试上面的代码,但是它应该让你对如何构造这个函数有一个大概的了解。

注2 。您应该避免在函数中修改try,这是一个不必要的副作用。最好将其卸载到主代码中。

注3 。从技术上讲,我的代码中的except .. Message是基于异常的逻辑的一个例子,这不是一件好事(但是,这比使用递归更好)。

答案 1 :(得分:0)

final
你的代码就是它的冗余; while语句可以执行已经有递归调用的操作。 imo,while语句更好,因为递归通常会占用更多内存,但这只是一种观点。