|
|
|
HW2
|
|
|
|
|
How to get started with Problem 3
|
|
|
|
|
Questions
|
|
|
|
|
Go over code from quiz question 4
|
|
|
|
|
Scrabble bingo
|
|
|
|
|
data: words in the dictionary and letters on tiles
|
|
|
|
|
go through each word in the dictionary, check if it can be made with the tiles
|
|
|
|
|
annoying to have a separate variable for each letter, impossible to have one for each word
|
|
|
|
|
need to way to group a bunch of related data together!
|
|
|
|
|
Python gives us the list
|
|
|
|
|
think of it as a slot in memory with its own numbered slots inside
|
|
|
|
|
NUMBERING STARTS AT ZERO!
|
|
|
|
|
tiles = ["D", "O", "B", "Y", "E", "G", "O"]
|
|
|
|
|
print(tiles[0])
|
|
|
|
|
D
|
|
|
|
|
print(tiles[6])
|
|
|
|
|
O
|
|
|
|
|
print(tiles[7])
|
|
|
|
|
IndexError
|
|
|
|
|
print(tiles[-2])
|
|
|
|
|
G
|
|
|
|
|
lists can be modified
|
|
|
|
|
tiles[2] = "L" print(tiles) # prints ["D", "O", "L", "Y", "E", "G", "O"]
|
|
|
|
|
We still need a way to avoid a separate line of code for each possible word
|
|
|
|
|
Examine our sequence of copy-pasted code—what changes each time?
|
|
|
|
|
We need a structure that repeats the same thing over-and-over, except changing one thing each time: for loop
|
|
|
|
|
for <loop variable> in <sequence>: <indented loop body>
|
|
|
|
|
for word in words: # check if tiles can make word
|
|
|
|
|
quick check: given a variable nums that stores a list, write a for loop that prints out each element of the list
|
|
|
|
|
for num in nums: print(num)
|
|
|
|
|
import sys words = ["bogeyed", "goodbyes", "goodbye", "phantasmagorical"] tiles = ["D", "O", "B", "Y", "E", "G", "O"]
for word in words: check = tiles.copy() for letter in word: if letter in check: check.remove(letter) if len(check) == 0 and len(word) == len(tiles): print("The Scrabble tiles", tiles, "can be played as a bingo:", word) sys.exit()
print("The Scrabble tiles", tiles, "cannot be played as a bingo")
|
|
|
|
|
strings are sequences just like lists, so we can loop over each letter with for letter in word
|
|
|
|
|
use the in keyword to get True or False for a value being present in a sequence
|
|
|
|
|
len is a function that takes a sequence and returns the number of elements in that sequence
|
|
|