0

I want to get a random number between (65, 90) and (97, 122) range. I can select random number in range using

import random
random.randint(65,95)

but ˋrandint` take the only integer so how can I do?? any idea

Thanks in advance

tupui
  • 5,738
  • 3
  • 31
  • 52
Kallz
  • 3,244
  • 1
  • 20
  • 38

3 Answers3

1

Alternatively:

def random():
  arr1 = np.random.randint(65,90)
  arr2 = np.random.randint(97,122)
  out = np.stack((arr1,arr2))
  out = np.random.choice(out)
  return out
Andreas Look
  • 151
  • 4
1
def random_of_ranges(*ranges):
  all_ranges = sum(ranges, [])
  return random.choice(all_ranges)

print(random_of_ranges(range(65, 90), range(97, 122)))

This is a very general way of handling this. You can pass any number of ranges (or subset of them). But it is rather costly, especially for very large sets (like range(1, 100000000)). For your usecase (and maybe several others in the vicinity) it would be sufficient, though.

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Why would you build `all_ranges` here? `random.choice(random.choice(ranges))` does the same without rebuilding a list each time... – Jon Clements Jul 31 '17 at 12:23
  • 2
    It does the same if all ranges are of equal size (which is the case in the Q above). In the general case this need not be true, and `choice(choice([ range(1, 100), range(200, 202) ]))` will return 200 and 201 way more often than e. g. 50 or 37. But of course, building the list just once and then use it in all calls with this input would be a good optimization. – Alfe Jul 31 '17 at 12:25
  • Good point - well made :) – Jon Clements Jul 31 '17 at 12:26
  • I have a feeling it's going to be slower, but...: `heapq.nlargest(1, itertools.chain(ranges), key=lambda L: random.random())` :p – Jon Clements Jul 31 '17 at 12:29
  • Why using `nlargest` instead of `max`? – Alfe Jul 31 '17 at 13:20
  • 1
    Just to make my non-serious suggestion more obviously non-serious? – Jon Clements Jul 31 '17 at 13:22
-1

Make your own?

import random

def my_rand():
  numbers = list()
  numbers.append(random.randint(65,95))
  numbers.append(random.randint(97,122))
  return numbers[random.randint(0,1)]
Nicola Coretti
  • 2,655
  • 2
  • 20
  • 22