|
#!/usr/bin/env python3 |
|
|
|
import numpy as np |
|
import matplotlib |
|
matplotlib.use('AGG') |
|
import matplotlib.pyplot as plt |
|
import copy |
|
import timeit |
|
|
|
|
|
iterations = 10000 |
|
|
|
|
|
def invert_edge_values_jpp(l): |
|
idx1 = next(i for i, j in enumerate(l) if j) |
|
idx2 = next(i for i, j in enumerate(l[::-1]) if j) |
|
|
|
l = np.array(l) |
|
l[:idx1] = True |
|
l[len(l)-idx2:] = True |
|
|
|
return l |
|
|
|
|
|
def invert_edge_values_laurent_h(l): |
|
l = copy.deepcopy(l) |
|
tempList = l[:] |
|
|
|
# Iterate from the beginning (and invert) until the element differs from the first one |
|
for i,v in enumerate(tempList): |
|
if v == tempList[0]: l[i] = not v |
|
else: break |
|
|
|
# Iterate from the end (and invert) until the element differs from the last one |
|
for i,v in reversed(list(enumerate(tempList))): |
|
if v == tempList[-1]: l[i] = not v |
|
else: break |
|
|
|
return l |
|
|
|
|
|
def invert_edge_values_kevin(l): |
|
for i in range(len(l)): |
|
if l[i]: |
|
break |
|
l[i] = True |
|
|
|
for i in range(len(l)-1, -1, -1): |
|
if l[i]: |
|
break |
|
l[i] = True |
|
|
|
return l |
|
|
|
|
|
def invert_edge_values_davidak(l): |
|
l = np.array(l) |
|
ind = np.where(l)[0] |
|
first, last = ind[0], ind[-1] |
|
|
|
l[:first] = True |
|
l[last + 1:] = True |
|
|
|
return l |
|
|
|
|
|
if __name__ == '__main__': |
|
# create long random list of booleans |
|
# with some False on the edges |
|
l = [] |
|
list_items = 100000 |
|
|
|
number_pre_false = np.random.randint(5) |
|
number_past_false = np.random.randint(5) |
|
number_random_bool = list_items - (number_pre_false + number_past_false) |
|
|
|
for i in range(number_pre_false): |
|
l.append(False) |
|
|
|
for i in range(number_random_bool): |
|
l.append(np.random.rand() > 0.5) |
|
|
|
for i in range(number_past_false): |
|
l.append(False) |
|
|
|
# l = [False, False, False, True, True, True, False, False, True, False, False] |
|
# list_items = len(l) |
|
|
|
jpp = timeit.timeit("invert_edge_values_jpp(l)", number=iterations, globals=globals()) |
|
laurent_h = timeit.timeit("invert_edge_values_laurent_h(l)", number=iterations, globals=globals()) |
|
kevin = timeit.timeit("invert_edge_values_kevin(l)", number=iterations, globals=globals()) |
|
davidak = timeit.timeit("invert_edge_values_davidak(l)", number=iterations, globals=globals()) |
|
|
|
print("jpp:", jpp) |
|
print("Laurent H.:", laurent_h) |
|
print("Kevin:", kevin) |
|
print("davidak:", davidak) |
|
|
|
dpi = 96 |
|
fig = plt.figure(num=None, figsize=(1024/dpi, 768/dpi), dpi=dpi) |
|
ax = fig.add_subplot(111) |
|
|
|
plt.title("Comparison of functions to invert edge values in python boolean list (with {} items)".format(list_items)) |
|
ax.set_ylabel('execution time of {} iterations in seconds'.format(iterations)) |
|
|
|
x = ['jpp', 'Laurent H.', 'Kevin', 'davidak'] |
|
y = [jpp, laurent_h, kevin, davidak] |
|
ax.bar(x, y) |
|
|
|
plt.savefig("test.svg") |