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:

  1. Convert to a list, modify, and convert back to a string:

    • Example:
      1
      2
      3
      4
      5
      s = "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'
  2. Use string slicing and concatenation:

    • Example:
      1
      2
      3
      s = "hello"
      s = 'H' + s[1:] # Modify the first character
      print(s) # Output: 'Hello'
  3. Use string methods to create a new string:

    • Example:
      1
      2
      3
      s = "hello"
      s = s.replace('h', 'H') # Use replace method to create a new string
      print(s) # Output: 'Hello'

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
      2
      s = ('Combining' 'literals')
      print(s)
    • Or it’s totally fine if these two literals has no space between them.
  • Multiplying a string by 0 or a negative integer results in an empty string:

    • Example:
      1
      2
      s = "Hello" * 0
      print(s) # Output: ''
    • Example:
      1
      2
      s = "Hello" * -1
      print(s) # Output: ''
  • Membership Test in strings:

    • Use in to check if a substring exists in a string.
      • Example:
        1
        2
        3
        s = "Hello, World!"
        result = "Hello" in s
        print(result) # Output: True
    • Use not in to 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
        19
              s = "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
  • Comparing the size and equality of strings:

    1
    2
    print("apple" <= "banana")  # Output: True
    print("apple" >= "apple") # Output: True
  • If 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
      2
      s = "Hello, World!"
      print(len(s)) # Output: 13
  • str.lower(): Converts the string to lowercase.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.lower()) # Output: hello, world!
  • str.upper(): Converts the string to uppercase.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.upper()) # Output: HELLO, WORLD!
  • str.strip(): Removes whitespace from both ends of the string.

    • Example:
      1
      2
      s = "   Hello, World!   "
      print(s.strip()) # Output: Hello, World!
  • str.split(): Splits the string into a list.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.split()) # Output: ['Hello,', 'World!']
  • str.join(iterable): Joins the elements of the iterable into a single string.

    • Example:
      1
      2
      words = ['Hello', 'World']
      print(' '.join(words)) # Output: Hello World
  • str.replace(old, new): Replaces occurrences of a substring.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.replace("World", "Python")) # Output: Hello, Python!
  • str.find(sub): Finds the position of a substring, returns -1 if not found.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.find("World")) # Output: 7
  • str.startswith(prefix): Checks if the string starts with the specified prefix.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.startswith("Hello")) # Output: True
  • str.endswith(suffix): Checks if the string ends with the specified suffix.

    • Example:
      1
      2
      s = "Hello, World!"
      print(s.endswith("World!")) # Output: True
  • ord(char): Returns the Unicode code point for a given character.

    • Example:
      1
      2
      3
      print(ord('A'))  # Output: 65
      print(ord('a')) # Output: 97
      print(ord('0')) # Output: 48
  • chr(code): Returns the character that represents the specified Unicode code point.

    • Example:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
          print(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
  • str.isalpha(): Checks if all characters in the string are alphabetic.

    • Example:
      1
      2
      3
      4
      s1 = "Hello"
      s2 = "Hello123"
      print(s1.isalpha()) # Output: True
      print(s2.isalpha()) # Output: False
  • str.isdecimal(): Checks if all characters in the string are decimal characters.

    • Example:
      1
      2
      3
      4
      s1 = "123"
      s2 = "123.45"
      print(s1.isdecimal()) # Output: True
      print(s2.isdecimal()) # Output: False
  • str.capitalize(): Capitalizes the first character of the string and converts the rest to lowercase.

    • Example:
      1
      2
      3
      4
      5
      s = "hello, world!"
      print(s.capitalize()) # Output: 'Hello, world!'

      s = "PYTHON programming"
      print(s.capitalize()) # Output: 'Python programming'

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
    16
      a = 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
  1. 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
      7
      a = 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
  2. 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
      5
      a = [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

  1. 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
      3
      a = 10
      b = 10
      print(id(a) == id(b)) # Output: True, because the integer 10 is cached and reused
  2. 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
      7
      a = 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
  3. String Interning:

    • Python caches and reuses short and common strings.
    • Example:
      1
      2
      3
      4
      5
      6
      7
      s1 = "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
  4. 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
      3
      list1 = [1, 2, 3]
      list2 = [1, 2, 3]
      print(id(list1) == id(list2)) # Output: False, because list1 and list2 are different objects
  5. Object Lifetime:

    • When an object is destroyed, its id may be reassigned to a new object.
    • Example:
      1
      2
      3
      4
      5
      a = [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
    5
    list1 = [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')
  • writelines() method: Writes a list of strings to the file.

    • Example:
      1
      2
      lines = ['First line\n', 'Second line\n', 'Third line\n']
      file.writelines(lines)

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
2
3
4
5
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
lines = ['First line\n', 'Second line\n', 'Third line\n']
file.writelines(lines)
# The file is automatically closed here

Random Module

The random module in Python provides functions to generate random numbers and perform random operations.

  1. random.random():

    • Returns a random float number between 0.0 and 1.0.
    • Example:
      1
      2
      import random
      print(random.random()) # Output: A random float between 0.0 and 1.0
  2. 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)
  3. random.choice(seq):

    • Returns a random element from the non-empty sequence seq.
    • Example:
      1
      2
      choices = ['apple', 'banana', 'cherry']
      print(random.choice(choices)) # Output: A random element from the list
  4. random.shuffle(seq):

    • Shuffles the sequence seq in place.
    • Example:
      1
      2
      3
      deck = [1, 2, 3, 4, 5]
      random.shuffle(deck)
      print(deck) # Output: The list shuffled in place
  5. random.sample(population, k):

    • Returns a list of k unique elements chosen from the population sequence or set.
    • Example:
      1
      2
      numbers = list(range(1, 11))
      print(random.sample(numbers, 3)) # Output: A list of 3 unique random elements from the list
  6. 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
  7. random.gauss(mu, sigma):

    • Returns a random float number from a Gaussian distribution with mean mu and standard deviation sigma.
    • Example:
      1
      print(random.gauss(0, 1))  # Output: A random float from a Gaussian distribution with mean 0 and standard deviation 1

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 is None).
    • reverse: A boolean value. If True, the sorted list is reversed (or sorted in descending order). Default is False.

Examples

  1. Sorting a list:

    1
    2
    3
    4
    5
    6
    7
    8
    9
       numbers = [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]
  2. Sorting a string:

    1
    2
    3
    s = "hello"
    sorted_s = sorted(s)
    print(sorted_s) # Output: ['e', 'h', 'l', 'l', 'o']
  3. Sorting using the key parameter:

    • Sorting by string length:

      1
      2
      3
      words = ["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
      8
      students = [
      {'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}]
作者

ntcs

发布于

2024-12-11

更新于

2024-12-11

许可协议

# 相关文章
  1.ENGG1340笔记
# 推荐文章
  1.邈想日集
  2.ENGG1340笔记
  3.ASCS笔记
  4.A2CS笔记
  5.浅谈今年CAIE的POE考试
  6.收集"你说得对"

评论