[英]How do I analyze this code for time and space complexity? Ideas for removing those?
while True:
try:
income = int(input("Please enter your taxable income in india: "))
except ValueError:
print("Sorry, We didn't understand that please enter taxable income as a number")
continue
if income <= 250000: #2 Lakh 50 thousand
tax = 0
elif income <= 500000: #5 Lakh
tax = (income - 250000) * 0.05
elif income <= 750000: #7 lakh 50 thousand
tax = (income - 500000) * 0.10 + 12500
elif income <= 1000000: #10 Lakh
tax = (income - 750000) * 0.15 + 37500
elif income <= 1250000: #12 lakh 50 thousand
tax = (income - 1000000) * 0.20 + 75000
elif income <= 1500000: #15 lakh
tax = (income - 1250000) * 0.25 + 125000
else:
tax = (income - 1500000) * 0.30 + 187500
print("you owe", tax, "Rupees in tax!")
也許collections.OrderedDict
+ itertools.dropwhile
? Idk 新添加的模式匹配可用於此類,但因為它是我正在傳遞的相當新的功能。
基本上,這個解決方案甚至可能比您的代碼慢(如果鏈比您想象的要快),但以后可能更容易維護。
想法是:
float("inf")
,這樣我們就可以避免任何if
塊。 (所以任何數字都會有比自己大的密鑰)itertools.dropwhile
和lambda x: x <= input_num
所以我們跳過所有小於輸入的鍵。next()
到itertools.dropwhile
迭代器,因為我們只對鍵中的第一個較大的數字感興趣。>>> income_table = {
... 250000: (0, 0, 0),
... 500000: (250000, 0.05, 0),
... 750000: (500000, 0.1, 12500),
... 1000000: (750000, 0.15, 37500),
... 1250000: (1000000, 0.2, 75000),
... 1500000: (1250000, 0.25, 125000),
... float("inf"): (1500000, 0.3, 187500),
... }
... ordered_table = OrderedDict(income_table)
... else_case = (1500000, 0.3, 187500)
>>> import itertools
>>> def check_range(input_num: int) -> float:
... matching_ceiling = next(itertools.dropwhile(lambda x: x < input_num, ordered_table.keys()))
... subtract, multiplier, addition = income_table[matching_ceiling]
... return (input_num - subtract) * multiplier + addition
>>> # test -------------
>>> check_range(14000)
0
>>> check_range(1000000000)
299737500.0
>>> check_range(150000)
0
>>> check_range(1500000)
187500.0
>>> check_range(2500000)
487500.0
>>> check_range(250000)
0
>>> check_range(250001)
0.05
我看到您是 StackOverFlow 的新手,歡迎您,如果您還沒有,請花幾分鍾時間進行SO 之旅,了解有關 StackOverFlow 的提示和指南!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.