Contents

  1. binaryToDecimal.py
  2. descendSort.py
  3. swap.py
  4. testingBinaryToDecimal.py

binaryToDecimal.py 1/4

[
top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# Added test functions that programmatically test if the function is behaving
# appropriately.
# 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


descendSort.py 2/4

[
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

def descendSort(listOfNumbers):
    """
    More general algorithm, where the list can be any length.
    """
    listOfNumbers.sort()
    listOfNumbers.reverse()

        
main()

swap.py 3/4

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

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

x = 5
y = 7

swap(x, y)


print("x =", x)
print("y =", y) 


testingBinaryToDecimal.py 4/4

[
top][prev][next]
# Demonstrates how we can include other's code in our code
# by importing them as modules.

from binaryToDecimal import *

def testIsBinary():
    """
    Test the isBinary function.
    Displays the correctness or incorrectness of the function.
    Does not return anything.
    """
    
    # ----------- Test where the result should be True ---------

    testBinaryTrue = ["0", "1", "10", "1001", "10000"]
    
    for test in testBinaryTrue:
        result = isBinary(test)
        if result:
            print(test, "successfully identified as binary")
        else:
            print("**ERROR! **", test, "considered not binary")
    
    # ----------- Test where the result should be False ---------
    testBinaryFalse = ["a", "3", "-100", "123"]
    
    for test in testBinaryFalse:
        result = isBinary(test)
        if not result:
            print(test, "successfully identified as not binary")
        else:
            print("**ERROR! **", test, "considered binary")
    
    # ------------ Alternatively, have a list of inputs and expected ----
    # Question: How difficult is it to verify additional test cases?
    inputs = [ "0", "1", "10", "1001", "10000", "a", "3", "-100", "123"]
    expectedResults = [ True, True, True, True, True, False, False, False, False]
    for pos in range(len(inputs)):
        testInput = inputs[pos]
        if isBinary(testInput) != expectedResults[pos]:
            print("Error on isBinary(", testInput, ")")
            print("Expected", expectedResults[pos], "but got", isBinary(testInput))
    

def testBinaryToDecimal():
    """Test the binaryToDecimal function.  
        Displays the correctness or incorrectness of the function.
        Nothing is returned."""
        
    paramInputs = ["0", "1", "10", "1001", "10000", "1101", "10110"]
    expectedResults = [ 0, 1, 2, 9, 16, 13, 22]
    for index in range(len(paramInputs)):
        paramInput = paramInputs[index]
        expectedResult = expectedResults[index]
        actualResult = binaryToDecimal(paramInput) 
        if actualResult != expectedResult:
            print("**ERROR! **", paramInput, "should be", expectedResult)
            print("Instead, got", actualResult)
        else:
            print("Success on binary to decimal conversion for", paramInput, "-->", actualResult)
            
            
testIsBinary()
testBinaryToDecimal()            

Generated by GNU Enscript 1.6.6.