mercredi 16 août 2017

Random in Python?

I've been working with Python for a while, and while trying to find a way to generate random numbers/put them into an equation (similar to how you can get client side input in C#). While looking for an answer, I came across another StackOverflow page that gave me some ideas. I used the code as a sort of "jumping off" point. I made some edits of my own and I have this:

from random import random, randint

Parentheses = ()

Number = ()

expressionRand = ()

binaryExpression = ()

def expressionRand(prob):
    p = random()
    if p > prob:
        return Number(randint(1, 100))
    elif randint(0, 1) == 0:
        return Parentheses(expressionRand(prob / 1.2))
    else:
        left = expressionRand(prob / 1.2)
        op = choice(["+", "-", "*", "/"])
        right = expressionRand(prob / 1.2)
        return binaryExpression(left, op, right)

for i in range(10):
    print(expressionRand(1))

Any ideas? Thanks!




Aucun commentaire:

Enregistrer un commentaire