【问题标题】:Logic Error in World Series Program世界大赛程序中的逻辑错误
【发布时间】:2015-11-24 02:27:30
【问题描述】:

这是作业:

"模块中有文件WorldSeriesWinners.txt。该文件包含 从 1903 年开始按时间顺序排列的世界大赛获胜球队名单 到 2009 年。(文件中的第一行是团队的名称 1903年获胜,最后一行是获胜球队的名字 2009)。

编写一个程序,让用户输入团队的名称,然后 显示该球队赢得世界大赛的次数 从 1903 年到 2009 年的时间段。

程序需要使用列表来读入数据和for in 用于计算获胜次数的循环。”

程序应如下所示:

Enter the name of a team: Chicago Cubs
The Chicago Cubs won the world series 2 times between 1903 and 2009.
=============================== RESTART ============================
Enter the name of a team: New York Yankees
The New York Yankees won the world series 26 times between 1903 and 2009.
=============================== RESTART ============================
Enter the name of a team: Lakeland Tigers
The Lakeland Tigers never won the world series.
=============================== RESTART ============================

我认为我已经非常接近解决问题了,除了一个逻辑错误。

这是我的代码:

# Write a program that lets the user enter the name of a team
# and then displays the number of times that team had won the World Series
# in the time period from 1903 to 2009

# Open the file
def main():
    infile = open('WorldSeriesWinners.txt', 'r') # Open the file

    winner = infile.readlines() # Read the contents of the file into the list

    infile.close() # Always remember to close the file

    team = input('Enter the name of a team: ') # Enter name of a baseball team

    counter = 0 # If said team won a game, count how many times
    for team in winner:
            result = counter + 1

    if result == 1: # Finally, print the results
        print("The", team, "won the world series", result, "time between 1903 and 2009.")
    elif result > 1:
        print("The", team, "won the world series", result, "times between 1903 and 2009.")
    else:
        print("The", team, "never won the world series.")

main()

这就是我按下 F5 时发生的情况:

>>> 
Enter the name of a team: Chicago Cubs
The Philadelphia Phillies won the world series 1 time between 1903 and 2009.
>>> 

两件事:我不仅没有输入费城费城人队,而且计数不正确,因为费城人队两次赢得世界大赛(1980 年和 2008 年),因此球队的名称在文本文件中出现了两次(是的,我检查以确保)。

【问题讨论】:

    标签: python python-3.x text-files python-3.4 for-in-loop


    【解决方案1】:

    那是因为您没有计算用户输入的团队,您只是循环遍历团队并为每个团队计数 1。此外,您的counter 始终为 0,向其添加 1 将始终为 1。您需要在每次团队获胜时增加它,这意味着您必须跟踪当前的获胜次数,即意味着您必须更改 counter 的值才能实际计算团队的获胜次数。你需要的是:

    for winning in winner:
        if(team == winning):
            counter += 1
    

    这应该会给你答案。而且您不再需要result


    附言。这是一个真正的建议,这是一个班级的作业。在 SO 上寻求解决方案会回答你的作业并为你赢得分数,但你只会在生活中学会复制粘贴,而不是解决问题。请先尽你所能自己解决。

    【讨论】:

    • 感谢您的建议。事实上,我对此感到很糟糕。我还是编程新手,虽然我觉得我对术语和概念有相当好的把握,但将其付诸实践有时会让我大吃一惊。我查看了过去的作业,并能够更接近这个特定的问题,但请记住,由于某种原因,我完全忘记了如何格式化这些计数循环,即使我之前已经做过。跨度>
    • 有一种叫做dry run的东西,努力练习吧。并教自己使用调试器,并在逐行运行时检查变量。
    • 谢谢你,@Kartik。顺便说一句,我输入了计数器循环,但它仍然计数不准确。但我会听取您的建议并尝试自己解决这个问题。
    【解决方案2】:

    我已将其他人的答案整理成一段完整的代码

    def main():
        infile = open('WorldSeriesWinners.txt', 'r') # Open the file
    
        winners = infile.readlines() # Read the contents of the file into the list
    
        infile.close() # Always remember to close the file
    
        team = input('Enter the name of a team: ') # Enter name of a baseball team
    
        counter = 0 # If said team won a game, count how many times
    
        for winner in winners:
            if team == winner:
                counter = counter + 1
    
        if counter == 1: # Finally, print the results
            print("The", team, "won the world series", counter, "time between 1903 and 2009.")
        elif counter > 1:
            print("The", team, "won the world series", counter, "times between 1903 and 2009.")
        else:
            print("The", team, "never won the world series.")
    
    main()
    

    你原来的程序中的错误是:

    • 计数不正确

    您使用 0 初始化 counter。然后在循环中执行 counter + 1,然后将其分配给 result。但是循环的每次迭代都做同样的事情,所以计数为 1。您需要重用计数器,以便它在每次迭代时递增。 (更改此设置会导致不再需要 result,因此程序的其余部分已相应更新为 counter。)

    您还需要将输入到team 变量中的文本与循环变量进行比较。否则计数将是文件中的项目数。

    • 团队名称不正确

    您在 for 循环中重用了变量 team

    这导致您的第二个错误是原始团队名称已被覆盖,因此您最初输入的值不再可用。

    【讨论】:

      【解决方案3】:

      您似乎为同一个概念使用了两个不同的变量名称,counterresult。如果您坚持使用一个或其他变量名称,您的程序会更好地运行。

      你的 for 循环逻辑在这里也是错误的。您不应该重复使用变量名称team(这就是您选择的团队被忽略的原因),其次您必须将循环变量与选择的团队进行实际比较:

      result = 0
      for test in winner:
          if team == test:
              result = result + 1
      

      【讨论】:

        【解决方案4】:

        好吧,我发现了这个帖子上没有人指出的最大问题:我必须剥离和分割线条! 当我以原始形式打印文件时,它都是一个每个团队之间有一堆'\ n'的单个块。 这就是它计数不正确的原因!因此,当我使用剥离的 '\n' 并在每个团队之间拆分行时,我的代码能够工作。另外,我将输入转换为小写,以便进行不区分大小写的输入。

        现在,我的解决方案:

        # Write a program that lets the user enter the name of a team
        # and then displays the number of times that team had won the World Series
        # in the time period from 1903 to 2009
        
        # Open the file
        def main():
            infile = open('WorldSeriesWinners.txt', 'r') # Open the file
        
            for line in open('WorldSeriesWinners.txt'):
                line = line.rstrip('\n')# But wait, strip the newlines first!
        
            winners = infile.read().splitlines() # Read the contents of the file into the list
        
            infile.close() # Always remember to close the file
        
            team = input('Enter the name of a team: ') 
        
            counter = 0 # If said team won a game, count how many times
        
            for winner in winners: # convert input to lowercase for case-insensitive input
                if team.lower() == winner.lower():
                    counter = counter + 1
        
            if counter == 1: # Finally, print the results
                print("The", team, "won the world series", counter, "time between 1903 and 2009.")
            elif counter > 1:
                print("The", team, "won the world series", counter, "times between 1903 and 2009.")
            else:
                print("The", team, "never won the world series.")
        
        
        main()
        

        我学到的最大教训是先将文件打印到 Python 中,看看是否有任何潜在问题!

        【讨论】:

          猜你喜欢
          • 2017-09-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-27
          • 1970-01-01
          相关资源
          最近更新 更多