1
\$\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
mdfst13
22.4k6 gold badges34 silver badges70 bronze badges
asked Jul 15, 2016 at 3:08
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please check your indentation. \$\endgroup\$ Commented Jul 15, 2016 at 3:25

1 Answer 1

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)]
answered Jul 19, 2016 at 6:52
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.