There are two useful string methods that are often used with lists:
comics = "ranma,maison ikkoku,scott pilgrim"
awesome_comics_list = comics.split(",")
print(awesome_comics_list)
print(" and ".join(awesome_comics_list))
['ranma', 'maison ikkoku', 'scott pilgrim']
ranma and maison ikkoku and scott pilgrim
If I have the following list, how do I put together each element with an exclamation point and space between each element? How do I turn the resulting string back to a list? →
hello = ["Bill", "Phil", "Gil", "Jill"]
names = "! ".join(hello)
print(names)
print(names.split("! "))
The random module offers some methods that can be used on lists:
Let's try using a couple of these methods →
import random
numbers = [1, 2, 3, 4, 5, 6, 7]
print(random.choice(numbers))
random.shuffle(numbers)
print(numbers)
What data do we want to store, and how do we represent it?
Write a short program that: →
# create deck and deal
deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] * 4
random.shuffle(deck)
player_hand = []
computer_hand = []
for i in range(2):
player_hand.append(deck.pop())
computer_hand.append(deck.pop())
Implement a function that takes a list of strings representing cards. It should calculate the sum of the cards
We can check out all possible combinations of 1's and 11's to see which is the closest combination to 21.
assert 21 == current_total(['A', '9', 'A']), "two aces, one 11 and one 1"
assert 12 == current_total(['A', 'A', '10']), "two aces, both 1"
assert 21 == current_total(['A', 'A', 'A', '8']), "three aces, one 11 and two 1"
assert 12 == current_total(['A', 'A', 'A', '9']), "three aces, three 1"
How about this one? →
def current_total(hand):
""" Sums the cards in hand. Aces count as 1 or 11. Will optimize for
highest total without going over 21. """
total, aces = 0, 0
for card in hand:
if card.isdigit():
total += int(card)
elif card in 'JQK':
total += 10
elif card == 'A':
aces += 1
total += 11
for i in range(aces):
if total > 21:
total -= 10
return total
assert 21 == current_total(['A', '9', 'A']), "two aces, one 11 and one 1"
assert 12 == current_total(['A', 'A', '10']), "two aces, both 1"
assert 21 == current_total(['A', 'A', 'A', '8']), "three aces, one 11 and two 1"
assert 12 == current_total(['A', 'A', 'A', '9']), "three aces, three 1"
Maybe for homework?