python应用-掷骰子模拟-pygal

2021-06-17 04:02

阅读:500

标签:def   svg   效果   file   install   info   imp   random   sid   

pygal安装:

Linux下:
pip install pygal
Windows下:
python -m pip install pygal

效果如图:
技术分享图片

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 23:07:29 2018
@author: pprp
"""

from random import randint
import pygal

class Die():
    def __init__(self,num_sides=6):
        self.num_sides=num_sides
        
    def roll(self):
        return randint(1,self.num_sides)
    
if __name__ == '__main__':    
    die1=Die()
    die2=Die()
    
    results=[]
    
    for roll_num in range(100000):
        result = die1.roll()+die2.roll()
        results.append(result)
        
        
    frequencies=[]
    max_result=die1.num_sides+die2.num_sides
    for val in range(2,max_result+1):
        frequency=results.count(val)
        frequencies.append(frequency)
        
    print(frequencies)
    
    hist=pygal.Bar()
    
    hist.title="Rolling one D6 1000 times"
    hist.x_labels=['2','3','4','5','6','7','8','9','10','11','12']
    hist.x_title="result"
    hist.y_title="Frequency"
    
    hist.add('D6 + D6',frequencies)
    hist.render_to_file('die_visual.svg')

python应用-掷骰子模拟-pygal

标签:def   svg   效果   file   install   info   imp   random   sid   

原文地址:https://www.cnblogs.com/pprp/p/9723068.html


评论


亲,登录后才可以留言!