Skip to content

Instantly share code, notes, and snippets.

@SheatNoisette
Last active October 31, 2019 17:07
Show Gist options
  • Save SheatNoisette/810027323fb6b063b4442fd329a542c8 to your computer and use it in GitHub Desktop.
Save SheatNoisette/810027323fb6b063b4442fd329a542c8 to your computer and use it in GitHub Desktop.
Insert a letter in alphabetical order in a list
#!/usr/bin/env python
# BASIC ALGORITHM
# Insert letter alphabetically in a list
# This quick and dirty example shows how to insert a letter in a list
# alphabetically
# CC-O for homework/class and Beerware Licence for other
test_1 = ["a", "b", "d", "e", "f"]
test_2 = ["i"]
def insert_alpha(letter, i_list):
list_size = len(i_list)
# No elements
if list_size == 0:
i_list.append(letter)
else:
for element in range(list_size):
# The letter is in the list ?
if letter == i_list[element]:
break
# Compare our letter at the current selected letter in
# a list. If our letter should be inserted BEFORE
# the selected letter, insert the letter at the selected
# letter place
elif letter < i_list[element]:
i_list.insert(element, letter)
break
# We are at the end of the list. Our letter isn't in the
# list and doesn't need to be inserted in the middle of
# the list. (Like Z)
elif element == list_size - 1:
i_list.append(letter)
break
# Middle insertion
insert_alpha("c", test_1)
print("insert c in test_1: " + str(test_1))
# ['a', 'b', 'c', 'd', 'e', 'f']
# Before insertion
insert_alpha("c", test_2)
print("insert c in test_2: " + str(test_2))
# ['c', 'i']
# Insert shuffled
shuffle = "aqwxszedcvfrtgbnhyujkiolmp"
shufflelist = []
for l in shuffle:
insert_alpha(l, shufflelist)
print("Shuffled insertion: " + str(shufflelist))
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
# 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment