Python - проверка списка на наличие возможных шаблонов и соответствие списка указанному условию c - PullRequest
2 голосов
/ 15 апреля 2020

Я новичок, делающий небольшую игру для учебных целей. Игра бросает кубики, основываясь на входах пользователя.

У меня возникли проблемы с тем, что я хочу проверить шаблоны в списке "бросков"

шаблоны включают в себя:

  1. все кости имеют одинаковое значение, а количество сторон> = 4 ПРИМЕР [1, 1, 1, 1] <значения одинаковы, по крайней мере 4 стороны. Если это правда, тогда пользователь user_Score будет иметь значение 10 </p>

  2. , по крайней мере, половина кубиков -> = "average_sum" с условием, что список должен иметь> = 5 кубиков

    • ПРИМЕР, если avg_sum = 2 и бросает = [2,3,4,1,1,] Если true, тогда пользователь 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


Не уверен, как заставить это утверждение искать в списке шаблон ^^^^^^

Ответы [ 3 ]

0 голосов
/ 15 апреля 2020

Вот простой, более быстрый и более «Pythoni c» способ сделать это.

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)]

Не стесняйтесь исследовать

0 голосов
/ 15 апреля 2020
  1. Ознакомьтесь с моим решением, где добавьте # ------ РЕШЕНИЕ НАЧИНАЕТСЯ ЗДЕСЬ -------
  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))
0 голосов
/ 15 апреля 2020

Определите функцию для проверки повторяющегося шаблона, который возвращает True или False

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

И затем определите функцию для проверки отсутствия дубликатов, которая возвращает True или False

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...