'Use threshold values in an if-else block as a key for a dictionary
My current if-else block looks like this -
def do_something(value):
if value <= 0:
return 1
elif value > 0 and value < 5:
return 2
else:
return 3
Please note that the example is not a direct representation of my code. I have significantly reduced the number of if-else blocks for the sake of brevity. What I would like to do is create a dictionary that can hold the threshold values for each condition as a key. Here's an example of what i mean by this.
dict_factory_pattern = {
0: 1,
1-4: 2,
5-inf: 3
}
# With the dictionary structure above I want to refactor my do_something () to as shown below
def do_something(value):
return dict_factory_pattern[value]
Is this possible?
Solution 1:[1]
To reduce the amount of code, you could declare the threshold values in a dict and iterate over them. This is essentially the same as having multiple if statements, except you don't have to spell them out yourself. You do however loose the flexibility of multiple conditions since the same comparison (e.g. less than or equal) is applied to all threshold values. The compactness of the rule set may be worth it.
thresholds = {
0: 1,
5: 2,
float('inf'): 3,
}
def find_value(n):
for threshold, result in thresholds.items():
if n <= threshold:
return result
[find_value(n) for n in [-0.5, 0, 0.5, 10]] # gives [1, 1, 2, 3]
Solution 2:[2]
Dictionary cannot do such thing. The selection alone can be done by a conditional. Assume your input is value
value = int(input("input value"))
res = 1 if value <= 0 else 2 if 1 <= value <= 4 else 5
I notice it's a factory pattern you are concerning. So for example you have three Object you want to create (build) then do
class FrogWorld:
pass
class Wizard:
pass
class StreetFighter:
pass
value = int(input("input value"))
res = FrogWorld if value <= 0 else Wizard if 1 <= value <= 4 else StreetFighter
res will be the made now. This is just a short answer. It can be more elaborate expression for this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Yehui He |
