Study Questions for 115 Final

Not guaranteed to be all inclusive, but good to work through. These will not be collected!! they may be referred to during class review.

I recommend highly that you look at previous study questions - they are still posted on the class web page.

  1. Put parentheses in this expression to show what order the operators are executed in. What is the final value of the expression?
          5 > 4 and 3 <= 7 or 5 != 7*2
    
  2. String methods: if str1 = " 987694 3290 " and st2 = "2"
    1. len(st2)
    2. st2 + str1
    3. str1 + st2
    4. str1[5:9]
    5. str1.split("9")
    6. str1.strip()
    7. str1.find(st2)
    8. str2.find(st1)
    9. str1.upper()
    10. str1.replace('9','5')
  3. Write a loop that will read in numbers from the keyboard until a 0 is entered, then report the largest and smallest numbers entered. Be careful NOT to process the zero. You _must_ use sentinel logic. This can be solved WITH a list and without. You should know how to do both.
  4. Write some code that will read in strings from the keyboard and find the total of their lengths, until the string "stop" is entered.
  5. Write the code to generate a random number that would simulate drawing a card from a deck of cards numbered 1 through 52.
  6. What is an alias? What is the output of the code below?
        p1 = [1, 3, 5]
        p2 = p1
        p2[2] = 7
        print(p1)
    
  7. Describe the effect on the input file of the following operators or functions: open, close, read, readline, readlines
  8. Describe the effect on the output file of the following operators or functions: open, close, print, write
  9. Describe a flag variable. What type should it be? why? List the three steps you do with a flag. What is the difference between the ANY pattern and the ALL pattern?
  10. Describe the "dot notation" and what it means. What kinds of objects did you see this semester? What kinds of methods?
  11. Why are each of these an infinite loop?
    a.      Answer = 'y'
            while Answer == 'y':
                n +=1
                ans = input("another loop? y/n")
    
    b.      i = n+1
            while i != n:
               i +=1
    	   print(i)
    
    
  12. Correct the logic errors in the code below.
       # Add numbers entered until sentinel -1 is encountered.
    	  n = int(input("enter a number"))
    	  sum = 0
              while n == -1:
                 sum = sum + n
    	  n = int(input("enter a number"))
    
    
  13. Which kind of loop do you want in these circumstances?
    1. You are writing a game where the user will guess numbers until they guess the one the computer picked at random.
    2. You are testing a student to see if they know the capitals of all 50 states. They only get one chance per state.
    3. You are drawing a standard-sized chessboard.
  14. What's the output?
    count = 0 
    loop = 0 
    
    while count < 4: 
         loop = loop + 1 
         count = count + 2 
    
    count = count + loop 
    print(count) 
    
  15. What's the output?
    def h(x,y):
      ans = x * x + y * y
      return ans
    
    def main():
      ans = 5
      result = h(3,4)
      print(ans, result)
    
    main()
    
  16. What's the output?
    count = 0
    for n in range(4):
         if n %2 != 0:  
              count = count + 2
    print(count)
    
  17. What's the output?
    count = 0
    for i in range(2):
         for j in range(2):
              if i == j:
                   count = count + 1
    print(count) 
    
  18. What's the output?
        list1 = []
        list2=[1,2,3]
        list1.append("start")
        list1.append(2)
        list1.append(list2[0])
        print(list1) 
    
  19. What's the output?
    count = 1
    sum = 0
    for number in range(2):
         while count  > number:
              sum = sum + 4
              count = count - 1
    print(sum) 
    
  20. What's the output?
    list3 = [0,0,0]
    for i in range(2):
        for j in range(2):
            if i == j:
                list3[i] = i-j
            else:
                list3[j] = j-i
    print(list3)
    
  21. What's the output?
    list2 = []
    for i in range(2,5):
        list2.append(i)
    for i in range(len(list2)):
        if i > 0:
            list2[i] = list2[i] + list2[i-1]
    print(list2)
    
  22. Write some code where you use a loop controlled by a counter to input 10 numbers and report the average of only the POSITIVE ones. Include the initializations needed.
  23. What is the output?
    def fun1 (a, b):
      	c = a+b
          	a = 25
    	b = 15
    	return c
    
    def main ():
    	x = 8
    	y = 3
    	print(x, y)
    	z = fun1 (x, y)
    	print(x, y, z)
    
    main()
    
  24. For lists, what's the difference between sort and sorted?
  25. Scope: local, parameter, global - what's the difference?
  26. What's the difference between scope and lifespan? What's the lifespan of a global variable? of a local variable? of a parameter?
  27. What does it mean to have a "reference parameter" in a function? What does it mean to say "a list is mutable" in Python?
  28. How many times would the body of this loop execute?
     		for i in range(5, 15, 2):
    
  29. Write a function that would accept two float parameters and return True if the two parameter values are within 0.01 of each other, and return False otherwise.
  30. Write a for loop and a while loop that count from 0 to 200 by 20's.
  31. Someone wrote the following code, intending to print 10 20 30 40.
    arr = [10, 20, 30, 40]
    for ctr in range(1,5):
            print(arr[ctr])
    

    What went wrong when it was run?

  32. Write some code which will open a file for input, read all the data from it at one time, and print out all the words in the file to the screen. You can assume words are delimited by whitespace. The words are to be printed out 2 per line with a tab between them. Example output:
    the 	cat
    and 	the 
    rat 	were
    good	friends
    
    from the file
    the cat and the rat were
    good friends
    
    Make sure you handle the case where there are an odd number of words in the file.
  33. Compare and contrast lists and external files. The factors to consider include permanence, speed of access, direct/sequential access, size. When do you use each? what are the tradeoffs?
  34. How do you call a function which is going to return a value? How do you call a function which is NOT going to return a value?
  35. Write some code that will get a string from the keyboard and try to typecast it as an integer number, storing it in the variable user_input. If the attempt fails, tell the user that their input is incorrect and store 0 in user_input.
  36. Write some code using try/except which protects a call to the sqrt function from crashing. Why would the function crash? what error name will you use in the except statement?
  37. Write a function that determines if its integer parameter is an Angstrom number or not and returns a True if it is, a False otherwise. An Angstrom number is one whose digits, when cubed, add up to the number itself. For instance, 153 is an Angstrom number, since 1*1*1 +5*5*5 + 3*3*3 =153. Write a program to input a number, and determine whether it is an Angstrom number or not. There is a way to do this using strings, and a way to do this with just numbers. Try both.
  38. Describe the algorithm of selection sort. You don't have to know the code for it, but you should be able to do a selection sort on some numbers by hand. What is a pass of a sorting algorithm?
  39. Suppose you were sorting this list [4, 9, 8, 3, 1] using the selection sort algorithm (ascending, using max). Show what the list would look like after one pass. Show what it looks like after 2 passes. How many passes would it take to completely be sorted?
  40. Trace this code:
    	array = [0]*5;
    	for i in range(0,5):
    		array[i] = i + 2
    	for i in range(0,5):
    		if array[i] > 4:
    			array[i] = 0
    	
    
  41. Calling a function with a list as an argument - can the function change the values in the list?
  42. Create a variable named Class_size which has a value of 35 and create a list quizAvg of size Class_size whose components contain 0.0.
  43. Show the contents of both lists after the code is executed.
            medium = 7
            number = [0] *medium
            val = [0] * medium
    
    	number[0] = 1
    	for i in range(1, medium):
    		number[i] = 2 * number[i-1]
    
    	for i in range(medium):
    		val[i] = number[i] * i
    
  44. Write a function prod that has parameters of two lists arr1 and arr2 that are both the same size. This function should return the product of all components of arr2 for which the corresponding components of arr1 are negative. For example,
    if arr1 were [-1, 4, 9, -2, 7]
    if arr2 were [9, 5, 4, 2, 1]
    
    the product returned would be 9 * 2 = 18.
    
  45. Write a function which has one parameter, n. This is an integer. It creates a 2-dimensional list where the first row has one element, value 0, the second row has 2 elements, both zero, the third row has 3 elements, all 3 zero, and so on, up to and including n. That is, the list should have n elements. Example call; triangle(4) would give:
    [[0], [0,0], [0,0,0], [0,0,0,0]]
    
    If n is zero, return an empty list.
  46. Write a function called found, with parameters of a list and an item that searches the list for any value greater than the value of item. If such a value is found, the function returns True, otherwise False is returned. Use only one return statement. This can be written in two different ways: using a for loop, and using a while loop. Which is more efficient?
  47. This code gives the output as double-spaced on the screen. Why? How would you fix it so it was not doube-spaced?
           def main():
               infile = open("data.txt","r")
               for line in infile:
                     print(line)
               infile.close()
    
  48. Consider the index method and the find method. What types do these operate on? What type do they return? What does their return value mean? How do they indicate failure? What is the value find returns if you search for a multi-character string?
  49. Trace these pieces of code. That means, show the values of the variables as they change in RAM, and show what is printed.
    a.        for i in range(2):
    	      for j in range(3):
    		  print(j, end="")
    	      print()
    
    b.        for i in range(3):
                 for j in range (i, 5):
                    print(j, end="")
                 print()
    
    c.        for i in range(5):
                 for j in range(i, 5-i):
                    print(j, end = "")
    	     print()
    
    
  50. What is the output of the following program? the input data is given below it.
    	    a = [0] * 10
                b = [0] * 10
    	    sumA = 0
                sumB = 0 
                sumDiff = 0
    	    m = int(input("Enter a number")
                for j in range(m):
                    a[j] = int(input("Enter a number "))
                    b[j] = int(input("Enter a number "))
    		sumA = sumA + a[j]
    		sumB = sumB + b[j]
    		sumDiff  = sumDiff +  (a[j] - b[j])
                for j in range (m-1, -1, -1):
                    print (a[j], b[j], a[j]-b[j])
                print()
                print (sumA, sumB, sumDiff)
    
    Data:  
    5
    11 15
    19 14
     4  2
    17 6
    1 3
    
  51. Show the contents of the list sample after the code segment is executed.

    	  sample = []
              for k in range(8):
    		sample.append(10 - k)
    
  52. Show the contents of the list sample after the code segment is executed.
                sample = []
                for i in range(8):
    		if i <= 3:
    			sample.append(1)
    		else:
    			sample.append(-1)
    

    Use the variables in the 2 following exercises.

    	MAXSTUD = 10
    	passing = [True] * MAXSTUD
            score = [0.0] * MAXSTUD
    
  53. Write a function called grader that has the passing list and the score list as parameters. Set the component of passing to False whenever the parallel value of score is less than 60. Example: calling grader with [True, True, True] and [95.0, 30.0, 60.0] as arguments would change the second True to False. The function does not return anything.
  54. Write a value-returning function PassTotal that takes the list passing and the list score as parameters. It returns the sum of the scores where the parallel value of passing was True. Example: sending in [True, False, False, True] and [13.0, 2.0, 1.0, 5.0] would return 18.0, the sum of 13.0 and 5.0.
  55. Write a function that will have one parameter, a filename. The function opens the file for input, reads the data and returns the count of lines in the file. Don't forget to close the file. You can assume the file does exist. There are several ways to solve this problem.
  56. Write a program that will read from the keyboard the following information, divided into lines as shown below.
    3  8
    121 19 148 254 30 15 188 200
    38  14 138 211 231 45 45 33
    152 32  14 123 255 255 255 255
    
    The first line has 2 numbers on it which tell you how many lines of data there are (3) and how many numbers on each line (8). The program should read this data in and build a two-dimensional list from it. After the list is built, the program should be able to find the sum of each row and of each column. The program should work for any sized list, not just the sample.
  57. Write a program to solve this problem:
    Assume the input data is structured as follows: First there is a non-negative integer specifying the number of employee timesheets to be read in. This is followed by data for each of the employees. The first number for each employee is an integer that specifies their pay per hour in cents. Following this are 5 integers, the number of hours they worked on each of the days of the workweek. Given this data, write a loop and any necessary code that reads the data and stores the total payroll of all employees in a variable called total. Note that you will have to add up the numbers worked by each employee and multiply that by that particular employee's pay rate to get the employee's pay for the week-- and sum those values into total. Output the total variable at the end. You can assume the input comes from the keyboard, standard input.
    An example:
    3
    1500 3 5 4 1 2
    2500 4 8 8 8 7
    1750 3 5 4 5 4
    
    the value of total 146750
  58. How do you compare strings? What does the comparison "11" > "7" produce? How about "999" > "Adams" ? Describe how comparing strings differs from comparing numbers.
  59. Write a program that inputs data from a file and counts the number of vowels (upper or lower case) in the file. It reports the number at the end of the program.
  60. How many lines does the last loop read?
    def main():
          infile = open("mydata.txt","r")
          for i in range(3):
              lin = infile.readline()
          data = infile.read()
          for line in infile:
                print(line)
          infile.close()
    main()
    
  61. What is the difference between concatenation and the append method and the extend method? What types do they work on? what do they return?
  62. What is the difference between the "write" mode and the "write" method?
  63. What is the difference between the "append" mode and the "append" method?
  64. OOP terms: what is a constructor? How is a constructor called?
  65. Know the difference between the four different methods of reading from an external file. What type do they return? how much data do they read? Does the data they read have newlines or not?
  66. Know what it means to open for reading, to open for writing, to open for appending.
  67. Write a function that will take two lists as parameters and return a NEW list which contains the larger of the two elements in each slot. If the lists are not the same size, return the empty list. example: make_bigger ([1,3,5], [2,0, 1]) would return [2, 3, 5]
  68. Write a function that will take one list as parameter, and returns a new list which is the "double" of the parameter. This means that the new list is twice as long as the original, each element in the original is duplicated in the new list.
    double([3,4,5]) should return [3,3,4,4,5,5]
    double([]) should return []
  69. Write a function that will have one parameter, an integer. It will create a 1-d list that has elements [1,2,3... up to the parameter value]. create(5) will return [1,2,3,4,5], create(0) will return [].