【问题标题】:Python - checking a list for possible patterns and if the list meets a specific conditionPython - 检查列表中可能的模式以及列表是否满足特定条件
【发布时间】:2020-07-28 21:42:06
【问题描述】:

我是一个新手,正在制作一个用于学习目的的小游戏。 游戏根据用户的输入掷骰子。

我遇到问题的部分是我想检查列表“rolls”中的模式

模式包括:

  1. 所有骰子的值相同,边数 >=4 示例 [1, 1, 1, 1]

  2. 至少一半的骰子 >= "average_sum",条件是列表必须有 >= 5 个骰子

    • 示例如果 avg_sum = 2 并且 rolls = [2,3,4,1,1,] 如果为真,则将 user_Score 乘以 5
  3. 所有骰子都是不同的值,条件是骰子数 > 4 和边数 > 骰子数 [10,11,12,13,14]

  4. 没有模式匹配。 -> 将 user_Score 乘以 1

number_dice = int( input( "How many dice are you using? Must be between 3-6 inclusive" ) )
faces = int( input( "how many sides are on your die? enter a number between 2-20 inclusive: "))

# Set range for number of dice
#generate a random number between 1 and faces
#Add dice_roll to the list

rolls = []
for die in range(number_dice):
    dice_roll = random.randint(1, faces)
    rolls.append(dice_roll)

#print the score from each dice rolled
print("You have rolled: " + str(rolls))

#calculate sum of score
sum = sum(rolls)

#calculate the average and round to the nearest integer
average_sum = round(sum / number_dice)

print("These die sum to: " + str(sum) + " and have an average value of: " + str(average_sum))


#Calculate the max possible score
max_score = (number_dice * faces)

#calculate the users score
user_score = float( sum / max_score )

print("your max possible score is " + str(max_score))

print("your score is " + str(user_score))

#-----------------------------------------------------------------------------------
#now calculate the bonus factor
#Check if the list "rolls" contains the same value for each index

if rolls == {repeatingvalues???} and rolls {number_dice>=4}:
    user_Score * 10
elif rolls == {half of dice > average} and {number_dice >=5}:
user_Score * 5
elif rolls == {all dice have different values} and { number_dice > 4}{faces> number_dice}:
    user_score * 8
else:
    user_score * 1


不确定如何使此语句在列表中搜索模式^^^^^^

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    这是一种简单、快速且更“Pythonic”的方法。

    if all(x == rolls[0] for x in rolls):
        print("Same")
    
    elif len(rolls) == len(set(rolls)):
        print("Unique")
    
    elif number_dice/2 <= [x > avg_sum for x in rolls].count(True): 
        print("Half")
    
    else:
        print("No match")
    

    缺少“和”条件。请随时添加它们。

    奖金

    from random import randint
    faces = int(input('Number of faces:'))
    number_dice = int(input('Number of dice:'))
    rolls = [randint(1, faces) for _ in range(number_dice)]
    

    随意探索

    【讨论】:

      【解决方案2】:
      1. 查看我的解决方案,其中添加 # ------ SOLUTION STARTS HERE -------
      2. 我也帮助重构了您的代码。您不应该在代码中使用sum 作为变量名(或标识符),因为它是一个保留的python 关键字。所以我把它改成了my_sum。检查它是否仍然可以正常工作。

      import math # import math at the top

      import random
      
      
      number_dice = int( input( "How many dice are you using? Must be between 3-6 inclusive" ) )
      faces = int( input( "how many sides are on your die? enter a number between 2-20 inclusive: "))
      
      # Set range for number of dice
      #generate a random number between 1 and faces
      #Add dice_roll to the list
      
      for die in range(number_dice):
          dice_roll = random.randint(1, faces)
          rolls.append(dice_roll)
      
      #print the score from each dice rolled
      print("You have rolled: " + str(rolls))
      
      #calculate sum of score
      my_sum = sum(rolls)
      
      #calculate the average and round to the nearest integer
      average_sum = round(my_sum / number_dice)
      
      print("These die sum to: " + str(my_sum) + " and have an average value of: " + str(average_sum))
      
      #Calculate the max possible score
      max_score = (number_dice * faces)
      
      #calculate the users score
      user_score = float( my_sum / max_score )
      
      print("your max possible score is " + str(max_score))
      
      # ------ SOLUTION STARTS HERE------
      
      rolls.sort() 
      rolls.reverse()
      for item in rolls:
          if (rolls.count(item) >= 4) and (number_dice >= 4):
              user_score *= 10
              break
          elif (rolls[math.ceil(len(rolls)/2) -1] >= average_sum ) and (number_dice >= 5):
              user_score *= 5
              break
          elif (sorted(rolls)==sorted(list(set(rolls))))and (number_dice > 4) and (faces > number_dice):
              user_score *= 8
              break
          else:
              user_score *= 1
      
      # ------ SOLUTION ENDS HERE------
      
      print("your score is " + str(user_score))
      

      【讨论】:

        【解决方案3】:

        定义一个函数来检查返回 TrueFalse 的重复模式

        def has_repeats(my_list):
            first = my_list[0]
            for item in mylist:
                if not item == first:
                    return False
            return True
        

        然后定义一个函数来检查返回TrueFalse的无重复项

        def all_different(my_list):
            # Remove duplicates from list
            my_list2 = list(dict.fromkeys(my_list))
            return len(my_list) == len(my_list2)
        

        最后定义一个函数来检查一半骰子是否大于平均值:

        def half_greater_than_averge(my_list, average):
            a = 0
            b = 0
            for item in my_list:
                if item > average:
                    a += 1
                else:
                    b += 1
            return a > b
        

        所以你的最终检查将是:

        if has_repeats(rolls) and number_dice >= 4:
            user_Score * 10
        elif half_greater_than_averge(rolls, average_sum) and number_dice >= 5:
        user_Score * 5
        elif all_different(rolls) and number_dice > 4 and faces > number_dice:
            user_score * 8
        else:
            user_score * 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-13
          • 1970-01-01
          • 2017-09-27
          • 2023-01-04
          • 2018-05-09
          相关资源
          最近更新 更多