Preview

03 - Python (Advanced)

 1. Which of the following is incorrect (False) about Python?
1. Python is interpreted
2. Python is based on functions, therefore not object orientated
3. Python is a low level programming language
4. Python can be used in webpages, directly in HTML
5. Python is considered open source

  3,4 are incorrect statements

  1,2,4 are incorrect statements

  1 and 4 are incorrect statements

  2,3,4 are incorrect statements

 2. In the following code, name the created class.
class Student:
      def __init__(self,name,test_score): 
          self.name=name
          self.test_score=test_score
          
      def hasAchievedTarget(self):
        if self.test_score>=90:
            print("Target met, Well done!")
        else:
            print("Target not achieved")

student1=Student("Jonathan",21) 
print(student1.name)
print(student1.test_score)
student1.hasAchievedTarget()

  Student

  self.name

  HasAchievedTarget

  student1

 3. Referring to the code above, when line 15 is executed, what is the output?

  Target met, Well done!

  21

  Jonathan

  Target not achieved

 4. For the following 2d array, what is the output?
nw=[["adam","seth","enoch"],["shield","belt","sword"]]
print(nw[0][1]) 

 5. The nested loop in the code below (lines 18-20) seeks to produce the same output as lines 5-7. Fill in the blanks to replace the question marks (line 20)
nw=[["adam","seth","enoch"],["shield","belt","sword"]]

print("Use sequence: print 2d array names with weapons")
print("============================================")
print("Player:",nw[0][0]," has a:",nw[1][0])
print("Player:",nw[0][1]," has a:",nw[1][1])
print("Player:",nw[0][2]," has a:",nw[1][2])

#Notice the patterns. the first 0,1,2 is inside the first list (0)
#The second 0,1,2 is happening inside the second list (1)
#We need a loop to loop through lists 1 and 2 (e.g 0 and 1)
#We need another loop to loop through each element 0,1,2 in each list.
print("")
print("")
print("Use nested loop: print names/weapons")
print("============================================")

for i in range(len(nw)):
  for j in range(len(nw[0])):
    print("Player",nw[i][j],"has a:",nw[?][j])

  j

  i

  j+1

  i+1

 6. In the following code, what is happening on line 21 and line 26? (2 marks)
class Stack:
     #start with this part which is like a constructor
     def __init__(self):
          self.items=[] #one attribute called self.items and start this as an empty stack
     #method needed to push items on to the stack
     def push(self,item):
          self.items.append(item) #items is the attribute, and we append a new item
     def pop(self):
          return self.items.pop()
     def size(self):
          return len(self.items) #returns the length of the list
     def report(self):
          return self.items #returns the elements contained in the stack
     def isEmpty(self):
          if self.items==[]: #test to see if items is equal to empty list, return True
               return True
          else:
               return False
#take in a word and reverse it
word=input("Enter a word:") #enter the word: "apple"
s=Stack()
for i in range(len(word)):
  s.push(word[i])
print(s.report())
letter=s.pop()
print(letter)

 7. Consider the following linked list based implementation of queue operations (incomplete). What is line 21-28 doing?
# A complete working Python program to demonstrate all  
# Queue operations using doubly linked list  
# Node class  
class Node: 
   
# Function to initialise the node object 
    def __init__(self, data): 
        self.data = data # Assign data 
        self.next = None # Initialize next as null 
        self.prev = None # Initialize prev as null 
           
# Queue class contains a Node object 
class Queue: 
   
    # Function to initialize head  
    def __init__(self): 
        self.head = None
        self.last=None
        

    def enqueue(self, data): 
        if self.last is None: 
            self.head =Node(data) 
            self.last =self.head 
        else: 
            self.last.next = Node(data) 
            self.last.next.prev=self.last 
            self.last = self.last.next

  Function to add an element to the Queue

  Function to check to see if the queue is full

  Check to see if the last element in the queue is empty (NULL) or contains an element

  Function to delete an element in the Queue

 8. In the following pseudocode implementation of a tree, the program _______ checks every node to see if it has a right and a left child; -1 indicates that there is _______.
procedure pre_order(tree_node)
   print (tree_node.value)
   if tree_node.left != -1  then
      pre_order(tree_node.left)
   endif
   if tree_node.right != -1 then
      pre_order(tree_node.right)
  endif
endprocedure

  recursively / no child

  iteratively / no child

  recursively /a left pointer value

  iteratively / a root child node

 9. What type of sorting algorithm has been implemented here? What needs to fill in the blanks on line 9? (2 marks)
def sorting(alist):
   for i in range(1,len(alist)):
       #element to be compared
       current = alist[i]
       #comparing the current element with the sorted portion and swapping
       while i>0 and alist[i-1]>current:
           alist[i] = alist[i-1]
           i = i-1
           alist[i] = ________?
   return alist
print(sorting([5,2,1,9,0,4,6]))

  Insertion Sort / alist[i] = current

  Merge Sort / alist[i] = i/2

  Quick Sort / alist[i] = current -i

  Bubble Sort / alist[i] = current

 10. What is the output of the following graph?
graph = {'A': ['B', 'C'],
         'B': ['A', 'D', 'E'],
         'C': ['A', 'F'],
         'D': ['B'],
         'E': ['B', 'F'],
         'F': ['C', 'E']}

def dfs_path(graph,start,end):
    result = []
    dfs(graph,start,end,[],result)
    return result

def dfs(graph,start,end,path,result):
    path+=[start]
    if start == end:
        result.append(path)
    else:
        for node in graph[start]:
            if node not in path:
                dfs(graph,node,end,path[:],result)
print(dfs_path(graph,'A','F')) 

  [['A', 'B', 'E', 'F'], ['A', 'C', 'F']]

  [['C', 'B', 'E', 'F'], ['A', 'A', 'F']]

  [['F', 'B', 'E', 'F'], ['A', 'C', 'A']]

  [['A', 'B', 'C', 'F'], ['A', 'C', 'F']]

 11. On what line in the following code is the first time you see recursion occuring?
def calc_factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))	

  line 6

  line 5

  line 4

  line 8

 12. With regard to the A* algorithm, decide whether the following statement is true or false.
When you use heuristics, you trade accuracy, correctness, and exactness for speedy processing. They will not offer perfect solutions, but they should give an approximation that can be used in decision-making

  FALSE

  TRUE

 13. What is the output of the following code and what data mapping type is being used?
def main():
    teacher_details={"Name": "Mr Moose","Subject": "Philosophy","Hobby":"Chess","School House":"Red House"}
     #this is getting at the specified key, and producing the value for that key
    print(teacher_details["Name"])
main()

  "Mr Moose" is output. A lambda map with curly brackets is being used.

  "Name". A python map lambda is being used.

  Error. A list should be being used but that uses square brackets.

  "Mr Moose" is output. A dictionary is being used.

 14. ______ is a free, open-source, full-stack web application framework written in Python. It is a set of ready-made components that help you rapidly build websites.

  Brython

  Django

  Machine Learning (ML)

  HTML

 15. The following code shows recursion to find the factorial of a number. There is one mistake. What is output from the code? How could you correct it to make it produce 5!=120
def fact(n):
    if n == 0:
        return 2
    else:
        return n * fact(n-1)

print(fact(5))

  Currently, 240 is output. Change lie 2 to "if n==1:"

  Currently, 240 is output. Change line 3 to 'return 1'

  Currently, 200 is output. Change line 3 to "return 0"

  Currently 200 is output. Change line 5 to "return n*fact(n*1)-1