Table of Contents
1, number of guesses
2. Guess the size
Home Backend Development Python Tutorial python knowledge analysis dice game

python knowledge analysis dice game

Apr 14, 2018 pm 02:24 PM
python

The content shared with you in this article is about python knowledge analysis and dice throwing game. It has certain reference value. Friends in need can refer to it. I recently learned some statistics and python knowledge, and tried to analyze the dice game. The dice has a standard 6 sides, and the results of throwing 1, 2, 3, and 4 dice at a time, and throwing 10, 100, 1,000, and 10,000 times are analyzed.

use tools
Jupyter Notebook analysis tool
matplotlib, pygal visualization package

1, number of guesses

1-6中每个数字出现的次数
Copy after login
# 导入包
import pygal
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
from random import randint
Copy after login
# 利用随机数据模拟掷骰子
# 每次显示1-6中的一个数

num_sides = 6  # 骰子的6个面
def getData(N, times):
    """
    定义函数,获取投掷数据
    N: 表示一次用几个骰子投
    times:表示总共投几次
    """  
    results = []    
    for n in range(1,N+1):    
        for roll_num in range(times):
            result = randint(1,num_sides)
            results.append(result)    
        return results
Copy after login
# 打印投掷结果
print(getData(1,10)) # 1个骰子掷10次
print(getData(2,5))  # 2个骰子掷5次
Copy after login
[2, 2, 2, 2, 1, 6, 4, 4, 5, 5]
[4, 3, 5, 6, 2, 2, 3, 6, 4, 4]
Copy after login
# 分析结果# 统计每个数字出现的次数并显示图片
    # N: 表示一次用几个骰子投
    # data 表示投掷数据def showResult(N, times):
    frequencies = []    for value in range(1, num_sides+1):
        frequency = getData(N, times).count(value)
        frequencies.append(frequency)    # 数据可视化
    # 本次利用 pygal 生成SVG格式矢量图
    hist = pygal.Bar()
    hist.title = str(N)+"个骰子掷"+ str(times) +"次的结果"
    hist.x_labels = ['1','2','3','4','5','6']
    hist.x_title = "点数"
    hist.y_title = "出现次数"

    hist.add(str(N)+'骰子', frequencies)
    hist.render_to_file('1-'+str(N)+str(times)+'.svg') # 储存为矢量图
Copy after login
# 一个骰子掷10,100, 1000, 10000次结果分析showResult(1,10)
showResult(1,100)
showResult(1,1000)
showResult(1,10000)
Copy after login

python knowledge analysis dice game

#
# 2个骰子掷10,100, 1000, 10000次结果分析showResult(2,10)
showResult(2,100)
showResult(2,1000)
showResult(2,10000)
Copy after login

python knowledge analysis dice game

3 dice , 4 dice will no longer take screenshots.

We found that the more times we throw, the closer the probability of each number appears, and finally tend to be the same.

2. Guess the size

每次投掷点数和
Copy after login
# 每次投掷点数和def getData2(N, times):
    """
    定义函数,获取投掷数据
    N: 表示一次用几个骰子投
    times:表示总共投几次
    """  
    results = []    for roll_num in range(times):
        result = 0
        for n in range(1,N+1):
            result += randint(1,num_sides)
        results.append(result)    
    return results
Copy after login
# 打印投掷结果print(getData2(1,10)) # 1个骰子掷10次print(getData2(2,5))  # 2个骰子掷5次
Copy after login
[4, 3, 6, 2, 5, 4, 5, 3, 6, 2]
[6, 10, 5, 8, 7]
Copy after login
# 分析结果# 统计数字和出现的次数并显示图片
    # N: 表示一次用几个骰子投
    # data 表示投掷数据def showResult2(N, times):
    frequencies = []    for value in range(N, N*num_sides+1):
        frequency = getData2(N, times).count(value)
        frequencies.append(frequency)    # 数据可视化
    # 本次利用 matplotlib 生成图片
    x_num = N*num_sides+1-N
    idx = np.arange(x_num)
    width = 0.5
    sn = str(N)
    sm = str(times)
    x_labels = [str(n) for n in range(N, N*num_sides+1)]  # X轴刻度

    plt.bar(idx, frequencies, width, color='red', label=sn+'个骰子')
    plt.xlabel('点数和')
    plt.ylabel('出现次数')
    plt.title(sn+'个骰子投掷'+ sm +'次的结果')
    plt.xticks(idx, x_labels)
    plt.legend()  # 显示图例
    plt.show()
Copy after login

It doesn’t make much sense to guess the size of one dice. Let’s directly analyze the situation of two dice.

#  2个骰子掷10,100, 1000, 10000次结果分析showResult2(2,10)
showResult2(2,100)
showResult2(2,1000)
showResult2(2,10000)
Copy after login

python knowledge analysis dice game

#  3个骰子掷10,100, 1000, 10000次结果分析showResult2(3,10)
showResult2(3,100)
showResult2(3,1000)
showResult2(3,10000)
Copy after login

python knowledge analysis dice game

#  4个骰子掷10,100, 1000, 10000次结果分析showResult2(4,10)
showResult2(4,100)
showResult2(4,1000)
showResult2(4,10000)
Copy after login

python knowledge analysis dice game

We can see from the above pictures that when the number of throws is enough Often, the probability of large/small points appearing is basically the same, and the point size shows the characteristics of a normal distribution.

Related recommendations:

dice rolling game-C language implementation

Dice game

C Dice game

practicing small Program: craps craps game

craps craps problem

The above is the detailed content of python knowledge analysis dice game. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles