python_test_13

  1. 有两个6面骰子,同时抛掷100000次,求两个骰子点数只和所占百分比。
    # 方法1:

    list1 = [1, 2, 3, 4, 5, 6]
    list2 = [1, 2, 3, 4, 5, 6]
    dict1 = {}
    n = 100000
    for _ in range(100000):
    		x = random.randint(0, 5)
    		y = random.randint(0, 5)
    		sum = list1[x] + list2[y]
    		list2.append(sum)
    
    for i in range(2, 13):
    		dict1.setdefault(i, "{a}{b}".format(a=list2.count(i) / 1000, b="%"))
    print(dict1)
    

# 方法2:

result = list()
for i in range(100000):
    # 骰子1
    a = random.randint(1, 6)
    # 骰子2
    b = random.randint(1, 6)
    result.append(a + b)

result_dict = dict()
for i in set(result):
    	result_dict[i] = "{:.2%}".format(result.count(i) / 100000)
print(result_dict)

输出结果:

{2: '2.78%', 3: '5.59%', 4: '8.43%', 5: '10.96%', 6: '13.97%', 7: '16.83%', 8: '13.78%', 9: '11.03%', 10: '8.24%', 11: '5.63%', 12: '2.77%'}

猜你喜欢

转载自blog.csdn.net/weixin_44786482/article/details/89051912