INFO1110 ORAL 笔记

INFO1110 ORAL笔记(部分转载)

原文地址

0. Datatype

0.1 What datatype is mutable in python?

mutable data type: list, dictionary, set
other data types are immutatble (string, int, float, tuple)

Some types can be modified “in place”, that is the original object is changed instead of creating a new object.

my_list = ['a', 'b', 'c']
also_my_list = my_list

my_string = 'abc'
also_my_string = my_string

my_list.extend(['d', 'e', 'f'])
my_string = my_string + "def"
'''
Result
my_list =  ['a', 'b', 'c', 'd', 'e', 'f']
also_my_list =  ['a', 'b', 'c', 'd', 'e', 'f']
my_string =  abcdef
also_my_string =  abc
'''

0.2.1 True or False: A tuple can vary in size

False

Because tuple is an immutable datatype, if we want to change its size, only way is to change its memory address which is creating a new tuple.

0.2.2 Describe the differences in lists and tuples

Be short, tuple is like a read-only list.

Elements in a list can be modified easily, as it is mutable. But elments in a tuple can’t be modified, unless you create a new tuple variable.

0.3.1 Describe the differences in lists and arrays

Lists (python built-in datatype) : each element is separately stored but contains address of the next element , can have multiple datatype, can vary in size (use append)

Arrays : all elements are stored together, can only have one datatype, can’t change size, can jump from one element to another

List view (the difference from the array)

  • The size of the list is not fixed, it is mutable
  • Any type of object can be be included
  • Elements can be inserted or removed in any position
  • Lists can be concatenated together
  • A subset of the list can be created from the list
  • Very different memory structure

0.3.2 Describe the differences in Arrays and ArrayLists

Array can contain primitive type and object type, it has a fixed size (Predefine its size is necessary), and it only contains the same datatype elements.

ArrayList only contains object datatype, its size is not fixed, but dynamically increasing.

0.3.3 Why an array can only consist one same datatype?

Because the accessing mecahnism of elements in arrays are in linear fashion, which means it skips exactly the same size of the type of data we stored every time. And arrays are bound to be storing only homogeneous data.
If we store other datatype in an array, it would fail to reach the next element’s memory address, due to the different size of data.

0.3.4 What is the difference between []*5 vs [0]*5?

[]*5 -> [] get a empty list with length 0
[0]*5 -> [0,0,0,0,0] get a list with length 5

0.4.0 iterator vs iterable

1. iterator: Any object that has a __next__()method is therefore an iterator. ’A stream of data’

2. iterable: An iterable is any object, not necessarily a data structure, that can return an iterator (using __iter__()with the purpose of returning all of its elements). ’A sequence of that can iterate through’

0.4.1 What datatype is iterable in python?

  • String
  • Tuple
  • List
  • Set
  • Dictionary
  • Iterator

0.5 What is the difference between == and is?

"==" compares value, if they have same value
"is" compares memory addrress. if they are pointing to the same object (have same reference)

1. Function

1.1.0 What is a function?

A function is a block of reusable code that is used to perform a specific action, will produce an output based on a number of input.

1.1.1 Why should we use a function?

  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Reuse of code

1.2.0 What is a pure function?

pure function is a function without side effects

1.2.1 What is side effect of a function?

A function is said to have a side-effect if the supplied values or anything in function’s environment like global variable gets updated within the function.

x_global = 10
def print_x():
    global x_global # Defined as global. Use outside x_global.
    x_global += 1 # Functions CAN modify outside GLOBAL variables if defined.
    print(x_global)
    
print_x() # Run the function

1.3.0 True or False: A function does not have to return anything

False
A function will always return None when the user doesn’t define a return

return whether None or user-defined return value

1.3.1 True or False: A function can have multiple returns

True

And we can store all of these variables returned directly from the function call.

def getPerson():
    name = "Leona"
    age = 35
    country = "UK"
    return name,age,country # mutiple values are returned

name,age,country = getPerson()
print(name)
print(age)
print(country)
>>>Leona
35
UK

1.4 What is functional programming?

Perform all operations as functions using only input and output, and do not store any state information outside the function call (which would cause side effects).

Benefits: security, testing, readability, scalability (complexity)

e.g. Write a program to print the length of each element in a given list of strings.

print (*list(map(len, [ "I", " set ", " the ", " toaster ", "to", " three", "-", " medium ", " brown ." ] )))
# get length of each element (map(function, iterable) -> 
# turn the iterator object into a list ->
#print each element in the list print(*list)

# When calling a function, the * operator can be used to unpack an iterable into the arguments in the function call:
# After calling with * operator, arguments will seperate individually.
'''
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato']
>>> print(fruits[0], fruits[1], fruits[2], fruits[3])
lemon pear watermelon tomato
>>> print(*fruits)
lemon pear watermelon tomato
'''

2. Control flow

2.1 What is a flow chart?

it is a chart that describes the flow structure of the code
diamond for condition and rectangle for statement.

2.2 What is a desk check?

“keep track of how variables changes throughout the program.”

Usage: desk check is used to identify logic errors in your program.

Procedure: In a desk check, you should go through your code line by line and record each time that a variable changes or an output is produced.

2.3 What are the advantages of using if-elif-else rather than a bunch of if statements

Using if-elif-else is much faster.
If we use a bunch of if statements, it will check every if statement when executed.
But it depends on our needs.

3. Variables

3.1 What is initializing in Python?

assign value to a variable (using =)

3.2 What is declaring a variable?

Python has no specific command for declaring a variable.
A variable is created the moment you first assign a value to it.

3.3.0 How do you modify a global variable in Python

Using the keyword global if the variable is str or int, if it is list or dictionary, we can just modify it directly.

3.3.1 Local variables only exist within the scope of a function

True

def function(a):# a is a function argument
# function arguments only exist in the scope of the function
	a = 1 # a is local variable
print(a) # NameErorr is raised

Scope is the memory space in which an object or variable exists, defines which parts of the code are able to access, reference, or manipulate each object.

4. Files

4.1True or False, you always have to close a file after reading or writing them. If not, when can you get away with it?

It depends on how we open the file.

If we open the file using open, then we need to close the file mannually.

f = open(filename, 'r')
lines = f.readlines()
f.close()# we must close it mannually

But if we use with open method, python will automatically close the file for you.

with open("text.txt",'r') as f:
    lines = f.readlines()

file will automatically close when you jump out of the scope.

4.2 What is a module?

A single file which stores the related definitions, functions and code.

After we imported a module, such as math, sys, random, we can use the functionalities inside.

The code we have imported is stored in an OBJECT

4.2.1 What is sys.stdout?

sys.stdout equals to the built-in function print()

5. Class and object

5.1 What happens when you try to create an object from a class that doesn’t have a pre-defined constructor?

If we don’t define constructor by ourselves, it will construct an object using default constructor method automatically.
Which means a blank constructor is generated in background

5.2 By default, what gets printed when you print an object?

If we don’t write __str__(), it will print <datatype, memory address>,
else if we write __str__(), it will print according to our definition.

class foo:
	def __init__(self):
		self.name ='hhh'
var = foo()
print(var)
>>> <__main__.foo object at 0x7fa0507888e0>

class foo:
	def __init__(self):
		self.name = 'hhh'
    def __str__(self):
        return str(self.__class__) + ':' + self.name
        # we can change it according to our desire
var = foo()
print(var)
>>> <class '__main__.foo'>:hhh

5.3 By default, what does Python compare when you compare two objects?

If you didn’t write__eq__():, it will compare their memory address

But if you did write__eq__(): this one compares by your defined method

class SillyString(str):
    # This method gets called when using == on the object
    def __eq__(self, other):
        print(f'comparing {self} to {other}')
        # Return True if self and other have the same length
        return len(self) == len(other) 
        # if their length is equal, True is returned
        
>>> 'hello world' == SillyString('world hello')
comparing world hello to hello world
True

5.4 What is the difference between static, class and instance methods?

  • Instance method has access to the object instance via the self argument. It only works on a specific instance object of a class

  • Class method has access to the class itself, rather than the object instance. It works on the class itself.

  • Static method can neither access the object instance state nor the class state. They work like regular functions but belong to the class’s (and every instance’s) namespace. In other word, these are like standalone functions. They can be taken out of the Class, but are usually kept inside for better organisation.

We can call class method and static method on a spefic instance object or on the class it self, but we can only call instance method on the instance we created.

class Foo:
    def instance_method(self):
        print("Instance method of class {} is called".format(Foo))
 
    @staticmethod
    def static_method():
        print("Static method is called")
 
    @classmethod
    def class_method(cls):
    	print("Class method is called")
foo = Foo() # Creating a instance object
foo.instance_method()
foo.static_method()
foo.class_method()
>>>
Instance method of class <class '__main__.Foo'> is called
Static method is called
Class method is called
---------------------------------------------------------
Foo.class_method()
Foo.static_method()
# above two is ok to call, but we can't call instance method on the class itself
#TypeError: instance_method() missing 1 required positional argument: 'self'
# TypeError will be raised if we do it

6. Testing and Exception

6.1.0 What is testing?

A test gets some input to (part of ) a program and then investigates the
output.

6.1.1 Why is testing important?

Testing allows the code we write to execute as desired without mistakes.

Testing type:
black box tests, white box tests. and below three
Slower and more complex

  1. End to End Tests
  2. integration Tests
  3. Unit Tests

Faster and simpler

6.1.2 What is test-driven-development(TDD)?

This is a way of software development that requires you to write the tests for a given function first, before you even write the function!

Benefits:

  • It makes you think exactly what you want
  • Your functions can do well both in terms of:
    1. what the normal functionality should be.
    2. what should happen when ‘bad’ input given.

6.2.1 What is unit test?

A unit test is a smallest test, one that checks that a single component operates in the right way. A unit test helps you to isolate what is broken in your application and fix it faster.

#e.g.
>>> assert sum([1, 2, 3]) == 6, "Should be 6"

6.2.2 What is integration testing?

Examine how different components of a system interact with one another, checking whether connection of two or more systems are working successfully. (used more about classes that are dependent on one another)

6.3 Describe the differences between black box testing and white box testing

Black box testing:

  • We can’t see the code and don’t know how it works
  • No knowledge of implementation is needed for writing testcases

White box testing:

  • We can look inside the box to see what’s going on.
  • Knowledge of implementation is required for writing testcases

6.4 How do you perform end-to-end testing?

End-to-End Tests will assess and test the full functionality of a system or program

We are using the diff bash command in the terminal

syntax:
python3 [program name] < [test].in | diff - [test].out

test.in is our user inputs,
test.out is our expected outputs.

6.5 What is regression testing

Testing every test cases (previous and current phases) as you progress through the testcases.

6.6 What does raise, try, except do respectively?

raiseallows you to throw an exception at any time. You can define what kind of error to raise, and the text to print to the user.
tryand exceptblock in Python is used to catch and handle exceptions.
Python executes code following the try statement as a “normal” part of the program.
The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

6.7 What class does exceptions belong to?

All exceptions must be instances of a class that derives from BaseException

6.8 What is OSError?

OSError is raised when a system operation causes a system-related error.

For example:
FileExistsError
Raised when trying to create a file or directory which already exists.
FileNotFoundError
Raised when a file or directory is requested but doesn’t exist.

±- OSError
| ±- BlockingIOError
| ±- ChildProcessError
| ±- ConnectionError
| | ±- BrokenPipeError
| | ±- ConnectionAbortedError
| | ±- ConnectionRefusedError
| | ±- ConnectionResetError
| ±- FileExistsError
| ±- FileNotFoundError
| ±- InterruptedError
| ±- IsADirectoryError
| ±- NotADirectoryError
| ±- PermissionError
| ±- ProcessLookupError
| ±- TimeoutError

7. Recursion

7.1.0 What is recursion?

Recursion is the technique to solve a problem by breaking down the complex problem into smaller and simpler problem, and the solution depends on solutions to smaller part of the same problem.

It consist of two parts:

  • recurrence (breaking bigger problems to smaller ones)
  • base case (smallest problem where solved without recurrence relation)

7.1.1 What are the advantages and the disadvantages of recursion?

Pros:

  • Code is usually clean
  • Easy to write/read/understand
  • Recursion is better at tree traversal (like desk check)
  • Some problems are much harder to solve in other ways (e.g. iteration)

Cons:

  • Recursion uses more memory: Because the function has to add to the stack with each recursive call and keep the values there until the call is finished, the memory allocation is greater than that of an iterative function.
  • Recursion can be slow. If not implemented correctly, it can be much slower than iteration. It is actually pretty difficult to write a recursive function where the speed and memory will be less than that of an iterative function completing the same task. The reason that recursion is slow is that it requires the allocation of a new stack frame.

8. Snippet

8.1 What does a store at the end of this code snippet?

a = [1, 2, 3, 4, 5, 6]
for i in a:
	i += 1

a is still a list of [1,2,3,4,5,6], because for loop is read only.

If we want to modify it by a for loop

a = [1, 2, 3, 4, 5, 6]
for each in range(len(a)): # create iterate index times by len(a)
	a[each] +=1

print(a)
>>>[2, 3, 4, 5, 6, 7]

9. General definitions

9.1 What is a program?

A sequence of instructions written to perform a specified task with a computer.

9.2 What is a compiler?

A program that convert human-readable code(Python) into machine-readable byte code.

Better explanation:
A special program that can translate source code from a high-level programming language to a lower level language (e.g. machine code) to create an executable program.

9.3.1 What is syntax?

Syntax refers to the structure of the language.

9.3.2 What is syntax error?

Syntax errors occur when the parser detects an incorrect statement, which means it fails to the structure of the language.

9.4 What is the terminal?

It is an interface to your machine, you can input commands to interact with your computer.

9.5 What language is Python used?

Python is an interpreted language.

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值