Python Note (ANU COMP6730) --- English Version

A function name in python may contain letters, numbers and underscores(_) , but must begin with a letter or underscore.

Reserved words cannot be used as names.

The function name is not valid if it contains a space: eg. def print alert():

The entire functions definition is a single statement.

1. Code quality

1.1 Commenting and documentation

1.2 Variable and function naming

1.3 Code organization (for large programs)

​ avoids repetition; fights complexity by isolating subproblems and encapsulating their solutions; raises the level of abstraction; helps you find what you’re looking for;

1.4 Code efficiency (somewhat)

def solve(f, y, lower, upper):
    """
    Find x such that f(x) = y (approximately).
    :param f: a monotonic function with one numeric parameter and return value.
    :param y: integer or float, the value of f to solve for.
    ...
    
    returns: float, value of x such that f(x) within +/− 1e−6 of y.
    """
  1. function name / variable name: should be clear, not cryptic
  2. no docstrings
  3. redundency
  4. repeated statement

2. Debugging and Testing

Identify test cases (arguments), particularly “edge cases”. Verify behaviour or return value in each case.

What are edge cases?

Integers: zero, positive, negative. float: zero, very small (1e-308) or big (1e308).

Sequences: empty string, empty list, length one. Any value that requires special treatment in the code.

3. Values, Types and expressions

An expression is a piece of code that produces a value when it is executed, it can consist of variables, literals, operators and function calls.

A statement is a complete line of code that performs an action. It doesn’t necessarily produce a value.

Expressions can act as statements (the return value is ignored), but statement cannot act as expressions.

The result of division is always a float. Float can be written in “scientific notation”, 2.99e8 means 2.99 * 10 ^ 8

4. Branching

The suite of a function can contain function calls, including calls to the same function.

The function suite must have a branching statement, such that a recursive call does not always take place (“base case”); otherwise, recursion never ends.

5. Iteration

Codes using iteration (loop) can be rewritten as recursion (function calling itself)

Codes with recursion (function calling itself) can be rewritten as iteration (loop)

6. Sequence types

python has three built-in sequence types:

  • lists (list) can contain a mix of value types;
  • tuples (tuple) are like lists, but immutable (unchangable).
  • strings (str): sequence of characters; immutable.

7. Lists

A list can contain elements of any type - including a mix of elements of different types in the same list.

a_list = [1, 2, 3]
b_list = a_list[:]    
a_list.append(4)
print(a_list)
print(b_list)

modifying list methods:

a_list.append(new element)
a_list.insert(index, new element)
a_list.pop(index)  # - index defaults to -1 (last element)
a_list.remove(a_value)
a_list.extend(an_iterable)
a_list.sort()
a_list.reverse()    # Note: Most do not return a value.

three ways to do shallow copy:

  1. Slicing: b = a[:]

  2. list function: b = list(a)

  3. copy function: b = a.copy()

In Python, the list.sort() method is used for in-place sorting of a list. In-place sorting means that the original list is modified directly during the sorting process, and the method does not return a new sorted list. Since it is an in-place operation, it returns None.

x = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
result = x.sort()
print(x)       # Outputs the sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
print(result)  # Outputs None

If you want to obtain a new sorted list without modifying the original list, you can use the sorted() function:

x = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_x = sorted(x)
print(x)         # Outputs the original list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(sorted_x)  # Outputs a new sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

8. Numpy arrays

A Numpy array can only keep elements of the same type.

NumPy arrays have a fixed size at creation, NumPy arrays can have arbitrary dimensions.

np.zeros

Np.linspace

As with lists, array assignment does not copy its elements

However, as opposed to lists, array slicing does not return a copy but a “view” to original array

When writing functions that modify NumPy arrays passed as arguments, use in-place arithmetics, e.g. a+=b is in-place addition.

9. Input/Output and files

Apart from the usual characters, text files typically also also contain control characters

Examples of control characters: newline character (denoted symbolically as \n) or tab character (denoted symbolically as \t)

tsv: tab-separated values, csv: comma-separated values

open a file

file = open("test.csv","r")

strip removes leading/trailing whitespace (including newlines)

split splits a string into list of strings using specified separator

newline = line.strip()  # remove whitespace and \n
second_newline = newline.split("\t")  # remove the \ts

Python’s text file objects are iterable, iterating yeilds one line at time.

file = open("note.txt","r")
line_num = 1
for line in file:
    print(line_num, ':', line)
    line_num += 1
file.close()

10. Dictionaries and sets

Dictionaries: Each key is associated to one and only one value, keys can be values of any immutable type

new_dic = {}    # create a new dictionary
word_counter = {"be": 2, "can": 1}
word_counter["the"] = 5.  # adds a new key-value pair
word_counter["can"] += 1  # updates the value of existing key 

A set is an unordered collection of (immutable) values without duplicates.

Dictionaries and sets are mutable objects, dict.copy() and set.copy() create a shallow copy of the dictionary or set.

iterate the dictionary:

for key, value in adict.items():
		print(key, value)
for key in adict.keys():
  	pass
for value in adict.values():
  	pass

11. Computational Complexity

Complexity analysis:

The time complexity of the given function is O(n^2), where n is the ___

When O(n):

The function uses a loop that iterates over each element of the input sequence. The loop runs 'n’times, where ‘n’ is the length of the sequence.

Inside the loop, there are constant-time operations (e.g. checking if ‘i’ is even and appending elements to the result list)

When O(n * n):

The outer loop runs ___ times, which is equivalent to n …

The inner loop runs ___ times, which is also equivalent to n …

When O(logn): calls by half with each step

12. The command-line interface

We can pass the arguments to the program from the command-line.

sys.argv is a list of strings where sys.argv[0] is the name of Python program and sys.argv[1:] are the arguments.

import sys
y0 = float(sys.argv[1])
v0 = float(sys.argv[2])
a = float(sys.argv[3])
t = float(sys.argv[4])
yt = y0 + v0*t + 0.5*a*t*t

$ python position.py 10 2 9.81 0.5

The argparse module provides very convenient way to “parse” command-line arguments with options

import argparse
parser.add_argument('--v0', '--initial_velocity', type=float, 
										default=0.0, help='initial veclocity')
parser.add_argument('--y0', '--initial_position', type=float, 
										default=0.0, help='initial position')
parser.add_argument('--a', '--acceleration', type=float, 
										default=1.0, help='acceleration')
parser.add_argument('--t', '--time', type=float, 
										default=1.0, help='time')

# read the command line and interpret the arguments
args = parser.parse_args()

# Extract values and evaluate formula
args = parser.parse_args()
y0 = args.y0; v0 = args.v0; a = args.a; t = args.t
yt = y0 + v0*t + 0.5*a*t**2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值