Skip to content

Instantly share code, notes, and snippets.

'''
Goal:
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma
and a space, with and inserted before the last item. For example, passing the previous spam list to the function would
return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.
'''
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma(a_list):
last = a_list[:-1]
all_but_last = a_list[0:-1]
result = ''
for item in all_but_last:
result += item
result += ','
@Gwith
Gwith / Ex
Created August 7, 2016 20:15
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma(a_list):
last = a_list[-1]
all_but_last = a_list[0:-1]
result = ''
for item in all_but_last:
result += item
result += ', '
result += 'and '
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma(a_list):
last = a_list[-1]
all_but_last = a_list[0:-1]
result = ''
for item in all_but_last:
result += item
result += ', '
result += 'and '
def comma(a_list):
last = a_list[-1]
all_but_last = a_list[0:-1]
new_all_but_last = ', '.join(all_but_last)
print(new_all_but_last + ', ' + 'and' + ' ' + last)
comma(spam)
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
@Gwith
Gwith / pp
Created August 7, 2016 22:49
spam = ['apples', 'bananas', 'tofu', 'cats']
def pretty_join(words):
if len(words) == 1:
return words[0]
else:
comma_separated = ", ".join(words[:-1])
last_word = words[-1]
return "{0}, and {1}".format(comma_separated, last_word)
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(v, k)
print("Total number of items: " + str(item_total))
displayInventory(stuff)
import math
def displayInventory(inventory):
print('Inventory')
for k, v in inventory.items():
print(v, k)
print('Total number of items:' + ' ' + str(sum(inventory.values())))
def addToInventory(inventory, addedItems):