Lists, Strings, and Random

Strings to Lists and Back

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

Split and Join

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("! "))

Random - Choice, Shuffle

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)

One Hand of Blackjack

Break Down the Problem

Representing Data

What data do we want to store, and how do we represent it?

Shuffling and Distributing Cards

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())

Calculating a Blackjack Hand

Implement a function that takes a list of strings representing cards. It should calculate the sum of the cards

Some Assertions

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"

Let's Think of Some Algorithms

How about this one?

Calculating a Blackjack Hand

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"

And The Rest

Maybe for homework?