Home > Enterprise >  Random Generate a Dictionary with random_names : random_integers
Random Generate a Dictionary with random_names : random_integers

Time:09-24

This code generate a set of random meaningless names:

def unique_names(k: int, ntokens: int,
               pool: str=string.ascii_letters) -> set:
    
    """
    Generate a set of unique string tokens.
    k: Length of each token
    ntokens: Number of tokens
    pool: Iterable of characters to choose from
    
    """
    seen = set()

    join = ''.join
    add = seen.add

    while len(seen) < ntokens:
        token = join(random.choices(pool, k=k))
        add(token)
    return seen

And its working. I am now trying to generate random k numbers of n digits_long integers:

import random

def numbers(k: int ,n: int) -> set:
    
    l = set()
    join = ''.join
    add = l.add
    for _ in range(k):
    
        n= join(["{}".format(randint(0, 9)) for num in range(0, n)])
        add(n)
    return l

and the code above works if a genarate only 1 number: numbers(1,3) -> output {'134'} This is my first problem.

What i want to to is to genarate a pair, value dict os random names and numbers, like this:

{'vffde':234234, 'hrtge': 342344, ....}

So ill need to fix the 2nd code and somehow use both functions to gt the result dictionary of ramdom names:numbers.

I am having a hard time to make it happens. Can anyone helpe me?

CodePudding user response:

You can do this with dict(zip(...)) like so:

def unique_names(k: int, ntokens: int,
                 pool: str = string.ascii_letters) -> set:
    """
    Generate a set of unique string tokens.
    k: Length of each token
    ntokens: Number of tokens
    pool: Iterable of characters to choose from

    """
    seen = set()

    join = ''.join
    add = seen.add

    while len(seen) < ntokens:
        token = join(random.choices(pool, k=k))
        add(token)
    return seen

def numbers(k: int, n: int) -> set:
    seen = set()
    join = ''.join
    add = seen.add
    while len(seen) < k:

        m = join(["{}".format(randint(0, 9)) for num in range(0, n)])
        add(m)
    return seen

random_pairs = dict(zip(unique_names(5,2), numbers(2, 6)))

There were two problems in your code: n= join(["{}".format(randint(0, 9)) for num in range(0, n)]) is reusing the variable n, so when k > 1, you've converted your integer to a string. It should also be a while loop if you're trying to always have at least k entries.

You're also using k for a very different purpose in unique_names and numbers. This isn't currently a bug, but it is extremely likely to lead to more future bugs related to variable name shadowing.

  • Related