Skip to content

Instantly share code, notes, and snippets.

@Makiyu-py
Last active January 27, 2022 13:34
Show Gist options
  • Save Makiyu-py/4db877ece8d23b7111db3fed147b36b3 to your computer and use it in GitHub Desktop.
Save Makiyu-py/4db877ece8d23b7111db3fed147b36b3 to your computer and use it in GitHub Desktop.
Creating a stem-and-leaf diagram/plot in 40~ lines of python code!
# import time
def make_stemnleaf_diagram(data: list, no_of_spaces: int=3):
# start_time = time.time()
# Storing the list data as a dict
dict_data = {}
for i in data:
i = str(i)
starts = i[:-1]
if not starts in dict_data:
dict_data[starts] = []
dict_data[starts].append(i[-1:])
# Getting count the biggest length of the nums (for the spacing maths)
biggest_num_len = len(sorted([*dict_data], key=len, reverse=True)[0])
# Making the horizontal lines of the table
main_format = "Stem" + " " * no_of_spaces + "Leaf\n"
amt_of_lines = ""
for i in range(len(main_format)):
amt_of_lines += "-" if len(amt_of_lines)-2 != biggest_num_len else "+"
amt_of_lines += "\n"
main_format += amt_of_lines
# Making the table itself
for key, item_list in dict_data.items():
if not len(key) == biggest_num_len:
main_format += " {0}{1}|{2}{3}\n".format(key, " " * biggest_num_len, " " * (((biggest_num_len + no_of_spaces) - 2) - len(key)), " ".join([*sorted(item_list)]))
else:
main_format += " {0} |{1}{2}\n".format(key, " " * (((biggest_num_len + no_of_spaces) - 1) - len(key)), " ".join([*sorted(item_list)]))
main_format += amt_of_lines
# Print the table!
print(main_format)
# print("Finished in {}ms".format(round((time.time() - start_time) * 1000, 3)))
# Showing off outout
make_stemnleaf_diagram([10, 34, 38, 12, 56, 52, 53, 101, 104, 107, 32], 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment