Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pythonic way to create a big random base-29 number

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading