Python Moodle Flashcards

1
Q

What is an algorithm?

A

A step by step sequence of instructions that if followed exactly will solve the problem under consideration.
Algorithms are like recipes: they must be followed exactly, they must be clear and unambiguous, and they must end.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a program?

A

A sequence of instructions that specifies how to perform a computation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The differences between natural and formal languages include:

A

ambiguity, redundancy, and literalness

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Source code is another name for:

A

the instrucions in a program, written in a high-level language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between a high-level programming language and a low-level programming language?

A

It is high-level if the program must be processed before it can run, and low-level if the computer can execute it without additional processing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between a compiler and interpreter?

A

Interpreter reads a high-level program line by line and performs computations.

A compiler reads the high-level program (soucre code) and translates it into object code. The object code is then executed without further translation.

Interpreter: line by line translation
Compiler: translates the whole book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is debugging?

A

tracking down programming errors and correcting them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What type of errors extist and explain?

A
  1. Syntax Error
    syntax = structure of the program
    Syntax errors are mistakes in using the language. Examples of syntax errors are missing a comma or a quotation mark, or misspelling a word. This is typically found by the compiler/interpreter.
  2. Runtime Error (=excpection)
    Runtime, or execution-time, errors are found when a script or function is executing (=found by the interpreter). Ex. divide by 0.
  3. Semantic Error (=logical error)
    semantic = meaning of a program
    A semantic error is a mistake in reasoning by the programmer, but it is not a mistake in the programming language (=can only be found by the programmer)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a token?

A

One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Python is a

A
  • general-purpose programming language
  • scripting language
  • interpreted language
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the order of the program execution process?

A
  1. Write the code
  2. Compile
  3. Debug
  4. Execute the compiled and debugged code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In a nutshell what are the key components of a computer program?

A

Input
Operations
Control Structures
Ouput

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the truncated division operator?

A

ex. 9//5 = 1
–> ignores the remainder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the modulus operator?

A

ex. 7 % 3 = 1
1 % 5 = 1 (5*0 + 1)
–> keeps only the remainder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are keywords?

A

Keywords define the language’s syntax rules and structure, and they cannot be used as variable names,
e.g. and, def, class, True, try, except, global

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is increment, bumping, and decrement?

A

increment: adding something to a variable
bumping: increment a variable by 1 ( x+= 1)
decrement: subtracting something to a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What to watch out for when using the input function?

A

Input function returns a string value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What to watch out for when choosing a variable name?

A
  • begin with a letter
  • no illigeal characters (+,$,..)
  • no keywords
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Write the Python code that displays the value of a,b,c in one line with the ‘+’ operator:

a = int(input(“please enter a number”))
b = input(“please enter a sentence”)
c = ‘the input sentence is: ‘

A

In order to use the + first, we have to make sure that all the variables have the same data type.

The value of b and c is a string but the value of a is an integer so we need to convert it to a string by using str().

print(str(a) + b + c)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Important difference between string and list?

A

Lists can be changed while strings are immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do we call a string that contains no characters?

A

empty string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the difference between lists and tuples?

A

lists:
[10, 20, 30, 40]
[“spam”, “bungee”, “swallow”]
mutable

tuples:
julia = (“Julia”, “Roberts”, 1967, “Duplicity”, 2009, “Actress”, “Atlanta, Georgia”)
immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you access the last character or middle character of the string fruit = “grape”?

A

lastchar = fruit[-1]
lastchar = fruit[len(fruit) - 1]

midchar = fruit[len(fruit) // 2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a slice operator?

A

The slice operator [n:m] returns the part of the string starting with the character at index n and go up to but not including the character at index m.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What does the ‘+’ operator and ‘*’ operator do with lists?

fruit = [“apple”,”orange”,”banana”,”cherry”]
print([1,2] + [3,4])
print(fruit+[6,7,8,9])
print([0] * 4)

A

+ concatenate
* repeats items in a list

[1, 2, 3, 4]
[‘apple’, ‘orange’, ‘banana’, ‘cherry’, 6, 7, 8, 9]
[0, 0, 0, 0]

Beware when adding different types together! Python doesn’t understand how to concatenate different types together. Thus, if we try to add a string to a list with [‘first’] + “second” then the interpreter will return an error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does the count method do?

a = “I have had an apple on my desk before!”
print(a.count(“e”))
———————
z = [‘atoms’, 4, ‘neutron’, 6, ‘proton’, 4, ‘electron’, 4, ‘electron’, ‘atoms’]
print(z.count(“4”))
print(z.count(4))
print(z.count(“a”))
print(z[0].count(“a”))
print(z.count(“electron”))

A

It requires that you provide one argument, which you would like to count. The method then returns the number of times that the argument occurred in the string/list the method was used on

5
———————
0
3
0
1
2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does the index method do?

music = “Pull out your music and dancing can begin”
bio = [“Metatarsal”, “Metatarsal”, “Fibula”, [], “Tibia”, “Tibia”, 43, “Femur”, “Occipital”, “Metatarsal”]

print(music.index(“m”))
print(music.index(“your”))

print(bio.index(“Metatarsal”))
print(bio.index([]))
print(bio.index(43))

A

The other method that can be helpful for both strings and lists is the index method. The index method requires one argument, and, like the count method, it takes only strings when index is used on strings, and any type when it is used on lists. For both strings and lists, index returns the leftmost index where the argument is found. If it is unable to find the argument in the string or list, then an error will occur.

14
9
0
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

song = “The rain in Spain…”
wds = song.split()
print(wds)
———————
song = “The rain in Spain…”
wds = song.split(‘ai’)
print(wds)

A

The split method breaks a string into a list of words.

[‘The’, ‘rain’, ‘in’, ‘Spain…’]

[‘The r’, ‘n in Sp’, ‘n…’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

wds = [“red”, “blue”, “green”]
glue = ‘;’
s = glue.join(wds)
print(s)
print(wds)

print(“***“.join(wds))
print(““.join(wds))

A

red;blue;green
[‘red’, ‘blue’, ‘green’]
redbluegreen
redbluegreen

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is printed by the following statements?

s = “python rocks”
print(len(s))

A

12 –> whitespace is a character

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is printed by the following statements?

L = [0.34, ‘6’, ‘SI106’, ‘Python’, -2]
print(len(L[1:-1]))

A

3
[n:m] –> n wird mitgezählt, m nicht

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What will be stored in the variable ty below?

qu = “wow, welcome week!”
ty = qu.index(“we”)

A

5

When we get the index of a string that is longer than one character, we get the index for the first character in the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What will be stored in the variable ty below?

qu = “wow, welcome week! Were you wanting to go?”
ty = qu.count(“we”)

A

2

There is a difference between “we” and “We” which means there are only two in the string –> case sensitive

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the ouput of this code?

for achar in “Go Spot Go”:
print(achar)

A

G
o

S
p
o
t

G
o

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the range function range(n)?

ex. range(3)

A

starts at 0 and goes up to but not including n.

range(3) –> [0,1,2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

When is the for variable _ used?

for _ in range(3):
print(“This line will execute three times”)
print(“This line will also execute three times”)

A

When we don’t intend to ever refer to the loop variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How many comparison operators exist in Python?

A

6
x == y
x != y
x > y
x < y
x >= y
x <= y

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What does the ‘in’ operator?

A

The in operator tests if one string is a substring of another:

print(‘p’ in ‘apple’)
print(‘i’ in ‘apple’)
print(‘’ in ‘a’)
print(‘’ in ‘apple’)

True
False
True
True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the type of m?

l = [‘w’, ‘7’, 0, 9]
m = l[1:2]

A

It’s a list! A slice returns a list no matter how large the slice size is.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the type of m?

l = [‘w’, ‘7’, 0, 9]
m = l[1]

A

It’s a string! [1] indicates it is the second element ‘7’ in the list, and the quotes around the number mean that this is a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is the type of a?

b = “My, what a lovely day”
x = b.split(‘,’)
z = ““.join(x)
y = z.split()
a = ““.join(y)

A

It’s a string!

The string is split into a list, then joined back into a string, then split again, and finally joined back into a string “Mywhatalovelyday”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the output message of the following code:

x,y,z = 1,2,3

def sum_two(x,y,z):
return x+y, y+z, x+z

result = sum_two(x,y,z)

a,b = result[::2]

print(str(a) +str(b))

A

34

Yes, result = (3,5,4) after calling sum_two function. a, b = (3,4) after executing result[::2]. Finally it concatenates ‘3’ and ‘4’.

result[::2] –> anfang bis ende in 2er Schritten
element 0, 2, 4, … –> a,b = (3,4)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Array-based structure vs. linked-based structure:

Which data structure is better?

A
  1. The array-based structure generally takes less memory as compared to the linked-based structure if the collection is considered relatively full.
  2. The array-based structure is preferred if the total number of elements of a collection can be predetermined at the start of the program implementation.
  3. The linked-based structure is preferred if adding new elements and removing existing elements are regularly performed at random positions; although the array-based structure is more efficient for accessing elements at random.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Which of the following can be used in Python? There are multiple answers for this question.

primitive data types
abstract data types
user-defined data types
predefined data types
all of the above

A

primitive data types
abstract data types
user-defined data types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Abstract data type is the built-in data type in Python. True or false?

A

False, primitive data types is the built-in data type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is an example for aliasing?

A

a = [81, 82, 83]
b = a
print(a is b)
——-
True

Since variables refer to objects, if we assign one variable to another, both variables refer to the same object. In general, it is safer to avoid aliasing when you are working with mutable objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What does the ‘is’ operator?

A

We can test whether two names refer to the same object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

When is it useful to use cloning lists?

A

If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference.

a = [81,82,83]

b = a[:] # make a clone using slice
print(a == b)
print(a is b)

b[0] = 5

print(a)
print(b)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is printed by the following statements:

s = “Ball”
s[0] = “C”
print(s)

A

Error, strings are immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What is printed by the following statements?

alist = [4,2,8,6,5]
blist = alist * 2
blist[3] = 999
print(alist)
[4,2,8,999,5,4,2,8,6,5]
[4,2,8,999,5]
[4,2,8,6,5]

A

[4,2,8,6,5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is printed by the following statements?

alist = [4,2,8,6,5]
alist = alist + 999
print(alist)

A

Error, you cannot concatenate a list with an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is printed by the following statements?

s = “python rocks”
print(s.count(“o”) + s.count(“p”))

A

3

53
Q

What is printed by the following statements?

s = “python rocks”
print(s[1]*s.index(“n”))

A

yyyyy

54
Q

What is printed by the following statements?

v = 2.34567
print(‘ {:.2f} {:.7f}’.format(v, v, v))

A

2.3 2.35 2.3456700

55
Q

What are simple/atomic data types?

A

The represented data values cannot be further decomposed, e.g. int, float, bool

56
Q

What are complex data types?

A

We have complex data types for representing collections of multiple data values, e.g. strings, lists, tuples, dictionaries, and sets.

57
Q

What is an array-based structure?

A
  • Array is a collection of data items organised and stored sequentially
  • Store collection of data items of the same type
  • Each data item can be randomly accessed using the concept of ‘indexing’
  • Has a fixed size
  • Is costly to Inserting new data items
58
Q

What is a linked-based structure?

A
  • Linked list is a collection of nodes where each node has two parts: 1. data and 2.
    Referencer to the next node
  • The data items are linked together as a collection using the concept of ‘referencing’.
  • Each data item can be accessed sequentially starting from the first data items
  • Has a dynamic size
  • No random access
  • Extra memory space for reference
59
Q

What are dictionary methods you have learned in class?

A

x.keys() –> returns a view of the keys in the dictionary

x.values() –> returns a view of the values in the dictionary

inventory = {‘apples’: 430, ‘bananas’: 312, ‘oranges’: 525, ‘pears’: 217}

for k, v in inventory.items():
print(“Got”, k, “that maps to”, v)
————–

x.get(key) or x.get(key,alt) –> returns the value associated with key none or alt otherwise

60
Q

As dictionaries are mutable what porblem can arise?

A

You need to be aware of aliasing!

opposites = {‘up’: ‘down’, ‘right’: ‘wrong’, ‘true’: ‘false’}
alias = opposites

print(alias is opposites)

alias[‘right’] = ‘left’
print(opposites[‘right’])
————–
True
left

61
Q

What are ‘sets’?

A

A set is a collection of unique, unordered items. Essentially, it is a list where there are no repeating elements.

a_set = set([1,2,3,3,4,5,2,2,2])
print(a_set)
————–
{1, 2, 3, 4, 5}

62
Q

How can you manipulate sets?

A

add(item), remove(item) (=discard(item) but no runtime error if item is not present)

pop() –> remove random item fromm set

clear() –> makes set empty

63
Q

What is printed by the following statements?

mydict = {“cat”:12, “dog”:6, “elephant”:23, “bear”:20}
print(23 in mydict)

A

False, the in operator returns True if a key is in the dictionary, False otherwise.

64
Q

What are class and instance variables?

A

For a class, variables defined outside the body of any methods are called class attributes –> global, can be accessed inside or outside of the classing using the dot operator.

Instance variables are unique to each instance of a class and they are defined with the self.keyword

65
Q

Which of these is not the fundamental concept of OOP?

  • abstraction
  • encapsulation
  • inheritance
  • polymophism
  • instantiation
A

instantiation

66
Q

Encapsulation vs. Abstraction

A
  • Hiding data complexity
  • Encapsulation means storing the code of each functionality in one place. While abstraction is responsible for presenting only non-sensitive information to the user by hiding the sensitive information.
67
Q

What is scoping?

A

Define the part of the program where a variable is accessible

68
Q

What is lifetime?

A

Define the duration for which a variable exists during the program execution

69
Q

What is a global variable?

A

Can be accessed throughout the entire program

Exists until the execution of the program terminated

70
Q

What is a locla variable?

A

Can only be accessed within the function it was defined

Exists until the function exists

71
Q

How many objects and reference variables are there for the given Python code?

class A:
print(“Inside class”)
A()
A()
obj=A()

A

3 objects, 1 reference variable

obj is the reference variable here and an object will be created each time A() is called.So there will be 3 objects created. Run the following code to see

72
Q

Which of the following is correct with respect to OOP concept in Python?

Objects are real world entities while classes are not real.

Classes are real world entities while objects are not real.

Both objects and classes are real world entities.

Both object and classes are not real.

A

Objects are real world entities while classes are not real.

In OOP, classes are basically the blueprint of the objects. They don’t have physical existence.

73
Q

What will be the output of the below Python code?

class A:

def \_\_init\_\_(self,num):

    num=3

    self.num=num

def change(self):

    self.num=7

a=A(5)

print(a.num)

a.change()

print(a.num)

A

3
7

74
Q

In python, what is the method inside class?

A

In OOP of Python, function is known by “method”.

75
Q

Which of the following is correct?
class A:

def \_\_init\_\_(self):

    self.count=5

    self.count=count+1

a=A()
print(a.count)

5
6
0
Error

A

It will throw an error as inside constructor, “count” is not defined.

76
Q

What does super() in OOP?

A

Super() will call every parent’s version of the function

77
Q

What is Stack ADT?

A

stack abstruct data type is an ordered collection where data items are accessed based on LIFO (last-In-First-Out)

push(item): add a new item onto the top of the stack

pop(): remove an existing item from the top of the stack

peek(): look at the top item of the stack; without modifying the stack

78
Q

What is Queue ADT?

A
  • An ordered collection where data items are accessed based on FIFO (First-In-First-Out)
  • adding new items at the “rear” of the queue
  • Removing existing items at the “head” of the queue

append(item)/Enqueue(): append a new item at the rear (end) of the queue
serve()/Dequeue(): remove an existing item from the front of the queue

79
Q

What is self in classes?

A

self is a variable referencing to the instance itself, when we create an instance of the Class.

The variables with prefix “self.” are called instance variables. The values are attached to the instance rather than the Class.

self is always put as the first argument when we define a Class method.

And of course, self is just a name. You can change it to other names, although it is not preferred.

80
Q

When a child class inherits from only one parent class, it is called?

A

When a child class inherits from only one parent class, it is called single inheritance.

81
Q

What does the built-in function type do in the context of classes?

A

Determines the class name of any value.

For example:&raquo_space;> help() usually gives information of the class on any built-in type or function.

82
Q

The child’s __init__() function overrides the inheritance of the parent’s __init__() function. True or False?

A

True!
The child’s __init__() function overrides the inheritance of the parent’s __init__() function.

83
Q

Which function makes the child class inherit all the methods and properties from its parent?

A

super () will make the child class inherit all the methods and properties from its parent

84
Q

Which inheritance is a blend of more than one type of inheritance?

A

Hybrid inheritance: This form combines more than one form of inheritance.

85
Q

What are available mode to open a file in Python?

A

r: open for reading
w: open for writing, tuncating the file first
x: open for exclusive creation, failing if the file already exists
a: open for writing, appending to the end of the file if it exists
b: binary mode (e.g. images, videos)
t: text mode
+: open for updating

86
Q

In which modes is readlines() not available?

A

With mode ‘w’ and ‘a’

87
Q

What is the problem?

with open(‘ingredients’, ‘r’) f:
i = f.readlines()
for l in lines:
print(l.split(‘\t’)[0])
f.close()

A

i is a list. It does not have split() method.

88
Q

Name the three most common types of test cases:

A
  • valid cases
  • invalid cases
  • boundary cases.
89
Q

Name 4 error messages in Python

A

SyntaxError:
error in the syntax, e.g. ‘:’

NameError:
try to use a value before initialising it or you attempt to use a package without first importing it

TypeError:
try to use incompatible data types within a single statement or passing arguments of the wrong type to a function, e.g. adding a string and an integer or passsing a list to a function that expacts an integer

ValueError:
function receives an argument with the correct data type but with an inappropriate value.
e.g. negative number in .sqrt()

90
Q

What is unittest?

A

unittest is a package to automate testing

91
Q

Why is testing important?

A
  • fixing a bug early is way cheaper in earlier stages
  • ensure correctness –> program has to work properly (and humans make mistakes)
  • to ensure the quality of our program is high –> stay competitive
92
Q

Working with file read/write:

inputFile.readline()
for line in inputFile
inputFile.readlines()
inputFile.read()

A

read one line at a time (‘\n’ is included) until the end of the file is reached

iterate through each of the lines on each iteration of the loop

read the entire content of a file and return it as a list

read the entire content of a file and return it as a string

93
Q

Name 4 levels of testing:

A

Unit testing:
- Individual units or components of a program are tested
- Validate that each unit is fully functional without errors

Integration testing:
- Individual units are combined and tested as a group
- Errors/defects might expose during the interaction between integrated units

System testing:
- The complete integrated application is tested as a whole
- Ensure that all the functionality and requirements are achieved

Acceptance testing:
- The complete application is tested by users before its deployment
- Evaluate the system complies with all the business requirements

94
Q

How is testing performed?

Explain basic vs. good testing strategy

A

Basic approach:
- Define a test strategy with various test cases identified, which are important to ensure the correctness of your program

Good testing strategy
- Make sure all the functionality can be covered/tested in a finite amount of testing time
- Composed of a reasonable and manageable number of test cases
- Maximise the chance of detecting an error or a defect

95
Q

What does assertEqual check?

A

check if a==b

assertEqual(first, second, msg=None)

96
Q

Assign SyntaxError, NameError, TypeError, and ValueError to the following codes:

  1. if a_number > 2
    print(a_number, “is greater than 2”)

2.
a_number = random.random()

3.
if a_number > 2:
print(a_number + “is greater than 2”)

4.
sum_of_two = int(‘1’) + int(‘b’)

A

SyntaxError –> missing ‘:’
NameError –> using random.random() before importing library random
TypeError –> concatenate int with string
ValueError –> passing a wrong value to a function, here string ‘b’ to int()

97
Q

Which of the following exception will be thrown for the given program?

def test_function(first_arg, second_arg):
result = first_arg + second_arg
return result

print(test_function(‘1’,2))

A

result = string + int –> TypeError

98
Q

Which of the following exception will be thrown for the given program?

NameError, AttributeError, RuntimeError, None of the above

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def get_x(self):
    return self.x
    
def get_y(self):
    return self.y a_point = Point(1,2) a_point.set_x(2)
A

.set_x() doesn’t exist –> AttributeError

99
Q

Which block lets you test a block of code for errors?

try
except
finally
none of the above

A

try

100
Q

It is raised when the requested module definition is not found.
Import Error

Import Error
EOF Error
Index Error
Type Error

A

Import Error

101
Q

What will be the output for the following code?

try:
print(x)
except:
print(““An exception occurred””)

A

An exception occurred be the output for the followinng code because the try block will generate an error, because x is not defined.

102
Q

What will be the output for the What will be the output for the following code?

x=10
y=8
assert x>y, ‘X too small’

A

No ouput.

assert x>y returns True and no other print ouput –> no ouput

if x<y output would print “X too small”

103
Q

Which exception is raised when a calculation exceeds the maximum limit for a numeric type?
StandardError
ArithmeticError
OverflowError
FloatingPointError

A

OverflowError : Raised when a calculation exceeds maximum limit for a numeric type

103
Q

What returns
random.random()
random.randint(a,b)
random.choice()

?

A

random.random():
Return a random floating number btw 0 and 1

random.randint(a,b):
Return a random number between and including a and b

random.choice(): Return a random element from a list

103
Q

What is re (Regular Expression)?

A

The Regular Expression (re or regex) is a string matching module that allows finding the specified pattern in the given string/text. For example, we have a very long text of 500 lines, and we want to find all the words that start with the character “P” and end with the symbol “N” it can be done using the regex.

104
Q

What does re.findall(pattern, text)?

A

The findall function works similarly to the search function, and the advantage is it finds all the matching and return the list of string or tuples.

105
Q

What does re.sub(pattern, replace_word, text)?

A

The sub-function finds and substitutes the pattern with a new given the word in the text. So, first, it searches and then does the substitution.

import re

text = “Python is fun. Python is fast, easy to learn, and awesome.”
pattern = r”Python”
replace_word = “python”

python is fun. python is fast, easy to learn, and awesome.

106
Q

What does pattern = r”[Pp].*?[nN]”?

A

’.*?’: it tries to match any number of characters and stops when the next character in the regex is found

107
Q

In a regular expression, the pattern “\w” is equivalent to:

A

Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].

108
Q

Consider the following code:

import numpy as np
a = np.arange(0,20,2)
a.shape = (2,5)
print(a[:,1])
What will be the output?

Index Error
[2 12]
[10 12 14 16 18]
[2]

A

a = array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])

a.shape = array([[ 0, 2, 4, 6, 8], [10, 12, 14, 16, 18]])

a[:1] = [2, 12]

109
Q

Which search algorithm have you learned in class?

A

Sequential Search:
Starting at the first item in the list, we simply move from item to item, following the underlying sequential ordering until we either find what we are looking for or run out of items. If we run out of items, we have discovered that the item we were searching for was not present.

–> less efficient, particularly when target item is at the end of the collection or not present
(–> sorted collecton can be an improvement here (sorted sequential search))

Binary Search (list needs to be sorted):
The binary search algorithm starts by picking an item that divides the list into approximately two halves. We then compare this middle item with the target item, which will result in three possible conditions:

The middle item is indeed the target item.
The target item is less than the middle item.
The target item is greater than the middle item.

110
Q

Which sortin algorithm did you learn in class?

A

Bubble Sort:

Selection Sort:

Insertion Sort:

111
Q

What is Bubble Sort?

A

The underlying idea is to bubble up the larger items to the top, or the end of the collection and sink down the smaller items to the bottom, or the start of the collection. Upon completing one iteration of traversing through the entire collection, the next largest item will be in place (i.e. at its correct position).

Bubble Sort is regarded as one of the most inefficient sorting algorithms due to the total number of swaps (or re-ordering) that need to be performed in the inner loop of the algorithm. If the list is in reverse order, the number of swaps can be expensive in terms of computation.

112
Q

What is Selection Sort?

A

the Selection Sort algorithm only requires one swap at the end of each iteration having traversed through the collection. In each iteration, we attempt to find the next smallest item (or it could be the next largest item) by comparing each pair of adjacent items and place the smallest item (or the largest item) at the correct position at the end of the iteration. Note that we are still required to perform n-1 iterations like Bubble Sort if there are n items in the collection.

You may realise that both Bubble Sort and Selection Sort algorithms perform the same number of comparisons. However, Selection Sort is slightly more efficient than Bubble Sort in general as it reduces the number of swaps (re-ordering) to only one in each iteration.

113
Q

What is Insertion Sort?

A

The basic idea is to pick each of the items from the unsorted sublist and insert it into the correct position within the sorted portion; as such the ‘sorted’ sublist grows each time a new sorted item is correctly placed.

Comparison with Bubble sort and Selection sort:
The total number of comparisons and reordering (shifting) could be reduced in particular if the collection is almost sorted

114
Q

Which two methods are used for an analgorithm’s performance evaluation:

A

Time Complexity:
- The amount of time needed to complete an algorithm’s execution.
- Big O notation to describe the performance
- Worst Case:
linear in the length of the list for linear_search
must search the entire list and not find it
- Best Case:
constant for linear_search
first element in any list

Space Complexity:
The amount of memory space needed to complete an algorithm’s execution.

115
Q

Time complexity of linear search?

A

O(n)

116
Q

Time complexity of binary search?

A

O(log n)

117
Q

Time complexity of bubble sort, selection sort, insertion sort?

A

O(n^2)

118
Q

What is the definition of divide-and-conquer?

A

The technique of breaking down a problem into small manageable chunks of code.

119
Q

What are the key parts of devide-and-conquer?

A

Divide: the problem into smaller and simpler sub-problems of the original problem.

Conquer: the subproblems by solving them recursively using the same solution (function) until a base case has been reached –> has to converge to the base case

Combine: the solutions of the sub-problems to get the solution for the original problem.

120
Q

Are recursive functions only capable of solving the simplest case.?

A

True

121
Q

What are the three key requirements for recursive functions?

A

Base case: The recursive function must have a base case (i.e. the simplest form)

Convergence: The recursive function must be able to decompose the original problem into sub-problems; and must be converging toward the base case

Recursive case: The recursive function must call itself recursively to solve the sub-problems

122
Q

What will the following code print?

def f(x = 0, y = 1):
return x * y

print(f(1))

A

In the function call f(1), only one argument is given. This gets assigned to the parameter x, and the parameter y takes its default value 1.

123
Q

How would you write
def f(x):
return x - 1

in an anonymous function with lambda expression?

A

lambda x: x-1

def func(args):
return ret_val

lambda args: ret_val

124
Q

Create an anonymous function that takes a string and returns the last character in that string.

A

lambda string: string[-1])(“help”)

125
Q

Explain the map() function

A

The map() function takes in a function and a sequence, and returns a map object. The first argument (i.e., function) inputs each element of the second argument (i.e., sequence) and replaces each respective element with the value returned by the first input.

def triple(value):
return 3*value

def tripleStuff(a_list):
new_seq = map(triple, a_list)
return list(new_seq)

def quadrupleStuff(a_list):
new_seq = map(lambda value: 4*value, a_list)
return list(new_seq)

print(list(map((lambda value: 5*value), [1, 2, 3])))

126
Q

What is a filter?

A

Going through a list and keeping only those items that meet certain criteria is called a filter.

127
Q

filter_obj = filter(lambda num: num % 3 == 0, range(10))
print(list(filter_obj))

filter_obj = filter(lambda num: False, range(10))
print(list(filter_obj))

filter_obj = filter(lambda num: True, range(10))
print(list(filter_obj))

filter_obj = filter(lambda num: 0, range(10)) .
print(list(filter_obj))

filter_obj = filter(lambda num: 1, range(10))
print(list(filter_obj))

A

[0, 3, 6, 9]
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[] #0 evaluates to False
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #1 evaluates to True