I have multiple files in this format:
car1.cr
module Cars
module Car1
BRAND = "TOYOTA"
end
end
All of these files are getting required by a main file where I can do this:
puts Cars::Car1::BRAND #=> TOYOTA
What I'm trying to do is puts all brands of all files dynamically, allowing me to just create a new file (or delete a file) in the first format and automatically being able to get printed without adding it manually (or removing it) .
I tried following this answer https://stackoverflow.com/a/50531198/13508702 but couldn't manage to achieve my goal.
Any help would be apreaciated!
Do you really need the constants? Couldn't your files just build up a hash?
# cars.cr
module Cars
BRANDS = {} of String, String
end
# car1.cr
module Cars
module Car1
BRANDS["Car1"] = "TOYOTA"
# Or if you really need the constant
BRAND = "TOYOTA"
BRANDS["Car1"] = BRAND
end
end
# Or if it really just defines the data
Cars::BRANDS["Car1"] = "TOYOTA"
I suspect you collect more info than the brand, so you may just define a value type:
module Cars
record Car, name : String, brand : String, model : String
CARS = [] of Car
end
Cars::CARS << Car.new("Car1", "TOYOTA", "AA")
The general answer here is, try to think of a way to restructure your program so that you don't need this meta-programming ability. That usually leads to cleaner and easier to follow code.
To answer the actual question:
module Cars
module Car1
BRAND = "TOYOTA"
end
module Car2
BRAND = "HONDA"
end
def self.collect_brands
{{#type.constants.map {|car| "#{car}::BRAND".id }}}
end
end
Cars.collect_brands # => ["TOYOTA", "HONDA"]
In case helpful, I don't know if you can have an Array of module but an array of instances!
module Car
abstract def brand : String
end
BRANDS = [] of Car
module Cars
class Car1
include Car
def brand : String
"TOYOTA"
end
end
end
BRANDS << Cars::Car1.new
Related
I just started with python and I am still a newbie , I want to create a function that grabs parts of filenames corresponding to a certain pattern these files are stored in s3 bucket.
So in my case, let's say I have 5 .txt files
Transfarm_DAT_005995_20190911_0300.txt
Transfarm_SupplierDivision_058346_20190911_0234.txt
Transfarm_SupplierDivision_058346_20200702_0245.txt
Transfarm_SupplierDivision_058346_20200703_0242.txt
Transfarm_SupplierDivision_058346_20200704_0241.txt
I want the script to go through these filenames, grab the string "Category i.e "Transfarm_DAT" and date "20190911"" and before the filename extension.
Can you point me in the direction to which Python modules and possibly guides that could assist me?
Check out the split and join functions if your filenames are always like this. Otherwise, regex is another avenue.
files_list = ['Transfarm_DAT_005995_20190911_0300.txt ', 'Transfarm_SupplierDivision_058346_20190911_0234.txt',
'Transfarm_SupplierDivision_058346_20200702_0245.txt', 'Transfarm_SupplierDivision_058346_20200703_0242.txt', 'Transfarm_SupplierDivision_058346_20200704_0241.txt']
category_list = []
date_list = []
for f in files_list:
date = f.split('.')[0].split('_',2)[2]
category = '_'.join([f.split('.')[0].split('_')[0], f.split('.')[0].split('_')[1]])
# print(category, date)
category_list.append(category)
date_list.append(date)
print(category_list, date_list)
Output lists:
['Transfarm_DAT', 'Transfarm_SupplierDivision', 'Transfarm_SupplierDivision', 'Transfarm_SupplierDivision', 'Transfarm_SupplierDivision'] ['005995_20190911_0300', '058346_20190911_0234', '058346_20200702_0245', '058346_20200703_0242', '058346_20200704_0241']
I'm a noob, working on making the Yahtzee game I programmed multiplayer. In Python 2.7, I want to have a prompt where a user can enter the number of players, i.e. 2, 3,4, 2007 etc., after which for the number of players entered, i.e. 3, the user will enter the names of the players, i.e. Mike, Tom, Jim, which I can then use in my program to keep score (i.e. Mike's score is 7, he's pretty bad, Jim has 250, he's pretty good etc.). I've seen suggestions to use dictionaries, classes and arrays, but I'm lost as to which one is best, and worst still, can't make what I'm trying to do work.
from collections import defaultdict
d = defaultdict(int)
d = {}
players = raw_input('How many players?')
players = int(players)
for i in range (1,players+1):
d = raw_input('Enter player name')
print d
my code on Repl.it is here
In your for loop you are assigning whatever the player types in as a name to be equal to d. d is therefore instantly no longer referring to any dictionary, but a string.. whatever the name was. A particular variable can only refer to one object at a time. Logically this is straight-forward if you think about what happens when you re-assign a variable to something new, how could the interpreter possibly differentiate between multiple possible objects when all it's provided is the label d..
Try something like this, a dict seems good to me:
players_dict = {}
num_players = raw_input("Enter number of players: ")
for i in num_players:
name = raw_input("Enter name for player %s:" % i)
# set initial score to 0
players_dict[name] = 0
Thanks all for the help. With your help, I figured out the following code (using a list and appending to it), which worked:
player_names = []
input_players = int(raw_input('how many players?'))
for i in range(0,input_players):
name = raw_input('enter player name')
name = name.upper()
player_names.append(name)
#using my new player names to iterate through turns:
for i in range(0,13):
for i in player_names:
print i # placeholder for my turn function
I am trying to use
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
while True
option = input("Choose an option: ")
if option = 1:
#What to put here?
I want to create an unlimited number of instances of the reader class, But I could only figure out how to do it a limited number of times by using variables for the class. I also need to call the info later (without losing it). Is it possible to do this with a class? Or would I be better off with a list, or dictionary?
First: if option == 1: is always false in python 3, input only reads strings there.
Second: python lists can be expanded until you run out of RAM.
So the solution would be to create a list in the surrounding code and call append on that every time you have a new item:
mylist = []
while True:
mylist.append(1)
It's perfectly possibly to populate a data structure (such as a list or dict) with instances of a class, given your code example you could put the instances into a list:
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
list = []
while True:
option = input("Choose an option: ")
if option == 1:
list.append(reader(name,booksread))
Note: I don't know how you are obtaining the values for 'name' or 'booksread', so their values in the list.append() line are just placeholders
To access the instances in that list, you can then iterate over it, or access elements by their indexes, e.g.
# access each element of the list and print the name
for reader in list:
print(reader.name)
#print the name of the first element of the list
print(list[0].name)
I'm trying to make a simple RPG game. I have a list of people that will be in the game, and want to create a character for each of them.
people = ['Mike','Tom']
class Character(object):
def __init__(self,name):
self.name = name
self.health = '100'
for x in people:
[x] = Character(x) # This is where I don't know what to do / if it's possible
That way I can call a character easily like
for x in people:
print ("%s: %s health" % (people[x].name, people[x].health))
Is such a thing possible, or am I going about this wrong? I read over How do I create a variable number of variables? but it seemed like dictionaries were the ultimate fix for their problem, and I have no idea how that would work in this situation.
It looks like you're just wanting to keep a list of Character objects. You don't need to reference people once you have that.
characters = [Character(person) for person in people]
Then, to print the character stats:
for c in characters:
print ("%s: %s health" % (c.name, c.health))
I'm working with the program Autodesk Maya.
I've made a naming convention script that will name each item in a certain convention accordingly. However I have it list every time in the scene, then check if the chosen name matches any current name in the scene, and then I have it rename it and recheck once more through the scene if there is a duplicate.
However, when i run the code, it can take as long as 30 seconds to a minute or more to run through it all. At first I had no idea what was making my code run slow, as it worked fine in a relatively low scene amount. But then when i put print statements in the check scene code, i saw that it was taking a long time to check through all the items in the scene, and check for duplicates.
The ls() command provides a unicode list of all the items in the scene. These items can be relatively large, up to a thousand or more if the scene has even a moderate amount of items, a normal scene would be several times larger than the testing scene i have at the moment (which has about 794 items in this list).
Is this supposed to take this long? Is the method i'm using to compare things inefficient? I'm not sure what to do here, the code is taking an excessive amount of time, i'm also wondering if it could be anything else in the code, but this seems like it might be it.
Here is some code below.
class Name(object):
"""A naming convention class that runs passed arguments through user
dictionary, and returns formatted string of users input naming convention.
"""
def __init__(self, user_conv):
self.user_conv = user_conv
# an example of a user convention is '${prefix}_${name}_${side}_${objtype}'
#staticmethod
def abbrev_lib(word):
# a dictionary of abbreviated words is here, takes in a string
# and returns an abbreviated string, if not found return given string
#staticmethod
def check_scene(name):
"""Checks entire scene for same name. If duplicate exists,
Keyword Arguments:
name -- (string) name of object to be checked
"""
scene = ls()
match = [x for x in scene if isinstance(x, collections.Iterable)
and (name in x)]
if not match:
return name
else:
return ''
def convert(self, prefix, name, side, objtype):
"""Converts given information about object into user specified convention.
Keyword Arguments:
prefix -- what is prefixed before the name
name -- name of the object or node
side -- what side the object is on, example 'left' or 'right'
obj_type -- the type of the object, example 'joint' or 'multiplyDivide'
"""
prefix = self.abbrev_lib(prefix)
name = self.abbrev_lib(name)
side = ''.join([self.abbrev_lib(x) for x in side])
objtype = self.abbrev_lib(objtype)
i = 02
checked = ''
subs = {'prefix': prefix, 'name': name, 'side':
side, 'objtype': objtype}
while self.checked == '':
newname = Template (self.user_conv.lower())
newname = newname.safe_substitute(**subs)
newname = newname.strip('_')
newname = newname.replace('__', '_')
checked = self.check_scene(newname)
if checked == '' and i < 100:
subs['objtype'] = '%s%s' %(objtype, i)
i+=1
else:
break
return checked
are you running this many times? You are potentially trolling a list of several hundred or a few thousand items for each iteration inside while self.checked =='', which would be a likely culprit. FWIW prints are also very slow in Maya, especially if you're printing a long list - so doing that many times will definitely be slow no matter what.
I'd try a couple of things to speed this up:
limit your searches to one type at a time - why troll through hundreds of random nodes if you only care about MultiplyDivide right now?
Use a set or a dictionary to search, rather than a list - sets and dictionaries use hashsets and are faster for lookups
If you're worried about maintining a naming convetion, definitely design it to be resistant to Maya's default behavior which is to append numeric suffixes to keep names unique. Any naming convention which doesn't support this will be a pain in the butt for all time, because you can't prevent Maya from doing this in the ordinary course of business. On the other hand if you use that for differntiating instances you don't need to do any uniquification at all - just use rename() on the object and capture the result. The weakness there is that Maya won't rename for global uniqueness, only local - so if you want to make unique node name for things that are not siblings you have to do it yourself.
Here's some cheapie code for finding unique node names:
def get_unique_scene_names (*nodeTypes):
if not nodeTypes:
nodeTypes = ('transform',)
results = {}
for longname in cmds.ls(type = nodeTypes, l=True):
shortname = longname.rpartition("|")[-1]
if not shortname in results:
results[shortname] = set()
results[shortname].add(longname)
return results
def add_unique_name(item, node_dict):
shortname = item.rpartition("|")[-1]
if shortname in node_dict:
node_dict[shortname].add(item)
else:
node_dict[shortname] = set([item])
def remove_unique_name(item, node_dict):
shortname = item.rpartition("|")[-1]
existing = node_dict.get(shortname, [])
if item in existing:
existing.remove(item)
def apply_convention(node, new_name, node_dict):
if not new_name in node_dict:
renamed_item = cmds.ls(cmds.rename(node, new_name), l=True)[0]
remove_unique_name(node, node_dict)
add_unique_name ( renamed_item, node_dict)
return renamed_item
else:
for n in range(99999):
possible_name = new_name + str(n + 1)
if not possible_name in node_dict:
renamed_item = cmds.ls(cmds.rename(node, possible_name), l=True)[0]
add_unique_name(renamed_item, node_dict)
return renamed_item
raise RuntimeError, "Too many duplicate names"
To use it on a particular node type, you just supply the right would-be name when calling apply_convention(). This would rename all the joints in the scene (naively!) to 'jnt_X' while keeping the suffixes unique. You'd do something smarter than that, like your original code did - this just makes sure that leaves are unique:
joint_names= get_unique_scene_names('joint')
existing = cmds.ls( type='joint', l = True)
existing .sort()
existing .reverse()
# do this to make sure it works from leaves backwards!
for item in existing :
apply_convention(item, 'jnt_', joint_names)
# check the uniqueness constraint by looking for how many items share a short name in the dict:
for d in joint_names:
print d, len (joint_names[d])
But, like i said, plan for those damn numeric suffixes, maya makes them all the time without asking for permission so you can't fight em :(
Instead of running ls for each and every name, you should run it once and store that result into a set (an unordered list - slightly faster). Then check against that when you run check_scene
def check_scene(self, name):
"""Checks entire scene for same name. If duplicate exists,
Keyword Arguments:
name -- (string) name of object to be checked
"""
if not hasattr(self, 'scene'):
self.scene = set(ls())
if name not in self.scene:
return name
else:
return ''