To create a histogram that displays how many times a specific die value is rolled out of a given number of rolls, you can modify your code as follows:
pythonimport random
def dice_histogram(die_value, total_rolls):
rolls = [random.randint(1, 6) for _ in range(total_rolls)]
count = rolls.count(die_value)
histogram_line = '*' * count
print(f"Die value {die_value} was rolled {count} times out of {total_rolls} rolls: {histogram_line}")
# Get user input
total_rolls = int(input('How many times would you like to roll the 6-sided die? '))
die_value = int(input('Which specific die value between 1 and 6 are you requesting? '))
# Call the function and print the histogram
dice_histogram(die_value, total_rolls)
This code uses a list comprehension to generate a list of random die rolls. Then, it counts how many times the specified die value appears in the list and creates a string of asterisks to represent the histogram line for that value. Finally, it prints the histogram line along with the count of the specified die value.
المزيد من المعلومات
لفهم الحلقة البرمجية بشكل أفضل، دعنا نلقي نظرة على كيفية عمل كل جزء من الكود:
-
استيراد الحزمة اللازمة:
pythonimport random
يتم استيراد حزمة
random
لاستخدام وظيفةrandint
التي تولد أرقامًا عشوائية. -
تعريف الدالة
dice_histogram
:pythondef dice_histogram(die_value, total_rolls): rolls = [random.randint(1, 6) for _ in range(total_rolls)] count = rolls.count(die_value) histogram_line = '*' * count print(f"Die value {die_value} was rolled {count} times out of {total_rolls} rolls: {histogram_line}")
- تقوم هذه الدالة بتوليد قائمة من القيم التي تم الحصول عليها بشكل عشوائي باستخدام
random.randint(1, 6)
، حيث يمثل1
و6
الحدود السفلية والعليا لقيم النرد. - تعداد عدد مرات ظهور القيمة المحددة
die_value
في القائمة باستخدامrolls.count(die_value)
وتخزينه فيcount
. - تنشئ سلسلة من النجوم (
*
) بطول يساويcount
لتمثيل الصف الواحد في الهيستوغرام. - تقوم بطباعة عدد مرات ظهور القيمة المحددة والهيستوغرام.
- تقوم هذه الدالة بتوليد قائمة من القيم التي تم الحصول عليها بشكل عشوائي باستخدام
-
الحصول على إدخال المستخدم:
pythontotal_rolls = int(input('How many times would you like to roll the 6-sided die? ')) die_value = int(input('Which specific die value between 1 and 6 are you requesting? '))
يتم سؤال المستخدم عن عدد مرات رمي النرد والقيمة المحددة التي يرغب في عرض عدد مرات ظهورها في الهيستوغرام.
-
استدعاء الدالة وطباعة النتيجة:
pythondice_histogram(die_value, total_rolls)
يتم استدعاء الدالة
dice_histogram
بالقيم التي أدخلها المستخدم وطباعة الهيستوغرام الناتج.
باستخدام هذه العملية، يمكنك الحصول على هيستوغرام يظهر عدد مرات ظهور قيمة معينة عند رمي النرد بعدد معين من المرات.