Как бы я сделал эту программу на Python со списками / массивами вместо нескольких переменных? - PullRequest
0 голосов
/ 28 сентября 2018

Я получил это на работу, но ужасно при составлении списков / вызове их.Кто-нибудь сможет сжать это в виде списка?(Не для домашней работы, уже законченной, просто для возможности / практики обучения, так что не спешите.) Я предполагаю, что моя переменная count может быть преобразована в список и вызвана в цикле for и во время окончательной печати. ​​

Thisбыл для игры в кости, которая отслеживала, сколько раз выпадало число после того, как 2 кости были брошены и сложены вместе.Довольно просто, я просто плохо разбираюсь в списках, поэтому объяснения с кодом были бы ВЕЛИКОЛЕПНЫМ, мой учебник недостаточно подробно изложен в этой теме.Первый пост в стеке, извините за любой испорченный жаргон или правила.Спасибо!

import random

count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
count10 = 0
count11 = 0
count12 = 0

rolls = int(input("How many times would you like to roll? "))



for i in range(rolls):

    die1 = random.randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = random.randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)


    if total == 2:
        count2 += 1
    elif total == 3:
        count3 += 1
    elif total == 4:
        count4 += 1
    elif total == 5:
        count5 += 1
    elif total == 6:
        count6 += 1
    elif total == 7:
        count7 += 1
    elif total == 8:
        count8 += 1
    elif total == 9:
        count9 += 1
    elif total == 10:
        count10 += 1
    elif total == 11:
        count11 += 1
    elif total == 12:
        count12 += 1


print("You rolled " + str(count2) + " 2's")
print("You Rolled " + str(count3) + " 3's")
print("You Rolled " + str(count4) + " 4's")
print("You Rolled " + str(count5) + " 5's")
print("You Rolled " + str(count6) + " 6's")
print("You Rolled " + str(count7) + " 7's")
print("You Rolled " + str(count8) + " 8's")
print("You Rolled " + str(count9) + " 9's")
print("You Rolled " + str(count10) + " 10's")
print("You Rolled " + str(count11) + " 11's")
print("You Rolled " + str(count12) + " 12's")

Ответы [ 5 ]

0 голосов
/ 28 сентября 2018

Я бы использовал словарь в этом случае.Или, в частности, defaultdict .

import random
from collections import defaultdict

roll_scores = defaultdict(int)
rolls = 10

for _ in range(rolls):
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total = die1 + die2

    print("Roll 1: ", die1)
    print("Roll 2:", die2)
    print("Total:", total)

    roll_scores[total] +=1

for k in roll_scores:
    print("You rolled {} {}'s".format(roll_scores[k], k))

Но если вы хотите использовать список, концепция почти идентична.изменив roll_scores на список из 13 пунктов (от 0 до 12):

roll_scores = [0]*13

И измените печать в конце:

for i in range(len(roll_scores)):
    print("You rolled {} {}'s".format(roll_scores[i], i))
0 голосов
/ 28 сентября 2018

Вы можете использовать список или словарь здесь.Я бы склонялся к словарю, который, я думаю, лучше всего представляет собой ту редкую структуру данных, к которой вы стремитесь (каков первый элемент вашего count списка? Он всегда будет нулевым, но не должен ли он быть на самом деле) ничто ? Имеет ли больше смысл, что ноль катился ни разу, или что его вообще нельзя катить?)

Этот словарь лучше всего определить просто как:

counts = {}

# You can also generalize your rolling 2d6!
def roll_dice(num_dice, sides):
    total = 0
    for _ range(num_dice):
        dieroll = random.randint(1, sides)
        total += dieroll
    return total

for _ in range(rolls):
    roll = roll_dice(2, 6)
    counts.setdefault(roll, 0) += 1  # this is using dict.setdefault

for roll, count in sorted(counts.items()):
    print("You rolled {} {}s".format(count, roll))

Вы также можете использовать collections.Counter для этого.

rolls = [roll_dice(2, 6) for _ in num_rolls]
# this will generate a list like [3, 12, 6, 5, 9, 9, 7, ...],
# just a flat list of rolls.

result = collections.Counter(rolls)
0 голосов
/ 28 сентября 2018

Немного изменил ваш код, и я думаю, что если вы используете словарь, это будет легко использовать и понимать.

import random

# count2 = 0
# count3 = 0
# count4 = 0
# count5 = 0
# count6 = 0
# count7 = 0
# count8 = 0
# count9 = 0
# count10 = 0
# count11 = 0
# count12 = 0

count = {i: 0 for i in range(2,13)}

rolls = int(input("How many times would you like to roll? "))



for i in range(rolls):

    die1 = random.randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = random.randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)



    # if total == 2:
    #     count2 += 1
    # elif total == 3:
    #     count3 += 1
    # elif total == 4:
    #     count4 += 1
    # elif total == 5:
    #     count5 += 1
    # elif total == 6:
    #     count6 += 1
    # elif total == 7:
    #     count7 += 1
    # elif total == 8:
    #     count8 += 1
    # elif total == 9:
    #     count9 += 1
    # elif total == 10:
    #     count10 += 1
    # elif total == 11:
    #     count11 += 1
    # elif total == 12:
    #     count12 += 1

    count[total] += 1
# print("You rolled " + str(count2) + " 2's")
# print("You Rolled " + str(count3) + " 3's")
# print("You Rolled " + str(count4) + " 4's")
# print("You Rolled " + str(count5) + " 5's")
# print("You Rolled " + str(count6) + " 6's")
# print("You Rolled " + str(count7) + " 7's")
# print("You Rolled " + str(count8) + " 8's")
# print("You Rolled " + str(count9) + " 9's")
# print("You Rolled " + str(count10) + " 10's")
# print("You Rolled " + str(count11) + " 11's")
# print("You Rolled " + str(count12) + " 12's")

for i in range(2,13):    
    print("You rolled " + str(count[i]) + " "+i+"'s")
0 голосов
/ 28 сентября 2018

Я только что немного отредактировал твой код:

from random import randint
rolls = int(input("How many times would you like to roll? "))
count = [0 for x in range(11)] #since 2 to 12 is 11 items
for i in range(rolls):
    die1 = randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)
    #total will start with 2, while count index with 0, so
    #minus 2 to make it match the index
    count[total-2] = count[total-2] +1
for x in range(11):
    print("You rolled " + str(count[x]) + " " + str(x+2)+ "'s")
0 голосов
/ 28 сентября 2018

Создайте список из 11 нулей:

counts = [0] * (12 - 2 + 1)

Чтобы увеличить счет:

counts[total - 2] += 1

Все вместе теперь:

import random

def roll_dice():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total = die1 + die2

    print(f"Roll number 1 = {die1}")
    print(f"Roll number 2 = {die2}")
    print(total)

    return total

min_count = 2
counts = [0] * (12 - min_count + 1)
rolls = int(input("How many times would you like to roll? "))

for i in range(rolls):
    total = roll_dice()
    counts[total - min_count] += 1

print('\n'.join(f"You rolled {x} {i + min_count}'s"
    for i, x in enumerate(counts)))
...