1. Head, tail, and more
You've managed to recreate the classical Unix command wc with Python. Dennis Ritchie and Ken Thompson send their regards.
They would like you to continue with a few more extremely useful Unix commands:
head: takes an input file name, number n, and an output file name; writes the first n lines of the input file to the output file. If the output file name is not provided, just write to the screen.
hint: what happens if there are less than n lines in the input file?
tail: very similar to head, only that it writes the last n lines.
more: takes an input file name. Writes the contents of the file to screen, but pause at a full screen and wait for input. Once the ENTER key is hit, show the next full screen of file content, until the entire file is shown.
hint: how do you know how many lines is a full screen? Make some assumptions. If you really want to be accurate, look up shutil.get_terminal_size().
Extension: what if the program accepts 'any key' instead of ENTER for the next screen of output? Do some research.
2. Everything has a price
You are a secret agent. You buy and sell classified information for a living. Such classified information has several properties:
- From country: a string of letters;
- To country: a string of letters;
- Classification level: a number between 1 and 5;
- Financial value: a number between 1 and 100.
When a piece of information is being traded, its price is calculated as follows:
1. You add values of all the letters in the from country, 'a' being 1 and 'z' being 26, to get a FC value;
2. You add values of all the letters in the to country, to get a TC value;
3. You use the Classification level C and Financial value F to calculate the CF value as follows: add up the squares of numbers from 1 to C, then add up the square roots of numbers from 1 to F, then add these 2 to get a CF value;
4. get the Price = (FC + TC) * CF
Get a list of classified information from an input file: jamesbondsclassifiedinformationforsaledontshowanybodybecauseitsstillnotencrypted.txt. Each line contains the from country, to country, classification level and the financial value. For each piece, write the calculated price to prices.txt.
First try to write the program without using functions. Then rewrite your program using functions. See if that simplifies your life.
3. Scopes of variables
Write some simple functions for example adding 2 numbers. Try different scenario like accessing values of local variables within / outside the functions, and accessing values of global variables within / outside the functions.
Also try changing values of variables within the functions, then see what happens to them outside the functions.
No comments:
Post a Comment