Creating instance names from a list (Python)

I have a function that creates a random number of instances of objects. For the sake of demonstrating the general idea, we are going to pretend that this is an algorithm for constructing a series of ridiculous rooms.

The requirements are such that I will not know how many copies will be in advance; they are generated randomly and on the fly.

As a brief note: I am fully aware that the following code is non-functional, but it should (hopefully)! demonstrate my goals.

import random

class Levelbuild(object):

    def __init__(self):
        self.l1 = dict({0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i'})
        # Pick a random number between 4 and 9.
        for i in range(random.randint(4,9)):
            self.l1[i] = Roombuilder()

Assuming the selected random integer is 5, the ideal result would be 5 instances of Roombuilder (); denoted by a, b, c, d and e, respectively.

Is there an easy way to do this? Is there any way to make this period?

- Edit -

"" . / - , , ;

import random

class Room(object):
    def __init__(self):
        self.size = (5,5)

class Level(object):

    def __init__(self):
        roomnames = ['a','b','c','d','e','f','g','h','i']
        self.rooms = {}
        for i in range(random.randint(4, 9)):
            self.rooms[roomnames[i]] = Room()

, "" , ...

test = Level()
print test.rooms['a'].size
>>> (5,5)
+3
3
import string
import random

class Levelbuild(object):

  def __init__(self,min_room_count,max_room_count):

    rooms_temp = [new RoomBuilder() for i in range(random.randint(min_room_count,max_room_count))]
    self.l1 = dict(zip(string.ascii_lowercase, rooms_temp))

. , 26 .

+3

. ; . (, , {...} dict, dict() .)

roomnames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
self.rooms = []
for i in range(random.randint(4, 9)):
    self.rooms.append(Roombuilder(roomnames[i]))

, , builder . - , ? , Room.

0

( , Nick ODell answer, , :

import string
import itertools

def generate_names(characters):
    for i in itertools.count(1):
        for name in itertools.product(characters, repeat=i):
            yield "".join(name)

, :

>>>print(dict(zip(generate_names(string.ascii_lowercase), range(30))))
{'aa': 26, 'ac': 28, 'ab': 27, 'ad': 29, 'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}

If you need to generate actual names, you have several options. If you need a real word, select a file from the dictionary (most Linux users have one in /usr/share/dict). If you need text words, I actually wrote a Python script to generate such β€œwords” using Markov Chains , which is available under the GPL. Naturally, you will have to check them for uniqueness.

0
source

All Articles