If I have multiple conditions (nested and/or otherwise) with boolean (either False or True) outputs; how could I further simplify the code and make it more efficient, comprehensive, and elegant?
For example, under such circumstances as follows:
if condition_1:
if condition_2:
# do one thing
pass
elif condition_3:
# do another thing
pass
else:
# do a third thing
pass
elif condition_2:
if condition_3:
# do a fourth thing
pass
and so on.
It's a exam project of mine, so not get too much help, I'll try and explain what my code should do.
I basically want to go through a dataset, looking for different things. Lets say its a dictionary, like this:
myDict = {'a': ['b', 'c'], 'b': ['c', 'd']}
If I go through the dict:
for item, element in myDict.items():
for letter in element:
if letter == 'd':
dflag = True
if letter == 'c':
cflag = True
if cflag:
if dflag:
print('cd!')
else:
print('only c')
Using 'if', 'elif', and 'else' is not bad if it is done efficiently. But in general, the answer to your question would really depend upon individual circumstances.
Having said that, however, one way to do it would be to put your conditions inside a dict (as highlighted by yourself in the tags).
Here are a few examples:
As a dict:
conditions = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: lambda x: x**2 # Can be substituted with actual functions defined elsewhere.
}
x = 3
if x in conditions.keys():
print(conditions[x])
returns:
Three
or in the case of a function:
x = 5
if x in conditions.keys():
func = conditions[x]
print(func(x))
returns:
25
Using a function to resemble switch...case:
To make it even clearer, and have something like a switch...case statement, you can do this:
def switch(case):
conditions = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: lambda x: x**2
}
return condition[case] if case in conditions else False
It is ran like so:
>>> print(switch(2))
2
or for a non-existent items:
>>> print(switch(6))
False
Implementation on your example:
switch...case function decorator (wrapper)
So to address the example you have added, we can do as follows:
First we need a general switch/case decorator:
def switch_case(switch):
def switcher(func):
def case(case):
return switch[case](case) if case in switch else None
return case
return switcher
Then we need a dictionary of our conditions, which are the one given in your example:
# Define the conditions in a dict.
conditions = {
'd': lambda x: True if 'd' else False, # You can say: True if 'a' or 'b' else False
'c': lambda x: True if 'c' else False
}
Now we Create a decorated switch-case function based on your conditions:
#switch_case(conditions)
def my_conditions(case):
return case
Then we specify the elements, or read them from a file, database or anything:
# Elements to be tested as string.
# It can be any flattened (not nested) iterable (str, tuple, list, numpy.array, etc.)
myDict = {'a': ['b', 'c'], 'b': ['c', 'd']}
elements = sum(myDict.values(), []) # Returns a flattened lists of values.
Evaluate the elements based on the conditions (generator object).
verdicts = map(my_conditions, elements)
Match the elements to the corresponding evaluation results (generator object).
status = zip(elements, verdicts)
Now we can positively regulate the outputs (discard None vlues) and create a dict in which the keys are the elements, and the values are the status of their conditions.
passed = {key+'flag': val for key, val in status if val is not None}
print(passed)
# output: {'cflag': True, 'dflag': True}
Add as variables to the namespace
At this point, you can use the dict as is; however, if you insist on adding it to the namespace, here is how:
# Rename values and add them to the name space.
locals().update(passed)
Test
Finally, let's test and ensure the values exist in the local namespace (notice that we haven't implemented any of these names before). So, if the condition returned a True value for the particular character in the sequence, a variable would have been created:
>>> print(dflag) # We had 'd' in `myDict` values.
True
On the other had, if the condition returned None, there will be no value in the namespace.
>>> print(aflag) # We didn't have 'a' in `myDict` values.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-26f7e9594747> in <module>()
24
---> 25 print(aflag)
NameError: name 'aflag' is not defined
Note: Under the existing structure, if the condition returns False, a variable will be created in the namespace and assigned a value of False.
Hope this helps.
Your code here about as simple as you can get.
The one way you can condense is by changing the last branch from:
elif flag2:
if flag3:
do a fourth thing
to
elif flag2 and flag3:
do a fourth thing
Have you considered refactoring? A well written function should do one thing, the fact you have three flags indicates this block of code is going to be doing AT LEAST 3 things, which brings in a lot of headaches for testing, code readability etc.
Are you sure this couldn't be refactored into three or more methods, check for the flags at the beginning and launch the corresponding methods.
You can use an iterator over flags. A dictionary could work too, depending on what your flags are, but it wouldn't really help if your flags are something like x==1, y==10, z=='a' that could all evaluate to a True or False only (because the keys can only be unique). If your flags are in the form of a == b you'd probably have to go with some sort of iterator.
def f(): print('f')
def g(): print('g')
def h(): print('h')
y = 3
x = 2
flags = [
# Outer condition
(y==1, (
# Inner conditions and actions
(x==1, f), (x==2, g), (x==3, h)
)),
(y==3, (
(x==1, g), (x==2, f), (x==3, h)
))
]
# Using next ensures that the rest of the flags/actions aren't even evaluated,
# the same way an if/elif would work
_, inner_flags_and_actions = next(
(flag, inner) for (flag, inner) in flags if flag
)
_, action = next(
(flag, action) for (flag, action) in inner_flags_and_actions if flag
)
# By now you have reached the action you want to take.
action()
This prints: f
You can use a dict :
d = { (False, False, False) : f1,
(False, False, True) : f2,
(False, True, False) : f3,
(False, True, True) : f4
...
Then call d[(flag1,flag2,flag3)]()
This is if you need an industrial amount of if/elses, otherwise just try to make the right simplifications.
Of course, if you are testing agains the same entry variable, or applying the same function with different parameters as output, then you can simplify even more by replacing booleans and functions with actual data.
Related
I have a more different type of keys in dict (there is no need to type values too)
'PL-1/KK-1/FO-1'
'PL-1/KK-2/GH-3'
'PL-1/KK-2'
'PL-1/KK-1/FO-4'
And I need a condition
if exist (key.split('/')[2])
do something
return data
else:
do something
return data
Desired output:
In the first condition, all keys make entries except 'PL-1/KK-2'.
Is there in python something like 'exist'?
No, there is no 'exists' operator.
In your case you should just test slashes:
if key.count('/') >= 2:
# ...
If you need to have the components of the key, store and test the length:
components = key.split('/')
if len(components) >= 2:
# ...
def has_key(i_dict, i_filter):
return any(k for k in i_dict.iterkeys() if i_filter(k))
# be it a dict called my_dict
# you could call it like
has_key(my_dict, lambda x: x.count("/") == 2)
# or
has_key(my_dict, lambda x: len(x.split("/"))==2)
here's a little test
>>> my_dict = {"a":1,"c":3}
>>> has_key(my_dict, lambda k:k=="a")
True
>>> has_key(my_dict, lambda k:k=="c")
True
>>> has_key(my_dict, lambda k:k=="x")
False
I'm writing some printouts for the debug mode of a script. Is there a compact way to print the names of those variables in a list that meet a condition?
specification_aw3 = 43534
specification_hg7 = 75445
specification_rt5 = 0
specification_nj8 = 5778
specification_lo4 = 34
specification_ee2 = 8785
specification_ma2 = 67
specification_pw1 = 1234
specification_mu6 = 0
specification_xu8 = 12465
specifications = [
specification_aw3,
specification_hg7,
specification_rt5,
specification_nj8,
specification_lo4,
specification_ee2,
specification_ma2,
specification_pw1,
specification_mu6,
specification_xu8
]
if any(specification == 0 for specification in specifications):
# magic code to print variables' names
# e.g. "variables equal to 0: \"specification_rt5\", \"specification_mu6\"
Just as 9000 suggests, it goes without saying that defining a dictionary is a rational approach for the minimal working example I have defined here. Please assume that this is not a feasible option for the existing code project and that I am looking for a quick, compact (plausibly ugly) bit of code to be used solely for debugging.
EDIT: illustration of something similar to what I want
So here's the beginnings of what I'm looking for:
print("specifications equal to zero:")
callers_local_objects = inspect.currentframe().f_back.f_locals.items()
for specification in [specification for specification in specifications if specification == 0]:
print([object_name for object_name, object_instance in callers_local_objects if object_instance is specification][0])
Basically, is there a compact way to do something like this?
I suggest that instead of a bunch of variables you use a dict:
specification = {
'aw3': 0,
'foo': 1,
'bar': 1.23,
# etc
}
You can access things by name like specification['aw3'].
Then you can find out names for which the value is 0:
zeroed = [name for (name, value) in specification.items() if value == 0]
In addition, since you mentioned printing the line would be:
for element in specification_dictionary:
print(element)
where you can combine it with a list comprehension as above for printing only the elements that meet your case. Element in this case only prints the variable name (key) if you want both the key and value just set it to use specification_dictionary.items(). Cheers.
>>> specification = { 'aw3': 0, 'foo': 1}
>>> for element in specification:
... print(element)
...
foo
aw3
>>> for (key, value) in specification.items():
... print(str(key) + " " + str(value))
...
foo 1
aw3 0
>>> for element in specification.items():
... print(element)
...
('foo', 1)
('aw3', 0)
Basically I'm looking for an implementation of itertools.product that allows me to change the order in which the combinations are generated.
Example: If I use itertools.product('AB', 'xy') it generates the combinations in this exact order:
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y')]
I need an implementation that responds to requests like "Please change A to B next", for example like this:
>>> generator = DynamicOrderProduct({'var1': 'AB', 'var2': 'xy'})
>>> generator.first()
{'var1': 'A', 'var2': 'x'}
>>> generator.change('var1')
{'var1': 'B', 'var2': 'x'}
>>> generator.change('var2')
{'var1': 'B', 'var2':, 'y'}
>>> generator.change('var2') # here it can't generate a new combination by
# changing var2, so it changes var1 instead
{'var1': 'A', 'var2': 'y'}
>>> generator.change('var2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Ideally, the generator would accept a list of variables like this:
generator.change(['var1', 'var2'])
It should then attempt to change the value of var1, and if that isn't possible, change the value of var2 instead, and so on.
How would I go about implementing this? Is there something in the standard lib that can help me?
Alright, I've managed to write an iterator that does what I want. It's the ugliest piece of code I've ever written, but it gets the job done.
I'm still hoping for a better solution though - this implementation keeps a set of all returned combinations, which can grow to use quite a bit of memory.
class DynamicOrderProduct:
"""
Given a dict of {variable: [value1,value2,value3,...]}, allows iterating
over the cartesian product of all variable values.
Each step in the iteration returns a mapping of {variable: value}.
To start the iteration, retrieve the first mapping by calling .first().
To retrieve subsequent mappings, call
.next(order_in_which_to_change_variable_values). This function's
parameter should be a list of variables sorted by which variable's value
should change next. If possible, the first variable in the list will
change value. If not, the 2nd variable in the list will change value
instead, and so on. Raises StopIteration if all combinations are
exhausted.
Example:
possible_values = {'B': [0,1], # B can take the value 0 or the value 1
'L': [1,2,3]}
iterator = DynamicOrderProduct(possible_values)
print(iterator.first())
import random
variables = list(possible_values.keys())
while True:
order = random.sample(variables, len(variables))
print('advancing variables in this order:', order)
try:
print(iterator.next(order))
except StopIteration:
break
You may also pass an incomplete list of variables to the .next function.
If no new combination of the given variables is possible, StopIteration is
raised. For example:
iterator = DynamicOrderProduct({var1: [1],
var2: [1,2]})
iterator.first() # this returns {var1: 1, var2: 1}
iterator.next([var1]) # raises StopIteration
Also, you may pass multiple lists to .next in order to change the value of
multiple variables. StopIteration will be raised only if no variable can
change value.
iterator = DynamicOrderProduct({var1: [1,2],
var2: [1,2]})
iterator.first() # this returns {var1: 1, var2: 1}
iterator.next([var1], [var2]) # returns {var1: 2, var2: 2}
"""
def __init__(self, possible_variable_values):
self.possible_variable_values = {k:tuple(v) for k,v in \
possible_variable_values.items()}
self.variable_order = list(possible_variable_values)
self.exhausted_combinations = set()
def first(self):
self.mapping = {var:vals[0] for var,vals in \
self.possible_variable_values.items()}
t = tuple(self.mapping[var] for var in self.variable_order)
self.exhausted_combinations.add(t)
return self.mapping
def next(self, *orders):
def advance(order, index, maxindex=2147483648):
while True: # loop to reduce recursion
try:
variable = order[index]
except IndexError:
raise StopIteration
value = self.mapping[variable]
valindex = self.possible_variable_values[variable].index(value)
start_index = valindex
while True: # change the value until we find a new combination
valindex += 1
try:
possible_values = self.possible_variable_values
value = possible_values[variable][valindex]
except IndexError:
valindex = 0
value = self.possible_variable_values[variable][0]
self.mapping[variable] = value
# if we've tried all values but none of them
# worked, try to change the next variable's
# value instead
if valindex == start_index:
if index+1 >= maxindex:
raise StopIteration
# instead of recursing, update our own parameters and
# start a new iteration
index += 1
break
t = tuple(self.mapping[var] for var in self.variable_order)
# if this combination isn't new, try
# changing the previous variables' values
if t in self.exhausted_combinations:
if index == 0:
continue
try:
return advance(order, 0, index)
except StopIteration:
continue
return t
total_order = []
fail = True
for order in orders:
# each iteration may also change the previous
# iterations' variables
total_order = order + total_order
try:
t = advance(total_order, 0)
except StopIteration:
fail = True
else:
fail = False
if fail:
raise StopIteration
self.exhausted_combinations.add(t)
return self.mapping
I have a list of dictionaries. Each dictionary has certain boolean flags. So, the list looks like -
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
Let's say I have a table, that assigns scores based on the combination of values of the flags. It's like a binary truth table:
flag1 True True False False
flag2 True False True False
score 1 2 3 4
I now want to iterate through the list, and assign these scores to each dictionary in the list, based upon the combination they specify. Is there an elegant way to do it, instead of if else loops? I have a lot of flags, and the combinations would increase with every new flag that's added - result - the code is just ugly.
You can use a dictionary for this:
scores = {(True, True): 1, (True, False): 2,
(False, True): 3, (False, False): 4}
Now you can find the score by simply looking up scores[flag1, flag2].
To do this on the whole list, use
for d in listA:
d["score"] = scores[d["flag1"], d["flag2"]]
Suppose that you have a function f that assigns these scores (it's not obvious how you do it in the above example) given a list of flags, then you can do:
for myDict in myList:
score = f(myDict['flag1], myDict['flag2'])
if you want to generalize this to an arbitrary number of flags:
def score(L):
""" This function takes a list of bools and returns a score.
In this case, the score is simply the number of bools that are True """
return sum(L)
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
for d in listA:
print "The score of", d, "is:", \
score([f for f,b in d.iteritems() if type(b) == bool])
I have a TList which is a list of lists. I would like to add new items to the list if they are not present before. For instance if item I is not present, then add to Tlist otherwise skip.Is there a more pythonic way of doing it ? Note : At first TList may be empty and elements are added in this code. After adding Z for example, TList = [ [A,B,C],[D,F,G],[H,I,J],[Z,aa,bb]]. The other elements are based on calculations on Z.
item = 'C' # for example this item will given by user
TList = [ [A,B,C],[D,F,G],[H,I,J]]
if not TList:
## do something
# check if files not previously present in our TList and then add to our TList
elif item not in zip(*TList)[0]:
## do something
Since it would appear that the first entry in each sublist is a key of some sort, and the remaining entries are somehow derived from that key, a dictionary might be a more suitable data structure:
vals = {'A': ['B','C'], 'D':['F','G'], 'H':['I','J']}
if 'Z' in vals:
print 'found Z'
else:
vals['Z'] = ['aa','bb']
#aix made a good suggestion to use a dict as your data structure; It seems to fit your use case well.
Consider wrapping up the value checking (i.e. 'Does it exist?') and the calculation of the derived values ('aa' and 'bb' in your example?).
class TList(object):
def __init__(self):
self.data = {}
def __iter__(self):
return iter(self.data)
def set(self, key):
if key not in self:
self.data[key] = self.do_something(key)
def get(self, key):
return self.data[key]
def do_something(self, key):
print('Calculating values')
return ['aa', 'bb']
def as_old_list(self):
return [[k, v[0], v[1]] for k, v in self.data.iteritems()]
t = TList()
## Add some values. If new, `do_something()` will be called
t.set('aval')
t.set('bval')
t.set('aval') ## Note, do_something() is not called
## Get a value
t.get('aval')
## 'in ' tests work
'aval' in t
## Give you back your old data structure
t.as_old_list()
if you need to keep the same data structure, something like this should work:
# create a set of already seen items
seen = set(zip(*TList)[:1])
# now start adding new items
if item not in seen:
seen.add(item)
# add new sublist to TList
Here is a method using sets and set.union:
a = set(1,2,3)
b = set(4,5,6)
c = set()
master = [a,b,c]
if 2 in set.union(*master):
#Found it, do something
else:
#Not in set, do something else
If the reason for testing for membership is simply to avoid adding an entry twice, the set structure uses a.add(12) to add something to a set, but only add it once, thus eliminating the need to test. Thus the following:
>>> a=set()
>>> a.add(1)
>>> a
set([1])
>>> a.add(1)
>>> a
set([1])
If you need the set elsewhere as a list you simply say "list(a)" to get "a" as a list, or "tuple(a)" to get it as a tuple.