Advertisement
daniilak

Untitled

Mar 17th, 2022
765
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. # Есть не сортированный список операций:
  2. operations = [
  3.     {"id": 1, "timestamp": 2, "amount": 1},
  4.     {"id": 2, "timestamp": 4, "amount": 8},
  5.     {"id": 1, "timestamp": 3, "amount": 2}
  6. ]
  7.  
  8. # В этом списке операции дублируются по id
  9. # если так случилось, то правильной операцией считается та,
  10. # у которой timestamp более поздний
  11.  
  12. # Задача: модифицировать функцию filter, так чтобы она
  13. # возвращала только правильные операции
  14. # как только все тесты пройдут - задача решена
  15.  
  16. def filter(operations: list) -> list:
  17.   sortedOperations = sorted(operations, key=lambda d: int(d['timestamp']), reverse=True)
  18.   currentID = -1
  19.   res = []
  20.   for _, el in enumerate(sortedOperations):
  21.         if int(el['id']) == currentID:
  22.             continue
  23.         res.append(el)
  24.         currentID = int(el['id'])
  25.   return res
  26.  
  27.  
  28.  
  29. # Do not touch this
  30. test_data = [
  31.     {"in": [], "out": []},
  32.     {"in": [{"id":1, "timestamp": 2}], "out": [{"id":1, "timestamp": 2}]},
  33.     {"in": [{"id":1, "timestamp": 2}, {"id":1, "timestamp": 3}], "out": [{"id":1, "timestamp": 3}]},
  34.     {"in": [{"id":1, "timestamp": 5}, {"id":1, "timestamp": 4}], "out": [{"id":1, "timestamp": 5}]}
  35. ]
  36.  
  37. def test():
  38.   for i, t in enumerate(test_data):
  39.     try:
  40.       assert filter(t["in"]) == t["out"]
  41.       print(f"Test#{i} [ok]")
  42.     except Exception as e:
  43.       print(f"Test#{i} [error]")
  44.    
  45. test()
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement