enkryptor

Untitled

Feb 21st, 2022
823
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. def variant1(s):
  2.   characters=['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
  3.   for c in characters:
  4.     s = s.replace(f'{c}', f'\\{c}')
  5.   return s
  6.  
  7.  
  8. escaped = "_*[]()~`>#+-=|{}.!"
  9.  
  10. def escape(c):
  11.    return '\\'+c if c in escaped else c
  12.  
  13. def variant2(s):
  14.    return ''.join(map(escape, s))
  15.  
  16.  
  17. import re
  18.  
  19. escaped_re = r"[_\*\[\]\(\)\~`\>#\+-=\|\{\}\.!]"
  20.  
  21. def replace(matchobj):
  22.   return f"\\{matchobj.group(0)}"
  23.  
  24. def variant3(s):
  25.    return re.sub(escaped_re, replace, s)
  26.  
  27.  
  28. test_data = """
  29. Hello! Escape testing (some cases).
  30. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  31. Hello! Escape testing (some cases).
  32. """
  33.  
  34. import time
  35.  
  36. def measure(f, arg):
  37.    start_time = time.perf_counter_ns()
  38.    result = f(arg)
  39.    print("--- %s ns ---" % (time.perf_counter_ns() - start_time))
  40.    return result
  41.  
  42. print(measure(variant1, test_data)) # 13900 ns
  43. print(measure(variant2, test_data)) # 66800 ns
  44. print(measure(variant3, test_data)) # 233800 ns
  45.  
Advertisement
Add Comment
Please, Sign In to add comment