1

I'm creating a program which has to handle rather big ints in python. Ranging from 0-104677. Internally, I represent them with as base-29 integers. Thus using the alfabet: 012345679ABCDEFGHIJKLMNOPQRS.

I created a function to create a random base-29 variable of any length in python. But is there a shorter, more pythonic way possible? (if this is even a proper way of doing it).

The function to create a random base-29 number:

import random

def random_base(base_number = 29, length = 10)
    alfabet = "012345679ABCDEFGHIJKLMNOPQRS"
    return [alfabet[random.randint(0,base_number - 1)] for _ in range(length)]

Thus, is there some built-in python function to perform this, or is this the way to go?

Please comment if things are unclear!

Thanks in Advance

Chiel
  • 1,324
  • 1
  • 11
  • 30
  • 2
    Seems like you've missed digit `8` – Yevhen Bondar Jan 04 '22 at 19:27
  • You could convert *any* random number to base-29 by making a trivial modification to the accepted answer to the question [Base 62 conversion](https://stackoverflow.com/questions/1119722/base-62-conversion). – martineau Jan 04 '22 at 19:30

1 Answers1

3

You can use slices and random.choices

import random

def random_base(base_number = 29, length = 10):
    alfabet = "0123456789ABCDEFGHIJKLMNOPQRS"
    return "".join(random.choices(alfabet[:base_number], k=length))
Yevhen Bondar
  • 4,357
  • 1
  • 11
  • 31