Replace the if switch with a lambda and a for loop

This commit is contained in:
Tobias Schmidl 2020-09-21 08:10:13 +02:00
parent d0cede7771
commit 98fb0be057

View file

@ -26,28 +26,21 @@ max_ping = datetime.timedelta(milliseconds = 1000) # in seconds
targets = ["https://www.google.de", "https://www.bing.com", "https://www.wikipedia.org"]
max_ping_in_ms = max_ping.total_seconds() * 1000
in_bin = lambda x, bin: x >= bin[0] and x <= bin[1]
class Themes:
# Themes are from http://colorbrewer2.org/
purple_green = ["#762a83", "#9970ab","#c2a5cf","#a6dba0","#5aae61","#1b7837"]
red_green = ["#d73027", "#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"]
original = ["#acacac","#ff0101","#cc673b","#ce8458","#6bbb15","#0ed812"]
selected_colors = red_green
generate_bins = lambda min_val, max_val, step_width = 2: [[x, x + step_width - 1] for x in range(min_val, max_val, step_width)]
bins = generate_bins(0, int(max_ping_in_ms), int(max_ping_in_ms / (len(selected_colors) - 1)))
def colorize(response_time):
# panda's "cut" functon would be an alternative here, but this would be overkill, to include numpy just for this
if response_time < max_ping_in_ms / 5:
return Themes.selected_colors[5]
elif response_time >= max_ping_in_ms / 5 and response_time < 2 * max_ping_in_ms / 5:
return Themes.selected_colors[4]
elif response_time >= 2 * max_ping_in_ms / 5 and response_time < 3 * max_ping_in_ms / 5:
return Themes.selected_colors[3]
elif response_time >= 3 * max_ping_in_ms / 5 and response_time < 4 * max_ping_in_ms / 5:
return Themes.selected_colors[2]
elif response_time >= 4 * max_ping_in_ms / 5 and response_time < max_ping_in_ms:
return Themes.selected_colors[1]
else:
for index, bin in enumerate(Themes.bins):
if in_bin(response_time, bin):
return Themes.selected_colors[len(Themes.selected_colors) - 1 - index]
return Themes.selected_colors[0]
def httping(targets):
@ -59,6 +52,7 @@ def httping(targets):
print(str(ex), file=sys.stderr)
responses[target] = None
response_times = [value for key, value in responses.items() if isinstance(value, float)]
if len(response_times) > 1:
return responses, statistics.median(response_times), statistics.stdev(response_times)
elif len(response_times) > 0: