How to name a list variable with ending "s" [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
How should one name a list variable with ending s:
fpss,frame_rates, audios,
or
fps_records = []
frame_rate_records = []
audio_records = []

I don't think adding _records to the end adds anything of value. Avoid adding length to names that don't add clarity or insight for future reviewers, which will certainly include yourself. Adding meaningless verbiage will only serve to make your code harder to read and therefore harder to maintain.
If you think you're going to look at fps later and forget it's a list, use fps_list, which directly tells what type it is to any reader.
Please no-one interpret me as suggesting Hungarian notation. But I do do this when I'm starting out with a list, realize order doesn't matter and I need set-like behavior, and then realize I actually needed a mapping in the first place. Using that sort of convention allows me to implement my new structure completely without breaking the old.
For example, see this Python-style pseudo-code:
Iteration 1
def foo():
data = []
get_data_from_source()...
Iteration 2
def foo():
data_list = []
data_set = set()
get_data_from_source()...
Iteration 3
def foo():
data_set = set()
data_dict = {}
get_data_from_source()...
Iteration 4
def foo():
data = {}
get_data_from_source()...
return data

I agree with #Arone, however if required I would go with adding lst(like lst_records) with list(same we follow in legacy lang like vb) variables so if you would start typing lst immediately IDE would start suggesting all list.

Related

How do I check if a string contains ANY element in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to detect if a string contains any element in an array. I want to know if the string(msg) has any element from the array(prefixes) in it.
I want this because I want to make a discord bot with multiple prefixes, heres my garbage if statement.
if msg.startswith(prefixes[any]):
The existing answers show two ways of doing a linear search, and this is probably your best choice.
If you need something more scalable (ie, you have a lot of potential prefixes, they're very long, and/or you need to scan very frequently) then you could write a prefix tree. That's the canonical search structure for this problem, but it's obviously a lot more work and you still need to profile to see if it's really worthwhile for your data.
Try something like this:
prefixes = ('a','b','i')
if msg.startswith(prefixes):
The prefixes must be tuple because startswith function does not supports lists as a parameter.
There are algorithms for such a search, however, a functional implementation in Python may look like this:
prefixes = ['foo', 'bar']
string = 'foobar'
result = any(map(lambda x: string.startswith(x), prefixes))
If you search for x at any position in string, then change string.startswith(x) to x in string.
UPDATE
According to #MisterMiyagi in comments, the following is a more readable (possibly more efficient) statement:
result = any(string.startswith(prefix) for prefix in prefixes)

Assign functions to variables, and use random on them [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Thanks for taking the time to ready thru my question.
At the moment I'm creating a method for a class, and below is what I've got so far.
def scramble_words_password(self, words):
if words:
words = words.split()
words_count = range(len(words))
while True:
num = random.choice(words_count)
del(words_count[num])
password = [letter for letter in list(words[num])]
A few months ago i came across a tutorial, that explained how to assing functions to variables, and use something like random on them but i cant find it again...
What I want in my function/method is a way to randomly use letter.lower() and letter.upper() on the comprehension on the bottom line of my function/method, but how can i achieve that and still keep it all in the comprehension.
FYI, I know that the function ATM is an infinity loop, so no smart remarks please ;)
User random.choice over a list of methods to call:
def scramble_words_password(self, words):
if words:
words = words.split()
words_count = range(len(words))
words_funcs = [str.upper, str.lower]
while True:
num = random.choice(words_count)
del(words_count[num])
password = [random.choice(words_funcs)(letter) for letter in list(words[num])]
Main call explain, random.choice(words_funcs)(letter), will choose a random element from the list, as they are callables you can just pass the letter to them. Keep in mind that all methods from strings (also other built-in types) can be called statically, so a list with str.lower and str.upper will do.
Function names act much like variables. You can pass them into other functions as parameters or make a list of functions. I suggest you create a list of functions and randomly select a list element.

How to convert a python list with string element without quotes to a proper list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Consider this list:
list1 = [home , school, ground, field]
As you can see that the elements of list are string without quotes, so this is an invalid list. Is there any way to convert this to proper list using python?
The list should look like this:
list1 = ['home' , 'school', 'ground', 'field']
Yeah, technically you can do it like this:
done = False
while not done:
try:
list1 = [home , school, ground, field]
except NameError as e:
varname = str(e).split("'")[1]
locals()[varname] = varname
else:
done = True
print(list1)
# ['home', 'school', 'ground', 'field']
but I wouldn't recommend it.
Maybe you could write a decorator that turns every NameError into a variable and re-runs whatever scope the code was run in, hopefully a function... but honestly... you're just going to turn your code into an unmaintainable, complicated mess.
Also, how would this code get written in the first place? Unless your scripts are templates which are generated by other programs... in which case, why not generate them correctly? :P

Is there a Python convention to avoid long lines of code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Should I create variables just to avoid having long lines of code? For example, in the code below the variable stream_records is only used once after it's set.
stream_records = stream.get_latest_records( num_records_to_correlate ).values('value')
stream_values = [float(record['value']) for record in stream_records]
Should I have done this instead?
stream_values = [float(record['value']) for record in stream.get_latest_records( num_records_to_correlate ).values('value')]
I am trying to optimize for readability. I'd love some opinions on whether it's harder to have to remember lots of variable names or harder to read long lines of code.
EDIT:
Another interesting option to consider for readability (thanks to John Smith Optional):
stream_values = [
float(record['value'])
for record in stream.get_latest_records(
num_records_to_correlate
).values('value')
]
PEP 8 is the style guideline from the beginning of Python, and it recommends that no source lines be longer than 79 characters.
Using a variable for intermediate results also performs a kind of documentation, if you do your variable naming well.
Newlines (carriage return) inside parentheses count as blank.
The same applies to newlines inside brackets, as pointed out by Bas Swinckels.
So you could do something like that:
stream_values = [
float(record['value'])
for record in stream.get_latest_records(
num_records_to_correlate
).values('value')
]
You can also use \ to continue a statement on the following line.
For example:
long_variable_name = object1.attribute1.method1(arg1, arg2, arg3) + \
object2.attribute2.method2(arg1, arg2, arg3)
the first one is definitely easier to read so if there are no performance concerns I would totally go for more variables as long as they have self-explanatory names. it's also way easier to debug if somebody (not you) has to.
The first one is indeed more readable. Creating a variable doesn't cost you a lot here, so you can leave your code with it. Plus, if you are debugging it, it will be much easier to see if the error comes from the call of get_latests_records or from your list comprehension.
However, another way nice way would be to construct your list with the map function:
stream_values = map(lambda x: float(x['value']),
stream.get_latest_records(num_records_to_correlate) \
.values('value')])
The lambda here is necessary, to apply float on the correct value of the dictionary. As you can see, I have limited the number of chars per line to respect the PEP8 convention, which can help to make the code readable too.

using split for appending to multiple lists [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to combine the two statements inside 'for' loop.
num_pro=raw_input("ENTER THE NUMBER OF PRODUCTIONS: ")
right=[];left=[];
for i in range(int(num_pro)):
l,r=raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->')
right.append(r);left.append(l)
sample input: E->abc
Append tuples to one list, then split out the lists using zip():
entries = []
for i in range(int(num_pro)):
entries.append(raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->'))
left, right = zip(*entries)
zip(*iterable) transposes the nested list; columns become rows. Because you have two 'columns' (pairs of values), you end up with two rows instead.
Not without making it more complex. Each method needs to be called individually, and the only way to do that is either explicitly, as you have done, or in a loop.
If you are willing to store the whole production (which isn't necessarily a bad idea, since it keeps both sides synchronized) then just append the split result instead.
productions = []
for ...
productions.append(....split('->'))

Categories