投擲骰子 -Python實現
from random import randint
import pygal
class Die():
"""表示一個骰子的類"""
def __init__(self, num_sides=6):
"""骰子預設6面"""
self.num_sides = num_sides
def roll(self):
"""返回一個位於1和骰子面數之間的隨機值"""
return randint(1, self.num_sides)
# 投擲一個骰子
die_1 = Die()
print(die_1.roll())
results = []
for roll_num in range(100):
result = die_1.roll()
results.append(result)
print(results)
for num in range(1, 7):
print("面為%-2d的出現的次數為:%d)" % (num, results.count(num)))
# 投擲兩個骰子
die_1 = Die()
die_2 = Die()
# 擲幾次骰子,並將結果儲存在一個列表中
results = []
for roll_num in range(100):
result = die_1.roll() + die_2.roll()
results.append(result)
# 列印擲骰子的結果
print("1", results)
# 分析結果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2,max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
print("面為%-2d的出現的次數為:%d)" % (value, results.count(value)))
# 列印每個面出現的次數
print(frequencies)
# 對結果進行視覺化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = [str(i) for i in range(2, 13)]
hist.x_tile = "Result"
hist.y_title = "Frequency of Result"
hist.add("D6+D6", frequencies)
hist.render_to_file("dice_visual.svg")
print("圖表製作成功")

兩個骰子的投擲結果.png
相關文章
- Python繪製直方圖 Pygal模擬擲骰子Python直方圖
- HarmonyOS(鴻蒙)運動手錶—從零實現投骰子小遊戲鴻蒙遊戲
- Python實現投遞多執行緒任務Python執行緒
- 在《骰子地下城》裡,你可以扮演一顆骰子
- jzoj8132 扔骰子
- 使用 Message Manager 實現開箱即用的驗證(Validation)資訊丟擲
- n個骰子的點數
- Python量化交易進階講堂-Markowitz模型實現最優投資組合Python模型
- Python爬蟲實戰之蘿蔔投研Python爬蟲
- 全網最適合入門的物件導向程式設計教程:23 類和物件的Python實現-丟擲異常物件程式設計Python
- 實現rabbitmq訊息重新投遞方案MQ
- 如何遠端投屏實現螢幕共享
- switch的python實現Python
- 字母排列(python實現)Python
- Python 字典實現原理Python
- Python實現建立字典Python
- C均值聚類 C實現 Python實現聚類Python
- 《神骰傳說》現已發售:肉鴿“寶可夢”,骰子玩出花
- Python實現火柴人的設計與實現Python
- 【Python】Python實現解壓rar檔案Python
- Spectral Matting的python實現Python
- Python實現氣泡排序Python排序
- 基於Python實現MapReducePython
- Go 實現的 python collectionsGoPython
- python實現密碼破解Python密碼
- 選擇排序(python)實現排序Python
- Python Turtle實現彈球Python
- python 介面實現類的Python
- Python實現的快速排序Python排序
- python實現貪吃蛇Python
- Python底層實現KNNPythonKNN
- JZ-074-n 個骰子的點數
- Python教程:Python如何實現窮舉搜尋?Python
- 【數值方法-Python實現】Crout分解+追趕法實現Python
- FM演算法python實現演算法Python
- python實現冒泡演算法Python演算法
- Python實現單連結串列Python
- Python之禪-import this的實現PythonImport