Adi219
Adi219

Reputation: 4814

How can I randomly choose a number without using an 'If'?

Basically, I'm messing around in Python (3) and I'm trying to define some functions to do some common tasks in single lines, using as less memory as possible

For example, in video games, you might want a character to turn some degrees left/right, but not 0 degrees. So, given an integer x, how could you return a random integer between -x and +x` (inclusive) which isn't 0?

Note, I'm going for one-liners using minimum memory.

I'm posting an answer but I'd also like to know how other people would approach this.

EDIT: This isn' school homework or anything, I'm just designing a video game and defining a few functions which will come in handy. I said no 'If's because I was wondering if it was possible, and if so, how.

Thanks :-)

Upvotes: 1

Views: 70

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51643

random.sample works with ranges which are very small compared to the range of numbers they provide.

This create a positive number between 1 and x and multiplies it with 1 or -1.

import random

def between(x):
    return random.sample(range(1, x+1),k=1)[0] * (-2*random.randint(0,1)+1)

After looking at kch answer, I would probably go his approach.

Upvotes: 0

Adi219
Adi219

Reputation: 4814

I would use:

import random

def between(x):
    return ((((random.randint(0, 1) * 2) - 1) * random.randint(1, x))

Upvotes: 0

kch
kch

Reputation: 698

I would suggest:

import random

def randint_between(x):
    return random.choice([-1, 1]) * random.randint(1, x)

Upvotes: 7

Related Questions