البرمجة

عرض هيستوغرام لرمي النرد

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:

python
import 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.

المزيد من المعلومات

لفهم الحلقة البرمجية بشكل أفضل، دعنا نلقي نظرة على كيفية عمل كل جزء من الكود:

  1. استيراد الحزمة اللازمة:

    python
    import random

    يتم استيراد حزمة random لاستخدام وظيفة randint التي تولد أرقامًا عشوائية.

  2. تعريف الدالة dice_histogram:

    python
    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}")
    • تقوم هذه الدالة بتوليد قائمة من القيم التي تم الحصول عليها بشكل عشوائي باستخدام random.randint(1, 6)، حيث يمثل 1 و 6 الحدود السفلية والعليا لقيم النرد.
    • تعداد عدد مرات ظهور القيمة المحددة die_value في القائمة باستخدام rolls.count(die_value) وتخزينه في count.
    • تنشئ سلسلة من النجوم (*) بطول يساوي count لتمثيل الصف الواحد في الهيستوغرام.
    • تقوم بطباعة عدد مرات ظهور القيمة المحددة والهيستوغرام.
  3. الحصول على إدخال المستخدم:

    python
    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? '))

    يتم سؤال المستخدم عن عدد مرات رمي النرد والقيمة المحددة التي يرغب في عرض عدد مرات ظهورها في الهيستوغرام.

  4. استدعاء الدالة وطباعة النتيجة:

    python
    dice_histogram(die_value, total_rolls)

    يتم استدعاء الدالة dice_histogram بالقيم التي أدخلها المستخدم وطباعة الهيستوغرام الناتج.

باستخدام هذه العملية، يمكنك الحصول على هيستوغرام يظهر عدد مرات ظهور قيمة معينة عند رمي النرد بعدد معين من المرات.

مقالات ذات صلة

زر الذهاب إلى الأعلى

هذا المحتوى محمي من النسخ لمشاركته يرجى استعمال أزرار المشاركة السريعة أو تسخ الرابط !!