CSC111 Programs Written in Class 2014

From dftwiki3
Jump to: navigation, search

--D. Thiebaut (talk) 10:40, 10 March 2014 (EDT)



021214.py


# 2/12/14
a = "hello"
b = "how are you?"
c = "short short short short"
la = len( a )
lb = len( b )
lc = len( c )
Max = la
if lb > la:
    Max = lb
if lc > Max:
    Max = lc

print( "max = ", Max )
print( "|%12s|" % a )
print( "|%12s|" % b )
print( "|%12s|" % c )

format = "|%-" + str( Max ) + "s|"
print( format )
print( format % a )
print( format % b )
print( format % c )

print( "====================" )
print( "|%*s|" % (Max, a ) )

021414.py


# rock-paper-scissors
# rock1.py
# D. Thiebaut
# example of the use of if-else for playing the game
# (this program is not very robust and will not work
# if the user does not enter an uppercase letter that is
# R, P, or S.
#
from random import choice

#--- constants ----
OPTIONS = [ 'R', 'P', 'S' ]
USERWINS = "You win!"
COMPUTERWINS = "I win!"

#--- computer picks a letter ---
computer = choice( OPTIONS )
#print( computer )

#--- user picks a letter ---
human    = input( "Your play? " )

print( "Your play: %s  Computer Play: %s" % ( human, computer ) )

#--- decide who wins ---
if human==computer:
    print( "It's a tie!" )
else:
    if human == 'P':
        # user plays Paper
        if computer == 'S':
            # computer plays Scissors
            print( COMPUTERWINS )    
        else:
            # computer plays 'R'
            print( USERWINS )  
    else:
        if human == 'R':
            # user plays Rock
            if computer == 'S':
                #computer plays Scissors
                print( USERWINS )  
            else:
                # computer plays Paper
                print( COMPUTERWINS )    
        else:
            # user has played Scissors
            if computer == 'R':
                # computer plays Rock
                print( COMPUTERWINS )    
            else:
                # computer plays Paper
                print( USERWINS )

#Version 2

#This is a tighter version. Shorter and still efficent. 
# rock-paper-scissors
# rock1.py
# D. Thiebaut
# example of the use of if-else for playing the game
# (this program is not very robust and will not work
# if the user does not enter an uppercase letter that is
# R, P, or S.
#
from random import choice

OPTIONS = [ 'R', 'P', 'S' ]
USERWINS = "You win!"
COMPUTERWINS = "I win!"

computer = choice( OPTIONS )
print( computer )

human    = input( "Your play? " )

print( "Your play: %s  Computer Play: %s" % ( human, computer ) )

if human==computer:
    print( "It's a tie!" )
elif human == 'P' and computer =='R':
    print( USERWINS )
elif human == 'P' and computer =='S':
    print( COMPUTERWINS )
elif human == 'R' and computer =='S':
    print( USERWINS )
elif human == 'R' and computer =='P':
    print( COMPUTERWINS )
elif human == 'S' and computer =='P':
    print( USERWINS )
#elif human == 'S' and computer =='R':
else:
    print( COMPUTERWINS )

#Version 3


#Even more tight, and still very efficient. 
# rock-paper-scissors
# rock1.py
# D. Thiebaut
# example of the use of if-else for playing the game
# (this program is not very robust and will not work
# if the user does not enter an uppercase letter that is
# R, P, or S.
#
from random import choice

OPTIONS = [ 'R', 'P', 'S' ]
USERWINS = "You win!"
COMPUTERWINS = "I win!"

computer = choice( OPTIONS )
print( computer )

human    = input( "Your play? " )

print( "Your play: %s  Computer Play: %s" % ( human, computer ) )

if human==computer:
    print( "It's a tie!" )
elif human == 'P' and computer =='R' \
     or human == 'R' and computer =='S' \
     or human == 'S' and computer =='P':
    print( USERWINS )
else:
    print( COMPUTERWINS )

atm.py


# atm.py
# Dominique Thiebaut  
# a program that takes some amount of $
# and breaks it down into some number of
# bills.

amount = 71

bills = amount  // 20
amount = amount % 20

if bills!=0:
    if bills > 1:
        print( bills, "$%d bills" % 20  )
    else:
        print( bills, "$%d bill" % 20 )
        
bills = amount  // 10
amount = amount % 10

bills = 3
if bills!=0:
    sb = "bills"
    if bills == 1:
        sb = "bill"
        #sb = sb.replace( 's', '' )
print( bills, "$%d %s" % (10, sb)  )

bills = amount  // 5
amount = amount % 5

if bills!=0:
    print( bills, "$%d bill(s)" % 5  )

if amount!=0:
    print( amount, "$%d bill(s)" % 1  )

blocks.py


# ATM_version1.py
# D. Thiebaut
# this program distributes some amount of dollars
# into bills and coins.
#
# Original amount
"""

amount = 124.45

# transform into two integer amounts, one for bills, one for coins
bAmount = int( amount )
cAmount = int( amount * 100 ) % 100

print( "Distributing $" + str( amount ) )

# distribute amount in different denominations
no20s = bAmount // 20
bAmount = bAmount % 20

no10s = bAmount // 10
bAmount = bAmount % 10

no5s = bAmount // 5
no1s = bAmount % 5

# display resulting bill distribution 
print( no20s, "$20-bill(s)" )
print( no10s, "$10-bill(s)" )
print( no5s,  "$5-bill(s)" )
print( no1s,  "$1-bill(s)" )

# distribute coins into different quantities
no25s = cAmount // 25
cAmount = cAmount % 25

no10s = cAmount // 10
cAmount = cAmount % 10

no5s = cAmount // 5
no1s = cAmount % 5

# display resulting coin distribution 
print()
print( no25s, "quarter(s)" )
print( no10s, "dime(s)" )
print( no5s,  "nickel(s)" )
print( no1s,  "cent(s)" )




"""







# ATM_version2.py
# D. Thiebaut
# this program distributes some amount of dollars
# into bills and coins.
#

def distribute( amount, d1, d2, d3, d4 ):
    n1 = amount // d1
    amount = amount % d1

    n2 = amount // d2
    amount = amount % d2

    n3 = amount // d3
    amount = amount % d3

    n4 = amount % d4
    
    print( "%d unit(s) of %d" % ( n1, d1 ) )
    print( "%d unit(s) of %d" % ( n2, d2 ) )
    print( "%d unit(s) of %d" % ( n3, d3 ) )
    print( "%d unit(s) of %d" % ( n4, d4 ) )

amount = 124.45
bAmount = int( amount )
cAmount = int( amount * 100 ) % 100
print( "Distributing $" + str( amount ) )

print()
distribute( bAmount, 20, 10, 5, 1 )

print()
distribute( cAmount, 25, 10, 5, 1 )

countKeywords.py


# countKeyword.py
# D. Thiebaut
# looks for 2 keywords in a series of input
# sentences.  Stops when the sentinel "Z END"
# is found.

#--- constant ---
SENTINEL = "Z END"
KEY1 = "MOTHER"
KEY2 = "FATHER"

#--- variables ---
key1Count = 0
key2Count = 0
line      = ""

# keep looping until we find sentinel
while line.find( SENTINEL ) == -1: 
    line = input().upper()

    if line.find( KEY1 ) != -1:
        key1Count = key1Count + 1

    if line.find( KEY2 ) != -1:
        key2Count += 1

print( "number of lines containing %-10s: %d" % ( KEY1, key1Count ) )
print( "number of lines containing %-10s: %d" % ( KEY2, key2Count ) )

countLower10.py


# countLower10.py
# D. Thiebaut
# keeps on accepting positive numbers on the input until a negative
# number is entered (sentinel)
# prints the count of numbers between 0 and 10 (included) in the input
#

counter = 0
timeToStop = False

while timeToStop == False:
    x = int( input( "> " ) ) 
    if x < 0:
        timeToStop = True
    elif x <= 10:
        counter = counter + 1

print( "%d numbers were found to be between 0 and 10" % counter )

findMax.py


# findMax.py
# D. Thiebaut
# longest of 3 strings
#

s1 = "a long string       "
s2 = "a short one         "
s3 = "a much longer string"

l1 = len( s1 )
l2 = len( s2 )
l3 = len( s3 )

# find the max lmax of l1, l2, l3
# (we assume that we do not know about the max() function!)

lmax = l3 # temporary
if l1 >= lmax:
    lmax = l1
if l2 >= lmax:
    lmax = l2
    
b1 = " " * ( lmax - l1 )
b2 = " " * ( lmax - l2 )
b3 = " " * ( lmax - l3 )


print( "|%s%s|" % ( s1, b1 ) )
print( "|%s%s|" % ( s2, b2 ) )
print( "|%s%s|" % ( s3, b3 ) )

first.py


# my very first program

print( "Hello DT's world!" )
print( 'Hello DT's world!' )

functionExamples.py


def f1( a, b )
    for i in range( b ):
        print( a, end=',' )
    print()

def f2( a, b )
    f1( '-', 20 )
    f1( a, 10 )
    f1( b, 5 )
    a = 0
    
def main( ):
    a = 100
    f2( ' ', ' ' )
    f2( 5, 6 )
    f2( "hello", "there" )

main()

functions1.py


def greetings():
    print( "+-----+" )
    print( "|hello|" )
    print( "+-----+" )


"""
for i in range( 10 ):
    greetings()
"""
def restaurant():
    student1()
    student2()
    student3()
    
def student1():
    print("Caramba!" )

def student2():
    print("No, No, No!" )

def student3():
    student1()
    print( "Si" )

# play
"""
for i in range( 3 ):
    student1()
student2()
student3()
student3()
#restaurant()

student2()
student1()
student3()
"""
def box( word ):
    print( "+" + ( "-" * len( word ) ) + "+" )
    print( "|" + word + "|" )
    print( "+" + ( "-" * len( word ) ) + "+" )

"""
box( "hello" )
box( "A very long sentence with lots of junk characters asldkfja;ldfkjas;lfkj" )

box( str( 23 ) )
"""
def student1_4( sentence ):
    print( sentence )
    
def student2_4( sentence ):
    print( "My T-Shirt says", sentence )

def student3_4( sentence ):
    print(  "And now listen to this: " )
    student1_4( sentence )

def superStudent( word1, word2, word3 ):
    student1_4( word1 )
    student2_4( word2 )
    student3_4( word3 )

        
# play
#student1_4( "I am tired" )
#student2_4( "I live for Chocolate" )
#student3_4( "Almost Spring Break!" )

#superStudent( "I am tired", "I live for Chocolate", "Almost Spring Break!" )
#superStudent( "My T-Shirt Says", "", "" )


def student1_5( sentence1, sentence2 ):
    student2_5( sentence1 )
    student3_5( sentence2 )
    
def student2_5( sentence ):
    print( "hear this: ", sentence )

def student3_5( sentence ):
    print(  "The news is: ", sentence )


student1_5( "Spring Break in two weeks!",  "Exam in a week and a half" )

hw5b.py


# hw5b.py skeleton program
# D. Thiebaut

from hw5data import array
from hw5data import noSamples
from hw5data import firstWordIndex
from hw5data import secondWordIndex
from hw5data import thirdWordIndex


# display whole array
print( "array = ", array )

# copy word 1 over word 2
j = secondWordIndex
for i in range( firstWordIndex, secondWordIndex ):
    array[ j ] = array[ i ]
    j = j + 1

print( "array = ", array )

# swap sample 3 with sample 12

i = 3
j = 12
temp = array[ i ]
array[ i ] = array[ j ]
array[ j ] = temp

print( "array = ", array )

hw5data.py


# hw5data.py
# D. Thiebaut
#
WORDLENGTH = 5
GAPLENGTH = 3
array = []
sign  = -1
for i in range(WORDLENGTH):
    array.append( (i*5%7+1) )

for i in range(GAPLENGTH):
    array.append( 0 )
    
for i in range(WORDLENGTH):
    array.append( (i+1)*2 )

for i in range(GAPLENGTH):
    array.append( 0 )
    
for i in range(WORDLENGTH):
    array.append( sign*(i*7%9+1) )
    sign = -sign

for i in range(GAPLENGTH):
    array.append( 0 )
    
#print( "array = ", array )
#print()
noSamples = len( array )
firstWordIndex = 0
secondWordIndex = noSamples//3
thirdWordIndex  = (2*noSamples)//3

jesSound2.py


file = pickAFile()
sound = makeSound( file )
#blockingPlay( sound )
noSamples = getLength( sound )
printNow( "number of samples = %d" % noSamples )
value = getSampleValueAt( sound, 0 )
setSampleValueAt( sound, 0, 1000 )
startClear = 10000
for i in range( startClear, noSamples ):
  setSampleValueAt( sound, i, 0 )
#blockingPlay( sound )
# echo
endWord = 10266
offset = 4000
for i in range( endWord, -1, -1):
    j = i + offset
    #print( i, j )
    valueLeft = getSampleValueAt( sound, i)
    valueRight =  getSampleValueAt( sound, j)
    setSampleValueAt( sound, j, valueLeft//4 + valueRight )

#print( array )
blockingPlay( sound )

lab1_demo.py


# tax rate table
# taxRate.py
# D. Thiebaut
# prints the first 10 years of an initial investment
# at a fixed yearly interest rate

# 1) set initial balance: $1000
InitialBal = 1000

# 2) set initial interest rate
IntRate    = 0.05

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 6) repeat 3, 4, 5 10 times  

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

# 3) balance after 1 year is initial balance + initial balance * interest rate
Bal1Year = InitialBal + InitialBal * IntRate

# 4) display balance after 1 year
print( "balance = ", Bal1Year )

# 5) make initial balance the balance after 1 year
InitialBal = Bal1Year

lecture2.py


# my second program of the week
# D. Thiebaut

name = "Hello World!"
#a = 3
#b = 5
#c = 10
#print(name)
#print(a, b, c)

for i in range( 10 ):
    print( i )
    #print( "+" + "-" * (len( name )+2) + "+" )
    #print( "|", name, "|"  )
    #print( "+" + "-" * (len( name )+2) + "+" )

quiz.py


"""
sum = 0
i = 0
print( "1", i )

while i <= 10:
   print( "2" )
   if i % 2 == 0:
      print( "3", i )
      sum = sum + 1
   else:
      print( "4", i )
   i = i + 1

print( "5", i )
print( "Done!" )

answer = input( "Do you like Python (Y/N)? " )
answer = answer.lower()
answer = answer.strip()

answer = answer[0]

while answer != 'y' and answer != 'n':
    answer = input( "Sorry, I didn't get that.  Please reenter: " )

print( "Thanks for your input!" )
"""
human = input( "Your play? " ).lower().strip()

#while human != 'p' and human != 's' and human != 'r'  :
#    human = input( "Invalid input, please try again: " ).lower().strip()
    

#while not ( human == 'p' or human == 'r' or human == 's' ):
#    human = input( "Invalid input, please try again: " ).lower().strip()


isValid = human == 'p' or human == 'r' or human == 's'   

while not isValid:
       human = input( "Invalid input, please try again: " ).lower().strip()

reverse.py


A =[ 5, 3, 2, 1, 10, -1]
print( A )
L =len( A )

for i in range( (L-1)//2, -1, -1 ):
    print( "Swapping %d and %d" % ( A[i], A[L-i-1] ) )
    temp = A[ i ]
    A[ i ] = A[L-i-1]
    A[L-i-1] = temp

print( A )

sound1.py


file = pickAFile()
sound = makeSound( file )
blockingPlay( sound)

for i in range( 0, getLength( sound ) ):
  value = getSampleValueAt( sound, i )
  setSampleValueAt( sound, i, value/2 )
  
blockingPlay( sound)

soundExercises.py


array = [4, 2, 3, 1, 0, 2, 3, 4, 5]

for sample in array:
    print( sample, end=" " )
print()

for i in range( len( array ) ):
    #print( i, end=" " )
    sample = array[ i ]
    print( sample, end=" " )
print()

# clear end of waveform
startIndex = 4
#i = startIndex
#while i < len( array ):
#    array[i] = 0
#    i = i + 1
#print( array )

for i in range( startIndex, len( array ) ):
    #print( i, end=" " )
    array[i] = 0
print( array )

# reverse
"""
for i in range( 0, len( array )//2 ):
    #print( i, end=" " )
    j = len( array )-1 -i
    #print( i, j )
    temp = array[ i ]
    array[ i ] = array[ j ]
    array[ j ] = temp
print( array )
"""
# echo
endWord = 3
offset = 2
for i in range( endWord, -1, -1):
    j = i + offset
    print( i, j )
    valueLeft = array[i]
    valueRight = array[j]
    array[j] = valueLeft//2 + valueRight

print( array )

teller.py


# Teller machine program
# teller.py
# D. Thiebaut

# initialize
# Amount = 123
amount = 1236



# compute
# number20s = amount // 20
number20s = amount // 20

# number10s = leftover // 10
leftover1 = amount % 20
number10s = leftover1 // 10

# number5s = leftover // 5
number5s = leftover1 // 5
leftover2 = leftover1 % 10

# number1s = leftover // 1
number1s = leftover2 // 1

print( amount, number20s, number10s, number5s, number1s )


# output number20s, number10s, number5s, number1s