# Untitled

By: a guest on Jul 15th, 2012  |  syntax: None  |  size: 1.26 KB  |  hits: 10  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1.
2. import timeit
3. import struct
4.
5. string = "ABCDEFGH"
6.
7. # Expected resutlt => GHEFCDAB
8.
9. def rev(a):
10.     new = ""
11.
12.     for x in range(-1, -len(a), -2):
13.         new += a[x-1] + a[x]
14.
15.     return new
16.
17. def rev2(a):
18.     return "".join(reversed([a[i:i+2] for i in range(0, len(a), 2)]))
19.
20. def rev3(a):
22.
23. def rev4(a):
24.     return "".join(map("".join, reversed(zip(*[iter(a)]*2))))
25.
26.
27. def rev5(a):
28.     n = len(a) / 2
29.     fmt = '%dh' % n
30.     return struct.pack(fmt, *reversed(struct.unpack(fmt, a)))
31.
32. def rev6(a):
33.     return "".join([a[x:x+2] for x in range(0,len(a),2)][::-1])
34.
35.
36. print "Greg Hewgill %f" %timeit.Timer("rev2(string)", "from __main__ import rev2, string").timeit(100000)
37. print "gnibbler %f" %timeit.Timer("rev3(string)", "from __main__ import rev3, string").timeit(100000)
38. print "gnibbler second %f" %timeit.Timer("rev4(string)", "from __main__ import rev4, string").timeit(100000)
39. print "Alok %f" %timeit.Timer("rev5(string)", "from __main__ import rev5, struct, string").timeit(100000)
40. print "elliot42 %f" %timeit.Timer("rev6(string)", "from __main__ import rev6, struct, string").timeit(100000)
41. print "me %f" %timeit.Timer("rev(string)", "from __main__ import rev, string").timeit(100000)