So this week has been crazy hectic in terms of assignments, essays, and presentations in general. That assignment #2 wasn't as bad the first one, in my opinion. But I'm sure there are different and more efficient ways of going about solving it. There is one thing that I learned when working on the second assignment, and was very disappointed by. Python doesn't have switch cases. WHY? You can read more about that here. But there are still numerous ways to go about comparing a variable to integral values.
1. Using if and elif blocks.
if variable == 1:
print ("One is a prime.")
elif variable == 2:
print ("Two is a prime.")
elif variable > 2:
print ("Prime numbers are only odd now!")
else: # similar to default
print ("Numbers!")
This is probably a common method and an easy one. Though it can get messy if you write really long if statements.
2. Using dictionaries (taking advantage of the fact that they are similar to associative arrays)
def check(var):
return {
1: 'one',
2: 'two',
3: 'three',
}.get(var, 'not important') # use get as default if x not found
or:
def zero():
return "Zero."
def one():
return "One."
def two():
return "Two."
def prime():
return "Prime numbers are odd now."
def check(var):
return {0 : zero(),
1 : one(),
2 : two()}.get(var, prime()) # use get as default if x not found
A third method would be to create your own class that acts similar to switch/case. That'd be good practice!
In terms of efficiency if/elif would probably be best as long as your not running complex expressions each time (just comparing two values, not calculating either of them). A dictionary could work, but you are now taking up extra memory and cpu cycles going through it. And if you do want to use if/elif with a complex expression, it will be more efficient since you'd run the expressions only until one returned true. In a dictionary you would have to preload all of them and use up all that ram and cpu power.
ReplyDelete