Python Question Solution
Python Question Solution
Python Question Solution
Exercise
Create a program that asks the user to enter their name and their age. Print
out a message addressed to them that tells them the year that they will turn
100 years old.
Extras:
1. Add on to the previous program by asking the user for another number
and printing out that many copies of the previous message. (Hint: order of
operations exists in Python)
2. Print out that many copies of the previous message on separate lines.
(Hint: the string "\n is the same as pressing the ENTER button)
Discussion
Concepts for this week:
• Getting user input
• Manipulating strings (a few ways)
What this will print in the terminal (or the shell, whatever you are running
Python in) will be:
>>> Give me your name: Michele
Your name is Michele
What happens at the end of input() is that it waits for the user to type
something and press ENTER. Only after the user presses ENTER does the
program continue.
In both cases, age will hold a variable that is an integer, and now you can
do math with it.
(Note, you can also turn integers into strings exactly in the opposite way,
using the str() function)
Second: Do math with strings. What do I mean by that? I mean, if I want to
combine (concatenate is the computer science word for this) strings, all I
need to do is add them:
print("Were" + "wolf")
print("Door" + "man")
print("4" + "chan")
print(str(4) + "chan")
and write a program that returns a list that contains only the elements that
are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes.
Extras:
1. Randomly generate two lists to test this
2. Write this in one line of Python (don’t worry if you can’t figure this out
at this point - we’ll get to it soon)
List properties
In other words, “things you can do with lists.”
One of the interesting things you can do with lists in Python is figure out
whether something is inside the list or not. For example:
>>> a = [5, 10, 15, 20]
>>> 10 in a
True
>>> 3 in a
False
You can of course use this in loops, conditionals, and any other
programming constructs.
list_of_students = ["Michele", "Sara", "Cassie"]
String Lists
strings lists index
3. Exercise
Ask the user for a string and print out whether this string is a palindrome
or not. (A palindrome is a string that reads the same forwards and
backwards.)
Discussion
Concepts for this week:
• List indexing
• Strings are lists
List indexing
In Python (and most programming in general), you start counting lists
from the number 0. The first element in a list is “number 0”, the second is
“number 1”, etc.
As a result, when you want to get single elements out of a list, you can ask
a list for that number element:
>>> a = [5, 10, 15, 20, 25]
>>> a[3]
20
>>> a[0]
5
The first number is the “start index” and the last number is the “end
index.”
You can also include a third number in the indexing, to count how often
you should read from the list:
>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:5:2]
[10, 20]
>>> a[3:0:-1]
[15, 10, 5]
To read the whole list, just use the variable name (in the above
examples, a), or you can also use [:] at the end of the variable name (in the
above examples, a[:]).
and write a program that returns a list that contains only the elements that
are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes.
the original directive and read about the set command in Python 3.3, or try to
implement this on your own and use at least one list comprehension in the
solution.
Extra:
• Randomly generate two lists to test this
Discussion
Concepts for this week:
• List comprehensions
• Random numbers, continued
List comprehensions
We already discussed list comprehensions in Exercise 7, but they can be
made much more complicated.
For example:
x = [1, 2, 3]
y = [5, 10, 15]
allproducts = [a*b for a in x for b in y]
At the end of this piece of code, allproducts will contain the list [5, 10, 15,
10, 20, 30, 15, 30, 45]. So you can put multiple for loops inside the
comprehension. But you can also add more complicated conditionals:
x = [1, 2, 3]
y = [5, 10, 15]
customlist = [a*b for a in x for b in y if a*b%2 != 0]
Now customlist contains [5, 15, 15, 45] because only the odd products are
added to the list.
In general, the list comprehension takes the form:
[EXPRESSION FOR_LOOPS CONDITIONALS]
This line of code will leave a containing a list of 5 random numbers from 0
to 99.
List Remove Duplicates
5. Exercise
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
• Write two different functions to do this - one using a loop and
constructing a list, and another using sets.
• Go back and do Exercise 5 using sets, and write the solution for that in a
different function.
Discussion
Concepts for this week:
• Sets
Sets
In mathematics, a set is a collection of elements where no element is
repeated. This becomes useful because if you know your data is stored in a
set, you are guaranteed to have unique elements.
Features of sets
• Sets are not ordered. This means that there is no “first element” or “last
element.” There are just “elements”. You cannot ask a set for it’s “next
element”.
• There are no repeat elements in sets.
• You can convert between sets and lists very easily.
In Python
In Python, you make and use a set with the set() keyword. For example:
names = set()
names.add("Michele")
names.add("Robin")
names.add("Michele")
print(names)
You can do to a set almost anything you can do to a list (except ask for
things like “the third element”). See the Python documentation about sets to
get a full list of things you can do to sets.
You can convert from a list to a set and a set to a list pretty easily:
names = ["Michele", "Robin", "Sara", "Michele"]
names = set(names)
names = list(names)
print(names)
In a tic tac toe game, the “game server” needs to know where the Xs and Os
are in the board, to know whether player 1 or player 2 (or whoever
is X and O won).
There has also been an exercise about drawing the actual tic tac toe
gameboard using text characters.
The next logical step is to deal with handling user input. When a player
(say player 1, who is X) wants to place an X on the screen, they can’t just
click on a terminal. So we are going to approximate this clicking simply by
asking the user for a coordinate of where they want to place their piece.
As a reminder, our tic tac toe game is really a list of lists. The game starts
out with an empty game board like this:
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
The computer asks Player 1 (X) what their move is (in the format row,col),
and say they type 1,3. Then the game would print out
game = [[0, 0, X],
[0, 0, 0],
[0, 0, 0]]
Concepts
One review concept that is definitely needed (in addition to the user
input that is the core of the exercise) is the need to “split” strings.
The user will input coordinates in the form “row,col”, which input() will
then read in as a string. But we really want the numbers that come out of
that string, to know which row and column to place the piece at.
One approach is to use the idea of strings as lists to extract the row and
column numbers. This works great if your row and column numbers are
always single digits - the row will always be at index 0 and the column will
always be at index 2. But this breaks when the numbers are larger than one
digit (I know, not going to happen in tic tac toe, but it’s easy to image
extending this to other games).
Instead, there are two string manipulation functions that will help you:
1. .split() - Takes a string and returns a list, using the separator as the
split criteria. So if you have a string name = "John Doe" and do name_list =
name.split(" "), name_list will be ["John", "Doe"]. You can use any
separator / split character you want. Just remember, that each of the
elements returned back will be a string as well.
2. .strip() - Takes a string and removes the whitespace on the left and
right sides of it. So you have a string name = " Michele ", and you do name
= name.strip(), and now name will just be "Michele" - nice and clean.
File Overlap
7. Exercise
Given two .txt files that have lists of numbers in them, find the numbers
that are overlapping. One .txtfile has a list of all prime numbers under
1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that can’t be divided by any
other number. And yes, happy numbers are a real thing in mathematics -
you can look it up on Wikipedia.
Fibonacci
8. Exercise
Write a program that asks the user how many Fibonnaci numbers to
generate and then generates them. Take this opportunity to think about
how you can use functions. Make sure to ask the user to enter the number
of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a
sequence of numbers where the next number in the sequence is the sum of the
previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8,
13, …)