Python Question Solution

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

1.

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)

User input in Python


To get user input in Python (3), the command you use is input(). Store the
result in a variable, and use it to your heart’s content. Remember that the
result you get from the user will be a string, even if they enter a number.
For example,
name = input("Give me your name: ")
print("Your name is " + name)

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.

Manipulating strings (a few ways)


What you get from the input() function is a string. What can you do with
it?
First: Make the string into a number. Let’s say you are 100% positive that
the user entered a number. You can turn the string into an integer with the
function int(). (In a later exercise or two or three there will be questions
about what to do when the user does NOT enter a number and you try to
do this; for now don’t worry about that problem). Here is what this looks
like:
age = input("Enter your age: ")
age = int(age)

(or, if you want to be more compact with your code)


age = int(input("Enter your age: "))

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

The same works for multiplication:


print(4 * "test")

but division and subtraction do not work like this. In terms of


multiplication, the idea of multiplyling two strings together is not well-
defined. What does it mean to multiply two strings in the first place?
However, it makes sense in a way to specify multiplying a string by a
number - just repeat that string that number of times. Try this in your own
program with all the arithmetic operations with numbers and strings - the
best way to get a feel for what works and what doesn’t is to try it!
List Overlap
2. Exercise
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

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"]

name = input("Type name to check: ")


if name in list_of_students:
print("This student is enrolled.")

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

There is also a convenient way to get sublists between two indices:


>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:4]
[10, 15, 20]
>>> a[6:]
[35, 40]
>>> a[:-1]
[5, 10, 15, 20, 25, 30, 35]

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[:]).

Strings are lists


Because strings are lists, you can do to strings everything that you do to
lists. You can iterate through them:
string = "example"
for c in string:
print "one letter: " + c

Will give the result:


one letter: e
one letter: x
one letter: a
one letter: m
one letter: p
one letter: l
one letter: e

You can take sublists:


>>> string = "example"
>>> s = string[0:5]
>>> print s
examp

Now s has the string “examp” in it.


Moral of the story: a string is a list.

List Overlap Comprehensions


4. Exercise
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

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]

as shown in the examples above.

Random numbers, continued


Try to use the Python random documentation to figure out how to generate a
random list. As a hint look below:
a = random.sample(range(100), 5)

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)

And the output will be;


set(['Michele', 'Robin'])

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)

And the result of this will be:


['Michele', 'Robin', 'Sara']

Tic Tac Toe Draw


6. Exercise

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]]

And ask Player 2 for their move, printing an O in that place.


Things to note:
• For this exercise, assume that player 1 (the first player to move) will
always be X and player 2 (the second player) will always be O.
• Notice how in the example I gave coordinates for where I want to move
starting from (1, 1) instead of (0, 0). To people who don’t program,
starting to count at 0 is a strange concept, so it is better for the user
experience if the row counts and column counts start at 1. This is not
required, but whichever way you choose to implement this, it should be
explained to the player.
• Ask the user to enter coordinates in the form “row,col” - a number, then
a comma, then a number. Then you can use your Python skills to figure
out which row and column they want their piece to be in.
• Don’t worry about checking whether someone won the game, but if a
player tries to put a piece in a game position where there already is
another piece, do not allow the piece to go there.
Bonus:
• For the “standard” exercise, don’t worry about “ending” the game - no
need to keep track of how many squares are full. In a bonus version,
keep track of how many squares are full and automatically stop asking
for moves when there are no more valid moves.

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, …)

Discussion Practice functions!

You might also like