Exercises: basic Python¶

Here are some exercises for practicing basic Python syntax. These exercises do not require any external libraries and focus solely on foundational Python concepts like variables, loops, conditionals, and basic arithmetic.

Tips for Practicing:¶

  • Pay attention to Python's syntax, such as indentation, which is crucial for defining loops and conditionals.
  • Use simple if statements, loops (like for and while), and basic arithmetic operators (+, -, *, /, %) to solve these problems.
  • Try using different inputs to test your functions and ensure they handle edge cases (e.g., empty lists, negative numbers).
  • Start from something that works then change it in stages rather than trying to guess at a complete working solution in one shot. For example, you don't need to create a function initially, just get your operation to work, then enclose into a function

1. Print a Greeting¶

  • Problem: Write a function greet(name) that takes a person's name as a string and prints a greeting in the format: "Hello, <name>!".
  • Example Input: greet("Alice")
  • Example Output: Hello, Alice!

2. Simple Addition¶

  • Problem: Create a function add_two_numbers(a, b) that takes two numbers a and b and returns their sum.
  • Example Input: add_two_numbers(3, 5)
  • Example Output: 8

3. Check Even or Odd¶

  • Problem: Write a function is_even(number) that takes an integer number and returns "Even" if the number is even, and "Odd" if the number is odd.
  • Example Input: is_even(4)
  • Example Output: "Even"
  • Example Input: is_even(7)
  • Example Output: "Odd"

4. Find the Maximum of Two Numbers¶

  • Problem: Implement a function find_max(a, b) that takes two numbers and returns the greater of the two.
  • Example Input: find_max(10, 20)
  • Example Output: 20

5. Counting Characters in a String¶

  • Problem: Write a function count_characters(word) that takes a string word and returns the number of characters in the string.
  • Example Input: count_characters("python")
  • Example Output: 6

6. Sum of Numbers in a List¶

  • Problem: Create a function sum_list(numbers) that takes a list of numbers and returns the sum of all the elements in the list.
  • Example Input: sum_list([1, 2, 3, 4, 5])
  • Example Output: 15

7. Print Numbers from 1 to N¶

  • Problem: Write a function print_numbers(n) that takes a positive integer n and prints all numbers from 1 to n.
  • Example Input: print_numbers(5)
  • Example Output:
    1
    2
    3
    4
    5

8. Check if a Number is Positive, Negative, or Zero¶

  • Problem: Write a function check_number(num) that takes a number num and returns "Positive" if the number is positive, "Negative" if it is negative, and "Zero" if it is zero.
  • Example Input: check_number(-5)
  • Example Output: "Negative"
  • Example Input: check_number(0)
  • Example Output: "Zero"

9. Find the Length of a List¶

  • Problem: Implement a function list_length(lst) that takes a list lst and returns the number of elements in the list.
  • Example Input: list_length([1, 2, 3, 4])
  • Example Output: 4

10. Reverse a String¶

  • Problem: Write a function reverse_string(s) that takes a string s and returns the string reversed.
  • Example Input: reverse_string("hello")
  • Example Output: "olleh"

11. Print the First N Even Numbers¶

  • Problem: Create a function print_even_numbers(n) that takes an integer n and prints the first n even numbers starting from 0.
  • Example Input: print_even_numbers(3)
  • Example Output:
    0
    2
    4

12. Check if a Character is a Vowel¶

  • Problem: Write a function is_vowel(char) that takes a single character char and returns True if it is a vowel (a, e, i, o, u) and False otherwise.
  • Example Input: is_vowel('a')
  • Example Output: True
  • Example Input: is_vowel('b')
  • Example Output: False

13. Simple Multiplication Table¶

  • Problem: Write a function multiplication_table(n) that takes a positive integer n and prints the multiplication table for that number from 1 to 10.
  • Example Input: multiplication_table(3)
  • Example Output:
    3 x 1 = 3
    3 x 2 = 6
    3 x 3 = 9
    3 x 4 = 12
    3 x 5 = 15
    3 x 6 = 18
    3 x 7 = 21
    3 x 8 = 24
    3 x 9 = 27
    3 x 10 = 30

14. Find the Smallest Number in a List¶

  • Problem: Implement a function find_min(numbers) that takes a list of numbers and returns the smallest number in the list.
  • Example Input: find_min([4, 2, 8, 1, 5])
  • Example Output: 1

15. Calculate the Factorial of a Number¶

  • Problem: Write a function factorial(n) that takes a positive integer n and returns its factorial. The factorial of n is the product of all positive integers less than or equal to n.
  • Example Input: factorial(4)
  • Example Output: 24

Exercises: Python math¶

Here are some practice problems to implement basic mathematical operations in Python. You can solve these problems using just Python's built-in arithmetic operators and functions, without relying on external libraries.

Tips:¶

  • For problems involving division, remember to handle division by zero errors.
  • Use loops and conditionals where necessary to practice basic Python control structures.

1. Basic Arithmetic Operations¶

  • Problem: Write a Python function called basic_arithmetic(a, b) that takes two numbers, a and b, as inputs and returns a tuple with the following values in order:

    • The sum of a and b
    • The difference between a and b
    • The product of a and b
    • The quotient of a divided by b (if b is not zero)
    • The remainder when a is divided by b
  • Example Input: basic_arithmetic(10, 3)

  • Example Output: (13, 7, 30, 3.3333333333333335, 1)

2. Area of a Circle¶

  • Problem: Write a function circle_area(radius) that calculates the area of a circle using the formula: [ \text{area} = \pi \times \text{radius}^2 ] Assume the value of (\pi) as 3.14159.

  • Example Input: circle_area(5)

  • Example Output: 78.53975

3. Even or Odd¶

  • Problem: Create a function is_even(number) that checks whether a given integer is even or odd. The function should return True if the number is even and False if it is odd.

  • Example Input: is_even(4)

  • Example Output: True

4. Power and Square Root¶

  • Problem: Implement a function power_and_square_root(base, exponent) that takes two numbers base and exponent and returns a tuple containing:

    • The result of raising base to the power of exponent
    • The square root of the base (calculate using base ** 0.5)
  • Example Input: power_and_square_root(16, 2)

  • Example Output: (256, 4.0)

5. Fahrenheit to Celsius Conversion¶

  • Problem: Write a function fahrenheit_to_celsius(fahrenheit) that converts a temperature from Fahrenheit to Celsius using the formula: [ \text{celsius} = \frac{5}{9} \times (\text{fahrenheit} - 32) ]

  • Example Input: fahrenheit_to_celsius(98.6)

  • Example Output: 37.0

6. Factorial of a Number¶

  • Problem: Create a function factorial(n) that calculates the factorial of a positive integer n. Use a for loop to implement this.

    • Hint: Factorial of ( n ) (denoted as ( n! )) is the product of all positive integers less than or equal to ( n ). For example, ( 4! = 4 \times 3 \times 2 \times 1 = 24 ).
  • Example Input: factorial(5)

  • Example Output: 120

7. Simple Interest Calculation¶

  • Problem: Write a function simple_interest(principal, rate, time) that calculates the simple interest using the formula: [ \text{simple interest} = \frac{\text{principal} \times \text{rate} \times \text{time}}{100} ]

  • Example Input: simple_interest(1000, 5, 2)

  • Example Output: 100.0

8. Sum of Digits¶

  • Problem: Implement a function sum_of_digits(number) that takes a positive integer number and returns the sum of its digits.

    • Hint: You can use the modulo % operator to extract digits.
  • Example Input: sum_of_digits(1234)

  • Example Output: 10

9. Maximum of Three Numbers¶

  • Problem: Write a function max_of_three(a, b, c) that returns the maximum of three numbers.

  • Example Input: max_of_three(5, 12, 7)

  • Example Output: 12

10. Reverse a Number¶

  • Problem: Create a function reverse_number(number) that takes a positive integer and returns its reverse. For example, if the input is 1234, the output should be 4321.

    • Hint: You can use string conversion or mathematical operations to extract and reverse digits.
  • Example Input: reverse_number(1234)

  • Example Output: 4321

Exercises: using lists for vectors and matrices¶

Here are some practice questions that involve accessing elements in nested lists representing vectors, matrices, and tensors. These exercises will help you understand how to navigate through nested lists in Python without relying on any external libraries. They involve accessing, slicing, and manipulating elements in vectors, matrices, and tensors represented by nested lists in Python.

Tips:¶

  • To navigate nested lists, use the appropriate number of indices (e.g., matrix[row][col] for 2D lists, tensor[depth][row][col] for 3D lists).
  • Use conditionals to handle out-of-bounds indexing to avoid errors.

1. Accessing Elements in a Vector (1D List)¶

  • Problem: Given a list vector = [3, 7, 1, 9, 5], write a function access_vector_element(vector, index) that returns the element at the specified index. If the index is out of bounds, return "Index out of bounds".

  • Example Input: access_vector_element([3, 7, 1, 9, 5], 2)

  • Example Output: 1
  • Example Input: access_vector_element([3, 7, 1, 9, 5], 5)
  • Example Output: "Index out of bounds"

2. Accessing Elements in a Matrix (2D List)¶

  • Problem: Given a 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], write a function access_matrix_element(matrix, row, col) that returns the element at the specified row and col. If the row or col is out of bounds, return "Index out of bounds".

  • Example Input: access_matrix_element([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1, 2)

  • Example Output: 6
  • Example Input: access_matrix_element([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 1)
  • Example Output: "Index out of bounds"

3. Accessing Elements in a Tensor (3D List)¶

  • Problem: Given a 3D list (tensor) tensor = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], write a function access_tensor_element(tensor, depth, row, col) that returns the element at the specified depth, row, and col. If any of the indices are out of bounds, return "Index out of bounds".

  • Example Input: access_tensor_element([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], 2, 1, 0)

  • Example Output: 11
  • Example Input: access_tensor_element([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], 3, 0, 1)
  • Example Output: "Index out of bounds"

4. Slicing a Row from a Matrix (2D List)¶

  • Problem: Given a 2D list matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]], write a function get_matrix_row(matrix, row) that returns the entire row as a list. If the row is out of bounds, return "Row index out of bounds".

  • Example Input: get_matrix_row([[10, 20, 30], [40, 50, 60], [70, 80, 90]], 1)

  • Example Output: [40, 50, 60]
  • Example Input: get_matrix_row([[10, 20, 30], [40, 50, 60], [70, 80, 90]], 3)
  • Example Output: "Row index out of bounds"

5. Slicing a Column from a Matrix (2D List)¶

  • Problem: Write a function get_matrix_column(matrix, col) that extracts a specific column from a given matrix. If the column index is out of bounds, return "Column index out of bounds".

    • Hint: You can use a for loop to iterate through each row and extract the column value.
  • Example Input: get_matrix_column([[10, 20, 30], [40, 50, 60], [70, 80, 90]], 2)

  • Example Output: [30, 60, 90]
  • Example Input: get_matrix_column([[10, 20, 30], [40, 50, 60], [70, 80, 90]], 3)
  • Example Output: "Column index out of bounds"

6. Sum of All Elements in a Matrix (2D List)¶

  • Problem: Write a function sum_matrix_elements(matrix) that calculates the sum of all elements in a 2D list.

  • Example Input: sum_matrix_elements([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

  • Example Output: 45

7. Finding Maximum Element in a Tensor (3D List)¶

  • Problem: Write a function max_in_tensor(tensor) that returns the maximum element in a 3D list (tensor). Use nested loops to iterate through all elements.

  • Example Input: max_in_tensor([[[1, 5], [3, 4]], [[9, 6], [7, 8]], [[2, 10], [11, 0]]])

  • Example Output: 11

8. Extracting a 2D Slice from a Tensor (3D List)¶

  • Problem: Given a 3D list tensor = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], write a function get_tensor_slice(tensor, depth) that returns the 2D list (slice) at the specified depth. If the depth is out of bounds, return "Depth index out of bounds".

  • Example Input: get_tensor_slice([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], 1)

  • Example Output: [[5, 6], [7, 8]]
  • Example Input: get_tensor_slice([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], 3)
  • Example Output: "Depth index out of bounds"

9. Flattening a Matrix (2D List) to a Vector (1D List)¶

  • Problem: Write a function flatten_matrix(matrix) that takes a 2D list and returns a flattened 1D list containing all the elements in row-major order.

  • Example Input: flatten_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

  • Example Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

10. Extracting Diagonal Elements from a Square Matrix (2D List)¶

  • Problem: Write a function get_diagonal(matrix) that takes a square 2D list and returns a list containing the diagonal elements. Assume the input is always a square matrix.

  • Example Input: get_diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

  • Example Output: [1, 5, 9]

Exercises: linear algebra with Python¶

Here are some practice problems that focus on implementing basic linear algebra operations using Python with vectors (1D lists) and matrices (2D lists). These exercises cover fundamental linear algebra operations such as addition, multiplication, transposition, and more.

Tips:¶

  • Use loops to iterate through vectors and matrices. To access elements in a 2D matrix, use matrix[row][col].
  • Always check for dimension compatibility when performing operations like addition, multiplication, or dot products to prevent errors.
  • Utilize basic arithmetic operations (+, -, *, ** 0.5) to implement these linear algebra functionalities.

1. Vector Addition¶

  • Problem: Write a function vector_addition(v1, v2) that takes two vectors (1D lists) of the same length and returns a new vector that is their element-wise sum. If the vectors are not the same length, return "Vectors must be of the same length".

  • Example Input: vector_addition([1, 2, 3], [4, 5, 6])

  • Example Output: [5, 7, 9]
  • Example Input: vector_addition([1, 2], [3, 4, 5])
  • Example Output: "Vectors must be of the same length"

2. Scalar Multiplication of a Vector¶

  • Problem: Implement a function scalar_multiply_vector(vector, scalar) that multiplies each element of a vector by a scalar value and returns the resulting vector.

  • Example Input: scalar_multiply_vector([1, 2, 3], 4)

  • Example Output: [4, 8, 12]

3. Dot Product of Two Vectors¶

  • Problem: Create a function dot_product(v1, v2) that calculates the dot product of two vectors of the same length. If the vectors are not of the same length, return "Vectors must be of the same length".

    • Hint: The dot product of two vectors ([a_1, a_2, \dots, a_n]) and ([b_1, b_2, \dots, b_n]) is given by: [ a_1 \times b_1 + a_2 \times b_2 + \dots + a_n \times b_n ]
  • Example Input: dot_product([1, 2, 3], [4, 5, 6])

  • Example Output: 32
  • Example Input: dot_product([1, 2], [3, 4, 5])
  • Example Output: "Vectors must be of the same length"

4. Matrix Addition¶

  • Problem: Write a function matrix_addition(m1, m2) that adds two matrices of the same dimensions element-wise. If the matrices do not have the same dimensions, return "Matrices must be of the same dimensions".

  • Example Input: matrix_addition([[1, 2], [3, 4]], [[5, 6], [7, 8]])

  • Example Output: [[6, 8], [10, 12]]
  • Example Input: matrix_addition([[1, 2, 3]], [[4, 5]])
  • Example Output: "Matrices must be of the same dimensions"

5. Matrix-Vector Multiplication¶

  • Problem: Create a function matrix_vector_multiplication(matrix, vector) that multiplies a matrix by a vector. The number of columns in the matrix should be equal to the length of the vector. If not, return "Incompatible dimensions for multiplication".

    • Hint: Multiply each row of the matrix by the vector using the dot product and return the resulting vector.
  • Example Input: matrix_vector_multiplication([[1, 2], [3, 4], [5, 6]], [7, 8])

  • Example Output: [23, 53, 83]
  • Example Input: matrix_vector_multiplication([[1, 2, 3]], [4, 5])
  • Example Output: "Incompatible dimensions for multiplication"

6. Transpose of a Matrix¶

  • Problem: Implement a function transpose_matrix(matrix) that returns the transpose of a given matrix. The transpose of a matrix is obtained by swapping rows with columns.

  • Example Input: transpose_matrix([[1, 2, 3], [4, 5, 6]])

  • Example Output: [[1, 4], [2, 5], [3, 6]]

7. Matrix Multiplication¶

  • Problem: Write a function matrix_multiplication(m1, m2) that multiplies two matrices m1 and m2. The number of columns in m1 must be equal to the number of rows in m2. If not, return "Incompatible dimensions for multiplication".

    • Hint: The element at position ((i, j)) in the resulting matrix is the dot product of the (i)-th row of m1 and the (j)-th column of m2.
  • Example Input: matrix_multiplication([[1, 2], [3, 4]], [[5, 6], [7, 8]])

  • Example Output: [[19, 22], [43, 50]]
  • Example Input: matrix_multiplication([[1, 2, 3]], [[4, 5]])
  • Example Output: "Incompatible dimensions for multiplication"

8. Norm of a Vector¶

  • Problem: Write a function vector_norm(vector) that calculates the Euclidean norm (magnitude) of a vector. The formula for the norm of a vector ([a_1, a_2, \dots, a_n]) is: [ \sqrt{a_1^2 + a_2^2 + \dots + a_n^2} ]

    • Hint: You can calculate the square root using ** 0.5.
  • Example Input: vector_norm([3, 4])

  • Example Output: 5.0

9. Checking Orthogonality of Two Vectors¶

  • Problem: Implement a function are_orthogonal(v1, v2) that checks if two vectors are orthogonal (perpendicular) to each other. Two vectors are orthogonal if their dot product is zero. If the vectors are not of the same length, return "Vectors must be of the same length".

  • Example Input: are_orthogonal([1, 2], [-2, 1])

  • Example Output: True
  • Example Input: are_orthogonal([1, 2, 3], [4, 5])
  • Example Output: "Vectors must be of the same length"

10. Trace of a Square Matrix¶

  • Problem: Write a function matrix_trace(matrix) that calculates the trace of a square matrix. The trace is the sum of the elements on the main diagonal (from the top-left to the bottom-right).

    • Hint: The input matrix should be square (same number of rows and columns). If it's not square, return "Matrix must be square".
  • Example Input: matrix_trace([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

  • Example Output: 15
  • Example Input: matrix_trace([[1, 2], [3, 4], [5, 6]])
  • Example Output: "Matrix must be square"