Code Developed in CSCI-1100 Spring Semester 2016¶
Lecture 1¶
Module: lec01_three_doubles
— Finds three consecutive pairs of double letters¶
Find all words containing three consecutive pairs of double letters in a file of all English words located at:
Modules used: urllib
Author: Sibel Adali <adalis@rpi.edu>, Chuck Stewart <cvstewart@gmail.com>
Returns: All words matching condition and the count of found words
Pseudo Code:
open the file from the web with all the words in English
for each word in the file:
for all positions l in the word
if the letters at positions (l and l+1) are the same
and the letters at positions (l+2 and l+3) are the same
and the letters at positons (l+4 and l+5) are the same then
output word and increment the count
Code:
""" Find all words containing three consecutive pairs of double letters
in a file of all English words located at:
http://www.greenteapress.com/thinkpython/code/words.txt
**Modules used:** :py:mod:`urllib`
**Author**: Sibel Adali <adalis@rpi.edu>, Chuck Stewart <cvstewart@gmail.com>
**Returns:** All words matching condition and the count of found words
**Pseudo Code**::
open the file from the web with all the words in English
for each word in the file:
for all positions l in the word
if the letters at positions (l and l+1) are the same
and the letters at positions (l+2 and l+3) are the same
and the letters at positons (l+4 and l+5) are the same then
output word and increment the count
"""
import urllib
def has_three_double(word):
""" Returns True if the word contains three consecutive pairs of
double letters and False otherwise.
"""
for l in range(len(word)-5):
if word[l] == word[l+1] and \
word[l+2]==word[l+3] and \
word[l+4]==word[l+5]:
return True
return False
# Comments that fit in a single line can be put in this format.
# Anything after a single pound sign is ignored.
# The main body of the program starts here
word_url = 'http://www.greenteapress.com/thinkpython/code/words.txt'
word_file = urllib.urlopen(word_url)
count = 0
for word in word_file:
word = word.strip().strip('\n')
if has_three_double(word):
print word
count = count + 1
if count == 0:
print 'No words found'
elif count == 1:
print "1 word found"
else:
print count, 'words were found'
Lecture 3¶
Module: lec03_raw_input
— Demonstrate the use of raw_input in the volume calculation code.¶
Code:
"""
Write a program to
read the dimensions of a rectangular prism,
compute the surface area and volume, and
print them.
"""
length = float(raw_input("Enter the length of the rectangular prism ==> "))
width = float(raw_input("Enter the width of the rectangular prism ==> "))
height = float(raw_input("Enter the height of the rectangular prism ==> "))
area = 2 * (length*width + length*height + width*height)
volume = length*width*height
print "Rectangular prism with length %.3f, width %.3f, height %.3f" %(length, width, height)
print "Area %.3f, Volume %.3f" %(area, volume)
Lecture 4¶
Module: lec04_exercise_set_1
— Demonstrate the use of some string functions for parts 3 and 4.¶
Code:
name2 = "Rensselaer Polytechnic Institute"
##a -> 1, e->a, 1->e
name2 = name2.replace("a","1")
name2 = name2.replace("e","a")
name2 = name2.replace("1","e")
print name2
word = 'Bring back the swarm'
word = word.title()
word = word.replace(" ", "")
word = "#" + word
print word
word = 'Bring back the swarm'
word = "#" + (word.title()).replace(" ","")
print word
Module: lec04_exercise_set_2
— Demonstrate the use of the math module¶
Code:
"""
Write a program to
read radius of a circle in float
compute its area and
print it.
"""
import math
radius = raw_input("Radius ==> ")
radius = float(radius)
## or
## radius = float(raw_input("Radius ==> "))
area = math.pi * radius**2
print "The area of a circle is:", area
print "The area of a circle is: %.2f" %area
Module: lec04_cylinder
— Demonstrate the use of some math modules to compute the area and volume of a cylinder.¶
Code:
""" Author CS-1 Staff
Purpose: This program reads radius and height
of a cylinder and outputs the area and volume.
"""
import math
# This is a comment
print "Computing the area and volume of a cylinder"
radius = float(raw_input("Enter radius ==> "))
height = float(raw_input("Enter height ==> "))
area = 2*math.pi*radius*height + 2*math.pi*radius**2
volume = math.pi*radius**2*height
print "Area is %.2f" % area
print "Volume is %.2f" %volume
Module: lec04_triangle
— Class exercise to calculate the hypotenuse of a right triangle¶
Code:
""" Author CS-1 Staff
Purpose: This program reads the lengths a and b
of the sides of a right triangle and outputs the
hypotenuse.
"""
import math
print "Computing the hypotenuse of a right triangle"
a = float(raw_input("Enter side a ==> "))
b = float(raw_input("Enter side b ==> "))
c = math.sqrt(a**2 + b**2)
print "Hypotenuse is %.2f" % c
Lecture 5¶
Module: lec05_surface_area
— Use two functions to compute surface area¶
Code:
'''
Demonstrate the writing and use of two functions that compute the area
of a circle and the surface area of a cylinder.
'''
import math
def area_circle(radius):
return math.pi * radius ** 2
def area_cylinder(radius,height):
circle_area = area_circle(radius)
height_area = 2 * radius * math.pi * height
return 2*circle_area + height_area
print 'The area of a circle of radius 1 is', area_circle(1)
r = 2
height = 10
print 'The surface area of a cylinder with radius', r
print 'and height', height, 'is', area_cylinder(r,height)
Lecture 6¶
Module: lec06_height
— Use if statements to compare height¶
Code:
""" Author: CS1 Staff
Simple program to demonstrate an if statement.
"""
name1 = "Dale"
height1 = int(raw_input("Enter the height of %s in cm ==> " %name1))
name2 = "Erin"
height2 = int(raw_input("Enter the height of %s in cm ==> " %name2,))
if height1 < height2:
print "%s is taller" %name2
max_height = height2
elif height1 > height2:
print "%s is taller" %name1
max_height = height1
else:
print "%s and %s have the same height!" %(name1, name2)
max_height = height1
print "The max height is %d" %max_height
Lecture 7¶
Module: lec07_ex1
— First image example: resize and convert¶
Code:
from PIL import Image
filename = "chipmunk.jpg"
im = Image.open(filename)
print '\n' '********************'
print "Here's the information about", filename
print im.format, im.size, im.mode
im.show()
gray_im = im.convert('L')
scaled = gray_im.resize( (128,128) )
print "After converting to gray scale and resizing,"
print "the image information has changed to"
print scaled.format, scaled.size, scaled.mode
scaled.show()
scaled.save(filename + "_scaled.jpg")
Module: lec07_ex2
— Second image example: crop and paste¶
Code:
from PIL import Image
im = Image.open("lego_movie.jpg")
w,h = im.size
## Crop out three columns from the image
## Note: the crop function returns a new image
part1 = im.crop((0,0,w/3,h))
part2 = im.crop((w/3,0,2*w/3,h))
part3 = im.crop((2*w/3,0,w,h))
## Create a new image
newim = Image.new("RGB",(w,h))
## Paste the image in different order
## Note: the paste function changes the image it is applied to
newim.paste(part3, (0,0))
newim.paste(part1, (w/3,0))
newim.paste(part2, (2*w/3,0))
newim.show()
Lecture 9¶
Module: lec09_overview
— Some basic while loop constructs¶
Code:
"""
This is a general program for practicing different loop
methods. The following are examples of:
1. Loops that count up or down, loops that end
Loop block
Printing (print all on one line)
Changing a list (make upper case)
Accumulate a value
Count by 1, 3 (print three in a line, check
for three letters in a word, ending conditions?)
Is it true that there are two consecutive repeated letters?
Count all farmer's markets in Albany
2. Loops that are undeterministic
Depends on an external condition
(while user does not say stop)
------ WE will continue with these the next time
Depends on a complex condition
(while found or end of list, farmer's market)
3. Double loops
Find all possible pairs of agents
Find pairs of agents with the same first letter in their name
"""
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', \
'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
agents = ['skye','may','fitz','simmons','caulson',\
'hunter', 'mack', 'morse', 'triplett', \
'hartley', 'deathlok', 'koenig', \
'gonzales', 'fury']
word = 'bookkeeper'
i=0
while i< len(months):
print "Month: %d is %s" %(i+1, months[i].capitalize() )
i += 1
print months
print
print agents
## Capitalize the values in list "agents"
i=0
while i < len(agents):
agents[i] = agents[i].capitalize()
i += 1
## Check if capitalized
print
print agents
##Count how many agents have first names that start with S
##Accumulation of values
i = 0
cnt = 0
while i < len(agents):
if agents[i][0] == 'S':
cnt += 1
i += 1
print "%d agents with first name starts with 'S'" %cnt
##Find if there any agents who name starts with F
##Print Yes if any agent with such name, No otherwise
i = 0
found = False
while i < len(agents):
if agents[i][0] == 'F':
found = True
i += 1
if found:
print 'Yes'
else:
print 'No'
print
print "This is a loop that counts up to 7"
i = 0
while i < 7:
i += 1
print i
print
print "This is a loop that counts 10 down to 1"
i=10
while i > 0:
print i
i -= 1
print
print "This is loop that counts by 2, starting with 1 and ending with 19"
i = 1
while i <= 20:
print i
i += 2
Module: lec09_user_stop
— Stop a while loop based on user input¶
Code:
""" This program shows how to write a loop that ends
on a given user input. So, we must make sure that
while loop executes once initially and also that we
set the conditions that would stop the loop manually
when the correct input is given.
"""
### write a loop that reads user input, until the
### user types stop
finished = False
while not finished:
cmd = raw_input("Enter a command (stop to stop) => ")
if cmd == 'stop':
finished = True
Module: lec09_co2
Use a while loop to process a list¶
Code:
"""
Illustrating while loops with the CO2 example
"""
co2_levels = [ (2001, 320.03), (2003, 322.16), (2004, 328.07),\
(2006, 323.91), (2008, 341.47), (2009, 348.92),\
(2010, 357.29), (2011, 363.77), (2012, 361.51),\
(2013, 382.47) ]
"""
First example, sum
"""
i=0
sum=0
while i< len(co2_levels):
sum += co2_levels[i][1]
i += 1
print
print "Total co2_levels is", sum
"""
Reverse order
"""
i=len(co2_levels)
while i > 0:
i -= 1
print "Year", co2_levels[i][0], \
"CO2 levels:", co2_levels[i][1]
"""
Levels above 350
"""
print
i=0
num = 0
while i < len(co2_levels):
if co2_levels[i][1] > 350:
num += 1
i += 1
print "%d years had CO2 levels greater than 350" % num
"""
Percent change
"""
print
i=1
num = 0
while i < len(co2_levels):
percent = 100 * (co2_levels[i][1] - co2_levels[i-1][1]) / co2_levels[i-1][1]
print "Percent change from %d to %d was %.2f" % (co2_levels[i-1][0], co2_levels[i][0], percent)
i+=1
"""
Levels that went down
"""
print
i=1
num = 0
while i < len(co2_levels):
if co2_levels[i][1] < co2_levels[i-1][1]:
print "From %d to %d CO2 levels went down" % (co2_levels[i-1][0], co2_levels[i][0])
i+=1
Lecture 10 (carry over from Lecture 9)¶
Module: lec10-closest
Find the two closest values in a list¶
Code:
'''
Purpose: Demonstrate the use of nested loops to find the two closest values in a list.
This could also be implemented - probably better - using for loops. The values
are stored in a list L, but in practice it would be better to input them from the user.
Author: Chuck Stewart
Date: March 3, 2016
'''
L = [34, 21, 12, 78, 28, 61 ]
# Initialize two variables to hold information about the minimum. The
# first is a tuple holding the indices of the two closest values. The
# second is the minimum distance. These values are initialized from the
# first two values in the list.
min_pair = (0,1)
min_dist = abs( L[0] - L[1] )
# In order to test each possible pair of indices, the index of the first
# component of the pair must start out 0.
i = 0
while i<len(L):
# The second index starts out at i+1 and runs through the end of
# the list.
j=i+1
while j < len(L):
dist = abs(L[i]-L[j])
# If the distance between the current pair of points is less than
# the current minimum, we have a new minimum pair
if dist < min_dist:
min_pair = (i,j)
min_dist = dist
j += 1
# This is outside the inner while loop so that i is incremented after
# the inner while loop ends.
i += 1
closest_i = min_pair[0]
closest_j = min_pair[1]
print "Closest values are %d and %d at indices %d and %d."\
%(L[closest_i], L[closest_j], closest_i, closest_j)
Lecture 11¶
Module: lec11_walk.py
Turtle performs a random walk¶
Code:
'''
Lecture 11 Example of a Random Walk
This code was started in class on March 7 and completed on March 10.
It simulates a random walk by turtle who in each time unit randomly
takes a step to the left or a step to the right until it falls off.
This is represented by creating a board of n spaces and starting the
turtle in space n/2. A step to the left decreases the turtle
position. A step to the right increases the turtle position.
The simulation is run with a delay between each step so we can watch
what is happening. Without this delay, the board would print too
fast.
'''
import random
import sys
import time # so that we can delay
def print_board( steps, n, turtle_pos):
'''
Print the board with the current turtle position on it. This assumes the turtle
position is at least 0 and less than n.
'''
board = '_' * turtle_pos + 'T' + '_'*(n-1-turtle_pos)
print "%4d: %s" %(steps, board)
def take_step( n, turtle_pos ):
'''
Take a step, return turtle tuple with the new position, and False if
turtle fell off
'''
ran_value = random.random()
if ran_value < 0.5:
''' Step to the left '''
turtle_pos -= 1
else:
''' Step to the right '''
turtle_pos += 1
fell_off = turtle_pos < 0 or turtle_pos >= n
return (turtle_pos, fell_off)
if __name__ == '__main__':
''' Read the input and check to make sure it is a positive integer '''
n = raw_input('Enter the board size for the turtle walk => ')
if not n.isdigit():
print 'Need a positive number'
sys.exit()
n = int(n)
print n
''' Initialize the turtle position in the middle and print the board. '''
turtle_pos = (n-1)/2
print_board( 0, n, turtle_pos )
''' Run one step at a time until the turtle falls off the board. '''
fell_off = False
steps = 0
while not fell_off:
(turtle_pos, fell_off) = take_step( n, turtle_pos )
steps += 1
if not fell_off:
print_board( steps, n, turtle_pos )
time.sleep(0.1) # delay by the given number of seconds so we can see what is happening
print 'The turtle fell off after', steps, ' steps.'
Lecture 12¶
Module: lec12_image_copy
Use for loops to copy one image into another¶
Code:
'''
Purpose: Start of the image exercises. Create a new image by looping
over the pixels of an old image
Author: Wes Turner
Date: March 8, 2016
'''
from PIL import Image
im = Image.open("bolt.jpg")
w,h = im.size
newim = Image.new("RGB", (w,h), "white")
newim.show()
pix = im.load() ## creates an array of pixels that can be modified
newpix = newim.load() ## creates an array of pixels that can be modified
for i in range(0,w):
for j in range(0,h):
newpix[i,j] = pix[i, j]
newim.show()
Module: lec12_image_bars
Use for loops to make black bars in an image¶
Code:
'''
Purpose: Start of the image exercises. Modify the new image by including
black bars in the center.
Author: Wes Turner
Date: March 8, 2016
'''
from PIL import Image
im = Image.open("bolt.jpg")
w,h = im.size
# For simplcity, we will resize the image to have an even number
# of pixels. This is a shortcut, and not strictly necessary, but when
# we handle later examples, this resizing will greatly simplify things.
if (w % 2) != 0:
w -= 1
if (h % 2) != 0:
h -= 1
# By making the initial image black instead of white, we can get by with four
# for loops.
newim = Image.new("RGB", (w,h), "black")
newim.show()
pix = im.load() ## creates an array of pixels that can be modified
newpix = newim.load() ## creates an array of pixels that can be modified
# Upper right quadrant
for i in range(0,w/2 - 5):
for j in range(0,h/2 - 5):
newpix[i,j] = pix[i, j]
# Upper left quadrant
for i in range(0,w/2 - 5):
for j in range(0,h/2 - 5):
newpix[i,j] = pix[i, j]
# Lower right quadrant
for i in range(0,w/2 - 5):
for j in range(0,h/2 - 5):
newpix[i,j] = pix[i, j]
# Lower left quadrant
for i in range(0,w/2 - 5):
for j in range(0,h/2 - 5):
newpix[i,j] = pix[i, j]
newim.show()
Module: lec12_image_rotate
Use for loops to rotate the quadrants of an image¶
Code:
'''
Purpose: Divide the image up into 4 equal quadrants and then rotate the
quadrants clockwise
Author: Wes Turner
Date: March 8, 2016
'''
from PIL import Image
# For simplcity, we will resize the image to have an even number
# of pixels. This is a shortcut, and not strictly necessary, but it simplifies
# things for us considerably.
im = Image.open("bolt.jpg")
w,h = im.size
if (w % 2) != 0:
w -= 1
if (h % 2) != 0:
h -= 1
newim = Image.new("RGB", (w,h), "black")
newim.show()
pix = im.load() ## creates an array of pixels that can be modified
newpix = newim.load() ## creates an array of pixels that can be modified
# Upper right to upper left
for i in range(0,w/2):
for j in range(0,h/2):
newpix[i + w/2,j] = pix[i, j]
# Upper left to lower left
for i in range(w/2, w):
for j in range(0,h/2):
newpix[i, h/2 + j] = pix[i, j]
# Lower left to lower right
for i in range(w/2, w):
for j in range(h/2, h):
newpix[i - w/2 ,j] = pix[i, j]
# Lower right to upper left
for i in range(0,w/2):
for j in range(h/2, h):
newpix[i,j - h/2] = pix[i, j]
newim.show()
Module: lec12_pixellate
Use for loops to pixellate an image¶
Code:
'''
Purpose: Pixellate the image by replacing each 8x8 block with the average
value for the block
Author: Wes Turner
Date: March 8, 2016
'''
from PIL import Image
'''
Purpose: Given the location of the upper left corner of an 8x8 block, write
the average value of the block from image_in to the corresponding
8x8 location in image_out
'''
def replace_block(corner, image_in, image_out):
valR = 0
valG = 0
valB = 0
for i in range(corner[0], corner[0]+8):
for j in range(corner[1], corner[1]+8):
valR += image_in[i,j][0]
valG += image_in[i,j][1]
valB += image_in[i,j][2]
valR /= 64
valG /= 64
valB /= 64
val = (valR, valG, valB)
for i in range(corner[0], corner[0]+8):
for j in range(corner[1], corner[1]+8):
image_out[i,j] = val
# Begin of main
im = Image.open("bolt.jpg")
w,h = im.size
# Again, resizing is not strictly needed, but using a multiple of 8 simplifies
# the process
w -= (w % 8)
h -= (h % 8)
print w, h
newim = Image.new("RGB", (w,h), "black")
newim.show()
pix = im.load() ## creates an array of pixels that can be modified
newpix = newim.load() ## creates an array of pixels that can be modified
# Call our function above for each 8x8 block in the input image.
for i in range(0,w,8):
for j in range(0,h,8):
replace_block((i,j), pix, newpix)
newim.show()