Home > Blockchain >  Python using different module package, and counts
Python using different module package, and counts

Time:04-16

yut.py is the following.

I need to define two variables:

throw_yut1() which randomly selects '배' or '등' by 60% and 40% respectively.

throw_yut4() which prints 4 results from throw_yut1() such as '배등배배' or '배배배배' etc.

import random

random.seed(10)

def throw_yut1():
    if random.random() <= 0.6 :
        return '배'
    else:
        return '등'
        

def throw_yut4():
    result = ''

    for i in range(4):
        result = result   throw_yut1()
    
    return result

main.py is the following.

Here, I need to repeat throw_yut4 1000 times and print the value and percentages of getting each variables that are listed in if statement.

import yut

counts = {}

for i in range(1000):
   
    result = yut.throw_yut4

    back = yut.throw_yut4().count('등') 
    belly = yut.throw_yut4().count('배')

    if back == 3 and belly == 1:
        counts['도'] = counts.get('도', 0)   1
    elif back == 2 and belly == 2:
        counts['개'] = counts.get('개', 0)   1
    elif back == 1 and belly == 3:
        counts['걸'] = counts.get('걸', 0)   1
    elif back == 0 and belly == 4:
        counts['윷'] = counts.get('윷', 0)   1
    elif back == 4 and belly == 0:
        counts['모'] = counts.get('모', 0)   1


for key in ['도','개','걸','윷','모']:
    print(f'{key} - {counts[key]} ({counts[key] / 1000 * 100:.1f}%)')

I keep getting

도 - 33 (3.3%)
개 - 115 (11.5%)
걸 - 131 (13.1%)
윷 - 22 (2.2%)
모 - 1 (0.1%)

but I am meant to get

도 - 157 (15.7%)
개 - 333 (33.3%)
걸 - 349 (34.9%)
윷 - 135 (13.5%)
모 - 26 (2.6%)

How can I fix my error?

CodePudding user response:

I think the problem is this part of the code:

for i in range(1000):
    result = yut.throw_yut4

    back = yut.throw_yut4().count('등') 
    belly = yut.throw_yut4().count('배')

Seems like it should be:

for i in range(1000):
    result = yut.throw_yut4()

    back = result.count('등') 
    belly = result.count('배')

Otherwise you are counting back/belly from independent yut.throw_yut4() calls, so some unhandled (and presumably unintended) results are possible like back=4 and belly=4 ... this is why the totals you count are less than 1000 and 100%

CodePudding user response:

It seems like your counts dictionary isn't getting filled with 1000 elements. It is likely because you are calling the yut.throw_yut4() twice, which give different results, such that none of your conditional checks pass.

try this instead:

result = yut.throw_yut4()
back = result.count('등')
belly = result.count('등')

천만에요

  • Related