Don't like this style? Click here to change it! blue.css
The one line version using lambdas:
So we know, vaguely, how to read a file line by line.
We should probably use cloud9 for file play, but you can actually create a file on repl.it and read from it:
Dir Task 1: Run the above code in its own window. Then in the terminal do the
following two commands:
import os then
print(os.listdir('.')). What do you see? What
do you think
Poet Task 2: Now create a new file called 'haiku' and write a Haiku about Python
into that file. Use
os.listdir('.') to see that it is there.
By the way if you want a more official source of info on this check out the Python3 IO docs.
We've seen how to iterate through a file line by line. Now let's load it all in at once.
Here is an example of
Here is an example of reading several "bytes" at a time:
Sleuth Task 3: What does
f.read() do? What does
Seek Task 4: Now do
seek(0) after this snippet. Then
print(f.read()) again. What do you think
Dictionary Task 5: Head to cloud9, download the dictionary file for the next HW.
Load it all into one big string using
read(). Now make a list of all words with
str.splitlines(). What is the 102nd word in that dictionary? How about the 666th word?
OK, so let's try something real out. I've made a GitHub Repo for a simple TicTacToe board.
Fork Task: Make a cloud9 workspace from the above GitHub Repo.
Read File Task: In that repo there is a file called
ttt.py and a file
ttt.py make the function
read_board() read in a game
board.txt. (It currently saves 3 characters per line, 3 lines total).
Once you've done that you can run the code and see the board that was saved into the file. Edit the file, see the new board, etc.
Write File Task: Now save the current game_state back into a file (imagine some
changes happened). Finish the function
write_board(the_game) to "persist" the game state into a
You've just written your first mini-database. Now a game could be continued after a long break, or play by email, etc.
So we have a test coming up, and I like to pause every now and again to work problems together. If we have the time to, head to this hackerrank Python3 problem, sign up with a GitHub account.
These problems are public ways for you to demonstrate python knowledge, and also helpful ways to self-assess your progress. The only thing you need to know if what they mean by "read from STDIN" and "write to STDOUT".
STDIN just means any input from the keyboard, you've been doing that since week one by using the
STDOUT is anything written "to the screen" using
Here is a solution to that problem:
Solve Hackerrank: I want you to attempt to solve the problem: Map and Lambda Expression
Itertools Follow-up Try this one now: itertools combinations with replacement
Count the number of times the letter 'z' appears in our dictionary.