rangeseeker
rangeseeker

Reputation: 403

How can I get unique random output while printing a loop in python?

so I want a script to give me a set of 10 simple polynomials to simplify. Lets ignore the fact that the current output is not a valid polynomial. I want to print 10 with random integers, variables and operations, but when I loop them I just get the same problem 10 times. How can I get a unique set every time?

I was having a hard time getting a unique term, but solved that problem by creating a unique term (term0, term1) etc. for each term.

import random

def int():
    interger = random.randint(2,10)
    return interger

def variable():
    letter  = ["x","y",""]
    variable = random.choice(letter)
    return variable

def op():
    op  = ["+","-","+"]
    operation = random.choice(op)
    return operation

term0 = op(), int(), variable()
term1 = op(), int(), variable()
term2 = op(), int(), variable()
term3 = op(), int(), variable()

for x in range(10):
    print(*term0,*term1,*term2,*term3,sep='',)

I would like to get a unique output for each loop, but currently I just get the same thing 10 times.

Upvotes: 2

Views: 935

Answers (2)

that other guy
that other guy

Reputation: 123410

Call your random selection functions inside the loop. This way elements will be randomly selected once per iteration, instead of once before the loop:

for x in range(10):
    term0 = op(), int(), variable()
    term1 = op(), int(), variable()
    term2 = op(), int(), variable()
    term3 = op(), int(), variable()
    print(*term0,*term1,*term2,*term3,sep='',)

Upvotes: 2

Prune
Prune

Reputation: 77837

You did not generate ten polynomials. You generated four terms for one polynomial, and then printed the same data ten times. If you want new values, you need to call your functions inside the loop, not outside.

for x in range(10):
    term0 = op(), int(), variable()
    term1 = op(), int(), variable()
    term2 = op(), int(), variable()
    term3 = op(), int(), variable()

    print(*term0, *term1, *term2, *term3, sep='',)

Upvotes: 0

Related Questions