# Reviews

  1. The value of the expression 17 % 7 is 3.

  2. Suppose that x is an non-negative integer variable. Determine the truth value of each of the following expressions.

    1. a. (x >= 0) or (x == 0)

    2. b. (x > 0) and (x == 0)

  3. Suppose x is 5 and y is 7 . Choose the value of the following expression: (x != 7) and (x <= y)

    • 0
    • false
    • true
    • null
  4. Assume you have three integer variables: x = 2, y = 6, and z . Determine the value of z given the following conditonal expression: z = x if (y / x > 0) else y . 2

  5. Which of the following expressions does not correctly determine that x is greater than 10 and less than 20?

    • 10 > x and x < 20
    • 10 < x and x < 20
    • 10 < x < 20
    • (10 < x < 20)
  6. Which of the following is the "not equal to" relational operator?

    • |
    • !
    • !=
    • not =
  7. The function returns a random number from among the numbers between the two arguments and including those numbers.

    • randrange
    • random
    • randint
    • randomNext
  8. If you need to know all of the names of the files in a specific directory for which you know the path you could use the function? listdir(path)

  9. Which file method is used to read the entire file in a single operation? read

  10. Where 's' is a string the expression needed to return a True if 's' contains only letters or False otherwise, would be? s.isalpha()

  11. While 's' is a string, to return a list of words in 's' using 'sep' as the delimiter and if no 'sep' is specified then any white space will act as the separator, you would use which string method? s.split([sep])

  12. Encoding techniques have been used for centuries. Using the Caesar cypher letter subsitution technique with n as an offset of 4, what would the encoded version of the word "emergency" be? iqivkirgc

  13. Given the variable data which refers to the string "No way!", the expression data[3:6] would evaluate to? way

  14. Given that 's' is a string in order to remove any leading or trailing whitespace you should use which command? s.strip()

  15. If you wanted to remove a specific file from a directory and you know the path to the file you could use the function remove(path) to remove the file.

  16. What would output at position m[0][0] given m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ?

    • 1
    • Nothing
    • [1, 2, 3]
    • 1, 2, 3
  17. What is min("Programming is super fun!") ?

    • P
    • r
    • a blank space character
    • u
    • !
  18. It may seem like lists and strings are quite similar in the ability to manipulate them, however, there is a big difference in that lists are mutable.

  19. The variable data refers to the list [5, 3, 7] . what would be the value of the following expression? data[-1] 7

  20. The insert method expects an integer index and the new list element as arguments.

  21. The variable data refers to the list [5, 3, 7] . what would be the value of the following expression? data += [2, 10, 5] 5, 3, 7, 2, 10, 5

  22. The in operator determines the presence or absence in a list.

  23. What gets printed given the following code?

    def foo(): 
        sval = "It is true…”
        print (sval) 
    # Global variable scope 
    sval = "I love python!"
    foo()
    print (sval)
    It is true...
    I love python!
    
  24. The expression list(map(math.sqrt, [9,36, 64])) will evaluate to? [3.0, 6.0, 8.0]

  25. When the range function is called with three arguments, those arguments indicate a lower bound, and upper bound and a step value.

  26. The following code would yield what result(s)?

    for i in range(0, 10, 2):
        print i / 10.0
    0.0
    0.2
    0.4
    0.6
    0.8
    
  27. What will render given the following code?

    def argstest(arg1, arg2, arg3):
        print "arg1:", arg1
        print "arg2:", arg2
        print "arg3:", arg3
        
    args = ("one", 1, 2)
    argstest(*args)
    arg1: one
    arg2: 1
    arg3: 2
    
  28. Describe what kwargs does?

    Uses ** to unpack a dictionary passed into the formal parameter list

  29. Finish coding the lines commented in the function setColors below…

    def setColor(**cstyles):
        //finish code below here to iterate through cstyles & print k,v pair
    setColor(color="turquoise", bold=True)
    for key, value in cstyles.items():       
        print (key,value)
  30. What is the outcome given the following code snippet?

    def m(list):
        v = list[0]
        for e in list:
            if v < e: v = e
        return v
    values = [[3, 4, 5, 1], [33, 6, 1, 2]]
    for row in values: 
        print(m(row), end=" ")
    • 1 1
    • 3 33
    • 5 33
    • 5 6

# Programs

  1. Create a python guessing game program that allows a user 3 choices to guess what a card is generated from a deck of 52 cards, consisting of each suite possible, that is 13 diamonds, 13 hearts, 13 clubs or 13 spades. Show the user the card generated if they won and when they lose.

    import random
    count = 0
    while count < 3:
        random.seed(1)
        # random number initiation for numbers as well as shapes
        forNumbers = random.randint(1, 13)
        forShapes = random.randint(1, 4)
        # Getting the user input values
        cardforNumbers = input(
            "Please enter a number 1-13(11-QUEEN,12-JACK,13-KING): ")
        cardforShapes = input(
            "Please enter a shape(1-SPADE,2-HEARTS,3-DIAMONDS,4-CLUBS): ")
        print("\nYour Entered Numbers are below:")
        print(cardforNumbers, cardforShapes)
        print("Randomly generated numbers by cardnumber / shape are below:")
        print(forNumbers, forShapes)
        
        # Conditions to check the entered and generated numbers are the same
        if (forNumbers == cardforNumbers):
            if(forShapes == cardforShapes):
                print("bingo!!! you have the same combination\n")
        else:
            print("Better luck next time\n")
        count = count + 1
  2. Join and sort the initial two lists defined below (list1 & list2). Ensure there are no duplicates in your new list. Starting at the first joined element, determine if any successive pairs of numbers are consecutive or not. List any successive pairs in your list for credit. For example given the joined list, [1, 3, 8, 9, 12, 13, 15, 16, -5, -4] the return pairs displayed should be something like (8,9),(12,13),(15,16),(-5,-4)

    list1=[1,3,-5,16,8,15]
    list2=[-4,9,-4,13,12]
    
    ist1=[1,3,-5,16,8,15]
    list2=[-4,9,-4,13,12]
    l=list(set(list1)^set(list2))
    print ("Orig. list =>%s" % l)
    print("Results:")
    for i in range(len(l)-1):
        if i%2==0:
            if l[i]<0 and l[i+1]<0: #case < 0
                if abs(l[i])-1==abs(l[i+1]):
                    print (l[i],l[i+1])
            elif l[i]+1==l[i+1]:
                print (l[i],l[i+1])
  3. Write a program that uses a two - dimensional array, which will simulate the process of counting the number of customers that are serviced through the checkout lanes of a retail store.

    The simulation will be used to analyze front - end store employee efficiency. Assuming that the store has six cashier lanes, your simulation will use random numbers to record customer counts as the fictitious customers pass through their respective cashier lanes. The two - dimensional array will store the customer count data for each hour, over an eight - hour span.
    The initial array that you will create will have 6 rows, for each of the cashier lanes, and 8 columns, for each hour in the eight - hour data study. The 6 times 8 or 48 array entries will be populated by random number generation. The first lane in the two - dimensional array will be a special 15 items or less checkout lane and thus will take on a larger random number value than the other checkout lanes.

    After you populate the array elements, display your grid and perform a statistical analysis on the collected data. The goal of the simulation is to determine if more bagging clerks are required to be utilized for increased productivity and faster checkout times for the store's customers. The determining factors for adding additional checkout clerks will be when the average number of customers served per hour per lane will be greater than some value, such as 10. Make message when this is the case.

    Run your simulation multiple times ( at least a few times ) to ascertain the rationale for adding more clerks.

    See (Program 7-18) in your text for sample code logic.

    Sample program run follows along with analytics
    Data simulation:

    hour 1hour 2hour 3hour 4hour 5hour 6hour 7hour 8
    lane116173131220139express checkout
    lane214232965
    lane345796784
    lane471957281
    lane53910610541
    lane682957665

    Data analysis:
    Row analysis:
    Cashier 1 customer count 103
    Average per hour 13

    Column analysis:
    For hour 3
    Customer count 40
    Average per hour 7

    import random
    rows = 6
    columns = 8
    table = [] * rows
    #  generate column titles
    j = 0
    print("\nData simulation: \n    ")
    while j < columns:
        print("\thr", (j + 1) , "", end = " ")
        j += 1
    print("\n")
    #  populate data for each cashier lane
    i = 0
    while i < rows:
        print("lane " , (i + 1), "  ", end = " ")
        j = 0
        row_attr = []
        while j < columns:
            #  express checkout lane
            randomInt1 = 1 + random.randrange(20)
            #  standard checkout lane
            randomInt2 = 1 + random.randrange(10)
            if i == 0:
                row_attr.append(randomInt1)
            else:
                row_attr.append(randomInt2)
            print(row_attr[j], "\t", end = " ")
            j += 1 
        table.append(row_attr)
        print("\n")
        i += 1
    # Data analysis
    rSum = 0
    rNum = int(input("Enter Cashier lane number: ")) - 1
    for c in range(len(table[rNum])):
        rSum += table[rNum][c]
    print("Customer count:",rSum, "Avg:", rSum // len(table[rNum]))
    cSum = 0
    cNum = int(input("Enter hour number: ")) - 1
    for r in range(rows):
        cSum += table[r][cNum]
    print("Hour count:",cSum, "Avg/hr:", cSum // rows)
  4. A matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following function to check whether a 3 x 3 matrix is a Markov matrix:

    def isMarkov(m):

    Write a test program that prompts the user to enter a matrix of numbers and tests whether it is a Markov Matrix (MM). Show a response for one that is and one that isn’t a MM. Here is a sample run:

    Enter the number of rows for square matrix: 3
    Enter value for row 1, column 1: .15
    Enter value for row 1, column 2: .875
    Enter value for row 1, column 3: .375
    Enter value for row 2, column 1: .55
    Enter value for row 2, column 2: .005
    Enter value for row 2, column 3: .225
    Enter value for row 3, column 1: .3
    Enter value for row 3, column 2: .12
    Enter value for row 3, column 3: .4
    Outcome: yes
    
    def isMarkov(m) : 
        
        # Outer loop to access rows 
        # and inner to access columns 
        for i in range(0, len(m)) : 
            
            # Find sum of current cols 
            sum = 0.0
            for j in range(0, len(m[i])) : 
                sum += m[j][i] 
            if (sum != 1.0) : 
                return False
                
        return True
    rows = int(input("Enter the number of rows for square matrix: ")) 
    cols = rows
    # Initialize matrix 
    matrix = []
    # For user input 
    # Fill the list with random numbers.
    for r in range(rows):
        row_arr = []
        for c in range(cols):
            num = float(input("Enter value for row {}, column {}: ".format(r + 1, c + 1)))
            row_arr.append(num)
        matrix.append(row_arr)
    # Calls the function check() 
    if (isMarkov(matrix)) : 
        print("Outcome: yes ") 
    else : 
        print("Outcome: no ")