改变骰子卷程序的内置功能

时间:2014-01-23 16:34:40

标签: python

我在python中编写一个代码,用于使用给定骰子数量的试验数量的直方图。我在堆栈溢出中找到了一个代码并对其进行了修改,根据我的要求给出了结果。这是我修改过的代码。

import random
from collections import defaultdict

def main(dice,rolls):
    result = roll(dice, rolls)
    maxH = 0
    for i in range(dice, dice * 6 + 1):
        if result[i] / rolls > maxH: maxH = result[i] / rolls
    for i in range(dice, dice * 6 + 1):
        print('{:2d}{:10d}{:8.2%} {}'.format(i, result[i], result[i] / rolls, '#' * int(result[i] / rolls / maxH * 40)))


def roll(dice,rolls):
    d = defaultdict(int)
    for _ in range(rolls):
        d[sum(random.randint(1, 7) for _ in range(dice))] += 1
    return d

但是,我应该在不使用内置函数(如defaultdict,random.randint,.format)的情况下实现它。是否有可能更换它们但仍能获得所需的输出?我尝试了几种方法,但无法取代它们。

1 个答案:

答案 0 :(得分:0)

不要在不使用random的情况下尝试获取随机数。超出此级别任何家庭作业所期望的FAR,即使专业程序员产生良好的PRNG也是一个非常重要的问题。我们可以删除defaultdictformat

import random

def roll(dice,rolls):
    d = {}
    i = 0
    while i < rolls: # to avoid the builtin range()
        result = sum((random.randint(1, 6) for _ in range(dice)))
        # or if you want to avoid the builtins sum() and range()
        #   result = 0
        #   dicerolled = 0
        #   while dicerolled < dice:
        #       result += random.randint(1,6)
        #       dicerolled += 1
        try: d[result] += 1
        except KeyError: d[result] = 1
        i += 1
    return d

def main(dice,rolls):
    results = roll(dice,rolls)
    MAXH = 60 # what's your hist scale
    maxH = max(results.values())
    # or if you want to avoid the builtin max() as well
    #   for count in result.values():
    #       if count/rolls > maxH: maxH = count
    SCALE = MAXH/maxH #this is your scale
    for theroll,count in sorted(results.items()):
        if len(str(theroll)) < 2: print(" ",end='')
        print(str(theroll) + " : " + "H"*int(count*SCALE))

我们最终得到的程序可以避免所有内置函数,但random模块,str()int()(无论如何都是技术构造函数)。最大的问题是:为什么!?!?!?!

Python是使用和利用库的MADE,而stdlib是包含电池的原因!使用您的建筑物,使用您的进口,或用其他语言编码。