I try to avoid writing If-else
or match-case
statements as much as possible. I'll explain why in future posts. So, what should you write instead?
Of course, it depends on the situation, but for many of the problems I encounter, I’ve solved them using a hashmap. Imagine you have a problem with specific or limited values. You need to solve it without writing if-else
statements. For example, let’s say you need to check if a number is divisible by 2, and if it is, print "even", otherwise print "odd". What would you do?
Here’s how I would approach it:
hashmap = {
0: "even"
}
number = int(input("Enter a number: "))
print(hashmap.get(number % 2, "odd"))
Now, let's make the problem a bit more complex. You're building a system for currency conversion. The user enters an amount, from currency, and to currency, and you need to calculate the conversion without using if-else
statements.
For example, here’s the data the user enters:
Amount: 24
From: USD
To: UZS
Now, you need to convert $24 into Uzbek Som (UZS). How would you do it?
Here’s my solution:
# Store the conversion rate for 1$ for each currency
currencies = {
"USD": 1,
"UZS": 11300,
"RUB": 90,
"EUR": 0.85,
}
# Conversion methods
convert = {
"TO_USD": lambda amount, rate: amount / rate,
"FROM_USD": lambda amount, rate: amount * rate,
}
# User input part
amount = float(input("Amount: "))
from_currency = input("From: ").upper()
to_currency = input("To: ").upper()
# Convert the amount to USD first, then convert it to the desired currency
in_usd = convert["TO_USD"](amount, currencies[from_currency])
# Now convert the USD amount to the target currency
result = convert["FROM_USD"](in_usd, currencies[to_currency])
print(result)
Think about lazy solutions like this. I’m glad if this was helpful!