Toby Hooper
Toby Hooper

Reputation: 71

Random numbers in Python that are between 2 and 64, but only 2 ** 2

I am trying to write some code to generate random numbers, but the only numbers I want it to generate are 2, 4, 8, 16, 32 and 64 (like a double dice). I have written it out like the below but cant seem to get only the numbers to show up, I keep getting any numbers between 2 and 64. help please.

rolling_result = random.randrange(2, 65)

print("You have rolled a ", rolling_result, sep = "")

Upvotes: 2

Views: 908

Answers (4)

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

If you need to do it many times it can be effective to pre-generate valid values and use random.choice().

import random

valid = tuple(2 ** x for x in range(1, 7))

def my_random():
  return random.choice(valid)

P.S. Depend on size of valid valuesit can be more effective to use list instead of tuple.

Upvotes: 0

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

and another way, without multiplying:

rolling_result = 1
while not rolling_result%2==0:
    rolling_result = random.randrange(2, 65)
print("You have rolled a ", rolling_result, sep = "")

HTH, Edwin

[edit] I just found out that random.randrange takes a "step" value, so now your code can become a simple as this:

rolling_result = random.randrange(2, 65, 2)
print("You have rolled a ", rolling_result, sep = "")

.

Upvotes: 0

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18855

Get random between 1-6 and use shift (<<) or 2 ** n to get the final number:

n = 1 << random.randrange(1, 7)
# or
n = 2 ** random.randrange(1, 7)

Shift should be significantly faster with integers.

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137497

Generate a random number between 1 and 6. Then return 2 to that power.

def roll_double_die():
    return 2 ** random.randint(1, 6)

Upvotes: 3

Related Questions