簡體   English   中英

如何分析此代碼的時間和空間復雜度? 刪除這些的想法?

[英]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 新添加的模式匹配可用於此類,但因為它是我正在傳遞的相當新的功能。

基本上,這個解決方案甚至可能比您的代碼慢(如果鏈比您想象的要快),但以后可能更容易維護。

想法是:

  1. 將用於計算相應稅收范圍的 3 個值的元組作為鍵。
  2. 也放float("inf") ,這樣我們就可以避免任何if塊。 (所以任何數字都會有比自己大的密鑰)
  3. 制作有序字典以確保鍵在迭代時始終按遞增順序排列。
  4. 使用itertools.dropwhilelambda x: x <= input_num所以我們跳過所有小於輸入的鍵。
  5. 調用next()itertools.dropwhile迭代器,因為我們只對鍵中的第一個較大的數字感興趣。
  6. 解包元組並進行計算
>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM