0% found this document useful (0 votes)
25 views10 pages

Fop Prac002 1

Uploaded by

shuvo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views10 pages

Fop Prac002 1

Uploaded by

shuvo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Prac02: Strings and Lists

Overview
Questions
 How do I work with string values and variables?
 How do I access the elements of strings and lists?
 How can I use random numbers to simulate real world situations?

Objectives
1. Define and use more complex datatypes (strings and lists) and variations on control
structures
2. Use slicing and indexing to access elements in a list
3. Use a supplied Python package to provide random number options
4. Understand and implement simple Monte Carlo algorithms

Introduction
In this practical we will enter and modify programs to work with and explore strings and lists.
We will then use random numbers to select list items without replacement. The final two tasks
will implement two Monte Carlo algorithms: calculating Pi and tossing coins.

Activity 1 - Setting up for the practical


Login to the computers as in Practical 1. Within your home directory (/home/student_id) you
should have the following structure:
FOP
|-- Prac00
|-- Prac01
|-- Prac02
|-- Prac03
|-- Prac04
|-- Prac05
|-- Prac06
|-- Prac07
|-- Prac08
|-- Prac09
|-- Prac10
|-- Prac11
Type ls FOP from your home directory to check your directory structure.
We will be working in the Prac02 directory today. If you do not have the directory structure
correct, your tutor can help you to rearrange it.
Copy the README file from your Prac01 directory to your Prac02 directory. Use cp
../Prac01/README . from within the Prac02 directory, then vim README to edit. Update
the README to refer to Prac02 and include the correct date.

Activity 2 - Everybody loves string(s)!


Strings are very important in Python and the language provides powerful options to manipulate
strings. The code below shows three different approaches to printing out a string in
reverse: while loops; for loops and using slicing.
Enter the following code as strings1.py…
PYTHON
#
# strings1.py: Read in a string and print it in reverse
# using a loop and a method call

instring = input('Enter a string... ')

# *** add (2) upper and (3) duplicating code here

# reversing with a while loop


print('Reversed string is : ', end='')
index = len(instring)-1
while index > -1:
print(instring[index], end='')
index = index - 1
print()
# reversing with a for-range loop
print('Reversed string is : ', end='')
for index in range(len(instring)-1, -1, -1):
print(instring[index], end='')
print()

# reversing with slicing


print('Reversed string is :', instring[::-1])
Test out the code to understand how it works. Note that in each case:
 start value is len(instring)-1
 stop value is -1
 step value is -1
Slicing doesn’t quite fit the pattern for start:stop:step, which would have the code as follows:
PYTHON
# WARNING: THIS WON"T WORK!
print('Reversed string is :', instring[len(instring)-1:-1:-1])
However, the -1 stop value would get interpreted as a negative index. Python slicing is smart
enough to know that when a negative step is used (e.g. -1), the default start and stop should be
switched around to the values len(instring)-1 & -1.
Continuing on with the activity, copy strings1.py to strings2.py and make the following
changes…
1. Change the start, stop and step values in each approach to print the string forwards
(instead of in reverse).
2. Update instring to uppercase (so that ‘abcd’ becomes ‘ABCD’)
3. Update instring to duplicate the string (ABCD becomes ABCDABCD)
4. Modify each of the three approaches print out every second character (ABCDABCD
becomes ACAC)
5. Modify each of the three approaches print out every second character, excluding the first
and last (ABCDABCD becomes BDB)
Activity 3 - Variables are like Buckets…
The Bucket List is a movie from 2007 where two men work through a list of experiences they
aim to have in life. This task will have you work with their bucket list.
The code below defines bucket1 directly as a list, then appends three values. To delete a value we
can use the index of the item in the list del bucket1[6] or by value bucket1.remove("Skydiving").
We then create a second list bucket2 and make a new list bucket from bucket1 + bucket2. Finally
we insert a new item and print out the buckets.
PYTHON
#
# bucket1.py - use a python list for items in a bucket list
#
print('\nBUCKET LIST\n')
bucket1 = ['Witness something truly majestic',
'Help a complete stranger',
'Laugh until I cry','Drive a Shelby Mustang']

bucket1.append('Kiss the most beautiful girl in the world')


bucket1.append('Get a tattoo')
bucket1.append('Skydiving')
del bucket1[5]

bucket2 = ['Visit Stonehenge',


'Drive a motorcycle on the Great Wall of China',
'Go on a Safari','Visit the Taj Mahal',
'Sit on the Great Egyptian Pyramids',
'Find the Joy in your life']

print('Bucket 1: ', bucket1)


print('Bucket 2: ', bucket2)
bucket = bucket1 + bucket2
bucket.insert(5, 'Get a tattoo')

print('\nThe bucket list is:')


print('Complete bucket list: ', bucket)

print('\nNicer formatting....\n')

for item in bucket: # for-each loop


print(item) # note improved formatting
We will now create a bucket list builder to interactively create a new bucket list…
PYTHON
#
# bucket2.py - bucket list builder
#
print('\nBUCKET LIST BUILDER\n')
bucket = []
choice = input('Enter selection: e(X)it, (A)dd, (L)ist...')
while choice[0] != 'X':
if choice[0] == 'A':
print('Enter list item... ')
newitem = input()
bucket.append(newitem)
elif choice[0] == 'L':
for item in bucket:
print(item)
else:
print('Invalid selection.')
choice = input('Enter selection: e(X)it, (A)dd, (L)ist..')
print('\nGOODBYE!\n')
Modify the code to:
1. Accept lowercase as well as uppercase letters as choices (hint: convert the inputs to
upper())
2. Provide an option for deleting items (hint: del bucket[int(delitem)])

Activity 4 - Assorted Creams


This program generates a list of items then prints out each selected item before deleting it. We
are using a “without replacement” approach as the selected items are no longer part of the pool to
be selected.
PYTHON
#
# assorted.py - selecting random biscuits from a pack
#
import random
biscuits = []
biscuits.extend(['Monte Carlo']*7)
biscuits.extend(['Shortbread Cream']*7)
biscuits.extend(['Delta Cream']*6)
biscuits.extend(['Orange Slice']*6)
biscuits.extend(['Kingston']*5)
print('\nASSORTED CREAMS\n')
print('There are ', len(biscuits), ' biscuits in the pack.')
print('\n', biscuits, '\n')
more = input('\nWould you like a biscuit (Y/N)... ')
while more != 'N':
choice = random.randint(0,len(biscuits)-1)
print('Your biscuit is : ', biscuits[choice])
del biscuits[choice]
more = input('\nWould you like a biscuit (Y/N)...')
print('\nThere are ', len(biscuits), ' biscuits left.')
print('\n', biscuits, '\n')

Challenge
Modify the code to check if the pack is empty before continuing the loop.
Hint 1
Hint 2
Answer

Activity 5 - Method of Darts


The lecture slides include code for calculating Pi using the Method of Darts.
Type the code in as darts.py and explore the accuracy you can achieve.

Activity 6 - Tossing Coins


In this program we will toss a coin 1000 times and see how many heads or tails we count.
PYTHON
#
# cointoss.py - simulate tossing a coin multiple times
#
import random
coin = ['heads','tails']
heads = 0
tails = 0
trials = 1000
print('\nCOIN TOSS\n')
for index in range(trials):
if random.choice(coin) == 'heads':
heads = heads + 1
else:
tails = tails + 1
print('\nThere were ', heads, ' heads & ', tails, ' tails.\n')
Modify the code to ask the user to enter the number of tosses.

Activity 7 - Practice Understanding and Documenting Code


The code below is something new, and has many potential fun applications. Enter the code and
add an introductory comment, and a comment on each line to describe what each part of the code
is doing.
The article Overwrite Previously Printed Lines may help.
PYTHON
import time

LINE_UP = '\033[1A'
LINE_CLEAR = '\x1b[2K'
numlines = 3

eyes = ["\n< @ > < @ >\n",


"\n<@ > <@ >\n",
"\n< @> < @>\n"]

for i in range(10):
if i % 2 == 0:
print(eyes[0])
elif i % 4 == 1:
print(eyes[1])
else:
print(eyes[2])
time.sleep(0.5)
for j in range(numlines):
print(LINE_UP, end=LINE_CLEAR)
If you change a few lines, note the change to the output:
PYTHON
numlines = 4

eyes = ["\n< @ > < @ > \n db\n \____/",


"\n<@ > <@ >\n db\n \____/",
"\n< @> < @>\n db\n \____/"]
Explore some ASCII art with this code base, e.g. a fish from the ASCII Art Archive:
Swimming left
/
/\/
\/\
\

Swimming right
\
\/\
/\/
/

Challenge
How would you write code to animate the fish to swimming left and right, adding/removing
spaces to move the fish across the screen?
Making Spaces
Left or Right?
Move it!
Full Solution

Activity 8 - Scaffolded Challenge: Vending Machine


You are tasked with writing a vending machine program which keeps track of the different
products (name, price and count) and dispenses the treat, if available.
We can write code to give the correct behaviour, then improve its presentation to be more
interesting and engaging.
An example of the complete program is below. Making a mock-up of output is one way to
specify requirements… from there, you can consider the variables and data storage required, and
the program logic needed to generate that output. There is also a need for imagination - what
would happen if the input was different, or if invalid input was entered?

You might also like