Contents

  1. binaryToDecimal.test.py
  2. descendSort.py
  3. oldmac.py
  4. pick4num_wfunctions.py
  5. swap.py
  6. swap_with_globals.py

binaryToDecimal.test.py 1/6

[
top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# By CSCI111

import sys

def main():
    # Read in the binary number as a string -- why?
    num = input("Enter the binary #: ")
    
    # --------- Validate the user input ----------
    if not isBinary(num):
        print(num, "is not a valid binary number.  Please try again.")
        sys.exit()
        
    decVal = binaryToDecimal(num)
    
    print("The decimal value for", num, "is", decVal)


def binaryToDecimal(binnum):
    """
    Converts the binary number to a decimal number
    Precondition: binary, a string that is a binary number
    Postcondition: returns the decimal value of the binary number
    """
    # accumulate the decimal value in this variable
    decVal = 0
    
    # go through the positions in the string
    for pos in range(len(binnum)):
        # num[pos] is a string; need to convert to an int
        bit = int(binnum[pos])
        # calculate which "place" the current bit is at
        place = 2**(len(binnum)-pos-1)
        # add to the decimal value
        decVal += place * bit
    return decVal

    
def isBinary(candidate):
    """
    Precondition: candidate is a string
    Postcondition: returns True iff candidate is a valid binary string
    """
    # check that it has all digits (no letters)
    if not candidate.isdigit():
        return False
     
    # Make sure that the inputted number only contains 0s and 1s
    for digit in candidate:
        if digit != "0" and digit != "1":
            return False
    return True

def testIsBinary():
    """
    Test the isBinary function.
    Displays the correctness or incorrectness of the function.
    Does not return anything.
    """
    
    testBinaryTrue = ["0", "1", "1000"]
    
    for test in testBinaryTrue:
        result = isBinary(test)
        if result:
            print(test, "successfully identified as binary")
        else:
            print("**ERROR! **", test, "considered not binary")
    
    testBinaryFalse = ["blue", "47", "11.1"]
    
    for test in testBinaryFalse:
        result = isBinary(test)
        if not result:
            print(test, "successfully identified as not binary")
        else:
            print("**ERROR! **", test, "considered binary")

def testBinaryToDecimal():
    """Test the binaryToDecimal function.  
        Displays the correctness or incorrectness of the function.
        Nothing is returned."""
        
    inputs = ["0", "1", "1000", "10", "0011"]
    expectedResults = [0, 1, 8, 2, 3]
    for index in range(len(inputs)):
        testInput = inputs[index]
        expectedResult = expectedResults[index]
        actualResult = binaryToDecimal(testInput)
        if actualResult != expectedResult:
            print("**ERROR! **", testInput, "should be", expectedResult)
            print("Instead, got", actualResult)
        else:
            print("Success on binary to decimal for", testInput, "-->", actualResult)
            
testIsBinary()
testBinaryToDecimal()            

descendSort.py 2/6

[
top][prev][next]
# Demonstrate passing lists to functions
# CSCI111

# this function tests the descend sort function
def main():
    # test descendSort3Nums
    list = [1,2,3]
    descendSort3Nums(list)
    print(list)

    list = [0, 5, -3]
    descendSort3Nums(list)
    print(list)
    
    list = [7,4,1]
    descendSort3Nums(list)
    print(list)
    
    list = [-1, -1, -3]
    descendSort3Nums(list)
    print(list)
    
    list = [-1, -5, -3]
    descendSort3Nums(list)
    print(list)

def descendSort3Nums(list3):
    """
    Parameter: a list containing three numbers
    Sorts the list in descending order
    Note: does not return anything, no output
    """
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp

    if list3[2] > list3[1]:
        # swap 'em
        tmp = list3[1]
        list3[1] = list3[2]
        list3[2] = tmp
    
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp
        
main()

oldmac.py 3/6

[
top][prev][next]
# Print out verses of the song Old MacDonald
# Sara Sprenkle

BEGIN_END = "Old McDonald had a farm"
EIEIO = ", E-I-E-I-O"

def main():
    # call the verse function to print out a verse
    printVerse("dog", "ruff")
    printVerse("duck", "quack")
    
    animal_type = "cow"
    animal_sound = "moo"
    
    printVerse(animal_type, animal_sound)
    

# QUESTION: What happens if main called function as
# printVerse("ruff", "dog")


def printVerse(animal, sound):
    """
    prints a verse of Old MacDonald, plugging in the animal and sound
    parameters (which are strings), as appropriate.
    """
    print(BEGIN_END + EIEIO)
    print("And on that farm he had a " + animal + EIEIO)
    print("With a " + sound + ", " + sound + " here")
    print("And a " + sound + ", " + sound + " there")
    print("Here a", sound)
    print("There a", sound)
    print("Everywhere a " + sound + ", " + sound)
    print(BEGIN_END + EIEIO)
    print()

# Used to prevent automatically executing the main function when the 
# program/module is imported.
if __name__ == '__main__':
    main()
#main()

pick4num_wfunctions.py 4/6

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111

from random import *
import sys

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

def main():

    pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")
    
    ######  handle bad input ######
    error = False
    errorMessage = "Error:\n"
    
    # Check that user enters a string that contains only numbers
    if not pickedNum.isdigit():
        errorMessage += "\tYour number must contain only numbers\n"
        error = True
    
    # User enters a number that is not four digits long
    if len(pickedNum) != 4:
        errorMessage += "\tYour number must contain four numbers"
        error = True
        
    if error:
        print(errorMessage)
        sys.exit()
    
    winningNum = generateWinningNum()
    
    print("The winning Pick 4 lottery number is ", winningNum)
    print()
    
    if winningNum == pickedNum:
        print("Congratulations!  You are very lucky and rich!")
        print("We should be friends!")
    else:
        print("Sorry, you lost.")
    
def generateWinningNum(numNums=NUM_PICKS):
    """
    generates a winning number based on constants defined for ...
    returns a string of random numbers of length numNums; 
    default numNums is NUM_PICKS
    """
    # Generate the random number
    winNum = "" # start it as empty
    
    for i in range(numNums):
        # generate a random number
        # add the random number to the previous random number
        winNum += str(randint(MIN_VALUE,MAX_VALUE))
        
    return winNum
    
main()

swap.py 5/6

[
top][prev][next]
# Attempt at swapping two variables in a function
# FAIL!  Swapping within a function won't work. :(
# Why?  Because in Python, we're only passing in *copies*
# of parameters, not the original variables


def main():
    x = 5
    y = 7
    
    swap(x, y)
    
    # at the end, y should be 5 and x should be 7
    print("x =", x)
    print("y =", y) 

def swap( a, b):
    tmp = a
    a = b
    b = tmp
    print(a, b)    
    
main()


swap_with_globals.py 6/6

[
top][prev][next]
# Swapping two variables in a function.
# Using global variables allows for a successful swap, 
# but we are not passing in x and y as parameters and using those
# parameters.

def swap():
    global x, y
    origx = x
    x = y
    y = origx    

x = 5
y = 7

swap()

# at the end, y should be 5 and x should be 7
print("x =", x)
print("y =", y) 



Generated by GNU enscript 1.6.4.