Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1.  
  2. #!/usr/bin/env python -tt
  3. """ File: kv_store.py """
  4.  
  5.  
  6. class TimedKVStore:
  7. """Summary line: The class is a key value structure that stores the time a values is added
  8. Description: The structure is initalised as a dictionary with a list as a value. This allows
  9. key value strusture as well as a sortable list for the values. The put method adds a list to
  10. in the key position, stotring the input value and the time. The get method will get the
  11. most resent added value or if a time is given the value just before the given time.
  12. """
  13.  
  14. def __init__(self):
  15. self.dict = defaultdict(list)
  16.  
  17.  
  18. def put(self, key, value):
  19. self.dict[key].append( [value, time.time()] )
  20.  
  21.  
  22. def get(self, key, time=0):
  23. xx = 0
  24. if time:
  25. for x in self.dict[key]:
  26. if self.dict[key][xx][1] < time:
  27. return self.dict[key][xx][0]
  28. xx += 1
  29.  
  30.  
  31. return None
  32.  
  33. return self.dict[key][len(self.dict['1']) - 1][0]
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40. if __name__ == '__main__':
  41. """Summary line: Display the TimedKVStore class usage.
  42. Description: Display the TimedKVStore class usage.
  43. """
  44.  
  45. from collections import defaultdict
  46. import time
  47.  
  48.  
  49. d = TimedKVStore()
  50.  
  51. t0 = time.time()
  52. d.put("1", 1)
  53.  
  54. # Add delay because computer executes statemnets nearly sumiltaniously
  55. time.sleep(0.1)
  56.  
  57. t1 = time.time()
  58. d.put("1", 1.1)
  59.  
  60. print d.get("1") # 1.1
  61. print d.get("1", t1) # 1
  62. print d.get("1", t0) # None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement