Skip to content

Instantly share code, notes, and snippets.

@Pinacolada64
Created October 19, 2021 03:48
Show Gist options
  • Save Pinacolada64/7f9522f69914e66dcea724f54e924346 to your computer and use it in GitHub Desktop.
Save Pinacolada64/7f9522f69914e66dcea724f54e924346 to your computer and use it in GitHub Desktop.
Print a list of items in a grammatically correct way
def grammatical_list(item_list):
print("Entered function")
for item in item_list:
if item[:-1] == 's':
item = "some " + item
if item.startswith(('a', 'e', 'i', 'o', 'u')):
item = "an " + item
# print(item, sep="and, ", end='')
print(item)
print("Exited function")
if __name__ == '__main__':
# should print "You see some bells, an apple, and a candle":
grammatical_list(["bells", 'apple', 'candle'])
@tanabi
Copy link

tanabi commented Oct 19, 2021

Try:

def grammatical_list(item_list):
    result_list = []
    for item in item_list:
        if item.endswith("s"):
            result_list.append(f"some {item}")
        elif item.startswith(('a', 'e', 'i', 'o', 'u')):
            result_list.append(f"an {item}")
        else:
            result_list.append(f"a {item}")

    # Add 'and' if we need it
    if len(result_list) > 1:
        result_list[-1] = f"and {result_list[-1]}"

    # Join it together
    return ", ".join(result_list)

@Pinacolada64
Copy link
Author

👍 It worked! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment