Python Classroom notes 01/Sep/2024

Lets solve some problems

Exercise 1: FizzBuzz Variation

  • Problem: Write a function called fizzbuzz_variant(n) that takes an integer n and returns a list of numbers from 1 to n. For multiples of three, append "Fizz" instead of the number, for multiples of five append "Buzz", and for multiples of both three and five append "FizzBuzz".
  • Expected Output:
    python
    fizzbuzz_variant(15)
    # Output: [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]

Exercise 2: Factorial with Recursion

  • Problem: Write a recursive function factorial(n) that returns the factorial of a given number n.
  • Expected Output:
    python
    factorial(5)
    # Output: 120

Exercise 3: List Comprehension Practice

  • Problem: Create a function squares_of_even_numbers(nums) that takes a list of integers and returns a list of the squares of all even numbers in the list using list comprehension.
  • Expected Output:
    python
    squares_of_even_numbers([1, 2, 3, 4, 5, 6])
    # Output: [4, 16, 36]

Exercise 4: Palindrome Checker

  • Problem: Write a function is_palindrome(s) that takes a string s and returns True if it is a palindrome (reads the same forwards and backwards), and False otherwise.
  • Expected Output:
    python
    is_palindrome("racecar")
    # Output: True

Exercise 5: Dictionary Manipulation

  • Problem: Write a function invert_dict(d) that takes a dictionary d and returns a new dictionary where the keys are the values and the values are the keys.
  • Expected Output:
    python
    invert_dict({"a": 1, "b": 2, "c": 3})
    # Output: {1: "a", 2: "b", 3: "c"}

Exercise 6: String Manipulation

  • Problem: Write a function vowel_count(s) that takes a string s and returns a dictionary with vowels as keys and their counts as values.
  • Expected Output:
    python
    vowel_count("hello world")
    # Output: {"e": 1, "o": 2}

Exercise 7: Nested Loops: Multiplication Table

  • Problem: Write a function multiplication_table(n) that prints the multiplication table of size n.
  • Expected Output:
    python
    multiplication_table(3)
    # Output:
    # 1 2 3
    # 2 4 6
    # 3 6 9

Exercise 8: Prime Number Checker

  • Problem: Write a function is_prime(n) that returns True if n is a prime number and False otherwise.
  • Expected Output:
    python
    is_prime(11)
    # Output: True

Exercise 9: Sum of Digits

  • Problem: Write a function sum_of_digits(n) that takes a positive integer n and returns the sum of its digits.
  • Expected Output:
    python
    sum_of_digits(1234)
    # Output: 10

Exercise 10: Custom Sorting

  • Problem: Write a function custom_sort(strings) that takes a list of strings and returns it sorted by the length of each string.
  • Expected Output:
    python
    custom_sort(["apple", "pie", "banana", "kiwi"])
    # Output: ["pie", "kiwi", "apple", "banana"]

Exercise 11: GCD (Greatest Common Divisor)

  • Problem: Write a function gcd(a, b) that returns the greatest common divisor of two integers a and b.
  • Expected Output:
    python
    gcd(48, 18)
    # Output: 6

Exercise 12: Caesar Cipher

  • Problem: Implement a function caesar_cipher(text, shift) that takes a string text and an integer shift, and returns the encoded text by shifting each letter by the given number in the alphabet. Assume the text contains only lowercase letters.
  • Expected Output:
    python
    caesar_cipher("abc", 3)
    # Output: "def"

Exercise 13: Flatten a Nested List

  • Problem: Write a function flatten_list(nested_list) that takes a nested list of integers and returns a flattened list.
  • Expected Output:
    python
    flatten_list([[1, 2, [3]], [4, 5], [6, [7, 8]]])
    # Output: [1, 2, 3, 4, 5, 6, 7, 8]

Exercise 14: Fibonacci Sequence

  • Problem: Write a function fibonacci(n) that returns the first n numbers in the Fibonacci sequence.
  • Expected Output:
    python
    fibonacci(7)
    # Output: [0, 1, 1, 2, 3, 5, 8]

Exercise 15: Anagram Checker

  • Problem: Write a function are_anagrams(s1, s2) that takes two strings s1 and s2 and returns True if they are anagrams of each other, and False otherwise.
  • Expected Output:
    python
    are_anagrams("listen", "silent")
    # Output: True

Exercise 16: Unique Elements

  • Problem: Write a function unique_elements(lst) that takes a list of integers and returns a list with only the unique elements, preserving the original order.
  • Expected Output:
    python
    unique_elements([1, 2, 2, 3, 4, 4, 5])
    # Output: [1, 2, 3, 4, 5]

Exercise 17: Transpose a Matrix

  • Problem: Write a function transpose_matrix(matrix) that takes a 2D list (matrix) and returns its transpose.
  • Expected Output:
    python
    transpose_matrix([[1, 2], [3, 4], [5, 6]])
    # Output: [[1, 3, 5], [2, 4, 6]]

Exercise 18: Sum of Squares

  • Problem: Write a function sum_of_squares(n) that returns the sum of the squares of all positive integers up to and including n.
  • Expected Output:
    python
    sum_of_squares(5)
    # Output: 55 (1^2 + 2^2 + 3^2 + 4^2 + 5^2)

Exercise 19: Letter Frequency

  • Problem: Write a function letter_frequency(s) that takes a string s and returns a dictionary with the frequency of each letter in the string.
  • Expected Output:
    python
    letter_frequency("hello")
    # Output: {"h": 1, "e": 1, "l": 2, "o": 1}

Exercise 20: Generate a List of Primes

  • Problem: Write a function generate_primes(n) that returns a list of prime numbers up to n.
  • Expected Output:
    python
    generate_primes(10)
    # Output: [2, 3, 5, 7]

Exercise 21: Merge Two Sorted Lists

  • Problem: Write a function merge_sorted_lists(list1, list2) that merges two sorted lists into a single sorted list.
  • Expected Output:
    python
    merge_sorted_lists([1, 3, 5], [2, 4, 6])
    # Output: [1, 2, 3, 4, 5, 6]

Exercise 22: Longest Word in a Sentence

  • Problem: Write a function longest_word(sentence) that takes a string sentence and returns the longest word in the sentence.
  • Expected Output:
    python
    longest_word("The quick brown fox jumps over the lazy dog")
    # Output: "jumps"

Exercise 23: Remove Duplicates from a List

  • Problem: Write a function remove_duplicates(lst) that takes a list and returns a new list with all duplicate elements removed.
  • Expected Output:
    python
    remove_duplicates([1, 2, 2, 3, 4, 4, 5])
    # Output: [1, 2, 3, 4, 5]

Exercise 24: Check for a Pangram

  • Problem: Write a function is_pangram(s) that checks whether a given string s is a pangram (contains every letter of the alphabet at least once).
  • Expected Output:
    python
    is_pangram("The quick brown fox jumps over the lazy dog")
    # Output: True

Exercise 25: Find the Second Largest Element

  • Problem: Write a function second_largest(lst) that returns the second largest element in a list of integers.
  • Expected Output:
    python
    second_largest([10, 20, 4, 45, 99])
    # Output: 45

Lambda

  • Lambda functions Refer Here
  • Lambda function is a function without name
lambda : expression

lambda arg: expression

List Comprehensions

Dictionary Comprehensions

Python Standard Library

1. Introduction to Python Standard Library

  • What is the Python Standard Library?
    • A collection of modules and packages included with Python.
    • Provides tools for various tasks like file handling, networking, math, and more.

2. Commonly Used Modules

2.1 os Module

  • Working with the Operating System:
    • os.getcwd() – Get current working directory.
    • os.listdir() – List files in a directory.
    • os.mkdir() – Create a directory.
    • os.remove() – Delete a file.

2.2 sys Module

  • System-Specific Parameters and Functions:
    • sys.argv – Command line arguments.
    • sys.exit() – Exit from Python.
    • sys.path – List of directories Python looks for modules.

2.3 math Module

  • Mathematical Functions:
    • math.sqrt() – Square root.
    • math.factorial() – Factorial of a number.
    • math.pi – Value of Ï€.
    • math.sin(), math.cos(), math.tan() – Trigonometric functions.

2.4 datetime Module

  • Date and Time Handling:
    • datetime.date() – Date object.
    • datetime.time() – Time object.
    • datetime.datetime.now() – Current date and time.
    • datetime.timedelta() – Time differences.

2.5 random Module

  • Random Number Generation:
    • random.randint() – Random integer.
    • random.choice() – Randomly choose from a list.
    • random.shuffle() – Shuffle a list.
    • random.sample() – Random sample from a list.

2.6 re Module

  • Regular Expressions:
    • re.match() – Match a pattern.
    • re.search() – Search for a pattern.
    • re.findall() – Find all occurrences.
    • re.sub() – Substitute strings.

2.7 json Module

  • JSON Handling:
    • json.dumps() – Convert Python object to JSON string.
    • json.loads() – Parse JSON string into Python object.
    • json.dump() – Write JSON data to a file.
    • json.load() – Load JSON data from a file.

2.8 collections Module

  • Advanced Data Structures:
    • Counter – Count elements in an iterable.
    • deque – Double-ended queue.
    • defaultdict – Dictionary with a default value.
    • namedtuple – Tuple with named fields.

3. File Handling with io and os

  • Reading and Writing Files:
    • open(), read(), write(), close() methods.
    • File modes (r, w, a, b).
  • Context Managers:
    • Using with statement for file handling.

4. Networking with socket and http

  • Creating a Basic Server and Client:
    • socket.socket() – Create a socket.
    • socket.bind(), socket.listen(), socket.accept() – Server functions.
    • socket.connect(), socket.send(), socket.recv() – Client functions.
  • HTTP Requests with http.client and urllib Modules:
    • urllib.request.urlopen() – Open a URL.
    • http.client.HTTPConnection() – Manage HTTP connections.

5. Error Handling with exceptions

  • Common Exceptions:
    • try, except, finally blocks.
    • raise – Trigger an exception.
    • Custom exceptions by subclassing Exception.

6. Concurrency with threading and multiprocessing

  • Creating Threads and Processes:
    • threading.Thread() – Create a new thread.
    • multiprocessing.Process() – Create a new process.
  • Synchronizing Threads:
    • threading.Lock(), threading.Semaphore().

7. Unit Testing with unittest

  • Writing Test Cases:
    • unittest.TestCase – Base class for writing tests.
    • assertEqual(), assertTrue(), assertRaises() – Common assertions.
  • Running Tests:
    • unittest.main() – Run all tests.

8. Data Compression and Archiving with zipfile, tarfile, and gzip

  • Creating and Extracting Archives:
    • zipfile.ZipFile() – Work with zip files.
    • tarfile.open() – Work with tar files.
    • gzip.open() – Work with gzip files.

9. Conclusion and Further Learning

Lets recreate vowel count with defaultdict, comprehnension and Counter

  • count characters in a string

Lets understand modules and packages

  • Look into classroom recording

Published
Categorized as Uncategorized Tagged

By continuous learner

devops & cloud enthusiastic learner

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Animated Social Media Icons by Acurax Responsive Web Designing Company

Discover more from Direct DevOps from Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading

Visit Us On FacebookVisit Us On LinkedinVisit Us On Youtube