Advertisement
MrMarvel

Router sorting

Jun 2nd, 2023 (edited)
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | Source Code | 0 0
  1. The best strategy is divide process to 3 parts:
  2. Read
  3. Sort
  4. Print
  5.  
  6. Reading from and filling data list can be done via raw list of lists or list of objects like I made in example below.
  7. Sorting you can make via bultin sorted function and key argument or use another way.
  8. Printing the result, I don't sure how it must shown so I printed content without formatting, but you can change it.
  9.  
  10. ```python
  11. from functools import cmp_to_key
  12. from operator import attrgetter
  13.  
  14.  
  15. class Router:
  16.    def __init__(self, name, wifi_spec, memory, price):
  17.        self.name = str(name)
  18.        self.wifi_spec = str(wifi_spec)
  19.        self.memory = int(memory)
  20.        self.price = int(price)
  21.  
  22.  
  23. def router_cmp(r1: Router, r2: Router):
  24.    # 1 - worse
  25.    # -1 - better
  26.    # 0 - tie
  27.    if r1.price > r2.price:
  28.        return 1
  29.    if r1.price < r2.price:
  30.        return -1
  31.    if r1.memory < r2.memory:
  32.        return 1
  33.    if r1.memory > r2.memory:
  34.        return -1
  35.    if r1.name > r2.name:
  36.        return 1
  37.    if r1.name < r2.name:
  38.        return -1
  39.    return 0
  40.  
  41.  
  42. def main():
  43.    router_list = []
  44.    # Input data
  45.    with open('routers.txt') as f:
  46.        for line in f.readlines():
  47.            name, wifi_spec, memory, price = line.split(',')
  48.            if wifi_spec in 'Wi-Fi 6' or wifi_spec in '802.11ax' or wifi_spec in 'ax' or wifi_spec in 'WiFi 6':
  49.                if 'MiB' in memory:
  50.                    m1 = int(memory[:-3])
  51.                    memory = m1 * 1024
  52.                elif 'GiB' in memory:
  53.                    m2 = int(memory[:-3])
  54.                    memory = m2 * 1024 * 1024
  55.            router = Router(name, wifi_spec, memory, price)
  56.            router_list.append(router)
  57.    # Sort data
  58.    sorted_router_list = sorted(router_list, key=cmp_to_key(router_cmp))
  59.    # Print data
  60.    for router in sorted_router_list:
  61.        print(router.name, router.wifi_spec, router.memory, router.price, sep=',')
  62.  
  63.  
  64. if __name__ == '__main__':
  65.    main()
  66.  
  67. ```
  68.  
  69. For example:
  70. ```txt
  71. Router1,Wi-Fi 6,802MiB,10500
  72. Router2,Wi-Fi 6,123MiB,13500
  73. Router3,Wi-Fi 6,2GiB,10500
  74. Router4,Wi-Fi 6,2GiB,10500
  75. ```
  76.  
  77. The output:
  78. ```txt
  79. Router3,Wi-Fi 6,2097152,10500
  80. Router4,Wi-Fi 6,2097152,10500
  81. Router1,Wi-Fi 6,821248,10500
  82. Router2,Wi-Fi 6,125952,13500
  83. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement