The input for price() would be STRINGS, as you see below. If the string starts with "-" I would like what follows to be stored in fiat_name and then retrieve the symbol from _KNOWN_FIAT_SYMBOLS. "--rub" (EXAMPLE) could be at any position in the list passed through price()
If the optional fiat_name does not exist in _KNOWN_FIAT_SYMBOLS i would like it to default to USD/$
I would like the code optimized and cleaned/minimized. I am trying to practice clean and read-able code.
import re
_KNOWN_FIAT_SYMBOLS = {"USD":"$", "RUB":"₽"} # this will be populated with more symbols/pairs later
def price(*arguments):
# default to USD/$
fiat_name = "USD"
arguments = list(arguments)
cryptos = []
for arg in arguments:
arg = arg.strip()
if not arg:
continue
for part in arg.split(","):
if part.startswith("-"):
fiat_name = part.upper().lstrip("-")
continue
crypto = re.sub("[^a-z0-9]", "", part.lower())
if crypto not in cryptos:
cryptos.append(crypto)
if not cryptos:
cryptos.append("btc")
fiat_symbol = _KNOWN_FIAT_SYMBOLS.get(fiat_name)
if not fiat_symbol:
fiat_name = "USD"
fiat_symbol = "$"
print(f"{cryptos} to: {fiat_name}{fiat_symbol}")
price("usd", "usdc", "--rub") # ['usd', 'usdc'] to: RUB₽ (becuase of the optional --rub)
price("usd,usdc,eth", "btc", "-usd") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase of the optional --usd)
price("usd", "usdc,btc", "-xxx") #['usd', 'usdc', 'btc'] to: USD$ (because xxx does not exist in _KNOWN_FIAT_SYMBOLS
price("usd,usdc,eth", "btc") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase no optional fiat_name was given)
price("usd,--rub,eth", "btc") # ['usd', 'eth', 'btc'] to: RUB₽ (becuase of the optional --rub)
price("--rub") # ['btc'] to: RUB₽ (becuase of the optional --rub and the cryptos is empty)
price("") # ['btc'] to: USD$ (becuase of the default USD and the cryptos is empty)