【问题标题】:Write a Python function that will receive a list as a parameter and count if the list repeats any number/s编写一个 Python 函数,该函数将接收一个列表作为参数,并在列表重复任何数字/秒时进行计数
【发布时间】:2016-09-03 17:06:29
【问题描述】:

我只是需要一些帮助来解决这个问题。所有细节都在下面提到的问题中。我已经做了一个解决方案,但我有点坚持这一点,如果有人能引导我走向正确的方向,我将不胜感激。

问题:每当我运行我的程序时,它总是说“你有:三个 5”,即使重复三次的数字不是 5。希望这是有道理的。我的程序在问题下方。

上面的网格可以在 Python 中表示为一个列表变量,如grid = [2,2,1,3,2]

编写一个 Python 函数 pokieTester(list),它将接收一个列表作为参数并

 计算列表中是否有 3,4 或 5 个相同的数字

 它将返回一个包含 2 个项目的列表:

o The first item will be the number of repeated numbers
o The second item will be the value of repeated numbers

编写一个没有参数的 Python 函数 makeList(),返回一个包含 5 个随机整数(包括 1 到 5)的列表

将您的函数组合到一个程序中,该程序显示适当的文本,说明用户是赢还是输。

(如果你没有 3、4 或 5 个相同的数字,你就输了。)

例如: 你赢了!或者对不起你输了

如果他们赢了,它应该显示有多少重复的数字和它们的值。

例如:

你赢了!你有三个 2

====== 这是我的程序=====

import random

def pokieTester(countList):

    count = countList.count(0)

    for num in [1,2,3,4,5]:
        if count < 3:
            count = countList.count(num)
    demoList = [count, num]        
    return demoList


def makeList():

    numList = []

    for count in [0,1,2,3,4]:
        a = random.randint(1,5)
        numList.append(a)
    return numList

gameList = makeList()

print (gameList)

matches = pokieTester(gameList)

count = matches[0]

num = matches[1]


num_List = ['three','four','five']

if count > 2:

        print ("You win")
        print ("You have: " , end = '' )

        if count == 3:
           print (num_List[0], num, end = '')

        elif count == 4:
           print (num_List[1], num, end ='')

        elif count == 5:
           print (num_List[2], num, end ='')

else:

    print ("Sorry, You lose")

【问题讨论】:

    标签: python list python-3.5


    【解决方案1】:

    pokieTester() 中,在for 循环结束时num 将始终为5,因为循环始终执行五次。如果检测到count >= 3,则需要尽早跳出循环。试试这个:

    def pokieTester(countList):
        for num in [1,2,3,4,5]:
            count = countList.count(num)
            if count >= 3:
                # there are 3, 4 or 5 instances of num
                return [count, num]
        return [0, 0]
    

    如果没有 3 个或更多的任何数字,返回值应该是什么规范是松散的,所以上面的函数只会返回 [0, 0],但它可以返回 None

    可以通过使用字典而不是列表num_List 来简化调用代码。然后您可以使用count 作为键来检索数字的文本版本:

    num_text = {3: 'three', 4: 'four', 5: 'five'}
    count, num = pokieTester(gameList)
    if count >= 3:
        print("You win")
        print("You have: {} {} s".format(num_text[count], num)
    

    【讨论】:

    • 嘿,我用你提供的那个替换了我的“def pokieTester”,它工作得很好。所以如果不是太麻烦,请问第二部分是什么意思?抱歉给您带来麻烦,我对python还很陌生,仍在努力理解一切。第二部分有必要吗?谢谢
    • 第二部分只是编写调用pokieTester()的代码的更简单方法。字典是一种更好的数据结构,用于将键值(在本例中为计数)映射到值(在本例中为计数的文本)。一旦你有了它,你就可以直接从计数到文本表示,而无需一大堆 if 语句。
    • 哦好的,开始明白了。我是否需要将第二部分放在我的代码中,或者它只是在那里,所以它更容易并且更有意义。
    • @Zubin:一般来说代码越少越好。它更灵活,以后修改更容易。您使用if/elif 语句完成此操作的方式需要更多代码来执行相同的操作。此外,测试 count == 3 然后索引到列表中也有点毫无意义 - 为什么不在 print 语句中简单地硬编码“三”。
    【解决方案2】:
    import random
    from collections import Counter
    from operator import itemgetter
    
    numerals = ('one', 'two', 'three', 'four', 'five')
    
    numbers = [random.randint(1, 5) for x in range(5)]
    print(numbers)
    
    matche = max(Counter(numbers).items(), key=itemgetter(1))
    count = matche[1]
    number = matche[0]
    
    if count > 2:
            print("You win!\nYou have: {} {}".format(numerals[count-1], number))
    else:
        print("Sorry, You lose")
    

    【讨论】:

    • 虽然这绝对是一种更好的方法,但它并不能帮助 OP 理解为什么他们的代码(这显然是家庭作业)不起作用,以及他们如何修复现有的代码。没有解释就转储代码是没有用的。
    • 嘿,谢谢你的时间,但因为我是学生,我们不允许使用 collections.counter 或 operator itemgetter,只能使用基本的东西。
    • @mhawke 你是对的。但我知道 Python 比英文好很多,所以有时我回答代码更容易。
    【解决方案3】:
    import random
    
    randlist = [random.randint(1,5) for i in range(5)]
    
    def pokieTest(randlist):
        num_List = {3: 'three', 4: 'four', 5: 'five'}
        for i in randlist:
            count = randlist.count(i)
            if count in num_List.keys():
                return [num_List[count], i]
    
    
    print randlist
    
    result = pokieTest(randlist)
    
    if result:
        print "You win!"
        print "You have: ", result
    else:
        print "Sorry, you lose"
    

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      相关资源
      最近更新 更多