0
\$\begingroup\$

I created this code and it works fine, but I think it's ugly. Could you show me a better way to create a list of three different random numbers from 1 to 9?

class Baseball_Engine(object):
    def __init__(self):
        self.count = 0
        self.random_number_list = [0, 0, 0]
        while self.count < 3:
            random_number = random.randint(1, 9)
            self.random_number_list[self.count] = random_number
                if self.random_number_list[self.count - 1] != random_number and self.random_number_list[self.count - 2] != random_number:
                self.count += 1
        print self.random_number_list
\$\endgroup\$
  • 1
    \$\begingroup\$ Please check your indentation. \$\endgroup\$ – 200_success Jul 15 '16 at 3:25
1
\$\begingroup\$

Without dwelling too deep into your code there are a few alternatives. After a very quick google search, I stumbled upon this question on SO.

They propose two different solutions.

import random
print random.sample(xrange(1, 10), 3)

This will create three distinct numbers with values ranging from 1 to 9. If you do not want the three numbers to be different, you could try the following

import random
print [random.randrange(1,10) for _ in range(3)]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.