vendredi 25 février 2022

Why is my if statement returning an unreasonable value?

This is my first post so I hope I'm not doing anything wrong.

I am trying to test the usefulness of a function I wrote that returns a random character in a string. So, if my string is "aeiou", it would ideally, at random, return either "a", "e", "i", "o", or "u", and each string would appear about 20% of the time.

I wrote some more code to go through the function a bunch of times and print out the result. Here it is:

import random

number = 100000

def random_char(chars):
    char = chars[random.randint(0, (len(chars) - 1))]
    return char

a = 0
e = 0
i = 0
o = 0
u = 0

for i in range(0, number):
    new_char = (random_char("aeiou"))
    if new_char == ("a"):
        a = a + 1
    elif new_char == ("e"):
        e = e + 1
    elif new_char == ("i"):
        i = i + 1
    elif new_char == ("o"):
        o = o + 1
    elif new_char == ("u"):
        u = u + 1

list = [a, e, i, o , u]
list_str = ["a", "e", "i", "o", "u"]
i = 0

while i < len(list):
    print("Group " + (list_str[i]) + " has " + str(list[i]) + " tokens.")
    i = i + 1

My output is what I would expect for strings "a", "e", "o", and "u", (about 20,000 tokens each), but for "i" I'm getting around 99,999 each time, which should be impossible. I am confused!

In addition, if there is anything I could be doing better in terms of code/code efficiency, please say so! I'm a beginner.




Aucun commentaire:

Enregistrer un commentaire