Exam Notes for ENGG 1330
Exam notes for ENGG 1330
ENGG 1330 Exam Notes
Lecture 2
Variable and Identifiers
To get a type of a variable, use
type(<variable>). The output would be:<class '<typeclass>'>, like<class 'int'>indicating integers.Identifiers cannot:
- Begin with numbers
- Be keywords
- include characters other than underscore, numbers and letters
Identifiers are: Case sensitive
Operators
| Operator | Name | Description |
|---|---|---|
| + | Addition | |
| - | Subtraction | |
| * | Multiplication | |
| / | Division | Regular division. |
| % | Modulo | return remainder |
| ** | Exponent | |
| // | Floor Division | return rounded result |
Lecture 3
List
Method
list.insert(<index>, <content>), which:- \
position count as the position of the available slot, starting from the 1 slot before the 1st element in the list as index 0. - \
content will be inserted.
- \
Method
list.remove(<index>), which:position of the element will be removed.
Method
list.clear(), which will clear the list.
Set
Used to store elements which has no redundancy. Elements inside set has no order, and unique.
Method
set.add(<element>), which:element to be added to the set.
Method
set.remove(<element>), which:element to be deleted. - If
does not exist, using set.remove()will raise KeyError.
Method
set.discard(<element>), which:element to be deleted. - If
does not exist, using set.discard()will NOT raise KeyError.
Lecture 4
String
Strings are Immutable datatypes. A string, once created, can never be changed.
Workarounds to “modify” a string:
Convert to a list, modify, and convert back to a string:
- Example:
1
2
3
4
5s = "hello"
s_list = list(s) # Convert string to list
s_list[0] = 'H' # Modify the list
s = ''.join(s_list) # Convert list back to string
print(s) # Output: 'Hello'
- Example:
Use string slicing and concatenation:
- Example:
1
2
3s = "hello"
s = 'H' + s[1:] # Modify the first character
print(s) # Output: 'Hello'
- Example:
Use string methods to create a new string:
- Example:
1
2
3s = "hello"
s = s.replace('h', 'H') # Use replace method to create a new string
print(s) # Output: 'Hello'
- Example:
Strings Escape characters
Strings are immutable data types.
| Characters | Description |
|---|---|
\n |
Newline |
\t |
Horizontal Tab |
\' |
Single Quote (转义) |
\" |
Double Quote (转义) |
\\ |
Backslash |
String Operations
- Use
+to add two string together. Two text literals next to each other will be automatically combined:
- Example:
1
2s = ('Combining' 'literals')
print(s) - Or it’s totally fine if these two literals has no space between them.
- Example:
Multiplying a string by 0 or a negative integer results in an empty string:
- Example:
1
2s = "Hello" * 0
print(s) # Output: '' - Example:
1
2s = "Hello" * -1
print(s) # Output: ''
- Example:
Membership Test in strings:
- Use
into check if a substring exists in a string.- Example:
1
2
3s = "Hello, World!"
result = "Hello" in s
print(result) # Output: True
- Example:
- Use
not into check if a substring does not exist in a string.- Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19s = "Hello, World!"
result = "Hi" not in s
print(result) # Output: True
---
### String Comparison
- You can use `>`, `<`, `<=`, `>=`, `==`, `!=` to compare two strings. Python compares strings lexicographically based on the Unicode code points of characters. For example:
- Comparing the size of strings:
```python
print("apple" > "banana") # Output: False, because 'a' has a lower Unicode code point than 'b'
print("apple" < "banana") # Output: True
- Comparing the equality of strings:
```python
print("apple" == "apple") # Output: True
print("apple" != "banana") # Output: True
- Example:
- Use
Comparing the size and equality of strings:
1
2print("apple" <= "banana") # Output: True
print("apple" >= "apple") # Output: TrueIf one string is a prefix of another, the shorter string is considered smaller:
1
print("app" < "apple") # Output: True, because "app" is a prefix of "apple"
String Functions
len(str): Returns the length of the string.- Example:
1
2s = "Hello, World!"
print(len(s)) # Output: 13
- Example:
str.lower(): Converts the string to lowercase.- Example:
1
2s = "Hello, World!"
print(s.lower()) # Output: hello, world!
- Example:
str.upper(): Converts the string to uppercase.- Example:
1
2s = "Hello, World!"
print(s.upper()) # Output: HELLO, WORLD!
- Example:
str.strip(): Removes whitespace from both ends of the string.- Example:
1
2s = " Hello, World! "
print(s.strip()) # Output: Hello, World!
- Example:
str.split(): Splits the string into a list.- Example:
1
2s = "Hello, World!"
print(s.split()) # Output: ['Hello,', 'World!']
- Example:
str.join(iterable): Joins the elements of the iterable into a single string.- Example:
1
2words = ['Hello', 'World']
print(' '.join(words)) # Output: Hello World
- Example:
str.replace(old, new): Replaces occurrences of a substring.- Example:
1
2s = "Hello, World!"
print(s.replace("World", "Python")) # Output: Hello, Python!
- Example:
str.find(sub): Finds the position of a substring, returns -1 if not found.- Example:
1
2s = "Hello, World!"
print(s.find("World")) # Output: 7
- Example:
str.startswith(prefix): Checks if the string starts with the specified prefix.- Example:
1
2s = "Hello, World!"
print(s.startswith("Hello")) # Output: True
- Example:
str.endswith(suffix): Checks if the string ends with the specified suffix.- Example:
1
2s = "Hello, World!"
print(s.endswith("World!")) # Output: True
- Example:
ord(char): Returns the Unicode code point for a given character.- Example:
1
2
3print(ord('A')) # Output: 65
print(ord('a')) # Output: 97
print(ord('0')) # Output: 48
- Example:
chr(code): Returns the character that represents the specified Unicode code point.- Example:
1
2
3
4
5
6
7
8
9
10
11print(chr(65)) # Output: 'A'
print(chr(97)) # Output: 'a'
print(chr(48)) # Output: '0'
- `str.isalnum()`: Checks if all characters in the string are alphanumeric.
- Example:
```python
s1 = "Hello123"
s2 = "Hello 123"
print(s1.isalnum()) # Output: True
print(s2.isalnum()) # Output: False
- Example:
str.isalpha(): Checks if all characters in the string are alphabetic.- Example:
1
2
3
4s1 = "Hello"
s2 = "Hello123"
print(s1.isalpha()) # Output: True
print(s2.isalpha()) # Output: False
- Example:
str.isdecimal(): Checks if all characters in the string are decimal characters.- Example:
1
2
3
4s1 = "123"
s2 = "123.45"
print(s1.isdecimal()) # Output: True
print(s2.isdecimal()) # Output: False
- Example:
str.capitalize(): Capitalizes the first character of the string and converts the rest to lowercase.- Example:
1
2
3
4
5s = "hello, world!"
print(s.capitalize()) # Output: 'Hello, world!'
s = "PYTHON programming"
print(s.capitalize()) # Output: 'Python programming'
- Example:
Lecture 5
Id
In Python, the id() function is used to get the unique identifier of an object. This identifier is unique and constant for the object during its lifetime.
- Description: Returns the unique identifier of an object.
- Return Value: An integer representing the unique identifier of the object.
Examples:
- Getting the id of an object:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16a = 10
b = 10
print(id(a)) # Output: Unique identifier of object a
print(id(b)) # Output: Unique identifier of object b, usually the same as a because integers are immutable and cached
**Important Concepts**
1. Uniqueness of Objects:
- The identifier returned by id() is unique and constant for the object during its lifetime.
- Example:
```python
a = [1, 2, 3]
print(id(a)) # Output: Unique identifier of object a
a.append(4)
print(id(a)) # Output: Same unique identifier, because a is still the same object
Mutability and Immutability:
- For immutable objects (like integers, strings, tuples), Python may return the same identifier for new objects with the same value because these objects are cached and reused.
- For mutable objects (like lists, dictionaries), even if the content is the same, new objects will have different identifiers.
- Example:
1
2
3
4
5
6
7a = 10
b = 10
print(id(a) == id(b)) # Output: True, because the integer object 10 is cached and reused
c = [1, 2, 3]
d = [1, 2, 3]
print(id(c) == id(d)) # Output: False, because c and d are different list objects
Object Lifetime:
- The identifier of an object is unique and constant during its lifetime. When the object is destroyed, its identifier may be reassigned to a new object.
- Example:
1
2
3
4
5a = [1, 2, 3]
id_a = id(a)
del a
b = [4, 5, 6]
print(id(b) == id_a) # May output True, because id_a may be reassigned to the new object b
Common Pitfalls
Immutable Object Caching:
- For immutable objects (like integers, strings, tuples), Python caches and reuses some common values, which means that two objects with the same value may have the same id.
- Example:
1
2
3a = 10
b = 10
print(id(a) == id(b)) # Output: True, because the integer 10 is cached and reused
Small Integer Caching:
- Python caches and reuses small integers (usually between -5 and 256), so their id values are always the same.
- Example:
1
2
3
4
5
6
7a = 256
b = 256
print(id(a) == id(b)) # Output: True, because 256 is within the cache range
c = 257
d = 257
print(id(c) == id(d)) # Output: False, because 257 is outside the cache range
String Interning:
- Python caches and reuses short and common strings.
- Example:
1
2
3
4
5
6
7s1 = "hello"
s2 = "hello"
print(id(s1) == id(s2)) # Output: True, because the string "hello" is cached and reused
s3 = "hello, world!"
s4 = "hello, world!"
print(id(s3) == id(s4)) # Output: May be True or False, depending on the implementation
Different id for Mutable Objects:
- For mutable objects (like lists, dictionaries), even if the content is the same, new objects will have different id values.
- Example:
1
2
3list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(id(list1) == id(list2)) # Output: False, because list1 and list2 are different objects
Object Lifetime:
- When an object is destroyed, its id may be reassigned to a new object.
- Example:
1
2
3
4
5a = [1, 2, 3]
id_a = id(a)
del a
b = [4, 5, 6]
print(id(b) == id_a) # May output True, because id_a may be reassigned to the new object b
Value Assignment and Aliasing
- When you assign a mutable object (like a list, dictionary, or set) to another variable, both variables will reference the same object. This is called aliasing.
- Example:
1
2
3
4
5list1 = [1, 2, 3]
list2 = list1 # list2 is an alias for list1
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
print(list2) # Output: [1, 2, 3, 4]
FileIO
Python provides a set of built-in functions for file operations, including opening files, reading files, writing files, and closing files.
Opening a File
Use the open() function to open a file. The open() function returns a file object and takes two main parameters: the filename and the mode.
Modes:
'r': Read mode (default).'w': Write mode. If the file exists, it will be overwritten; if the file does not exist, a new file will be created.'a': Append mode. If the file exists, new data will be appended to the end; if the file does not exist, a new file will be created.'b': Binary mode.'t': Text mode (default).'+': Read and write mode.Example:
1
2# Open a file for writing
file = open('example.txt', 'w')
Writing to a File
Use the file object’s write() method or writelines() method to write content to the file.
write()method: Writes a single string to the file.- Example:
1
file.write('Hello, World!\n')
- Example:
writelines()method: Writes a list of strings to the file.- Example:
1
2lines = ['First line\n', 'Second line\n', 'Third line\n']
file.writelines(lines)
- Example:
Closing a File
Use the file object’s close() method to close the file. Closing the file ensures that all buffered content is written to the file and releases the file resource.
Example: file.close()
Using the with statement can automatically handle opening and closing files, ensuring that the file is properly closed after its suite finishes.
For instance:
1 | with open('example.txt', 'w') as file: |
Random Module
The random module in Python provides functions to generate random numbers and perform random operations.
random.random():- Returns a random float number between 0.0 and 1.0.
- Example:
1
2import random
print(random.random()) # Output: A random float between 0.0 and 1.0
random.randint(a, b):- Returns a random integer N such that
a <= N <= b. - Example:
1
print(random.randint(1, 10)) # Output: A random integer between 1 and 10 (inclusive)
- Returns a random integer N such that
random.choice(seq):- Returns a random element from the non-empty sequence
seq. - Example:
1
2choices = ['apple', 'banana', 'cherry']
print(random.choice(choices)) # Output: A random element from the list
- Returns a random element from the non-empty sequence
random.shuffle(seq):- Shuffles the sequence
seqin place. - Example:
1
2
3deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck) # Output: The list shuffled in place
- Shuffles the sequence
random.sample(population, k):- Returns a list of
kunique elements chosen from the population sequence or set. - Example:
1
2numbers = list(range(1, 11))
print(random.sample(numbers, 3)) # Output: A list of 3 unique random elements from the list
- Returns a list of
random.uniform(a, b):- Returns a random float number N such that
a <= N <= b. - Example:
1
print(random.uniform(1.0, 10.0)) # Output: A random float between 1.0 and 10.0
- Returns a random float number N such that
random.gauss(mu, sigma):- Returns a random float number from a Gaussian distribution with mean
muand standard deviationsigma. - Example:
1
print(random.gauss(0, 1)) # Output: A random float from a Gaussian distribution with mean 0 and standard deviation 1
- Returns a random float number from a Gaussian distribution with mean
Built-ins
sorted() Function
The sorted() function in Python is used to sort an iterable and return a new sorted list. The sorted() function does not modify the original object but returns a new sorted list.
- Description: Sorts an iterable and returns a new sorted list.
- Syntax:
sorted(iterable, key=None, reverse=False)iterable: The iterable to be sorted (e.g., list, tuple, string, etc.).key: A function to extract a comparison key from each element (default isNone).reverse: A boolean value. IfTrue, the sorted list is reversed (or sorted in descending order). Default isFalse.
Examples
Sorting a list:
1
2
3
4
5
6
7
8
9numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
2. **Sorting in descending order**:
```python
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]Sorting a string:
1
2
3s = "hello"
sorted_s = sorted(s)
print(sorted_s) # Output: ['e', 'h', 'l', 'l', 'o']Sorting using the
keyparameter:Sorting by string length:
1
2
3words = ["banana", "pie", "Washington", "book"]
sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['pie', 'book', 'banana', 'Washington']Sorting by a dictionary key:
1
2
3
4
5
6
7
8students = [
{'name': 'John', 'age': 25},
{'name': 'Jane', 'age': 22},
{'name': 'Dave', 'age': 23}
]
sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)
# Output: [{'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 23}, {'name': 'John', 'age': 25}]
Exam Notes for ENGG 1330
http://naughtychas.github.io/2024/12/11/Exam Notes for ENGG1330/