我已经调查过了,但是我找不到任何对我有帮助的东西(如果有类似的答案,我很抱歉)。我正在编写一个货币转换器,它有大量的if
代码,看起来效率不高,也无法想象可读性很好,因此我想知道如何在这种情况下编写更高效的代码:
prompt = input("Input") #For currency, inputs should be written like "C(NUMBER)(CURRENCY TO CONVERT FROM)(CURRENCY TO CONVERT TO)" example "C1CPSP"
if prompt[0] == "C": #Looks at first letter and sees if it's "C". C = Currency Conversion
#CP = Copper Piece, SP = Silver Piece, EP = Electrum Piece, GP = Gold Piece, PP = Platinum Piece
ccint = int(''.join(list(filter(str.isdigit, prompt)))) # Converts Prompt to integer(Return string joined by str.(Filters out parameter(Gets digits (?), from prompt))))
ccalpha = str(''.join(list(filter(str.isalpha, prompt)))) #Does the same thing as above expect with letters
if ccalpha[1] == "C": #C as in start of CP
acp = [ccint, ccint/10, ccint/50, ccint/100, ccint/1000] #Array of conversions. CP, SP, EP, GP, PP
if ccalpha[3] == "C": #C as in start of CP
print(acp[0]) #Prints out corresponding array conversion
if ccalpha[3] == "S": #S as in start of SP, ETC. ETC.
print(acp[1])
if ccalpha[3] == "E":
print(acp[2])
if ccalpha[3] == "G":
print(acp[3])
if ccalpha[3] == "P":
print(acp[4])
if ccalpha[1] == "S":
asp = [ccint*10, ccint, ccint/10, ccint/10, ccint/100]
if ccalpha[3] == "C":
print(asp[0])
if ccalpha[3] == "S":
print(asp[1])
if ccalpha[3] == "E":
print(asp[2])
if ccalpha[3] == "G":
print(asp[3])
if ccalpha[3] == "P":
print(asp[4])
if ccalpha[1] == "E":
aep = [ccint*50, ccint*5 ,ccint , ccint/2, ccint/20]
if ccalpha[3] == "C":
print(aep[0])
if ccalpha[3] == "S":
print(aep[1])
if ccalpha[3] == "E":
print(aep[2])
if ccalpha[3] == "G":
print(aep[3])
if ccalpha[3] == "P":
print(aep[4])
if ccalpha[1] == "G":
agp = [ccint*100, ccint*10, ccint*2, ccint, ccint/10]
if ccalpha[3] == "C":
print(agp[0])
if ccalpha[3] == "S":
print(agp[1])
if ccalpha[3] == "E":
print(agp[2])
if ccalpha[3] == "G":
print(agp[3])
if ccalpha[3] == "P":
print(agp[4])
if ccalpha[1] == "P":
app = [ccint*1000, ccint*100, ccint*20, ccint*10, ccint]
if ccalpha[3] == "C":
print(app[0])
if ccalpha[3] == "S":
print(app[1])
if ccalpha[3] == "E":
print(app[2])
if ccalpha[3] == "G":
print(app[3])
if ccalpha[3] == "P":
print(app[4])
另一种方法是使用矩阵(实际上只是列表列表):
首先创建货币换算矩阵。 然后用一个数字来匹配货币(在其他语言如C或Java中非常像
enum
)。为此,您可以使用字典:它类似于一个列表,只是您定义了索引(它不是从0到长度-1)。 然后你得到适当的转换率,乘以你的数字,然后打印出来。你知道吗这和MSeifert答案非常相似,只是你用的字典少了一些,所以如果你对这些不太熟悉的话,可能更容易理解。你知道吗
您可以始终使用词典进行查找:
那么你所有的
if
基本上都包含在:但是,是否可能包含其他字符?然后你需要引入一个后备策略:
如前所述,它不是最有效的方法,因为它每次都计算每个转换(甚至是不必要的转换)。有一个基线(例如
P
)并保存因子可能更有效:与其直接从源单元转换到目标单元,不如分两步进行:
这个代码就是你所需要的。你可以这样称呼它:
相关问题 更多 >
编程相关推荐