├── .vscode └── settings.json ├── CoursePy.py ├── Exam ├── Exam1.py └── Exam2.py ├── Exercises ├── 1-Beginner.py ├── Built_in_fs │ ├── docs.py │ └── main.py ├── Class │ ├── class (1).jpg │ ├── class (2).jpg │ ├── class (3).jpg │ └── readme.md ├── Difficults │ ├── ip_address.py │ ├── maxArea.py │ └── n_th_cons_prime.py ├── Functions │ ├── Function.jpg │ ├── Functions (1).png │ ├── Functions (2).png │ └── main.py ├── Modules │ ├── module (1).png │ ├── module (2).png │ ├── module (3).png │ ├── module (4).png │ └── module (5).png ├── __init__.py ├── decor_itr.py ├── decorators │ ├── docs.py │ └── main.py ├── dict.py ├── file_handling.py ├── integer.py ├── list.py ├── loops │ ├── For-Loop.png │ ├── While loop.png │ ├── main.py │ └── sowpods.txt ├── set.py ├── string.py ├── tree.py └── tuple.py ├── Lessons ├── 10lesson.py ├── 11lesson.py ├── 12lesson.py ├── 13lesson.py ├── 14lesson.py ├── 15lesson.py ├── 16lesson.py ├── 17lesson.py ├── 18lesson.py ├── 19lesson.py ├── 1lesson.py ├── 2lesson.py ├── 3lesson.py ├── 4lesson_MOCK.EXAM.py ├── 5lesson.py ├── 6lesson.py ├── 7lesson.py ├── 8lesson.py ├── 9lesson.py ├── __pycache__ │ └── 19lesson.cpython-311.pyc └── regular_expression.txt ├── LessonsExersisesAll ├── ExLesson10.py ├── ExLesson11.py ├── ExLesson12.py ├── ExLesson13.py ├── ExLesson2.py ├── ExLesson3.py ├── ExLesson4.py ├── ExLesson6.py ├── ExLesson7.py ├── ExLesson8.py ├── ExLesson9.py ├── PythonList280EX.py └── PythonString113EX.py ├── Mini_Games_And_Projects ├── GuessNumber.py ├── HelloWorld_with_cycle.py └── Quiz-Game-main │ ├── __init__.py │ ├── __pycache__ │ ├── app.cpython-312.pyc │ ├── constructor.cpython-311.pyc │ └── constructor.cpython-312.pyc │ ├── app.py │ ├── constructor.py │ ├── lv_up.mp3 │ ├── right.mp3 │ ├── sweet.mp3 │ ├── tests.py │ ├── triumph.mp3 │ └── wrong.mp3 ├── POSTGRES ├── 1-First-lesson.md ├── 2-Second-lesson.md ├── 3-Third-lesson.md ├── Task 1.txt ├── Task 2.txt ├── Task 3.txt ├── Task 4.txt ├── create-file.psql └── exam.md ├── Pipfile ├── Pipfile.lock ├── README.md ├── Test.md ├── chromedriver.exe └── www. ISTAM_COMPANY /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.analysis.autoImportCompletions": true, 3 | "python.analysis.typeCheckingMode": "basic" 4 | } -------------------------------------------------------------------------------- /Exam/Exam1.py: -------------------------------------------------------------------------------- 1 | #1 2 | 3 | # def mulyply_list(list1): 4 | # result = 1 5 | # for i in list1: 6 | # result *= i 7 | # return result 8 | # print(mulyply_list([1,2,3])) 9 | 10 | #2 11 | 12 | # def smallest_greatesr_sum(arr): 13 | # max1 = max(arr) 14 | # min1 = min(arr) 15 | # res = max1 + min1 16 | # if res %2 == 0: 17 | # print(f"summa чисел {max1} i {min1} четный") 18 | # else: 19 | # print(f"summa чисел {max1} i {min1} нечетный") 20 | # smallest_greatesr_sum([1,2,3]) 21 | 22 | #3 23 | 24 | # def count_strings(arr): 25 | # result = [] 26 | # for i in arr: 27 | # a = i[0:2] 28 | # if a[::-1] == i[-2:]: 29 | # result.append(i) 30 | # return f"Result: {result}" 31 | # print(count_strings(['abc', 'xyz', 'aba', '1212381923128321', 'istammatsi'])) 32 | 33 | #4 34 | 35 | # def sort_tuple(tup:tuple): 36 | # evens = [x for x in tup if x % 2 == 0] 37 | # odds = [x for x in tup if x % 2 != 0] 38 | # evens.sort(reverse=True) 39 | # odds.sort(reverse=True) 40 | # return tuple(evens+odds) 41 | # print(sort_tuple((3,1,4,1,5,9,2,6,5,3,5))) 42 | 43 | #5 44 | 45 | # def remove_key(dc, _key): 46 | # dc_copy = dc.copy() 47 | # dc_copy.pop(_key) 48 | # return dc_copy 49 | # print(remove_key(dict(a =1,b = 2,c = 3),'a')) 50 | 51 | #6 52 | 53 | # 6. Write a Python program to remove duplicates from the dictionary. 54 | # First, leave at least one item from duplicates 55 | # Second, delete all duplicates 56 | # RU: Напишите программу Python для удаления дубликатов из словаря. 57 | # Во-первых, оставьте хотя бы один элемент из дубликатов 58 | # Во-вторых, удалите все дубликаты 59 | # def remove_duplicates(dict): 60 | 61 | # def remove_duplicates(dict): 62 | # result = {} 63 | # values = [] 64 | # for k, v in dict.items(): 65 | # if v not in values: 66 | # result[k] = v 67 | # values.append(v) 68 | # return result 69 | # new_dict = remove_duplicates({'x':1, 'y':2, 'z':2, 'a':3, 'b':1, 'c':3}) 70 | # print(new_dict) 71 | 72 | # ex: {'x':1, 'y':2, 'z':2, 'a':3, 'b':1, 'c':3} 73 | # => {x':1, 'y':2, 'a':3} 74 | 75 | # ========================================================================== 76 | # 7. Write a function that takes a dict as first argument and number as second argument. 77 | # Return a list of all the keys that have values greater than the number passed as second argument. 78 | # RU: Напишите функцию, которая принимает словарь в качестве первого аргумента и число в 79 | # качестве второго аргумента. Верните список всех ключей, у которых значения больше, чем число, 80 | # переданное в качестве второго аргумента. 81 | # Input: {'a': 100, 'b': 200, 'c': 300, 'd': "Hello world", 'e': True}, 150 82 | # Output: {'b': 200, 'c': 300} 83 | 84 | # def get_keys_greater_than(dict, num): 85 | # a = {k:v for k,v in dict.items() if isinstance(v , int) and v > num} 86 | # return a 87 | # print(get_keys_greater_than({'a': 100, 'b': 200, 'c': 300, 'd': "Hello world", 'e': True},150)) 88 | 89 | # ========================================================================== 90 | # 8. Write a function that takes a dictionary as an argument and returns 91 | # a new dictionary with the keys and values reversed. 92 | # RU: Напишите функцию, которая принимает словарь в качестве аргумента 93 | # и возвращает новый словарь с обратными ключами и значениями. 94 | 95 | # def reverse_dict(d): 96 | # a ={v:k for k,v in d.items()} 97 | # return a 98 | # print(reverse_dict({"a":1, "b":2})) 99 | 100 | # ========================================================================== 101 | # 9. Write a function that takes a list of dictionaries as an argument 102 | # and returns a sum of numeric values of all dicts 103 | # RU: Напишите функцию, которая принимает список словарей в качестве аргумента 104 | # и возвращает сумму числовых значений всех словарей 105 | # x = {'a': 1, 'b': "2", "c": "Hello"} 106 | # z = {'d': "4", 'e': 3, "f": "World"} 107 | # a = {'g': 5, 'h': "!!!", "i": "6"} 108 | # arr = [x, z, a] 109 | # # test(arr) # 21 110 | 111 | # x = {'a': 1, 'b': "2", "c": "Hello"} 112 | # z = {'d': "4", 'e': 3, "f": "World"} 113 | # a = {'g': 5, 'h': "!!!", "i": "6"} 114 | # arr = [x, z, a] 115 | 116 | # def sum_numeric_values(arr_of_dicts): 117 | # total = 0 118 | # for dict in arr_of_dicts: 119 | # for val in dict.values(): 120 | # if str(val).isnumeric(): 121 | # total += int(val) 122 | # return total 123 | # print(sum_numeric_values(arr)) 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /Exam/Exam2.py: -------------------------------------------------------------------------------- 1 | #FIRST TEST /// https://proglib.io/tests/test-na-znanie-yazyka-python 2 | #SECOND TEST /// https://itproger.com/test/python 3 | 4 | # EXAM EXERCISES 5 | 6 | # 1. Create a function that finds n number of prime numbers. 7 | # RU: Создайте функцию, которая находит n количество простых чисел. 8 | 9 | # 2. Create a function that counts how much time that 10 | # function takes to execute. 11 | # RU: Создайте функцию, которая подсчитывает, сколько 12 | # времени занимает выполнение этой функции. 13 | 14 | # 3. Create a class that takes this function as a method 15 | # and returns the execution time. Then, create an object 16 | # and call the method. 17 | # RU: Создайте класс, который принимает эту функцию как метод. 18 | # и возвращает время выполнения. Затем создайте объект 19 | # и вызовем метод. 20 | 21 | import time 22 | 23 | 24 | def calc_time(func): 25 | def wrapper(*args, **kwargs): 26 | start_time = time.time() 27 | result = func(*args, **kwargs) 28 | end_time = time.time() 29 | total_time = end_time - start_time 30 | print(f"the f:{func.__name__} take {round(total_time, 5)} seconds") 31 | return result 32 | return wrapper 33 | 34 | 35 | @calc_time 36 | def prime_nums(n): 37 | prime_numbers = [] 38 | num = 2 39 | while len(prime_numbers) < n: 40 | is_prime = True 41 | for i in range(2, int(num**0.5) + 1): 42 | if num % i == 0: 43 | is_prime = False 44 | break 45 | if is_prime: 46 | prime_numbers.append(num) 47 | num += 1 48 | return prime_numbers 49 | 50 | 51 | @calc_time 52 | def calculate_time(function, *args): 53 | result = function(*args) 54 | return result 55 | 56 | 57 | nums_primes_before = 10000 58 | print(prime_nums(nums_primes_before)) 59 | 60 | result = calculate_time(prime_nums, nums_primes_before) 61 | 62 | 63 | class Timer: 64 | def __init__(self, func): 65 | self.func = func 66 | 67 | def f(self, *args): 68 | start_time = time.time() 69 | result = self.func(*args) 70 | end_time = time.time() 71 | finish_time = end_time - start_time 72 | return result, finish_time 73 | 74 | 75 | timer = Timer(prime_nums) 76 | result, execution_time = timer.f(nums_primes_before) 77 | print(round(execution_time, 5)) 78 | -------------------------------------------------------------------------------- /Exercises/Class/class (1).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Class/class (1).jpg -------------------------------------------------------------------------------- /Exercises/Class/class (2).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Class/class (2).jpg -------------------------------------------------------------------------------- /Exercises/Class/class (3).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Class/class (3).jpg -------------------------------------------------------------------------------- /Exercises/Class/readme.md: -------------------------------------------------------------------------------- 1 | # Dunders 2 | 3 | - Dunders are the methods that start with double 4 | underscore '__' and end with double underscore '__' 5 | and they are also called magic methods. 6 | RU: Дандеры - это методы, которые начинаются с двойного 7 | подчеркивания '__' и заканчиваются двойным подчеркиванием '__' и их также называют магическими методами. 8 | - Dunders are used to emulate some built-in behaviour within python. 9 | (ex: operator overloading or __init__ method or __repr__, __str__ methods ...) 10 | RU: Дандеры используются для эмуляции некоторого встроенного поведения внутри python 11 | (например: перегрузка операторов или методы __init__, __repr__, __str__ ...) 12 | 13 | #### METHODS 14 | 1. __init__ method - is used to initialize the object. 15 | RU: метод __init__ - используется для инициализации объекта. 16 | 2. __call__ method - is used to call the object like a function. 17 | RU: метод __call__ - используется для вызова объекта как функции. 18 | 3. __repr__ method - is used to return the string representation of the object. 19 | 4. __str__ method - is used to return the string representation of the object. 20 | 5. __add__ method - is used to add two objects. 21 | ... 22 | 23 | #### EXAMPLES 24 | ```python 25 | class Employee: 26 | def __init__(self, name, age): 27 | self.name = name 28 | self.age = age 29 | 30 | def __repr__(self): 31 | return f"Employee('{self.name}', {self.age})" 32 | 33 | def __str__(self): 34 | return f"Employee name: {self.name}, age: {self.age}" 35 | 36 | def __add__(self, other): 37 | return self.age + other.age 38 | 39 | ex: 40 | emp1 = Employee('John', 25) 41 | emp2 = Employee('Jane', 30) 42 | 43 | print(emp1 + emp2) # 55 44 | 45 | def __len__(self): 46 | return len(self.name) 47 | 48 | ex: 49 | emp1 = Employee('John', 25) 50 | print(len(emp1)) # 4 (len of 'John') 51 | 52 | def __call__(self, *args, **kwargs): 53 | print(f"Employee name: {self.name}, age: {self.age}") 54 | 55 | ex: 56 | emp1 = Employee('John', 25) 57 | emp1() # Employee name: John, age: 25 58 | 59 | def __getitem__(self, item): 60 | if isinstance(item, int): 61 | # This is for index access (ex: emp1[0]) 62 | return self.name[item] 63 | elif isinstance(item, slice): 64 | # This is for slicing (ex: emp1[1:3]) 65 | return self.name[item.start:item.stop:item.step] 66 | elif isinstance(item, str): 67 | # This is for key access (ex: emp1['name']) 68 | return self.__dict__[item] 69 | 70 | emp1 = Employee('John', 25) 71 | print(emp1[0]) # J 72 | print(emp1[1:3]) # oh 73 | print(emp1['name']) # John 74 | 75 | ``` 76 | 77 | --- 78 | 79 | -------------------------------------------------------------------------------- /Exercises/Difficults/ip_address.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import requests # to install: pip install requests 4 | 5 | 6 | def find_person_by_ip(ip_address): 7 | url = "http://ip-api.com/json/" 8 | response = requests.get(url, ip_address) 9 | data = json.loads(response.content) 10 | return data 11 | 12 | 13 | # type ipconfig in cmd 14 | my_ip_address = "192.168.0.111" 15 | 16 | geolocation_data = find_person_by_ip(my_ip_address) 17 | print(geolocation_data) 18 | -------------------------------------------------------------------------------- /Exercises/Difficults/maxArea.py: -------------------------------------------------------------------------------- 1 | # You are given an integer array height of length n. 2 | # There are n vertical lines drawn such that the two endpoints 3 | # of the ith line are (i, 0) and (i, height[i]). 4 | 5 | # Find two lines that together with the x-axis form a container, 6 | # such that the container contains the most water. 7 | 8 | # Return the maximum amount of water a container can store. 9 | 10 | # Notice that you may not slant the container. 11 | 12 | 13 | # Input: height = [1,8,6,2,5,4,8,3,7] 14 | # Output: 49 15 | # Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. 16 | # In this case, the max area of water (blue section) 17 | # the container can contain is 49. 18 | 19 | 20 | # The problem is to find the maximum amount of water that can be stored in a 21 | # container formed by two vertical lines drawn on a plane. The input is an 22 | # array of integers representing the heights of the vertical lines. 23 | # The output should be the maximum amount of water that can be stored in the container. 24 | # The container must be formed by two vertical lines and the x-axis, and it cannot be slanted. 25 | 26 | 27 | # Define a function named maxArea that takes a list of integers as input and returns an integer. 28 | def maxArea(heights: list[int]) -> int: 29 | # Initialize a variable named max_area to 0. 30 | max_area = 0 31 | # Loop through the indices of the input list using the range function. 32 | for i in range(len(heights)): 33 | # Loop through the indices of the input list starting from i+1 using the range function. 34 | for j in range(i + 1, len(heights)): 35 | # Calculate the area of the container formed by the two vertical lines at indices i and j. 36 | # The area is the minimum of the heights of the two lines multiplied by the distance between them. 37 | area = min(heights[i], heights[j]) * (j - i) 38 | # Update the max_area variable if the current area is greater than the previous max_area. 39 | max_area = max(max_area, area) 40 | # Return the maximum area that was found. 41 | return max_area 42 | 43 | 44 | # The maxArea function takes a list of integers as input and returns an integer. 45 | # It calculates the maximum amount of water that can be stored in a container formed by 46 | # two vertical lines drawn on a plane. The input is an array of integers representing the 47 | # heights of the vertical lines. The output should be the maximum amount of water that can 48 | # be stored in the container. The container must be formed by two vertical lines and the 49 | # x-axis, and it cannot be slanted. 50 | 51 | # To calculate the maximum amount of water, the function loops through the indices of the 52 | # input list using the range function. For each index, it loops through the indices of the 53 | # input list starting from the next index using the range function. It calculates the area of 54 | # the container formed by the two vertical lines at the current indices. The area is the 55 | # minimum of the heights of the two lines multiplied by the distance between them. It updates 56 | # the maximum area variable if the current area is greater than the previous maximum area. 57 | # Finally, it returns the maximum area that was found. 58 | 59 | 60 | # Call the maxArea function with the input list [1, 8, 6, 2, 5, 4, 8, 3, 7] and print the result. 61 | # print(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])) 62 | print(maxArea([6, 3, 7])) 63 | -------------------------------------------------------------------------------- /Exercises/Difficults/n_th_cons_prime.py: -------------------------------------------------------------------------------- 1 | # The prime 41, can be written as the sum of six consecutive primes: 2 | # This is the longest sum of consecutive primes that adds to a prime 3 | # below one-hundred. 4 | # 41 = 2 + 3 + 5 + 7 + 11 + 13 5 | # The longest sum of consecutive primes below one-thousand that adds 6 | # to a prime, contains 21 terms, and is equal to 953 7 | # Which prime, below one-million, can be written as the sum of the most 8 | # consecutive primes? 9 | 10 | # ======================================================================= 11 | # ======================================================================= 12 | 13 | # This program generates a list of prime numbers up to a given limit. 14 | # It uses the Sieve of Eratosthenes algorithm to efficiently find primes. 15 | # The program first initializes a list of integers from 0 to the limit, 16 | # with 0 and 1 marked as not prime. It then iterates through the list, 17 | # marking all multiples of each prime number as not prime. The remaining 18 | # numbers are prime and are added to a separate list. The program prints 19 | # the length of the list of primes and the largest prime number found. 20 | 21 | # RU: Эта программа генерирует список простых чисел до заданного предела. 22 | # Она использует алгоритм решета Эратосфена для эффективного поиска простых чисел. 23 | # Программа сначала инициализирует список целых чисел от 0 до предела, 24 | # с 0 и 1 помеченных как не простые. Затем она перебирает список, 25 | # помечая все кратные каждого простого числа как не простые. Оставшиеся 26 | # числа являются простыми и добавляются в отдельный список. Программа печатает 27 | # длину списка простых чисел и наибольшее найденное простое число. 28 | 29 | # ======================================================================= 30 | # ======================================================================= 31 | 32 | # Set the limit for finding primes 33 | limit = 1000000 34 | 35 | 36 | # Set the limit for finding primes 37 | limit = 1000000 38 | 39 | # Create a list of integers up to the limit, with 0 and 1 marked as not prime 40 | is_prime = [True] * limit 41 | 42 | # Create an empty list to store prime numbers 43 | prime_numbers = [] 44 | 45 | # Mark 0 and 1 as not prime 46 | is_prime[0] = is_prime[1] = False 47 | 48 | # Iterate through the list of integers 49 | for number in range(2, limit): 50 | # If the current number is prime 51 | if is_prime[number]: 52 | # Add it to the list of primes 53 | prime_numbers.append(number) 54 | # Mark all multiples of the current prime as not prime 55 | for multiple in range(number * number, limit, number): 56 | is_prime[multiple] = False 57 | 58 | # Print "done" to indicate the program has finished 59 | print("done") 60 | 61 | # Print the number of primes found 62 | print(len(prime_numbers)) 63 | 64 | # Print the largest prime found 65 | print(prime_numbers[-1]) 66 | 67 | # Print 100 primes 68 | print(prime_numbers[0:100]) 69 | 70 | # Set max_sum to 0 and max_consecutive_primes to -1 71 | max_sum = 0 72 | max_consecutive_primes = -1 73 | 74 | # Iterate through the list of prime numbers 75 | for i in range(0, len(prime_numbers)): 76 | # Set current_sum to 0 77 | current_sum = 0 78 | # Iterate through the remaining prime numbers 79 | for j in range(i, len(prime_numbers)): 80 | # Add the current prime number to the sum 81 | current_sum += prime_numbers[j] 82 | # If the sum is greater than the limit, break out of the loop 83 | if current_sum > limit: 84 | break 85 | 86 | # If the sum is greater than the current max_sum 87 | # and the number of consecutive primes is greater 88 | # than the current max_consecutive_primes, update 89 | # the max_sum and max_consecutive_primes 90 | if current_sum > max_sum and j - i > max_consecutive_primes: 91 | max_consecutive_primes = j - i 92 | max_sum = current_sum 93 | 94 | print("max_sum: ", max_sum) 95 | print("максимум последовательность простых: ", max_consecutive_primes) 96 | -------------------------------------------------------------------------------- /Exercises/Functions/Function.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Functions/Function.jpg -------------------------------------------------------------------------------- /Exercises/Functions/Functions (1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Functions/Functions (1).png -------------------------------------------------------------------------------- /Exercises/Functions/Functions (2).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Functions/Functions (2).png -------------------------------------------------------------------------------- /Exercises/Functions/main.py: -------------------------------------------------------------------------------- 1 | # 1. Factorial => !5 = 5*4*3*2*1 2 | # factorial(10) => !10 = 10*9*8*7*6*5*4*3*2*1 3 | def factorial(n): 4 | if n == 1: 5 | return 1 6 | return n * factorial(n - 1) 7 | 8 | 9 | print(factorial(5)) 10 | 11 | # ============== 12 | # 2. Fibonacci => 0, 1 = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... 13 | # fibbo(50) => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 14 | 15 | 16 | def fibonacci(max, first=0, second=1): 17 | if first > max: 18 | return [] 19 | else: 20 | return [first, *fibonacci(max, second, first+second)] 21 | 22 | 23 | print(fibonacci(50)) 24 | # ============== 25 | # 3. Piramid 26 | # piramid(10) 27 | # * 28 | # *** 29 | # ***** 30 | # ******* 31 | # ********* 32 | # *********** 33 | # ************* 34 | # *************** 35 | # ***************** 36 | # ******************* 37 | 38 | 39 | def piramid_recursion(n_times): 40 | if n_times == 1: 41 | return "*" 42 | else: 43 | return "*" * n_times + "\n" + piramid_recursion(n_times-1) 44 | # =============== 45 | # With loop 46 | # result = "" 47 | # for i in range(n_times): 48 | # result += "*" * (i+1) + "\n" 49 | # return result 50 | 51 | 52 | piramid_recursion(10) 53 | 54 | # ==================================================================== 55 | # ! USE RECURSION 56 | 57 | 58 | def rotate_string_recursively(string, remaining_str=""): 59 | if len(remaining_str) == 0: 60 | remaining_str = string 61 | 62 | new_str = string[-1] + string[:-1] 63 | if len(remaining_str) == 1: 64 | print(new_str) 65 | return 66 | 67 | print(string) 68 | return rotate_string_recursively(new_str, remaining_str[:-1]) 69 | 70 | # rotate_string_recursively("Hello world") 71 | # >> Hello world 72 | # >> dHello worl 73 | # >> ldHello wor 74 | # >> rldHello wo 75 | # >> orldHello w 76 | # >> worldHello 77 | # >> worldHello 78 | # >> o worldHell 79 | # >> lo worldHel 80 | # >> llo worldHe 81 | # >> ello WorldH 82 | # >> Hello World 83 | # ==================================================================== 84 | -------------------------------------------------------------------------------- /Exercises/Modules/module (1).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Modules/module (1).png -------------------------------------------------------------------------------- /Exercises/Modules/module (2).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Modules/module (2).png -------------------------------------------------------------------------------- /Exercises/Modules/module (3).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Modules/module (3).png -------------------------------------------------------------------------------- /Exercises/Modules/module (4).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Modules/module (4).png -------------------------------------------------------------------------------- /Exercises/Modules/module (5).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/Modules/module (5).png -------------------------------------------------------------------------------- /Exercises/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/__init__.py -------------------------------------------------------------------------------- /Exercises/decor_itr.py: -------------------------------------------------------------------------------- 1 | # Make a chain of function decorators. 2 | # Standardize mobile numbers when given N mobile numbers. Sort them in ascending order. Print them in the standard format. 3 | # Compress the given string S. If the string contains a character 'c,' that occurs X times consecutively. Replace 'c' with (X, c) in the string. 4 | # Print all possible size k replacement combinations of the given string S in lexicographically sorted order. 5 | # Build a name directory using decorators for a given piece of information about N people where every person’s name has first and last name, age, and sex. Sort their ages in ascending order and print their names accordingly. So, the name of the youngest person should be printed first. If there are two people of the same age, then you print them in the order of their input. 6 | 7 | 8 | -------------------------------------------------------------------------------- /Exercises/decorators/docs.py: -------------------------------------------------------------------------------- 1 | import math 2 | import time 3 | 4 | # def fn_1(): 5 | # print("Function first") 6 | 7 | 8 | # def fn_2(): 9 | # print("Function Second") 10 | 11 | 12 | # def fn_3(fn): 13 | # print('-----------------------------------') 14 | # print("Befor calling {}".format(fn.__name__)) 15 | # fn() 16 | # print("After calling {}".format(fn.__name__)) 17 | 18 | 19 | # fn_3(fn_1) 20 | # fn_3(fn_2) 21 | # ==================================================================================================== 22 | # ==================================================================================================== 23 | # ==================================================================================================== 24 | 25 | lesson = "Decorators & Wrappers" 26 | # Decorators are functions that take another function as an argument, add some kind of functionality, 27 | # and then return another function. All of this without altering the source code of the original 28 | # function that we passed in. In Python, functions are first-class objects, which means that we can 29 | # pass them as arguments to other functions. We can also return them as the values from other functions. 30 | # This is the basis of decorators. 31 | 32 | #################################################################################### 33 | #################################################################################### 34 | #################################################################################### 35 | # BASIC DECORATOR 36 | 37 | 38 | # def decorator_function(original_function): 39 | # def wrapper_function(*args, **kwargs): 40 | # print("Wrapper executed this before {}".format( 41 | # original_function.__name__)) 42 | # return original_function(*args, **kwargs) 43 | # return wrapper_function 44 | 45 | 46 | # @decorator_function 47 | # def original_function(): 48 | # print("Original function ran") 49 | 50 | #################################################################################### 51 | # defining a decorator 52 | 53 | 54 | # def hello_decorator(func): 55 | 56 | # # inner1 is a Wrapper function in 57 | # # which the argument is called 58 | 59 | # # inner function can access the outer local 60 | # # functions like in this case "func" 61 | # def inner1(): 62 | # print("Hello, this is before function execution") 63 | # # calling the actual function now 64 | # # inside the wrapper function. 65 | # result = func() 66 | # print("This is after function execution") 67 | # return result 68 | 69 | # return inner1 70 | 71 | 72 | # # defining a function, to be called inside wrapper 73 | # def function_to_be_used(): 74 | # print("This is inside the function !!") 75 | 76 | 77 | # # # passing 'function_to_be_used' inside the 78 | # # # decorator to control its behaviour 79 | # function_to_be_used = hello_decorator(function_to_be_used) 80 | 81 | 82 | # # calling the function 83 | # function_to_be_used() 84 | 85 | 86 | #################################################################################### 87 | #################################################################################### 88 | #################################################################################### 89 | # Practical example 1 90 | # find out the execution time of a function using a decorator. 91 | 92 | # decorator to calculate duration 93 | # taken by any function. 94 | # def calculate_time(func): 95 | 96 | # # added arguments inside the inner1, 97 | # # if function takes any arguments, 98 | # # can be added like this. 99 | # def inner1(*args, **kwargs): 100 | 101 | # # storing time before function execution 102 | # begin = time.time() 103 | 104 | # func(*args, **kwargs) 105 | 106 | # # storing time after function execution 107 | # end = time.time() 108 | # print("Total time taken in : ", func.__name__, end - begin) 109 | 110 | # return inner1 111 | 112 | 113 | # # this can be added to any function present, 114 | # # in this case to calculate a factorial 115 | # @calculate_time 116 | # def factorial(num): 117 | 118 | # # sleep 2 seconds because it takes very less time 119 | # # so that you can see the actual difference 120 | # time.sleep(2) 121 | # print(math.factorial(num)) 122 | 123 | 124 | # # calling the function. 125 | # factorial(10) 126 | 127 | #################################################################################### 128 | #################################################################################### 129 | #################################################################################### 130 | # RETURN A VALUE 131 | 132 | # def hello_decorator(func): 133 | # def inner1(*args, **kwargs): 134 | 135 | # print("before Execution") 136 | 137 | # # getting the returned value 138 | # returned_value = func(*args, **kwargs) 139 | # print("after Execution") 140 | 141 | # # returning the value to the original frame 142 | # return returned_value 143 | 144 | # return inner1 145 | 146 | 147 | # # adding decorator to the function 148 | # @hello_decorator 149 | # def sum_two_numbers(a, b): 150 | # print("Inside the function") 151 | # return a + b 152 | 153 | 154 | # a, b = 1, 2 155 | 156 | # # getting the value through return of the function 157 | # sum = sum_two_numbers(a, b) 158 | # print("Sum =", sum) 159 | #################################################################################### 160 | #################################################################################### 161 | #################################################################################### 162 | # MEMOIZATION 163 | # Factorial program with memoization using decorators. 164 | 165 | # A decorator function for function 'f' passed 166 | # as parameter 167 | # memory = {} 168 | 169 | 170 | # def memoize_factorial(f): 171 | 172 | # # This inner function has access to memory 173 | # # and 'f' 174 | # def inner(num): 175 | # if num not in memory: 176 | # memory[num] = f(num) 177 | # print('result saved in memory') 178 | # else: 179 | # print('returning result from saved memory') 180 | # return memory[num] 181 | 182 | # return inner 183 | 184 | 185 | # @memoize_factorial 186 | # def facto(num): 187 | # if num == 1: 188 | # return 1 189 | # else: 190 | # return num * facto(num-1) 191 | 192 | 193 | # print(facto(5)) 194 | # print(facto(5)) # directly coming from saved memory 195 | # print(memory) 196 | -------------------------------------------------------------------------------- /Exercises/decorators/main.py: -------------------------------------------------------------------------------- 1 | # 1. Write a Python program to create a decorator that logs the arguments and return value of a function. 2 | # RU: Напишите программу на Python для создания декоратора, который регистрирует аргументы и возвращаемое значение функции. 3 | def decorator_fn(fn): 4 | def wrapper(*args, **kwargs): 5 | print( 6 | f"Printing args before execution of original function {fn.__name__}") 7 | print(args) 8 | return fn(*args, **kwargs) 9 | return wrapper 10 | 11 | 12 | @decorator_fn 13 | def test_fn2(string): 14 | print("Inside the original function") 15 | return string 16 | 17 | 18 | test_fn2("Test-Sentence") 19 | # ################################################################################### 20 | # ################################################################################### 21 | # ################################################################################### 22 | 23 | # 2. Write a Python program to create a decorator function to measure the execution time of a function. 24 | # RU: Напишите программу на Python для создания декоратора функции для измерения времени выполнения функции. 25 | 26 | 27 | def calculate_time_dec(fn): 28 | def wrapper(*args, **kwargs): 29 | import time 30 | start = time.time() 31 | result = fn(*args, **kwargs) 32 | end = time.time() 33 | print(f"Execution time: {end - start}") 34 | return result 35 | return wrapper 36 | 37 | 38 | @calculate_time_dec 39 | def test_fn(string): 40 | print("Inside the original function") 41 | return string 42 | 43 | 44 | test_fn("Test-Sentence") 45 | 46 | # ################################################################################### 47 | # ################################################################################### 48 | # ################################################################################### 49 | 50 | # 3. Create a decorator to check the input values of a function and 51 | # raise an exception if the input values are not of the expected type. 52 | # RU: Создайте декоратор для проверки входных значений функции и 53 | # вызовите исключение, если входные значения не соответствуют ожидаемому типу. 54 | # Expected types of input: int, string 55 | # raise Exception("Invalid input type") 56 | 57 | 58 | def check_input(fn): 59 | """is used to check if the given input is alpha-numerical""" 60 | def wrapper(*args, **kwargs): 61 | for item in args: 62 | if not item.isalnum(): 63 | raise Exception("Invalid value") 64 | return fn(*args, **kwargs) 65 | return wrapper 66 | 67 | 68 | @check_input 69 | def get_text(string): 70 | print("Inside the original function") 71 | return string 72 | 73 | # answer = input("Enter a alpha numeric value please: ") 74 | # print(get_text(answer)) 75 | 76 | 77 | # ################################################################################### 78 | # 4. Write a Python program that implements a decorator to retry a function 79 | # 3 times in case of failure. 80 | # RU: Напишите программу на Python, которая реализует декоратор для повторного 81 | # вызова функции 3 раза в случае сбоя. 82 | def retry(fn): 83 | def wrapper(*args, **kwargs): 84 | for i in range(3): 85 | try: 86 | return fn(*args, **kwargs) 87 | except: 88 | print("Retrying...") 89 | return wrapper 90 | 91 | 92 | @retry 93 | def test_fn3(string): 94 | print("Inside the original function") 95 | raise Exception("Test exception") 96 | 97 | 98 | # ################################################################################### 99 | # 5. Write a Python program that implements a decorator that records time when 100 | # the function has been called 101 | def record_time(fn): 102 | def wrapper(*args, **kwargs): 103 | import time 104 | start = time.time() 105 | result = fn(*args, **kwargs) 106 | end = time.time() 107 | print(f"Execution time: {end - start}") 108 | return result 109 | return wrapper 110 | 111 | 112 | @record_time 113 | def test_fn4(string): 114 | print("Inside the original function") 115 | return string 116 | 117 | # ################################################################################### 118 | # 6. Write a Python program that implements a decorator to handle exceptions raised 119 | # by a function and provide a default response. 120 | 121 | 122 | def handle_exception(fn): 123 | def wrapper(*args, **kwargs): 124 | try: 125 | return fn(*args, **kwargs) 126 | except: 127 | print("Exception handled") 128 | return "Default response" 129 | return wrapper 130 | 131 | 132 | @handle_exception 133 | def test_fn5(string): 134 | print("Inside the original function") 135 | raise Exception("Test exception") 136 | 137 | # ################################################################################### 138 | # 7. Write a Python program that implements a decorator to measure the memory usage of a function. 139 | 140 | 141 | def measure_memory(fn): 142 | def wrapper(*args, **kwargs): 143 | import memory_profiler 144 | 145 | # install memory_profiler with pip install memory_profiler 146 | result = memory_profiler.memory_usage() 147 | # memory usage shows the memory usage of the current process in kilobytes 148 | return result 149 | return wrapper 150 | 151 | 152 | @measure_memory 153 | def test_fn6(string): 154 | print("Inside the original function") 155 | return string 156 | 157 | # ################################################################################### 158 | 159 | 160 | # 8. Write a Python program that implements a decorator to provide caching 161 | # cache = {} 162 | 163 | 164 | # def cache(fn): 165 | def wrapper(*args, **kwargs): 166 | cache[args] = fn(*args, **kwargs) 167 | return cache[args] 168 | return wrapper 169 | 170 | 171 | # @cache 172 | # def test_fn7(string): 173 | print("Inside the original function") 174 | return string 175 | # ################################################################################### 176 | -------------------------------------------------------------------------------- /Exercises/file_handling.py: -------------------------------------------------------------------------------- 1 | # 1. Create and write to a file with names and read the file and print the names and the number of times they appear in the file. 2 | # RU: Создайте и запишите в файл имена, прочитайте файл и напечатайте имена и количество раз, которое они встречаются в файле. 3 | def read_names(): 4 | file = open("nameslist.txt", "r") 5 | names = file.read().split("\n") 6 | names.sort() 7 | names_set_list = list(set(names)) 8 | names_set_list.sort(key=lambda x: names.count(x)) 9 | for name in names_set_list: 10 | print(name + ": " + str(names.count(name))) 11 | 12 | 13 | def create_names(names): 14 | file = open("nameslist.txt", "w") 15 | for name in names: 16 | file.write(name + "\n") 17 | file.close() 18 | 19 | 20 | names = [ 21 | "Oliver", "George", "Harry", "Jack", "Jacob", "Noah", 22 | "Charlie", "Muhammad", "Thomas", "Oscar", "William", 23 | "James", "Leo", "Alfie", "Henry", "Archie", "Ethan", 24 | "Charlie", "Muhammad", "Thomas", "Oscar", "William", 25 | "Joseph", "Freddie", "Samuel", "Alexander", "Logan" 26 | ] 27 | 28 | create_names(names) 29 | read_names() 30 | 31 | # ====================================================================================================================== 32 | # ====================================================================================================================== 33 | # 2. Create a file with numbers and read the file and print the sum of all numbers. 34 | # RU: Создайте файл с числами, прочитайте файл и напечатайте сумму всех чисел. 35 | 36 | 37 | def read_numbers_and_sum(): 38 | file = open("numbers.txt", "r") 39 | numbers = file.read().split("\n") 40 | print("numbers: ", numbers) 41 | numbers = [int(n.strip()) for n in numbers if n] 42 | print(sum(numbers)) 43 | 44 | 45 | def create_numbers(): 46 | numbers = [int(n.strip()) 47 | for n in input("Enter numbers: ").split(',') if n.strip().isnumeric()] 48 | file = open("numbers.txt", "w") 49 | for number in numbers: 50 | file.write(str(number) + "\n") 51 | file.close() 52 | 53 | 54 | create_numbers() 55 | read_numbers_and_sum() 56 | 57 | 58 | # ====================================================================================================================== 59 | # ====================================================================================================================== 60 | -------------------------------------------------------------------------------- /Exercises/integer.py: -------------------------------------------------------------------------------- 1 | # 1. Reverse an integer. 2 | # RU: Обратный порядок целого числа. 3 | def reverse_integer(num): 4 | return str(num)[::-1] 5 | 6 | # 2. Print the Fibonacci series using the recursive method. 7 | # fibonacci(10) => 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ... 8 | # RU: Выведите ряд Фибоначчи с помощью рекурсивного метода. 9 | def fibonacci(max, first:int=0, second:int=1): 10 | # ================================================================ 11 | # FIRST METHOD---------------------------------------------------- 12 | if max > first: 13 | return [] 14 | return [first] + fibonacci(max, second, first + second) 15 | # ================================================================ 16 | # SECOND METHOD--------------------------------------------------- 17 | # List comprehension 18 | # return [first] + fibonacci(max, second, first + second) if max > first else [] 19 | # ================================================================ 20 | # THIRD METHOD---------------------------------------------------- 21 | # if max <= 1: 22 | # return max 23 | # else: 24 | # return fibonacci(max-1) + fibonacci(max-2) 25 | 26 | 27 | 28 | # 3. Return the Nth value from the Fibonacci sequence. 29 | # fibonacci(10) => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... => 34 30 | # RU: Вернуть N-е значение из последовательности Фибоначчи. 31 | 32 | 33 | # 4. Find an average number of given numbers of the list and return nearest integer 34 | # from given list 35 | # RU: Найти среднее число данного списка и вернуть ближайшее целое число 36 | # из данного списка. 37 | # INPUT: [1, 10, 40, 35, 20, 30, 50, 60, 70] 38 | # OUTPUT: 37.777... => 35 => index-3 39 | # ================================================================================= 40 | 41 | # 5. Print stars downwards starting from n number 42 | # RU: Распечатать звезды вниз, начиная с числа n 43 | def print_stars(max): 44 | # for i in range(max): 45 | # print('*' * (max - i)) 46 | if max==0: 47 | return 48 | print(max * '*') 49 | return print_stars(max-1) 50 | print_stars(10) 51 | 52 | # ================================================================================= 53 | # 6. Print stars (*) in the shape of a pyramid with N number of steps. 54 | # pyramid(4) => 55 | # * 56 | # *** 57 | # ***** 58 | # ******* 59 | # ================================================================================= 60 | 61 | 62 | # 5. Convert Celsius to Fahrenheit. 63 | # RU: Преобразование Цельсия в Фаренгейт. -------------------------------------------------------------------------------- /Exercises/list.py: -------------------------------------------------------------------------------- 1 | # LIST EXERCISES 2 | 3 | # 1. Write a Python function that takes a list of words and returns the length 4 | # of the longest one. 5 | # RU: Напишите функцию Python, которая принимает список слов и возвращает 6 | # длину самого длинного слова. 7 | def longest_word(words): # самое_длинное_слово 8 | print(max(words, key=len)) 9 | # return max(words, key=lambda x: len(x)) 10 | 11 | 12 | # 2. Write a Python program to count the occurrences of each word in a given sentence. 13 | # RU: Напишите программу Python, чтобы подсчитать количество вхождений каждого слова в заданном предложении. 14 | def count_occurences(string): # подсчитать_вхождения 15 | dict = {} 16 | for i in string.split(): 17 | dict[i] = string.count(i) 18 | return dict 19 | # return {i: string.count(i) for i in string.split()} 20 | 21 | # 3. Write a Python program to sum all the items in a list. 22 | # RU: Напишите программу Python, чтобы сложить все элементы в списке. 23 | 24 | 25 | def sum_list(list): # сложить_список 26 | return sum(list) 27 | 28 | 29 | # 4. Write a Python program to multiplies all the items in a list. 30 | # RU: Напишите программу Python, чтобы умножить все элементы в списке. 31 | def multiply_list(list): # умножить_список 32 | result = 1 33 | for i in list: 34 | result *= i 35 | return result 36 | # return [result := result * i for i in list][-1] 37 | 38 | 39 | # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] 40 | # result = 1 41 | # [result := result*num for num in arr] 42 | # print(result) 43 | 44 | 45 | # 5. Write a Python program to get the largest number from a list. 46 | # RU: Напишите программу Python, чтобы получить наибольшее число из списка. 47 | 48 | 49 | # 6. Get the largest and smallest numbers of the list and sum both. 50 | # Afterwards, check if the number of the equation is even or odd 51 | # RU: Получите наибольшее и наименьшее числа списка и сложите их. 52 | # После этого проверьте, является ли число уравнения четным или нечетным 53 | # UZ: Ro'yxatning eng katta va eng kichik sonlarini oling va ularni yig'ing. 54 | # Keyin, tenglamani soni juft yoki toq ekanligini tekshiring 55 | def smallest_greatest_sum(arr): 56 | arr2 = sorted(arr) 57 | largest = arr2[-1] 58 | smallest = arr2[0] 59 | sum = largest + smallest 60 | if sum % 2 == 0: 61 | print(f'{sum} is even') 62 | else: 63 | print(f'{sum} is odd') 64 | 65 | # test_arr = [2, 123, 3, 32, 22, 15] 66 | # smallest_greatest_sum(test_arr) 67 | # ========================================================================== 68 | 69 | # 7. Write a Python program to count the number of strings from a given 70 | # list of strings. The string length is 2 or more and the first 71 | # and last characters are the same. 72 | # RU: Напишите программу Python, чтобы подсчитать количество строк из заданного 73 | # список строк. Длина строки 2 или более, а первые 2 и последние 2 символы одинаковы. 74 | # ['abc', 'xyz', 'aba', '1212381923128321'] 75 | # Expected Result : 2 76 | 77 | 78 | def count_strings(arr): 79 | result = 0 80 | for el in arr: 81 | first_two = el[0:2] 82 | if first_two[::-1] == el[-2:]: 83 | result += 1 84 | return result 85 | # return len([x for x in z if x[:2] == x[-2:][::-1]]) 86 | # return [el[:2][::-1]==el[-2:] for el in arr].count(True) 87 | 88 | # print(count_strings(['abc', 'xyz', 'aba', '1212381923128321'])) 89 | 90 | 91 | # ========================================================================== 92 | 93 | # 8. Write a Python program to remove duplicates from a list. 94 | # RU: Напишите программу Python, чтобы удалить дубликаты из списка. 95 | def remove_duplicates(arr): 96 | result = [] 97 | for item in arr: 98 | if item not in result: 99 | result.append(item) 100 | return result 101 | 102 | 103 | # ========================================================================= 104 | linked_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] 105 | # 9. Merge two singly linked lists without creating new nodes. 106 | # RU: Объедините два односвязных списка без создания новых узлов. 107 | 108 | 109 | def merge_linked_lists(list1, list2): 110 | list1.extend(list2) 111 | return list1 112 | 113 | # ========================================================================== 114 | # 10. Find the middle element of the linked list in a single pass. 115 | # RU: Найдите средний элемент связанного списка за один проход. 116 | 117 | 118 | def middle_element(list): 119 | return list[len(list) // 2] 120 | 121 | # ========================================================================== 122 | 123 | # 11. Insert a node in a linked list. 124 | # RU: Вставьте узел в связанный список. 125 | 126 | 127 | def insert_node(list, node): 128 | list.append(node) 129 | return list 130 | 131 | # ========================================================================== 132 | 133 | 134 | # 12. Find the second number of linked lists from the last in a single pass. 135 | # RU: Найдите второе число связанных списков с конца за один проход. 136 | def second_last(list): 137 | return list[-2] 138 | 139 | 140 | # ========================================================================== 141 | 142 | # 13. Create a function that takes a list of numbers and returns the max value 143 | # using list comprehension 144 | # RU: Создайте функцию, которая принимает список чисел и возвращает максимальное 145 | # значение с использованием генератора списка 146 | def get_max_using_comprehensio(arr): 147 | pass 148 | 149 | # ========================================================================== 150 | # 14. Create a function that takes a list of names and returns the 151 | # ones that start with a vowel. 152 | # RU: Создайте функцию, которая принимает список имен и возвращает те, 153 | # которые начинаются с гласной буквы. 154 | 155 | 156 | def get_names_starting_with_vowel(arr): 157 | return [name for name in arr if name[0].lower() in 'aieuo'] 158 | 159 | 160 | # ========================================================================== 161 | # 15. Create a function that takes a list of strings and returns a list with 162 | # only numbers that come after counting the strings that have the letter 'w' in it. 163 | # RU: Создайте функцию, которая принимает список строк и возвращает список с 164 | # только числа, которые идут после подсчета строк, в которых есть буква «w». 165 | def check_w_and_get_length(arr: list[str], letter: str = 'w'): 166 | # total = [] 167 | # for word in arr: 168 | # if letter in word: 169 | # total.append(word) 170 | # return sum([len(x) for x in total]) 171 | # return sum([len(x) for x in [word for word in arr if letter in word]]) 172 | return sum([len(x) for x in list(filter(lambda x: letter in x, arr))]) 173 | 174 | 175 | x = ["hello", "world", "whats", "up", "my", "friend"] 176 | print(check_w_and_get_length(x)) 177 | 178 | 179 | # EX: ['waffle', 'wonderful', 'water', 'phone', 'tree', 'wonderland'] 180 | # => [waffle, wonderful, water, wonderland] => [6, 9, 5, 10] => 30 181 | 182 | # ========================================================================== 183 | # 16. Create a function that takes a list of strings and returns a list with 184 | # only the lengths of strings that are divisible by 5. 185 | # RU: Создайте функцию, которая принимает список строк и возвращает список с 186 | # только длины строк, которые делятся на 5. 187 | -------------------------------------------------------------------------------- /Exercises/loops/For-Loop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/loops/For-Loop.png -------------------------------------------------------------------------------- /Exercises/loops/While loop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Exercises/loops/While loop.png -------------------------------------------------------------------------------- /Exercises/tree.py: -------------------------------------------------------------------------------- 1 | # Find the maximum possible path sum between two leaf nodes when given a binary tree with each node element containing a number. The leaf node is a node connected to exactly one different node. 2 | # Given a binary tree T, find its height. 3 | # Given a binary search tree, BT, write a code to count the leaves. 4 | # Given a binary tree T, write a code in Python to print the right view of the tree. 5 | # For a given binary tree T, write a code in Python to print the height of the binary tree. 6 | # For a given AVL tree, insert a value into the tree from given N values to be inserted. -------------------------------------------------------------------------------- /Exercises/tuple.py: -------------------------------------------------------------------------------- 1 | # 1. Create a tuple with numbers and print one last item. 2 | # RU: Создайте кортеж с числами и выведите один последный элемент. 3 | # ================================================================ 4 | # 2. Create a tuple with numbers and check if a given element exists in the tuple. 5 | # RU: Создайте кортеж с числами и проверьте, существует ли в кортеже заданный элемент. 6 | def check_if_exists(tup, items_arr): 7 | obj = {} 8 | for item in items_arr: 9 | obj[item] = item in tup 10 | return all(obj.values()) 11 | # print(check_if_exists((1, 2, 3, 4, 5), [1, 5, 4])) 12 | # ================================================================ 13 | # 3. Create a tuple with numbers and find the index of a given element in the tuple. 14 | # RU: Создайте кортеж с числами и найдите индекс заданного элемента в кортеже. 15 | 16 | 17 | def get_index(tup, item): 18 | return tup.index(item) if item in tup else "Not found" 19 | # print(get_index((1, 2, 3, 4, 5), 10)) 20 | # ================================================================ 21 | # 4. Create a tuple with numbers and find the number of occurrences 22 | # of a given element in the tuple. 23 | # RU: Создайте кортеж с числами и найдите количество вхождений заданного 24 | # элемента в кортеж. 25 | 26 | 27 | def count_item(tup, item): 28 | # return tup.count(item) 29 | # return len([i for i in tup if i==item]) 30 | result = 0 31 | for i in tup: 32 | if i == item: 33 | result += 1 34 | return result 35 | 36 | # test_tup = (1, 2, 3, 4, 5, 5, 5, 5) 37 | # print(count_item(test_tup, 5)) 38 | # ================================================================ 39 | # Write a Python function that takes a tuple of integers as input 40 | # and returns a new tuple with the same integers sorted in descending 41 | # order, but with the even numbers before the odd numbers. 42 | # RU: Напишите функцию Python, которая принимает в качестве входных данных 43 | # кортеж целых чисел и возвращает новый кортеж с теми же целыми числами, 44 | # отсортированными в порядке убывания, но с четными числами перед нечетными. 45 | # INPUT: => (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) 46 | # OUTPUT: => (6, 4, 2, 9, 5, 5, 5, 3, 3, 1, 1) 47 | 48 | 49 | def sort_tuple(tup: tuple) -> tuple: 50 | evens = [x for x in tup if x % 2 == 0] 51 | odds = [x for x in tup if x % 2 != 0] 52 | # evens_sorted = sorted(evens, reverse=True) 53 | # odds_sorted = sorted(odds, reverse=True) 54 | evens.sort(reverse=True) 55 | odds.sort(reverse=True) 56 | return tuple(evens+odds) 57 | 58 | 59 | print(sort_tuple((3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5))) 60 | -------------------------------------------------------------------------------- /Lessons/11lesson.py: -------------------------------------------------------------------------------- 1 | # DICTIONARIES 2 | # Словари - это структуры данных, которые хранят данные в виде пар ключ-значение. 3 | # x = { 4 | # "first": "Один", "second": "Два", 5 | # "third": "Три", "fourth": "Четыре", 6 | # "fifth": "Пять", "sixth": "Шесть", 7 | # "seventh": "Семь", "eighth": "Восемь", 8 | # } 9 | # print(x.get("fourth", "Не нашлось")) 10 | # print(x["fourth"]) # => Четыре 11 | # print(x["www"]) # => # Error if not found 12 | # ------------------------------------------------ 13 | # z = [ "Один", "Два", "Три", "Четыре", "Пять", "Шесть", "Семь" ] 14 | # for i in z: 15 | # if i == "Четыре": 16 | # print(i) 17 | # NOTE: 18 | # If there are 1000 doors, when using list and seeking some of them, 19 | # the loop we are using, opens every door one by one to check them 20 | # But, if we use dictionary here, it directly opens the needed one. 21 | # RU: Если есть 1000 дверей, когда мы используем и ищем 22 | # некоторые из них, цикл, который мы используем, открывает каждую дверь 23 | # по одной, чтобы проверить их. Но, если мы используем здесь , 24 | # он сразу же открывает нужную. 25 | # ------------------------------------------------ 26 | # IN JAVA-SCRIPT 27 | # function Person(name, ..., ...) { 28 | # this.name = name 29 | # this.name = name 30 | # this.name = name 31 | # ... 32 | # } 33 | # let person1 = new Person(..., ..., ...) 34 | # ------------------------------------------------ 35 | # IN PYTHON 36 | # dict() => dict(key=value, key=value, key=value) 37 | # person = dict(name='Kamron', bemiyya=True) 38 | # print(person) 39 | # list() => [] 40 | # str() => '' 41 | # int() => 0 42 | # float() => 0.0 43 | # bool() => False 44 | # set() => set() 45 | # dict() => {} 46 | 47 | 48 | # # ACCESSING ITEMS --------------------------------------------------------------------------- 49 | # dict[key] => берёт значение по ключу 50 | # dict.get(key) => берёт значение по ключу 51 | # dict.get(key, default) => берёт значение по ключу, если его нет, то возвращает default 52 | 53 | # Object.keys(dict) => возвращает список ключей (JS) 54 | # dict.keys() => возвращает список ключей 55 | 56 | # Object.values(dict) => возвращает список ключей (JS) 57 | # dict.values() => возвращает список значений 58 | 59 | # Object.entries(dict) => возвращает список ключей (JS) 60 | # dict.items() => возвращает список кортежей (ключ, значение) 61 | 62 | # person1 = dict(name='Javox', bemiyya='True') 63 | # print(person1.items()) 64 | 65 | 66 | # # ADDING ITEMS ----------------------------------------------------------------------------- 67 | # person1 = dict(name='Mirsaid', bemiyya=False) 68 | # print(person1.items()) 69 | # person1['bemiyya'] = True 70 | # person1['...'] = "..." 71 | # person1[1] = 1 72 | # print(person1.items()) 73 | # ----------------- 74 | # Update => updates the dict (changes the original) 75 | # dict.update({key:value, key:value, key:value}) 76 | # person1.update({ 77 | # "name": "Alex", 78 | # "address": "Samarkand", 79 | # "bemiyya":True 80 | # }) 81 | # print(person1) 82 | # ----------------- 83 | # If the key is not found, a new key:value pair is added to the dictionary. 84 | # RU: Если ключ не найден, в словарь добавляется новая пара ключ: значение. 85 | 86 | # But if it exists, then the value of the key is NOT updated. 87 | # RU: Но если он существует, то значение ключа НЕ обновляется. 88 | # dict.setdefault(key, value) 89 | # person1 = dict(name='Mirsaid', bemiyya=False) 90 | # person1.setdefault("address", "Tashkent") 91 | # print(person1) 92 | 93 | 94 | # # REMOVING ITEMS --------------------------------------------------------------------------- 95 | # person1 = dict(name='Mirsaid', bemiyya=False) 96 | 97 | # dict.pop(key) 98 | # del_val = person1.pop('name') 99 | # print("del_val: ", del_val) 100 | # print("person1: ", person1) 101 | 102 | # res = person1.pop('www', None) 103 | # print("Result: ", res) 104 | # print(person1) 105 | # dict.pop(key, default) 106 | 107 | # dict.popitem() => removes the last inserted item 108 | # res = person1.popitem() 109 | # print("Result: ", res) 110 | # print("Remaining: ", person1) 111 | 112 | # del dict[key] 113 | # del person1['bemiyya'] 114 | # del person1 # deletes the whole dict 115 | # print("Remaining: ", person1) 116 | 117 | # # MERGE ------------------------------------------------------------------------------------ 118 | # person1 = dict(name='Mirsaid', bemiyya=False) 119 | # person2 = dict(name="Covid", contageous=True) 120 | # person3 = dict(name="Bemiyya", widespread=True) 121 | # print("Before: ", person1) 122 | # person1 |= person2 123 | # print("After: ", person1) 124 | # person1 |= person2 | person3 125 | # print("After: ", person1) 126 | # dict1.update(dict2) 127 | # dict1 |= dict2 128 | # dict1 |= dict2 | dict3 | dict4 129 | # {**dict1, **dict2, **dict3, **dict4} 130 | # print("Original: ", person1) 131 | # result = {**person1, **person2, **person3} 132 | # print("New: ", result) 133 | 134 | 135 | # person2 = { "name2":"John", "age2":20, "surname2":"Khan", "address2":"Samarkand" } 136 | # person3 = {1:'a', 2:'b'} 137 | # ----------------------------------- 138 | # person |= person2 | person3 139 | # ----------------------------------- 140 | # a = {**person, **person2, **person3 } 141 | # works like spread operator in JS 142 | # ----------------------------------- 143 | 144 | 145 | # # OTHER METHODS ---------------------------------------------------------------------------- 146 | # dict.clear() 147 | # dict.copy() 148 | 149 | # for key, val in person.items(): 150 | # person[key] = "" 151 | 152 | # p2 = person.copy() 153 | # p2.update({"name":"Ali"}) 154 | # print(p2) 155 | # print(person) 156 | 157 | # person = { 158 | # "name": "John", 159 | # "age": 20, 160 | # "surname": "Khan", 161 | # "address": "Samarkand" 162 | # } 163 | 164 | # dict.fromkeys(iterable, value) -> is used to create a new dictionary from the given 165 | # sequence of elements with a value provided by the user. 166 | # EX: 167 | # fruits = ['apple', 'mango', 'banana'] 168 | # result = dict.fromkeys(fruits, 0) 169 | # print(result) 170 | # x = dict.fromkeys(['name', 'age'], 'unknown') 171 | # print(x) 172 | 173 | # # -------------------------------------------------------------------------------------------- 174 | # # -------------------------------------------------------------------------------------------- 175 | # from random import randint 176 | # def random_dict_of_github_issue_ids(stop: int, max_count: int, start: int = 0): 177 | # return dict.fromkeys( 178 | # [str(randint(start, stop)) for _ in range(randint(0, max_count))], "" 179 | # ) 180 | # print(random_dict_of_github_issue_ids(100, 10)) 181 | # # -------------------------------------------------------------------------------------------- 182 | # # -------------------------------------------------------------------------------------------- 183 | # zip() function 184 | # zip(iterator1, iterator2, ...) 185 | # Result: ...(zip object) => (1, 'a'), (2, 'b'), (3, 'c') 186 | 187 | # itr1 = list('abcdefghijklmnopqrstuvwxyz') 188 | # itr2 = range(len(itr1)) 189 | # zipped = zip(itr1, itr2) 190 | 191 | # for (item, item2) in zipped: 192 | # print(item, item2) -------------------------------------------------------------------------------- /Lessons/12lesson.py: -------------------------------------------------------------------------------- 1 | # DICT COMPREHENSION 2 | 3 | #First Exersise 4 | 5 | # x1 = {'a': 1, 'b': 2} 6 | # x2 = {'c': 3, 'd': 4} 7 | # x3 = {'e': 5, 'f': 6} 8 | # def concatenate_dict(*args): 9 | # return {key:value for dict in args for key,value in dict.items()} 10 | # print(concatenate_dict(x1, x2, x3)) 11 | 12 | #Second Exersise 13 | 14 | # def check_key(dict,key): 15 | # return "HAS" if key in dict else "NOT" 16 | # x1 = {'a': 1, 'b': 2} 17 | # print(check_key(x1,'b')) 18 | 19 | #Third Exersise 20 | 21 | # def iterate_over_dict(dict): 22 | # # for k,v in dict.items(): 23 | # # print(k,v) 24 | # {"":print(k,v) for k,v in dict.items()} 25 | # 26 | # iterate_over_dict({ 27 | # 'name' : 'John', 28 | # 'age' : 26, 29 | # 'addres' : 'Norway' 30 | # }) 31 | 32 | #Fourth Exersise 33 | 34 | # mdict = {"a": "1", "b": 2, "c": 3} 35 | # num = sum(v if isinstance(v, int) else int(v) for v in mdict.values()) 36 | # num = 0 37 | # for v in mdict.values(): 38 | # if type(v) == int: 39 | # num += v 40 | # elif v.isnumeric(): 41 | # num += int(v) 42 | # print("Сумма :", num) 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Lessons/13lesson.py: -------------------------------------------------------------------------------- 1 | # my_set = {"apple", "banana", "cherry"} 2 | # my_set = ["apple", "banana", "cherry", "cherry", "cherry"] 3 | # print(set(my_set)) 4 | # {'banana', 'apple', 'cherry'} 5 | 6 | # or use the set function and create from an iterable, e.g. list, tuple, string 7 | # my_set_2 = set(["one", "two", "three"]) 8 | # my_set_2 = set(("one", "two", "three")) 9 | # print(my_set_2) 10 | # {'three', 'one', 'two'} 11 | 12 | # my_set_3 = set("aaabbbcccdddeeeeeffff") 13 | # print(my_set_3) 14 | # {'b', 'c', 'd', 'e', 'f', 'a'} 15 | 16 | # # careful: an empty set cannot be created with {}, 17 | # as this is interpreted as dict 18 | # # use set() instead 19 | # a = {} 20 | # print(type(a)) 21 | # # 22 | # a = set() 23 | # print(type(a)) 24 | # # 25 | # # ----------------------------------------------------------------------------------- 26 | # # NOTES ----------------------------------------------------- 27 | 28 | # test_set = {1, 2, 3, 4, 5} 29 | # Don't allow duplications 30 | # Doesn't have order, index, keys, values, items, slices, etc... 31 | 32 | 33 | # test_set = {1, True, False, 0} 34 | # print(set(test_set)) 35 | # 1 and True are the same and 0 and False are the same 36 | # 1 == True => True 37 | # 0 == False => True 38 | # 1 is True => False 39 | # 0 is False => False 40 | 41 | 42 | # ----------------------------------------------------------------------------------- 43 | # ACCESSING ITEMS -------------------------------------------- 44 | # loop || ... in ... 45 | # x = {1, 2, 3, 4, 5} 46 | # for n in x: 47 | # if ... in x: 48 | # pass 49 | # print(n) 50 | 51 | # ----------------------------------------------------------------------------------- 52 | # ADDING ----------------------------------------------------- 53 | 54 | # add() Adds an element to the set 55 | # EX: x.add(4) => changes the original set 56 | # l = {1, 2, 3} 57 | # l.add(1) # NOTHING IS ADDED 58 | # l.add(4) 59 | 60 | # update() Updates the set with the union of this set and others 61 | # EX: x.update([4, 5, 6]) => changes the original set 62 | # l = {1, 2, 3} 63 | # l.update([3, 2, 4, 5, 6]) 64 | # print(l) 65 | 66 | 67 | # # ----------------------------------------------------------------------------------- 68 | # # Union and Intersection 69 | 70 | # odds = {1, 3, 5, 7, 9} 71 | # evens = {0, 2, 4, 6, 8} 72 | # primes = {2, 3, 5, 7} 73 | 74 | # union(): combine elements from both sets, no duplication 75 | # note that this does not change the two sets 76 | # u = odds.union(evens) 77 | # u = odds | evens 78 | # print(u) 79 | # EX: 80 | # a = x.union(y) # => x | y 81 | 82 | # # intersection(): take elements that are in both sets 83 | # # return a new set, that only contains the items that are present in both sets. 84 | # взять элементы, которые есть в обоих наборах возвращаем новый набор, 85 | # содержащий только те элементы, которые присутствуют в обоих наборах 86 | # i = odds.intersection(evens) # => x & y 87 | # print("intersection 1: ", i) # => {} 88 | # # EX: x.intersection(y) # => x & y 89 | 90 | # i = odds.intersection(primes) # => {3, 5, 7} 91 | # print("intersection 2: ", i) 92 | 93 | # i = evens.intersection(primes) # => {2} 94 | # print("intersection 3: ", i) 95 | 96 | 97 | # # ----------------------------------------------------------------------------------- 98 | # # DIFFERENCE of sets 99 | # setA = {1, 2, 3, 4, 5, 6, 7, 8, 9} 100 | # setB = {1, 2, 3, 10, 11, 12} 101 | 102 | # # difference() : returns a set with all the elements from the setA that are not in setB or in C,D... . 103 | # # x.difference(y) => x - y 104 | # # x.difference(y, z) => x - y - z 105 | 106 | # diff_set = setA.difference(setB, {8, 9}) 107 | # print("difference 1: ", diff_set) 108 | 109 | # # A.difference(B) is not the same as B.difference(A) 110 | # diff_set = setB.difference(setA) 111 | # print("difference 2: ", diff_set) 112 | 113 | # # symmetric_difference() : returns a set with all the elements that are in setA and setB but not in both 114 | # diff_set = setA.symmetric_difference(setB) 115 | # print("difference 3: ", diff_set) 116 | 117 | # # A.symmetric_difference(B) = B.symmetric_difference(A) 118 | # diff_set = setB.symmetric_difference(setA) 119 | # print("difference 4: ", diff_set) 120 | 121 | # # ----------------------------------------------------------------------------------- 122 | # # DELETE 123 | 124 | # remove(x): removes x, raises a KeyError if element is not present 125 | #Ru: удаляет x, вызывает KeyError, если элемент отсутствует 126 | my_set = {"apple", "banana", "cherry"} 127 | # my_set.remove("apple") 128 | # print(my_set) 129 | 130 | # # KeyError: 131 | # # my_set.remove("orange") 132 | 133 | # # discard(x): removes x, does nothing if element is not present 134 | #Ru: удаляет x, ничего не делает, если элемент отсутствует 135 | # my_set.discard("cherry") 136 | # my_set.discard("blueberry") 137 | # print(my_set) 138 | 139 | 140 | 141 | # # clear() : remove all elements 142 | # my_set.clear() 143 | # print(my_set) 144 | 145 | # # pop() : return and remove a random element 146 | # a = {True, False, 2, "hi", "hello"} 147 | # result = a.pop() 148 | # print(result) 149 | # print(a) 150 | 151 | # # ----------------------------------------------------------------------------------- 152 | # # Check if element is in Set 153 | # my_set = {"apple", "banana", "cherry"} 154 | # if "apple" in my_set: 155 | # print("yes") 156 | 157 | 158 | # # ----------------------------------------------------------------------------------- 159 | # # UPDATE sets 160 | # setA = {1, 2, 3, 4, 5, 6, 7, 8, 9} 161 | # setB = {1, 2, 3, 10, 11, 12} 162 | 163 | # # update() : Update the set by adding elements from another set. 164 | #Ru: Обновит набор, добавив элементы из другого набора. 165 | # setA.update(setB) 166 | # print("Set update", setA) 167 | 168 | # Keep ONLY the Duplicates 169 | # intersection_update() : Update the set by keeping only 170 | # the elements found in both 171 | # setA.intersection_update(setB) 172 | # print("Set intersection_update", setA) 173 | 174 | # # difference_update() : Update the set by removing elements found in another set. 175 | # setA.difference_update(setB) 176 | # print("Set difference_update", setA) 177 | 178 | # # symmetric_difference_update(): Keeps only the elements that 179 | # are NOT present in both sets. 180 | # # Keep All, But NOT the Duplicates. 181 | # setA = {1, 2, 3, 4, 5, 6, 7, 8, 9} 182 | # setA.symmetric_difference_update(setB) 183 | # print("Set symmetric_difference_update", setA) 184 | 185 | # Note: all update methods also work with other 186 | # iterables as argument, e.g lists, tuples 187 | # setA.update([1, 2, 3, 4, 5, 6]) 188 | 189 | # # ----------------------------------------------------------------------------------- 190 | # # Copying --------------------------------------------------------------------------- 191 | # set_org = {1, 2, 3, 4, 5} 192 | 193 | # # this just copies the reference to the set, so be careful 194 | # set_copy = set_org 195 | 196 | # # now modifying the copy also affects the original 197 | # set_copy.update([3, 4, 5, 6, 7]) 198 | # print(set_copy) 199 | # print(set_org) 200 | 201 | # # use copy() to actually copy the set 202 | # set_org = {1, 2, 3, 4, 5} 203 | # set_copy = set_org.copy() 204 | 205 | # # now modifying the copy does not affect the original 206 | # set_copy.update([3, 4, 5, 6, 7]) 207 | # print(set_copy) 208 | # print(set_org) 209 | 210 | 211 | # # ----------------------------------------------------------------------------------- 212 | # super => always parent 213 | # sub => always child 214 | 215 | # # Subset, Superset, and Disjoint ---------------------------------------------------- 216 | # setA = {1, 2, 3, 4, 5, 6} 217 | # setB = {1, 2, 3} 218 | # # issubset(setX): Returns True if setX contains the set 219 | # print(setA.issubset(setB)) 220 | # print(setB.issubset(setA)) # True 221 | 222 | # # issuperset(setX): Returns True if the set contains setX 223 | # print(setA.issuperset(setB)) # True 224 | # print(setB.issuperset(setA)) 225 | 226 | # # isdisjoint(setX) : Return True if both sets have a 227 | # null intersection, i.e. no same elements 228 | # setC = {7, 8, 9} 229 | # print(setA.isdisjoint(setB)) 230 | # print(setB.isdisjoint(setA)) 231 | # print(setA.isdisjoint(setC)) 232 | # # ----------------------------------------------------------------------------------- 233 | # # ------------------------------------------------------------------------------------ 234 | # # FROZENSET 235 | # Frozen set is just an immutable version of normal set. 236 | # While elements of a set can be modified at any time, elements of frozen set 237 | # remains the same after creation. Creation with: my_frozenset = frozenset(iterable) 238 | 239 | # a = frozenset([0, 1, 2, 3, 4]) 240 | 241 | # The following is NOT allowed: 242 | # a.add(5) 243 | # a.remove(1) 244 | # a.discard(1) 245 | # a.clear() 246 | # a.update([1,2,3]) 247 | 248 | 249 | # Other set operations work 250 | # odds = frozenset({1, 3, 5, 7, 9}) 251 | # evens = frozenset({0, 2, 4, 6, 8}) 252 | # print(odds.union(evens)) 253 | # print(odds.intersection(evens)) 254 | # print(odds.difference(evens)) 255 | # frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) 256 | # frozenset() 257 | # frozenset({1, 3, 5, 7, 9}) 258 | 259 | # In order to change the SET 260 | # we can change its type to a normal set or another sequence type 261 | # odds = frozenset({1, 3, 5, 7, 9}) 262 | # changed_fz_set = list(odds) 263 | # print(changed_fz_set) 264 | #_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ 265 | 266 | # a = set(['a','b','c','c','c','c','c','b','b','b','b','a']) 267 | # print("set",a) 268 | # b = a 269 | # c = list(a) 270 | # print("sorted list set",sorted(c)) -------------------------------------------------------------------------------- /Lessons/14lesson.py: -------------------------------------------------------------------------------- 1 | lesson = "File handling" 2 | """ 3 | # CREATE A FILE 4 | # To create non-existing file we use "x" mode 5 | # Also, if the file IS FOUND then it returns an error 6 | # ex: 7 | # f = open("myfile.txt", "x") # => x mode allows to create a 8 | # file if it does not exist, 9 | # otherwise it raises an error. 10 | # if we don't want to get an error then we have to use os 11 | # import os 12 | # if os.path.exists("myfile.txt"): 13 | # print("The file exists") 14 | # =========================================================== 15 | # READ FILE 16 | # When we open the file we have to always remember to close it 17 | # If we don't close it then we can't open it again until we restart the program 18 | # For reading the file we use 'r' mode 19 | # Also, if the file is NOT FOUND then it returns an error 20 | 21 | # 1. read() => reads whole file (we also can specify how many characters to read) 22 | # 2. readline => reads only one line 23 | # 3. readlines() => reads the file line by line (all lines) 24 | # 4. loop through the file line by line 25 | 26 | # ex: 27 | # f = open("myfile.txt", "r") 28 | # print(f.read()) 29 | 30 | # =========================================================== 31 | # UPDATE A FILE 32 | # To update an existing file, we use "a" mode or "w" mode 33 | # --- (w) write mode replaces the content of the file 34 | # --- (a) append mode appends the content to the end of the file 35 | # ex: 36 | # f = open("myfile.txt", "a") 37 | # f.write("Now the file has more content!") 38 | # ---------------------------- 39 | # using keyword WITH 40 | # with open("myfile.txt", "a") as f: 41 | # f.write("Now the file has more content!") 42 | # =========================================================== 43 | # DELETE A FILE 44 | # To delete a file, we use os.remove() function 45 | # ex: 46 | # import os 47 | # os.remove("myfile.txt") 48 | 49 | # =========================================================== 50 | # "r" - Read - Default value. Opens a file for reading, error if the file does not exist 51 | # "a" - Append - Opens a file for appending, creates the file if it does not exist 52 | # "w" - Write - Opens a file for writing, creates the file if it does not exist 53 | # "x" - Create - Creates the specified file, returns an error if the file exists 54 | # "t" - Text - Default value. Text mode 55 | # "b" - Binary - Binary mode (e.g. images) 56 | 57 | # Combinations of modes: 58 | "a+" - Read and Append - Opens a file for reading and appending, creates the file if it does not exist 59 | "w+" - Write and Read - Opens a file for writing and reading, creates the file if it does not exist 60 | "r+" - Read and Write - Opens a file for reading and writing, error if the file does not exist 61 | 62 | # =========================================================== 63 | # WORKING WITH DIRECTORIES and os 64 | # import os 65 | # os.mkdir("myfolder") # => creates a folder 66 | # os.rmdir("myfolder") # => removes a folder 67 | # os.rename("oldname", "newname") # => renames a folder 68 | # os.getcwd() # => returns the current working directory 69 | # os.path.exists("myfolder") # => checks if the folder exists 70 | # os.path.isdir("myfolder") # => checks if the folder exists 71 | # os.path.isfile("myfile.txt") # => checks if the file exists 72 | # os.path.join("myfolder", "myfile.txt") # => joins the folder and the file 73 | """ -------------------------------------------------------------------------------- /Lessons/15lesson.py: -------------------------------------------------------------------------------- 1 | # lesson = "Class && OOP" 2 | # _1 = 'Abstract and Inheritance' 3 | 4 | # from abc import ABC, abstractmethod 5 | 6 | 7 | # class AnimalAbstractClass(ABC): 8 | 9 | 10 | # def __init__(self, name,*args): 11 | # print("Class obj has been crated") 12 | # self.name = name 13 | 14 | 15 | # def __str__(self): 16 | # return f"class {self.name}" 17 | 18 | 19 | # @abstractmethod 20 | # def get_info(self): 21 | # raise NotImplementedError 22 | 23 | 24 | 25 | # class Tiger(AnimalAbstractClass): 26 | # def __init__(self, name:str, age:int, speed:int) -> None: 27 | # super().__init__(name) 28 | # self.age = age 29 | # self.speed = speed 30 | 31 | # def get_info(self): 32 | # return f"{self.name} is {self.age} years old and can run {self.speed}" 33 | 34 | # tiger1 = Tiger("White tiger", 10, 25) 35 | # print(tiger1) 36 | # print(tiger1.get_info()) 37 | 38 | # ==================================================================================== 39 | # from abc import ABC, abstractmethod 40 | 41 | 42 | # class AbcBook(ABC): 43 | # def __init__(self, name, page): 44 | # self.name = name 45 | # self.page = page 46 | 47 | 48 | # class Paper_Book(AbcBook): 49 | # def __init__(self, name, page): 50 | # super().__init__(name, page) 51 | 52 | 53 | # def get_description(self): 54 | # return f"In {self.name} {self.page} pages" 55 | 56 | 57 | # Book = Paper_Book("PaperBook", "100") 58 | # print(Book.get_description()) 59 | 60 | 61 | # class Ebook(AbcBook): 62 | # def __init__(self, ip, bbooks): 63 | # super().__init__("Ebook", ip) 64 | # self.bbooks = bbooks 65 | # self.ip = ip 66 | 67 | # def get_description(self): 68 | # return f"ip {self.bbooks} is {self.ip }" 69 | 70 | 71 | # EEBook = Ebook("192.168.0.132", "Ebook") 72 | # print(EEBook.get_description()) 73 | 74 | # class Online_Book(AbcBook): 75 | # def __init__(self, pagess, ipps, pigass): 76 | # super().__init__("Online_Book", ipps) 77 | # self.pagess = pagess 78 | # self.ipps = ipps 79 | # self.pigass = pigass 80 | 81 | # def get_description(self): 82 | # return f"ip {self.pagess} is {self.ipps }\n{self.pagess} pages = {self.pigass} " 83 | 84 | 85 | # OnBook = Online_Book("Online_Book", "192.168.0.132", 100) 86 | # print(OnBook.get_description()) 87 | 88 | # ==================================================================================== 89 | 90 | # from abc import ABC, abstractmethod 91 | 92 | # class Paper_Book(ABC): 93 | # def __init__(self, name, page): 94 | # self.name = name 95 | # self.page = page 96 | 97 | # @abstractmethod 98 | # def get_description(self): 99 | # pass 100 | 101 | 102 | # class Electronic_Book(Paper_Book): 103 | # def __init__(self, name, paper, ip): 104 | # super().__init__(name,paper) 105 | # self.ip = ip 106 | # self.paper = paper 107 | # def get_description(self): 108 | # return f"In {self.name} is {self.paper}, and ip is {self.ip} " 109 | # el_books = Electronic_Book("El_Book", 100, "12432.234324.234") 110 | # print(el_books.get_description()) 111 | 112 | 113 | # class Online_Book(Electronic_Book): 114 | # def __init__(self, name, paper): 115 | # self.paper = paper 116 | # self.name = name 117 | # def get_description(self): 118 | # return f"In {self.name} is {self.paper} paper" 119 | # onl_books = Online_Book("Olivers_book", 20) 120 | # print(onl_books.get_description()) 121 | 122 | 123 | 124 | 125 | # ==================================================================================== 126 | 127 | # Abstract 128 | # Inheritance 129 | 130 | # this == self 131 | 132 | # class User: 133 | # def __init__(self, name): 134 | # print(f"User {name} is created") 135 | # self.name = name 136 | 137 | # user1 = User("John") 138 | # print(user1) 139 | # print(user1.name) 140 | 141 | 142 | # __init__ => is a constructor method which is used to initialize the attributes of a class 143 | # it is called automatically when an object is created 144 | 145 | ############################################################################################# 146 | ################ Abstraction 147 | 148 | # "abc" here stands for abstract base class. It is first imported and then used as 149 | # a parent class for some class that becomes an abstract class. Its simplest implementation 150 | # can be done as below. 151 | 152 | 153 | # from abc import ABC, abstractmethod 154 | # class AbcAnimal(ABC): 155 | # def __init__(self, name, food): 156 | # self.name = name 157 | # self.food = food 158 | 159 | # @abstractmethod 160 | # def get_description(self): 161 | # pass 162 | # # raise NotImplementedError 163 | 164 | 165 | # class Pets(AbcAnimal): 166 | # def __init__(self, name, food, speed): 167 | # super().__init__(name, food) 168 | # self.speed = speed 169 | 170 | # def get_description(self): 171 | # return f"{self.name} eats {self.food}" 172 | 173 | 174 | # dog = Pets("Dog", "Meat", 10) 175 | # print(dog) 176 | # print(dog.get_description()) 177 | 178 | 179 | 180 | # abs module is used to create abstract classes 181 | # it is helpful when we want to create a class that will be used as a base class 182 | # abstractmethod is used to declare abstract methods which will be implemented by the child classes 183 | # is it used to ensure that the child classes will have the same method as the parent class 184 | # and returns an error if the child class does not have the same method as the parent class 185 | # RU: абстрактный класс - это класс, который не предназначен для создания экземпляров, 186 | # а предназначен для использования в качестве родительского класса для других классов 187 | # абстрактный метод - это метод, который объявлен, но не реализован в базовом классе. 188 | 189 | ############################################################################################# 190 | ################ Inheritence 191 | 192 | # Inheritance allows us to define a class that inherits all the methods 193 | # and properties from another class. 194 | # Parent class is the class being inherited from, also called base class. 195 | # Child class is the class that inherits from another class, also called derived class. 196 | 197 | # is a way of creating a new class for using details of an existing class without modifying it. 198 | # The newly formed class is a derived class (or child class). 199 | # Similarly, the existing class is a base class (or parent class). 200 | 201 | # class Parent: 202 | # def __init__(self, name): 203 | # self.name = name 204 | 205 | # def test(self): 206 | # print("Hello world") 207 | 208 | # class Child(Parent, ABC): 209 | # # Inherited members from parent class 210 | # # Additional members of the child class 211 | # def __init__(self, name, age): 212 | # super().__init__(name) # => calls the parent class constructor 213 | # self.age = age 214 | 215 | # def test(self): 216 | # print("Hello world from child") 217 | 218 | # def __repr__(self) -> str: 219 | # ''' 220 | # Is used to represent the object with a string. 221 | # It is used for debugging and logging. 222 | # ''' 223 | # return f"{self.name} is {self.age} years old" 224 | 225 | # def __str__(self) -> str: 226 | # ''' 227 | # Is used to represent the object with a string. 228 | # It is used for the end user. 229 | # ''' 230 | # return f"{self.name} is {self.age} years old" 231 | 232 | 233 | # child = Child("John", 20) 234 | # print(child) 235 | # print(child.test()) 236 | -------------------------------------------------------------------------------- /Lessons/16lesson.py: -------------------------------------------------------------------------------- 1 | ############### Polymorphism 2 | # Polymorphism allows you define one interface and have multiple implementations. 3 | # Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. 4 | 5 | class Animal: 6 | def __init__(self, name): 7 | self.name = name 8 | 9 | def speak(self): 10 | raise NotImplementedError("Subclass must implement abstract method") 11 | 12 | class Dog(Animal): 13 | def speak(self): 14 | return self.name+' says Woof!' 15 | 16 | class Cat(Animal): 17 | def speak(self): 18 | return self.name+' says Meow!' 19 | 20 | dog = Dog("Max") 21 | print(dog.speak()) 22 | cat = Cat("Alice") 23 | print(cat.speak()) 24 | 25 | ############################################################################################ 26 | ############### Encapsulation 27 | # is used to restrict access to methods and variables. 28 | # This prevents data from direct modification which is called encapsulation. 29 | 30 | class Alpha: 31 | def __init__(self): 32 | self.test = "This is test" 33 | self._a = 2. # Protected member ‘a’ (for us) 34 | self.__b = 2. # Private member ‘b’ 35 | 36 | def do_smth(self): 37 | return self.__b * 2 38 | 39 | @property 40 | def get_b(self): 41 | return self.__b 42 | 43 | a = Alpha() 44 | print(a.test) 45 | print(a.get_b) 46 | print(a.do_smth()) 47 | 48 | ############################################################################################ 49 | ################### DECORATORS 50 | 51 | # @property is a built-in decorator in Python that is used to define the properties 52 | # of an object. The @property decorator makes the work easier by 53 | # automatically calling the getter method when the value of the attribute is accessed. 54 | 55 | # @classmethod is a built-in decorator in Python that is used to create class methods. 56 | # The class method can be called by both the class and the object. 57 | # This method accepts the class as the first argument that is passed automatically 58 | # when the method is called. 59 | 60 | # @staticmethod is a built-in decorator in Python that defines a static method. 61 | # A static method doesn’t receive any reference argument whether it is called by an 62 | # instance of a class or by the class itself. This means that a static method can neither 63 | # modify object state nor class state. Static methods are restricted in what data they can 64 | # access - and they’re primarily a way to namespace your methods. 65 | 66 | # -- Static method knows nothing about the class and just deals with the parameters. 67 | # -- Class method works with the class since its parameter is always the class itself. 68 | 69 | # Link that is about difference of two decorators: 70 | # https://sparkbyexamples.com/python/python-difference-between-staticmethod-and-classmethod/#h-1-what-is-staticmethod 71 | 72 | # from datetime import date 73 | # class Student: 74 | # def __init__(self, name, age): 75 | # self.name = name 76 | # self.age = age 77 | 78 | # @classmethod 79 | # def fromBirthYear(cls, name, year): 80 | # return cls(name, date.today().year - year) 81 | 82 | # @staticmethod 83 | # def isAdult(age): 84 | # return age > 18 85 | 86 | # student1 = Student('Rolf', 19) 87 | # print(student1.isAdult(22)) 88 | # print(student1.age) 89 | 90 | # student2 = Student.fromBirthYear('Anna', 1990) 91 | # print(student2.age) 92 | 93 | 94 | 95 | 96 | # #################################################################################### 97 | # #################################################################################### 98 | # _3 = 'Dunder methods' 99 | 100 | # from abc import ABC, abstractmethod 101 | # # __...__ 102 | 103 | 104 | # class AbstractUserClass(ABC): 105 | # name: str 106 | # surname: str 107 | # age: int 108 | # email: str 109 | 110 | # @abstractmethod 111 | # def get_info(self): 112 | # raise NotImplementedError( 113 | # "This is an abstract method and needs to be implemented in the child class.") 114 | 115 | 116 | # class User(AbstractUserClass): 117 | # def __init__(self, name: str, surname: str, age: int = 0, email: str = '') -> None: 118 | # self.name = name 119 | # self.surname = surname 120 | # self.age = age 121 | # self.email = email 122 | 123 | # def __str__(self) -> str: 124 | # return f'{self.name} {self.surname} is {self.age} years old.\nEmail: {self.email}' 125 | # def __repr__(self) -> str: 126 | # return f'{self.name} {self.surname} is {self.age} years old.\nEmail: {self.email}' 127 | 128 | # def __call__(self, *args, **kwargs): 129 | # print(f"Это вызов из __call__") 130 | # for i in args: 131 | # print(i) 132 | # return '' 133 | # # ex: 134 | # # user1("test1", "test2", "test3") => This is call fn from __call__ 135 | 136 | # def __add__(self, other): 137 | # return "This user has $" + str(other.budget) 138 | 139 | # def get_info(self): 140 | # print(f'{self.name} {self.surname}') 141 | # return '' 142 | 143 | # @classmethod 144 | # def from_string(cls, string): 145 | # if not string.count(',') == 3: 146 | # raise Exception("String must have 4 values separated by comma.") 147 | 148 | # # string => "John, Doe, 25, test@gmail.com" 149 | # splitted_str = string.split(",") 150 | # name, surname, age, email = splitted_str 151 | # # name = splitted_str[0] 152 | # # surname = splitted_str[1] 153 | # # age = splitted_str[2] 154 | # # email = splitted_str[3] 155 | # return cls(name, surname, int(age), email) 156 | 157 | # @staticmethod 158 | # def is_adult(age): 159 | # return age > 18 160 | 161 | 162 | # class Client(User): 163 | # def __init__(self, name: str, surname: str, budget: float) -> None: 164 | # super().__init__(name, surname) 165 | # self.budget = budget 166 | 167 | # def __str__(self) -> str: 168 | # return f'{self.name} {self.surname} has ${self.budget} budget.' 169 | 170 | # def __repr__(self) -> str: 171 | # return f'{self.name} {self.surname} has ${self.budget} budget.' 172 | 173 | # def get_info(self): 174 | # print(f'{self.name} {self.surname} has ${self.budget} budget.') 175 | # return '' 176 | 177 | 178 | # # ================================================= 179 | # user1 = User('John', 'Doe', 25, 'test@gmail.com') 180 | # print(user1.get_info()) 181 | # # ================================================= 182 | # client1 = Client("Cathrine", "Mackwold", 10000) 183 | # print(client1.get_info()) 184 | # # ================================================= 185 | # result = user1 + client1 186 | # print(result) 187 | # # ================================================= 188 | # user1 = User.from_string("John, Doe, 25, test@gmail.com") # classmethod 189 | # print(user1) 190 | # print(User.is_adult(user1.age)) # staticmethod 191 | -------------------------------------------------------------------------------- /Lessons/17lesson.py: -------------------------------------------------------------------------------- 1 | # def decorator_function(org_func): 2 | # def wrapper_function(*args, **kwargs): 3 | # print(f"Wrapper execude this before {org_func.__name__}") 4 | # return org_func(*args,**kwargs) 5 | # return wrapper_function 6 | 7 | 8 | # @decorator_function 9 | # def original_function(*args): 10 | # print("Original function ran") 11 | 12 | # x = [1,2,3,4,5] 13 | # original_function(x) 14 | 15 | #======================================================================================== 16 | 17 | # import math 18 | # import time 19 | 20 | # def calculate_time(func): 21 | # def inner1(*args,**kwargs): 22 | # begin = time.time() 23 | # func(*args,**kwargs) 24 | # end = time.time() 25 | # print("Total time taken in : ", func.__name__, end - begin) 26 | # return inner1 27 | 28 | 29 | # @calculate_time 30 | # def factorial(num): 31 | # time.sleep(2) 32 | # print(math.factorial(num)) 33 | 34 | # factorial(5) 35 | 36 | #======================================================================================== 37 | 38 | 39 | # memory = {} 40 | 41 | # def memoize_factorial(f): 42 | # def inner(num): 43 | # if num not in memory: 44 | # memory[num] = f(num) 45 | # print('result saved in memory') 46 | # else: 47 | # print('FROM SAVED MEMORY: ', memory[num]) 48 | # return memory[num] 49 | # return inner 50 | 51 | 52 | # @memoize_factorial 53 | # def facto(num): 54 | # if num ==1: 55 | # return 1 56 | # else: 57 | # return num*facto(num-1) 58 | 59 | # print(facto(5)) 60 | # print(facto(5)) 61 | # print(facto(3)) 62 | # print(memory) 63 | 64 | #======================================================================================== 65 | 66 | # defining a decorator 67 | # def hello_decorator(func): #2 STEP 68 | 69 | # # inner1 is a Wrapper function in 70 | # # which the argument is called 71 | 72 | # # inner function can access the outer local 73 | # # functions like in this case "func" 74 | # def inner1(): #3 STEP 75 | # print("Hello, this is before function execution") 76 | 77 | # # calling the actual function now 78 | # # inside the wrapper function. 79 | # func() 80 | 81 | # print("This is after function execution") 82 | # return inner1 #4 STEP 83 | 84 | 85 | # # defining a function, to be called inside wrapper 86 | # def function_to_be_used(): 87 | # print("This is inside the function !!") 88 | 89 | 90 | # # passing 'function_to_be_used' inside the 91 | # # decorator to control its behaviour 92 | # function_to_be_used = hello_decorator(function_to_be_used) #1 STEP 93 | 94 | 95 | # # calling the function 96 | # function_to_be_used() #5 STEP 97 | 98 | lesson = "Decorators & Wrappers" 99 | # Decorators are functions that take another function as an argument, add some kind of functionality, 100 | # and then return another function. All of this without altering the source code of the original 101 | # function that we passed in. In Python, functions are first-class objects, which means that we can 102 | # pass them as arguments to other functions. We can also return them as the values from other functions. 103 | # This is the basis of decorators. 104 | 105 | #################################################################################### 106 | #################################################################################### 107 | #################################################################################### 108 | # BASIC DECORATOR 109 | 110 | 111 | # def decorator_function(original_function): 112 | # def wrapper_function(*args, **kwargs): 113 | # print("Wrapper executed this before {}".format( 114 | # original_function.__name__)) 115 | # return original_function(*args, **kwargs) 116 | # return wrapper_function 117 | 118 | 119 | # @decorator_function 120 | # def original_function(): 121 | # print("Original function ran") 122 | 123 | #################################################################################### 124 | # defining a decorator 125 | 126 | 127 | # def hello_decorator(func): 128 | 129 | # # inner1 is a Wrapper function in 130 | # # which the argument is called 131 | 132 | # # inner function can access the outer local 133 | # # functions like in this case "func" 134 | # def inner1(): 135 | # print("Hello, this is before function execution") 136 | # # calling the actual function now 137 | # # inside the wrapper function. 138 | # result = func() 139 | # print("This is after function execution") 140 | # return result 141 | 142 | # return inner1 143 | 144 | 145 | # # defining a function, to be called inside wrapper 146 | # def function_to_be_used(): 147 | # print("This is inside the function !!") 148 | 149 | 150 | # # # passing 'function_to_be_used' inside the 151 | # # # decorator to control its behaviour 152 | # function_to_be_used = hello_decorator(function_to_be_used) 153 | 154 | 155 | # # calling the function 156 | # function_to_be_used() 157 | 158 | 159 | #################################################################################### 160 | #################################################################################### 161 | #################################################################################### 162 | # Practical example 1 163 | # find out the execution time of a function using a decorator. 164 | 165 | # decorator to calculate duration 166 | # taken by any function. 167 | # def calculate_time(func): 168 | 169 | # # added arguments inside the inner1, 170 | # # if function takes any arguments, 171 | # # can be added like this. 172 | # def inner1(*args, **kwargs): 173 | 174 | # # storing time before function execution 175 | # begin = time.time() 176 | 177 | # func(*args, **kwargs) 178 | 179 | # # storing time after function execution 180 | # end = time.time() 181 | # print("Total time taken in : ", func.__name__, end - begin) 182 | 183 | # return inner1 184 | 185 | 186 | # # this can be added to any function present, 187 | # # in this case to calculate a factorial 188 | # @calculate_time 189 | # def factorial(num): 190 | 191 | # # sleep 2 seconds because it takes very less time 192 | # # so that you can see the actual difference 193 | # time.sleep(2) 194 | # print(math.factorial(num)) 195 | 196 | 197 | # # calling the function. 198 | # factorial(10) 199 | 200 | #################################################################################### 201 | #################################################################################### 202 | #################################################################################### 203 | # RETURN A VALUE 204 | 205 | # def hello_decorator(func): 206 | # def inner1(*args, **kwargs): 207 | 208 | # print("before Execution") 209 | 210 | # # getting the returned value 211 | # returned_value = func(*args, **kwargs) 212 | # print("after Execution") 213 | 214 | # # returning the value to the original frame 215 | # return returned_value 216 | 217 | # return inner1 218 | 219 | 220 | # # adding decorator to the function 221 | # @hello_decorator 222 | # def sum_two_numbers(a, b): 223 | # print("Inside the function") 224 | # return a + b 225 | 226 | 227 | # a, b = 1, 2 228 | 229 | # # getting the value through return of the function 230 | # sum = sum_two_numbers(a, b) 231 | # print("Sum =", sum) 232 | #################################################################################### 233 | #################################################################################### 234 | #################################################################################### 235 | # MEMOIZATION 236 | # Factorial program with memoization using decorators. 237 | 238 | # A decorator function for function 'f' passed 239 | # as parameter 240 | # memory = {} 241 | 242 | 243 | # def memoize_factorial(f): 244 | 245 | # # This inner function has access to memory 246 | # # and 'f' 247 | # def inner(num): 248 | # if num not in memory: 249 | # memory[num] = f(num) 250 | # print('result saved in memory') 251 | # else: 252 | # print('returning result from saved memory') 253 | # return memory[num] 254 | 255 | # return inner 256 | 257 | 258 | # @memoize_factorial 259 | # def facto(num): 260 | # if num == 1: 261 | # return 1 262 | # else: 263 | # return num * facto(num-1) 264 | 265 | 266 | # print(facto(5)) 267 | # print(facto(5)) # directly coming from saved memory 268 | # print(memory) 269 | -------------------------------------------------------------------------------- /Lessons/18lesson.py: -------------------------------------------------------------------------------- 1 | # JavaScript Object Notation (JSON) 2 | import requests 3 | from faker import Faker 4 | import json 5 | 6 | 7 | # In js we would do: 8 | # axios.get('https://...') 9 | 10 | URL = 'https://jsonplaceholder.typicode.com/todos/1' 11 | 12 | # In python we do: 13 | response = requests.get(URL) 14 | 15 | # To get the status code: 16 | print("status_code: ",response.status_code) 17 | 18 | # To get the content: 19 | print("content: ",response.content) 20 | 21 | # To get the json: 22 | print("json(): ",response.json()) 23 | 24 | 25 | # JSON.stringify(data) 26 | # JSON.parse(data) 27 | 28 | # stringify [{...}, {...}, {...}] => "..." 29 | # parse "..." => [{...}, {...}, {...}] 30 | 31 | # json.dumps(...) => "..." 32 | # json.loads(...) => {...} 33 | 34 | -------------------------------------------------------------------------------- /Lessons/19lesson.py: -------------------------------------------------------------------------------- 1 | # import time 2 | # import unittest 3 | 4 | # from selenium import webdriver 5 | # from selenium.webdriver.chrome.options import Options 6 | # from selenium.webdriver.chrome.service import Service 7 | # from selenium.webdriver.common.by import By 8 | 9 | # # https://chromedriver.chromium.org/downloads 10 | # PATH = "D:\\Pythonres\\chromedriver.exe" 11 | 12 | # HALF_SECOND = 0.5 13 | 14 | 15 | # class Fullstack(unittest.TestCase): 16 | 17 | # def setUp(self): 18 | # options = Options() 19 | # # options.add_argument('--headless') 20 | # self.driver = webdriver.Chrome(service=Service(PATH), options=options) 21 | # self.driver.maximize_window() 22 | # # self.current_test = self.id().split(".")[-1] 23 | 24 | # def tearDown(self): 25 | # self.driver.close() 26 | # self.driver.quit() 27 | # print(f"Ending test for {self.driver}") 28 | 29 | # def test_login_to_facebook(self): 30 | # pass 31 | 32 | # def test_wikipedia(self): 33 | # self.driver.get("https://www.wikipedia.org/") 34 | # print("Getting url...") 35 | # slogan = self.driver.find_element(By.CLASS_NAME, "localized-slogan") 36 | # print(slogan) 37 | # print("ID: -> ", slogan.get_property("id")) 38 | # print("link.text: -> ", slogan.text) 39 | 40 | # text_to_write = "FullStack programming" 41 | # search_input = self.driver.find_element(By.ID, "searchInput") 42 | # search_input.send_keys(text_to_write) 43 | # time.sleep(HALF_SECOND) 44 | # btn = self.driver.find_element(By.CLASS_NAME, "svg-search-icon") 45 | # btn.click() 46 | # time.sleep(HALF_SECOND*2) 47 | # expected_heading = self.driver.find_element(By.ID, "firstHeading") 48 | # assert expected_heading.text == "Search results" 49 | # assert "Search results" in self.driver.page_source 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | # from time import sleep 68 | # from selenium import webdriver 69 | # from selenium.webdriver.common.by import By 70 | 71 | # url="https://www.instagram.com/" 72 | 73 | # def main(): 74 | # def get_password(): 75 | # return 'Xusen_553'#'Istamake_553' 76 | 77 | 78 | # driver=webdriver.Chrome() 79 | # driver.get(url=url) 80 | # sleep(2) 81 | 82 | # email='husen_ake07' 83 | # email_getter=driver.find_element(By.XPATH,'//*[@id="loginForm"]/div/div[1]/div/label/input') 84 | # email_getter.send_keys(email) 85 | # sleep(2) 86 | 87 | # pw_getter=driver.find_element(By.XPATH,'//*[@id="loginForm"]/div/div[2]/div/label/input') 88 | # pw_getter.send_keys(get_password()) 89 | 90 | # btn=driver.find_element(By.XPATH,'//*[@id="loginForm"]/div/div[3]') 91 | # btn.click() 92 | # sleep(40) 93 | 94 | # if __name__ == '__main__': 95 | # main() 96 | 97 | 98 | 99 | 100 | import unittest 101 | from time import sleep 102 | from selenium import webdriver 103 | from selenium.webdriver.common.by import By 104 | 105 | class InstagramRegistrationTest(unittest.TestCase): 106 | def setUp(self): 107 | self.url = "https://www.instagram.com/" 108 | self.driver = webdriver.Chrome() 109 | 110 | def tearDown(self): 111 | self.driver.quit() 112 | 113 | def test_registration(self): 114 | self.driver.get(url=self.url) 115 | sleep(2) 116 | 117 | 118 | signup_link = self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a') 119 | signup_link.click() 120 | sleep(2) 121 | 122 | 123 | email = 'husen_ake07' 124 | email_getter = self.driver.find_element(By.NAME, 'emailOrPhone') 125 | email_getter.send_keys(email) 126 | sleep(2) 127 | 128 | full_name = 'Husen Ake' 129 | full_name_getter = self.driver.find_element(By.NAME, 'fullName') 130 | full_name_getter.send_keys(full_name) 131 | sleep(2) 132 | 133 | password = 'Xusen_553' 134 | password_getter = self.driver.find_element(By.NAME, 'password') 135 | password_getter.send_keys(password) 136 | sleep(2) 137 | 138 | signup_btn = self.driver.find_element(By.XPATH, '//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[7]/div/button') 139 | signup_btn.click() 140 | sleep(5) 141 | 142 | profile_picture = self.driver.find_elements(By.CLASS_NAME, '_6q-tv') 143 | self.assertTrue(profile_picture, "Registration failed.") 144 | 145 | if __name__ == '__main__': 146 | unittest.main() 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | # from typing import Union, assert_never 169 | 170 | # def handle_value(value: Union[int, str, float]): 171 | # if isinstance(value, int): 172 | # print("Handling an integer...") 173 | # elif isinstance(value, str): 174 | # print("Handling a string...") 175 | # elif isinstance(value, float): 176 | # print("Handling a float...") 177 | # else: 178 | # assert_never(value) 179 | 180 | # handle_value([]) 181 | 182 | 183 | # import unittest 184 | 185 | # class MyTest(unittest.TestCase): 186 | 187 | # def setUp(self): 188 | # self.var = 1 189 | 190 | # def tearDown(self): 191 | # self.var = None 192 | 193 | 194 | # def test(self): 195 | # self.assertEqual(1,1) 196 | 197 | # def test_2(self): 198 | # self.assertNotEqual(1,2) 199 | 200 | # def test_3(self): 201 | # self.assertTrue(True) 202 | 203 | # def test_4(self): 204 | # self.assertFalse(False) 205 | 206 | # def test_5(self): 207 | # self.assertIs(1,1) 208 | 209 | # def test_6(self): 210 | # self.assertIsNone(None) 211 | 212 | # def test_7(self): 213 | # self.assertIn(1, [1,2,3]) 214 | 215 | # def test_8(self): 216 | # self.assertIsInstance(1,int) 217 | 218 | # to run this test from command line: 219 | # python -m unittest -v file_name.py 220 | # -v => verbose mode (means that we will see all the output from the test) 221 | # -m => module (means that we will run the test from the module) 222 | 223 | 224 | # assertNotEqual(a, b): This assertion checks if a is not equal to b. 225 | 226 | # assertTrue(x): This assertion checks if the value of x is True. 227 | 228 | # assertFalse(x): This assertion checks if the value of x is False. 229 | 230 | # assertIs(a, b): This assertion checks if a is b. 231 | 232 | # assertIsNone(x): This assertion checks if the value of x is None. 233 | 234 | # assertIn(a, b): This assertion checks if a is in b. 235 | 236 | # assertIsInstance(a, b): This assertion checks if a is an instance of b. 237 | -------------------------------------------------------------------------------- /Lessons/1lesson.py: -------------------------------------------------------------------------------- 1 | #нету 2 | # print(bool("")) 3 | 4 | # HTTPS_status = 200 5 | # match HTTPS_status: 6 | # case 200 | 201: 7 | # print ('ok') 8 | # case 404: 9 | # print('Not found') 10 | # case 301 | 302: 11 | # print('redirect') 12 | # case _: 13 | # print('unknown') 14 | 15 | # a = input('>>>') 16 | # if a == a[::-1]: 17 | # print('pal') 18 | # else: 19 | # print('not pal') 20 | 21 | 22 | # a = input('>>>') 23 | # print(a[::-1]) 24 | 25 | 26 | # numbers = [1, 2, 3, 4, 5] 27 | # numbers[0], numbers[-1] = numbers[-1], numbers[0] 28 | # print(numbers) 29 | 30 | 31 | # def remove_nth_index(string, index): 32 | # return(string [:index] + string[index +1:]) 33 | # print(remove_nth_index('istam',2)) 34 | 35 | 36 | # string = "123456789" 37 | # string1 = "" 38 | # for i in range(len(string)): 39 | # if i % 2 == 0: 40 | # string1 += string[i] 41 | # print(string1) 42 | 43 | 44 | 45 | # def x (string ): 46 | # return (string [::2] + string[1::2]) 47 | # print(x('123456')) 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /Lessons/3lesson.py: -------------------------------------------------------------------------------- 1 | ''' 2 | recursion 3 | ''' 4 | # def stars(n, i = 1): 5 | # print ('*'*i) 6 | # if i < n: 7 | # return stars(n, i+1) 8 | # stars(10) 9 | 10 | 11 | # def stars1(n, i = 10): 12 | # print('*'*i) 13 | # if i > n: 14 | # return stars1(n, i-1) 15 | # stars1(1) 16 | 17 | # def factorial(n): 18 | # if n == 1: 19 | # return n 20 | # return factorial(n-1) * n 21 | # print(factorial(5)) 22 | 23 | ''' 24 | test 25 | lambda 26 | ''' 27 | # test_lambda = lambda string1 , string2 : string1 + string2 28 | # print (test_lambda("ist", "am")) -------------------------------------------------------------------------------- /Lessons/4lesson_MOCK.EXAM.py: -------------------------------------------------------------------------------- 1 | #1 2 | # def insert_string(string,string_to): 3 | # x = (string[0:round(len(string)/2)]) + string_to + string[round(len(string)/2)::] 4 | # print(x) 5 | # insert_string('istam','i') 6 | 7 | 8 | #2 9 | # def firt_three(string): 10 | # return(string[0:3]) 11 | # print(firt_three('Hello')) 12 | 13 | 14 | #3 15 | # def firt_half_even(string): 16 | # if len(string)%2 == 0: 17 | # return string[:len(string)//2] 18 | # else: 19 | # return string[:len(string)//2 - 1] 20 | # print(firt_half_even('istam')) 21 | 22 | 23 | #4 24 | # def concat_string(string,string1): 25 | # return string + string1 26 | # print(concat_string('Is','Tam')) 27 | 28 | 29 | #5 30 | # def remove_indentation(string): 31 | # return string.replace(' ' , '') 32 | # print(remove_indentation("Istam 1istam 2istam 3istam")) 33 | 34 | 35 | #6 36 | # def count_vowels(*strings): 37 | # vowels = ["a","e","i","o","u","y"] 38 | # count = 0 39 | # for string in strings: 40 | # for letter in string: 41 | # if letter in vowels: 42 | # count += 1 43 | # return count 44 | # print (count_vowels('i' ,'st', 'a' ,'m' ,'a' ,'k', 'e')) 45 | 46 | 47 | #7 48 | # def swap_cases(string): 49 | # return(string.swapcase()) 50 | # print(swap_cases('IsTaM')) 51 | 52 | 53 | #8 54 | # def check_duplicates_letters(string): 55 | # for string in string: 56 | 57 | #9 58 | # def repeat_first_letter(string): 59 | # return string + string[:1] * 3 60 | # print(repeat_first_letter("Istam")) 61 | 62 | # for i in range(100): 63 | # print("100") 64 | 65 | 66 | -------------------------------------------------------------------------------- /Lessons/5lesson.py: -------------------------------------------------------------------------------- 1 | """ 2 | # number types => int, float, complex 3 | # str 4 | # sequence => list, tuple, range 5 | # searching type, mapping => dict (Object in JS) 6 | # set => set, frozenset 7 | # binary type => bytes, bytearray, memoryview 8 | # bool => True, False 9 | # None => None 10 | # ========================================================================= 11 | # 0 = 0 12 | # 1 = 1 13 | # 2 = 10 14 | # 3 = 11 15 | # 4 = 100 16 | # 5 = 101 17 | # 6 = 110 18 | # 7 = 111 19 | # 8 = 1000 20 | # 9 = 1001 21 | # ... 22 | # ========================================================================= 23 | # In JavaScript 24 | # try {} catch {} => попробуй, если получится, а если нет то перехвати ошибку 25 | # ========================================================================= 26 | # In Python 27 | # try: ... except: ... => попробуй, если получится, а если нет то пропускай ошибку 28 | # ========================================================================= 29 | # from typing import Union 30 | # try: 31 | # x = 'Hello world' 32 | # print(x).print(x) 33 | # except Union[NameError, TypeError]: 34 | # print('Переменная не объявлена') 35 | # ========================================================================= 36 | # Types of errors 37 | # 1. SyntaxError => не правильно написан код и 38 | # невозможно его прочитать для питона 39 | # EX: 1. print("Hello world) 40 | # 2. print("Hello world')) 41 | # ------------------------ 42 | # 2. TypeError => не правильно написан код и 43 | # питон не может выполнить действие 44 | # EX: 1. print(5 + 'Hello world') 45 | # 2. print(5 + [1, 2, 3]) 46 | # ------------------------ 47 | # 3. NameError => не правильно написан код и 48 | # питон не может найти переменную 49 | # EX: 1. print(x) 50 | # 2. print(y) 51 | 52 | # ========================================================================= 53 | # 2==2 ? True : False => In JavaScript 54 | # ------------------------------------- 55 | # Ternary operator in Python 56 | # "Yes" if condition==True else "No" 57 | # if 2==2: 58 | # print('Yes') 59 | # else: 60 | # print('No') 61 | # # ------------------------ 62 | # print("yes") if 2==2 else "No" 63 | # ========================================================================= 64 | # Range 65 | # range(10) => range(0, 10) 66 | # list(range(10)) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 67 | # list(range(10, 20)) => [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 68 | # list(range(10, 30, 5)) => [10, 15, 20, 25] 69 | # ========================================================================= 70 | # for num in range(10, 50, 2): 71 | # print(num) if num%10==0 else print('Not devidible to 10') 72 | # ========================================================================= 73 | """ 74 | """ 75 | for num in range(10, 50, 2): 76 | print(num) if num % 10 == 0 else print(f'{num} не делиться на 10') 77 | 78 | 79 | import time 80 | start = time.time() 81 | 82 | def even_nums(): 83 | result = [] 84 | for num in range(1000000): 85 | result.append(num) if num % 2 == 0 else "It is ODD" 86 | return result 87 | 88 | print(even_nums()) 89 | end = time.time() 90 | print(f"time take: {round(end - start, 5)}") 91 | """ 92 | 93 | 94 | -------------------------------------------------------------------------------- /Lessons/6lesson.py: -------------------------------------------------------------------------------- 1 | """ 2 | UPDATE 3 | # a = ["istam", "rustam", "shaxa"] 4 | # a[0] ="shaxa" 5 | # print(a) 6 | """ 7 | # print(type([])) 8 | """ 9 | # range(10) => range(0, 10) 10 | # list(range(10)) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 11 | # range(10, 20) # => range(10, 20) 12 | # range(10, 20, 2) # => range(10, 20, 2) 13 | # list(range(10, 20, 2)) => [10, 12, 14, 16, 18] 14 | # --------------------------------------------------------- 15 | # for (let i=0; i<10; i++) {} 16 | # for num in range(10): 17 | # print(num) 18 | # # num = num + 1 19 | # num += 1 20 | # typeof([]) => object 21 | # print(type([])) => 22 | # --------------------------------------------------------- 23 | # UPDATE 24 | # x_list[...:...] = [...] => updates from ... to ... by [...] 25 | # --------------------------------------------------------- 26 | # ADD 27 | # [].insert(position, element_to_add) => вставлять 28 | # [].append() => добавит элемент в конец листа 29 | # [].extend() => добавит элементы в конец листа 30 | # --------------------------------------------------------- 31 | # REMOVE 32 | # "..." in x => проверяет есть ли элемент в листе 33 | # [].pop() => удаляет последний элемент 34 | # [].remove() => удаляет элемент по значению 35 | # --------------------------------------------------------- 36 | # COPY 37 | # [].copy() => копирует лист 38 | # --------------------------------------------------------- 39 | # SORT 40 | # [].sort(reverse=True) => меняет оригинальный лист 41 | # sorted([]) => не меняет оригинальный лист 42 | # и можно присвоить новой переменной 43 | # --------------------------------------------------------- 44 | # REVERSE 45 | # [].reverse() => меняет оригинальный лист 46 | """ 47 | 48 | #1 способ 49 | # def multiply_list(list,n): 50 | # result = [] 51 | # for elements in list: 52 | # x = result.append(elements * n) 53 | # return x 54 | # print(multiply_list(["abc"],3)) 55 | 56 | #2 EX: 57 | 58 | # def get_max(arr): 59 | # max_num = arr[0] 60 | # for number in arr: 61 | # if max_num < number: 62 | # max_num = number 63 | # print(max_num) 64 | # get_max([1,2,3,4,5,6,7]) 65 | 66 | #3 EX: 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /Lessons/7lesson.py: -------------------------------------------------------------------------------- 1 | # data = [2,3,4,5,6,7,8,9] 2 | # # data = [x+3 for x in data] 3 | # # print(data) 4 | 5 | # data = [x for x in range(101) if x % 4 == 0 ] 6 | # print(data) 7 | 8 | 9 | # users = ['Aziz', 'Jomol', 'Bexruz', 'Istam', 'mmm'] 10 | 11 | # m = [name.center(len(name)+2,'*') for name in users if name.endswith('m')] 12 | # print(m) 13 | 14 | # z = [name if name.endswith('z') else 'Not Found' for name in users] 15 | # print(z) 16 | 17 | # z = [name if name.startswith('A') else 'NO start with A' if name.endswith('z') else 'Not Found' for name in users] 18 | # print(z) 19 | 20 | 21 | # arr = range(1,100) 22 | # s = [f"Even {num}" if num % 2 == 0 else f"odd {num}" for num in list(arr) if num<51] 23 | # print(s) 24 | 25 | # List comprehension 26 | # [ for x in if ] 27 | # [ <выражение> for x in <последовательность>, if <условие>] 28 | # ----------------------------------------------------- 29 | # result = [v for v in "Hello world" if v in 'aioue'] 30 | # print(result) 31 | 32 | 33 | # data = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] 34 | 35 | # Ex1: List comprehension: updating the same list 36 | # data = [number+3 for number in data] 37 | # print("Updating the list: ", data) 38 | 39 | # # Ex2: List comprehension: creating a different list with updated values 40 | # new_data = [x*2 for x in data] 41 | # print("Creating new list: ", new_data) 42 | 43 | # # Ex3: With an if-condition: Multiples of four: 44 | # fourx = [x for x in new_data if x % 4 == 0] 45 | # print("Divisible by four: ", fourx) 46 | 47 | # # Ex4: Alternatively, we can update the list with the if condition as well 48 | # fourxsub = [el-1 for el in new_data if el % 4 == 0] 49 | # print("Divisible by four minus one: ", fourxsub) 50 | 51 | # # Ex5: Using range function: 52 | # nines = [x for x in range(100) if x % 9 == 0] 53 | # print("Nines: ", nines) 54 | # --------------------------------------------- 55 | # users = ['Aziz', 'Jomol', "Farzod", "Diana", "Laziz"] 56 | 57 | # [x…() for … in … if … ] 58 | 59 | # z = [name.upper() for name in users if name.endswith('z')] 60 | 61 | # z = [] 62 | # for name in users: 63 | # if name.endswith('z'): 64 | # name = name.upper() 65 | # z.append(name) 66 | # print(z) 67 | # --------------------------------------------- 68 | 69 | 70 | # users = ['istam', 'rustam', 'kachok'] 71 | # users = [name if name.endswith("m") else "not Endswith M" for name in users] 72 | # print(users) 73 | 74 | # [if … else for … in … ] 75 | # a = [name if name.endswith('z') else 'Not ends with Z' for name in users] 76 | # a = [] 77 | # for name in users: 78 | # if name.endswith('z'): 79 | # a.append(name) 80 | # else: 81 | # a.append('Not Z') 82 | # print(a) 83 | # --------------------------------------------- 84 | # arr = range(100) 85 | # s = [ 86 | # f"Even {num}" if num % 2 == 0 else f"Odd {num}" 87 | # for num in list(arr) if num < 50 88 | # ] 89 | # s = [] 90 | # for num in list(arr): 91 | # if num < 50: 92 | # if num % 2 == 0: 93 | # s.append(f"Even {num}") 94 | # else: 95 | # s.append(f"Odd {num}") 96 | # ============================================== 97 | # for i in s: 98 | # print(i) 99 | # --------------------------------------------- 100 | # def double(*arr, **kwargs): 101 | # return [num*2 for num in arr] 102 | 103 | 104 | # res = double(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, bemiyya="Kamron") 105 | # print(res) 106 | 107 | 108 | 109 | 110 | 111 | # --------------------------------------------- 112 | 113 | 114 | # TUPLE 115 | # [] => mutable => Можно изменять 116 | # () => immutable => Нельзя изменять 117 | # --------------------------------------------- 118 | # Tuple comprehension 119 | # x = ("apple", "banana", "cherry") 120 | # x = tuple([fruit.upper() for fruit in x]) 121 | # print(x) 122 | # for item in x: 123 | # print(item.upper()) 124 | 125 | # --------------------------------------------- 126 | # ordered => means that every item has its own index starting from 0 127 | # RU: каждый элемент имеет свой индекс, начиная с 0 128 | # UZ: har bir elementning o'zining indeksi bor, 0 dan boshlanadi 129 | # unchangeable => means that we can not change the items after the tuple 130 | # has been created 131 | # THERE IS AN EXAMPLE above 132 | # RU: после создания кортежа мы не можем изменить его элементы 133 | # ЕСТЬ ПРИМЕР выше 134 | # UZ: tuple yaratilgandan keyin elementlarni o'zgartira olmaymiz 135 | # yuqorida misol bor 136 | # Tuple Length => len() 137 | 138 | # Двоичная система 139 | # 0 = 0 140 | # 1 = 1 141 | # 2 = 10 142 | # 3 = 11 143 | # 4 = 100 144 | # 5 = 101 145 | # 6 = 110 146 | # 7 = 111 147 | # 8 = 1000 148 | # 9 = 1001 149 | # 10 = 1010 150 | # 11 = 1011 151 | # 12 = 1100 152 | # 13 = 1101 153 | # 14 = 1110 154 | # 15 = 1111 155 | # 16 = 10000 156 | 157 | 158 | # Fibonacci 159 | # 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ... 160 | # We have to add the last two numbers to get the next number 161 | # RU: Мы должны добавить последние два числа, чтобы получить следующее число 162 | 163 | # def fib(limit:int): 164 | # result=[] 165 | # p=0 166 | # c=1 167 | # for i in range(limit): 168 | # result.append(p) 169 | # cx=c+p 170 | # p=c 171 | # c=cx 172 | # return result 173 | # print(fib(100)) 174 | 175 | # -------------------------------------------------------------------------- 176 | # Create Tuple With One Item => ('...',) 177 | # tuple() => tuple([..., ...]) 178 | # Change Tuple Values => list(("apple", "banana", "cherry")) 179 | 180 | # Unpacing (In JS) 181 | # let [x,y] = [1, 2] 182 | 183 | # (In Python) 184 | # Using Asterisk * || _ * _ || _ _ * 185 | # a, *b, c = ("apple", "banana", "cherry") 186 | 187 | # Multiply 188 | # print(("apple", "banana", "cherry") * 2) 189 | 190 | 191 | # ------------------------------------------------------------------- 192 | # append() Adds an element at the end of the list 193 | # RU: Добавляет элемент в конец списка 194 | # clear() Removes all the elements from the list 195 | # RU: Удаляет все элементы из списка 196 | # copy() Returns a copy of the list 197 | # RU: Возвращает копию списка 198 | # count() Returns the number of elements with the specified value 199 | # RU: Возвращает количество элементов с указанным значением 200 | # extend() Add the elements of a list (or any iterable), to the end of the current list 201 | # RU: Добавляет элементы списка (или любого итерируемого объекта) в конец текущего списка 202 | # index() Returns the index of the first element with the specified value 203 | # RU: Возвращает индекс первого элемента с указанным значением 204 | # insert() Adds an element at the specified position 205 | # RU: Добавляет элемент в указанную позицию 206 | # pop() Removes the element at the specified position 207 | # RU: Удаляет элемент в указанной позиции 208 | # remove() Removes the item with the specified value 209 | # RU: Удаляет элемент с указанным значением 210 | # reverse() Reverses the order of the list 211 | # RU: Изменяет порядок списка на обратный 212 | # sort() Sorts the list (changes the original) [].sort() 213 | # RU: Сортирует список (изменяет оригинал) 214 | # sorted() Sorts the list (does not change the original) sorted([]) 215 | # RU: Сортирует список (не изменяет оригинал) 216 | 217 | 218 | 219 | def test(*arr,**kwargs): 220 | return arr, kwargs 221 | print(test(1,2,3,4,5,Kamron="bimmiya")) -------------------------------------------------------------------------------- /Lessons/8lesson.py: -------------------------------------------------------------------------------- 1 | # import time 2 | # start_time = time.time() 3 | # for i in range(10): 4 | # for i2 in range(10): 5 | # print(i2) 6 | # end_time = time.time() 7 | # a = "Taken time:", round(end_time - start_time, 10) 8 | # print(a) 9 | 10 | #------------------------------------------------------------------------------- 11 | 12 | # itr1 = ['a','b','c'] 13 | # itr2 = [1,2,3] 14 | # itr3 = ['x', 'y','z'] 15 | # zipped_itr = zip(itr1,itr2,itr3) 16 | # # print(list(zipped_itr)) 17 | # for first,second,third in zipped_itr: 18 | # print(first,second,third) 19 | 20 | #------------------------------------------------------------------------------- 21 | # import random 22 | # letters = "abcdefghijklmnopqrstuvwxyz" 23 | # letters_ru = "абвгдеёжз" 24 | # numbers = "1234567890" 25 | # symbols = "!@#$%^&()_+<>?/;:" 26 | # total_sybols_for_password = 20 27 | 28 | # everything_includes = letters + letters_ru + numbers + symbols 29 | # created_password = "" 30 | 31 | # for i in range(total_sybols_for_password): 32 | # random_int = random.randint(0, len(everything_includes)-1) 33 | # created_password += everything_includes[random_int] 34 | # print(created_password) 35 | 36 | #------------------------------------------------------------------------------- 37 | 38 | # test_obj = { 1:'a', 2:'b', 3:'c'} 39 | # --------------------------------------------------------- 40 | # In JS 41 | # Object.keys(my_obj), Object.values(my_obj), Object.entries(my_obj) 42 | # --------------------------------------------------------- 43 | # In Python 44 | # my_obj.keys(), my_obj.values(), my_obj.items() 45 | # --------------------------------------------------------- 46 | # for value in test_obj.values(): 47 | # print(value) 48 | # for key in test_obj.keys(): 49 | # print(key) 50 | # for key, value in test_obj.items(): 51 | # print(key, value) 52 | 53 | # ----------WHILE LOOP 54 | # SYNTAXIS 55 | # condition = 2==2 56 | # while condition == True: 57 | # do something 58 | 59 | # ----------FOR LOOP 60 | # SYNTAXIS 61 | # for x in []: 62 | # print(x) 63 | # ----------ENUMERATE 64 | # enumerate is used to get an index for the item that we are taking from list 65 | # ex: 66 | # for index, item in enumerate(list): 67 | # print(index, item) 68 | # --------------------------------------------------------- 69 | # arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 70 | # for idx, item in enumerate(arr): 71 | # print(idx, item) 72 | 73 | # ============================================================================== 74 | # break => breaks up the current loop 75 | # RU: прерывает текущий цикл 76 | # continue => skips the current iteration of the loop 77 | # RU: пропускает текущую итерацию цикла 78 | # --------- 79 | # fruits = ["apple", "banana", "kiwi", "mango", "disgusting cherry", "kiwi", "mango"] 80 | # for fruit in fruits: 81 | # if 'disgusting' in fruit: 82 | # break 83 | # elif 'kiwi' == fruit: 84 | # continue 85 | # else: 86 | # print(fruit) 87 | # ================================================================== 88 | # round((time.time() - start_time), 2) 89 | # ------------ 90 | # round => rounds the number to the specified number of digits 91 | # RU: округляет число до указанного количества цифр 92 | # EX: print(round(3.454, 2)) => 3.45 93 | # --------------------------------------------------------- 94 | # import time 95 | # start_time = time.time() 96 | # for i in range(10): 97 | # for i2 in range(10): 98 | # print(i2) 99 | # end_time = time.time() 100 | # print("Time taken: ", round(end_time - start_time, 4)) 101 | # --------------------------------------------------------- 102 | # import time 103 | # time.time() => returns the number of seconds passed since epoch 104 | # EX: start_time = time.time() 105 | # end_time = time.time() 106 | # difference = end_time - start_time 107 | # 108 | # from datetime import datetime as dt 109 | # start_time = dt.now() 110 | # for n in range(100): 111 | # print(n) 112 | # for n2 in range(100): 113 | # print(n2) 114 | 115 | # end_time = dt.now() 116 | # print("Execution time: ", end_time - start_time) 117 | # ================================================================== 118 | # for i in range(10): 119 | # pass 120 | # for i in "Some text": 121 | # pass 122 | # ================================================================== 123 | # itr1 = list('abcdefghijklmnopqrstuvwxyz') 124 | # itr2 = range(len(itr1)) 125 | # itr3 = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 126 | # 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 127 | # 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 128 | # 'ю', 'я'] 129 | 130 | # zipped = zip(itr2, itr3) 131 | # for (letter, number) in zipped: 132 | # print(letter, number) 133 | # ================================================================== 134 | # itr1 = ['a', 'b', 'c'] 135 | # itr2 = [ 1, 2, 3, 4 ] 136 | # itr3 = ['x', 'y', 'z', 'w', 'u'] 137 | # zipped_itr = zip(itr1, itr2, itr3) 138 | 139 | # for first, second, third in zipped_itr: 140 | # print(first, second, third) 141 | 142 | # ================================================================== 143 | # loop with dictionaries 144 | # for key, value in dict.items(): 145 | # print(key, value) 146 | # ================================================================== 147 | -------------------------------------------------------------------------------- /Lessons/9lesson.py: -------------------------------------------------------------------------------- 1 | # 1. max() 2 | # Return the largest item in an iterable or the largest of two or more arguments. 3 | # RU: Возвращает наибольший элемент в итерируемом объекте или наибольший из двух или более аргументов. 4 | 5 | # If one item is given, it should be iterable. The largest item in the iterable is returned. 6 | # RU: Возвращает наибольший элемент в итерируемом объекте или наибольший из двух или более аргументов. 7 | # max(iterable, *[, key, default]) 8 | 9 | # If two or more positional arguments are provided, the largest of the positional arguments is returned. 10 | # RU: Если предоставлено два или более позиционных аргумента, возвращается наибольший из позиционных аргументов. 11 | # max(arg1, arg2, *args[, key]) 12 | 13 | # There are two optional keyword-only arguments. 14 | # RU: Есть два необязательных аргумента только ключевых слов. 15 | 16 | # key- key function where the iterables are passed and comparison is performed based on its return value 17 | # RU: key- ключевая функция, в которой передаются итерируемые объекты, 18 | # и сравнение выполняется на основе возвращаемого значения 19 | # EX: 20 | # iterable = ['geeks', 'code', 'python', 'java'] 21 | # max(iterable, key=len) => 'python' 22 | # iterable = [30, 15, 20, 25, 30] 23 | # print(max(iterable, key=lambda x: x%15)) # => 25 24 | # => here the remainder after dividing each element by 25 | # 15 is calculated and the maximum of those values is returned 26 | # ex: 10%15 = 10, 15%15 = 0, 20%15 = 5, 25%15 = 10, 30%15 = 0 27 | 28 | # The default argument specifies an object to return if the provided iterable is empty. 29 | # If the iterable is empty and the default is not provided, a ValueErroris raised. 30 | # EX: 31 | # iterable = [] 32 | # max(iterable, default=100) => 100 33 | # max(iterable) => ValueError: max() arg is an empty sequence 34 | # ================================== 35 | # 2. min() Works the same way as max(), but returns the smallest value 36 | 37 | # =========================================================================================== 38 | # 3. map() Returns a map object (which is an iterator) of the results after applying the 39 | # given function to each item of a given iterable (list, tuple etc.) 40 | # RU: Возвращает объект отображения (который является итератором) результатов после применения 41 | # заданной функции к каждому элементу заданного итерируемого объекта (список, кортеж и т. Д.) 42 | # EX: 43 | # def wordCount(n): 44 | # return len(n) 45 | # # Or we could use: 46 | # # wordCount = lambda n: len(n) 47 | # x = map(wordCount, ('apple', 'banana', 'cherry')) 48 | # print(list(x)) => [5, 6, 6] 49 | # ------------------------------------------------------------------------------ 50 | # 4. filter() Use a filter function to exclude items in an iterable object 51 | # RU: Используйте функцию фильтра, чтобы исключить элементы в итерируемом объекте 52 | # EX: 53 | # def myFunc(n): 54 | # # if n > 18: 55 | # # return True 56 | # # else: 57 | # # return False 58 | # ------------------- 59 | # # return True if n > 18 else False 60 | # ------------------- 61 | # return n > 18 62 | 63 | 64 | # x = filter(myFunc, (5, 7, 18, 25, 32)) 65 | # print(list(x)) => [25, 32] 66 | # NOTE: The callback function should return True/False 67 | # depending on the value in the iterable 68 | # RU: Функция обратного вызова должна возвращать True / False 69 | # в зависимости от значения в итерируемом объекте 70 | # ------------------------------------------------------------------------------ 71 | # 5. reduce() Use a function to reduce an iterable to a single value 72 | # RU: Используйте функцию для сокращения итерируемого объекта до одного значения 73 | # EX: 74 | # from functools import reduce 75 | # def myFunc(acc, next): 76 | # """ 77 | # acc - accumulator 78 | # next - next value 79 | # NOTE: the initial value of the accumulator is the first value of the iterable 80 | # if not given as last argument 81 | # """ 82 | # return acc + next 83 | # # return acc if acc > next else next 84 | 85 | # x = reduce(myFunc, (1, 2, 3, 4)) 86 | # print(x) # => 10 87 | 88 | # x = map(lambda x: x*2, arr) 89 | # print(list(x)) 90 | 91 | 92 | # def myFunc(current, next): 93 | # if current > next: 94 | # print("current > next", current) 95 | # return current 96 | # else: 97 | # print("current > next", next) 98 | # return next 99 | # arr = [11, 22, 3, 4515, 56] 100 | # res = reduce(myFunc, arr) 101 | # print(res) -------------------------------------------------------------------------------- /Lessons/__pycache__/19lesson.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Lessons/__pycache__/19lesson.cpython-311.pyc -------------------------------------------------------------------------------- /Lessons/regular_expression.txt: -------------------------------------------------------------------------------- 1 | Регулярные выражения (regex или regexp) очень эффективны для извлечения информации из текста. Для этого нужно произвести поиск одного или нескольких совпадений по определённому шаблону (т. е. определённой последовательности символов ASCII или unicode). 2 | 3 | Области применения regex разнообразны, от валидации до парсинга/замены строк, передачи данных в другие форматы и Web Scraping’а. 4 | 5 | Одна из любопытных особенностей регулярных выражений в их универсальности, стоит вам выучить синтаксис, и вы сможете применять их в любом (почти) языке программирования (JavaScript, Java, VB, C #, C / C++, Python, Perl, Ruby, Delphi, R, Tcl, и многих других). Небольшие отличия касаются только наиболее продвинутых функций и версий синтаксиса, поддерживаемых движком. 6 | 7 | Давайте начнём с нескольких примеров. 8 | 9 | Основы 10 | Якоря — ^ и $ 11 | ^Привет соответствует строке, начинающейся с Привет -> тест 12 | пока$ соответствует строке, заканчивающейся на пока 13 | ^Привет пока$ точное совпадение (начинается и заканчивается как Привет пока) 14 | воробушки соответствует любой строке, в которой есть текст воробушки 15 | Квантификаторы — * + ? и {} 16 | abc* соответствует строке, в которой после ab следует 0 или более символов c -> тест 17 | abc+ соответствует строке, в которой после ab следует один или более символов c 18 | abc? соответствует строке, в которой после ab следует 0 или один символ c 19 | abc{2} соответствует строке, в которой после ab следует 2 символа c 20 | abc{2,} соответствует строке, в которой после ab следует 2 или более символов c 21 | abc{2,5} соответствует строке, в которой после ab следует от 2 до 5 символов c 22 | a(bc)* соответствует строке, в которой после ab следует 0 или более последовательностей символов bc 23 | a(bc){2,5} соответствует строке, в которой после ab следует от 2 до 5 последовательностей символов bc 24 | Оператор ИЛИ — | или [] 25 | a(b|c) соответствует строке, в которой после a следует b или c -> тест 26 | a[bc] как и в предыдущем примере 27 | Символьные классы — \d \w \s и . 28 | \d соответствует одному символу, который является цифрой -> тест 29 | \w соответствует слову (может состоять из букв, цифр и подчёркивания) -> тест 30 | \s соответствует символу пробела (включая табуляцию и прерывание строки) 31 | . соответствует любому символу -> тест 32 | Используйте оператор . с осторожностью, так как зачастую класс или отрицаемый класс символов (который мы рассмотрим далее) быстрее и точнее. 33 | 34 | У операторов \d, \w и \s также есть отрицания ― \D, \W и \S соответственно. 35 | 36 | Например, оператор \D будет искать соответствия противоположенные \d. 37 | 38 | \D соответствует одному символу, который не является цифрой -> тест 39 | Некоторые символы, например ^.[$()|*+?{\ , необходимо выделять обратным слешем \ . 40 | 41 | \$\d соответствует строке, в которой после символа $ следует одна цифра -> тест 42 | Непечатаемые символы также можно искать, например табуляцию \t, новую строку \n, возврат каретки \r. 43 | 44 | Флаги 45 | Мы научились строить регулярные выражения, но забыли о фундаментальной концепции ― флагах. 46 | 47 | Регулярное выражение, как правило, записывается в такой форме /abc/, где шаблон для сопоставления выделен двумя слешами /. В конце выражения, мы определяем значение флага (эти значения можно комбинировать): 48 | 49 | g (global) ― не возвращает результат после первого совпадения, а продолжает поиск с конца предыдущего совпадения. 50 | m (multi line) ― с таким флагом, операторы ^ и $ вызовут совпадение в начале и конце строки ввода (line), вместо строки целиком (string). 51 | i (insensitive) ― делает выражение регистронезависимым (например, /aBc/i соответствует AbC). 52 | Средний уровень 53 | Скобочные группы ― () 54 | a(bc) создаём группу со значением bc -> тест 55 | a(?:bc)* оперетор ?: отключает группу -> тест 56 | a(?bc) так, мы можем присвоить имя группе -> тест 57 | Этот оператор очень полезен, когда нужно извлечь информацию из строк или данных, используя ваш любимый язык программирования. Любые множественные совпадения, по нескольким группам, будут представлены в виде классического массива: доступ к их значениям можно получить с помощью индекса из результатов сопоставления. 58 | 59 | Если присвоить группам имена (используя (?...)), то можно получить их значения, используя результат сопоставления, как словарь, где ключами будут имена каждой группы. 60 | 61 | Скобочные выражения ― [] 62 | [abc] соответствует строке, которая содержит либо символ a или a b или a c -> такой же эффект от a|b|c -> тест 63 | [a-c] то же, что и выше 64 | [a-fA-F0–9] строка, представляющая одну шестнадцатеричную цифру без учёта регистра -> тест 65 | [0–9]% строка, содержащая символ от 0 до 9 перед знаком % 66 | [^a-zA-Z] строка, которая не имеет буквы от a до z или от A до Z. В этом случае ^ используется как отрицание в выражении -> тест 67 | Помните, что внутри скобочных выражений все специальные символы (включая обратную косую черту \) теряют своё служебное значение, поэтому нам ненужно их экранировать. 68 | 69 | Жадные и ленивые сопоставления 70 | Квантификаторы ( * + {}) ― это «жадные» операторы, потому что они продолжают поиск соответствий, как можно глубже ― через весь текст. 71 | 72 | Например, выражение <.+> соответствует
simple div
в This is a
simple div
test. Чтобы найти только тэг div ― можно использовать оператор ?, сделав выражение «ленивым»: 73 | 74 | <.+?> соответствует любому символу, один или несколько раз найденному между < и >, расширяется по мере необходимости -> тест 75 | Обратите внимание, что хорошей практикой считается не использовать оператор . , в пользу более строгого выражения: 76 | 77 | <[^<>]+> соответствует любому символу, кроме < или >, один или более раз встречающемуся между < и > -> тест 78 | Продвинутый уровень 79 | Границы слов ― \b и \B 80 | \babc\b выполняет поиск слова целиком -> тест 81 | \b ― соответствует границе слова, наподобие якоря (он похож на $ и ^), где предыдущий символ ― словесный (например, \w), а следующий ― нет, либо наоборот, (например, это может быть начало строки или пробел). 82 | 83 | \B ― соответствует несловообразующей границе. Соответствие не должно обнаруживаться на границе \b . 84 | 85 | \Babc\B соответствует, только если шаблон полностью окружён словами -> тест 86 | Обратные ссылки — \1 87 | ([abc])\1 \1 соответствует тексту из первой захватываемой группы -> тест 88 | ([abc])([de])\2\1 можно использовать \2 (\3, \4, и т.д.) для определения порядкового номера захватываемой группы -> тест 89 | (?[abc])\k мы присвоили имя foo группе, и теперь ссылаемся на неё используя ― (\k). Результат, как и в первом выражении -> тест 90 | Опережающие и ретроспективные проверки — (?=) and (?<=) 91 | d(?=r) соответствует d, только если после этого следует r, но r не будет входить в соответствие выражения -> тест 92 | (?<=r)d соответствует d, только если перед этим есть r, но r не будет входить в соответствие выражения -> тест 93 | Вы можете использовать оператор отрицания ! 94 | 95 | d(?!r) соответствует d, только если после этого нет r, но r не будет входить в соответствие выражения -> тест 96 | (? тест 97 | Заключение 98 | Как вы могли убедиться, области применения регулярных выражений разнообразны. Я уверен, что вы сталкивались с похожими задачами в своей работе (хотя бы с одной из них), например такими: 99 | 100 | Валидация данных (например, правильно ли заполнена строка time) 101 | Сбор данных (особенно веб-скрапинг, поиск страниц, содержащих определённый набор слов в определённом порядке) 102 | Обработка данных (преобразование сырых данных в нужный формат) 103 | Парсинг (например, достать все GET параметры из URL или текст внутри скобок) 104 | Замена строк (даже во время написания кода в IDE, можно, например преобразовать Java или C# класс в соответствующий JSON объект, заменить “;” на “,”, изменить размер букв, избегать объявление типа и т.д.) 105 | Подсветка синтаксиса, переименование файла, анализ пакетов и многие другие задачи, где нужно работать со строками (где данные не должны быть текстовыми). 106 | Перевод статьи Jonny Fox: Regex tutorial — A quick cheatsheet by examples 107 | 108 | regular expression 109 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson10.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | # 5. Write a Python program that accepts a word 7 | # from the user and reverses it. 8 | 9 | # def reverse_text(string): 10 | # return string[::-1] 11 | # print(reverse_text(input('enter text to reverse: '))) 12 | 13 | 14 | 15 | # 6. Write a Python program to count the number of even and odd 16 | # numbers in a series of numbers 17 | # Sample numbers : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) 18 | # Expected Output : 19 | # Number of even numbers : 5 20 | # Number of odd numbers : 4 21 | 22 | # def even_and_odds(numbers): 23 | # even = 0 24 | # odd = 0 25 | # for num in numbers: 26 | # if num % 2 == 0: 27 | # even += 1 28 | # else: 29 | # odd += 1 30 | # return even, odd 31 | # numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) 32 | # even_count, odd_count = even_and_odds(numbers) 33 | # print("even nums count:", even_count) 34 | # print("odd nums count:", odd_count) 35 | 36 | 37 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson11.py: -------------------------------------------------------------------------------- 1 | # def count_letters(lst): 2 | # count_char = {} 3 | # for char in lst: 4 | # if char in count_char: 5 | # count_char[char] += 1 6 | # else: 7 | # count_char[char] = 1 8 | # for letter, count_char in count_char.items(): 9 | # print(letter, "=", count_char) 10 | 11 | # count_letters("Istamrustam") 12 | 13 | 14 | # def test (string): 15 | # res = '' 16 | # for index ,i in enumerate(string): 17 | # if index % 2 == 0: 18 | # res+=i.upper() 19 | # continue 20 | # res+=i.lower() 21 | # return res 22 | 23 | # print(test("istam")) 24 | 25 | 26 | # 2. Напишите программу на Python, чтобы создать 27 | # функцию, которая принимает один аргумент, и этот 28 | # аргумент будет умножен на неизвестное заданное число. 29 | # Пример вывода: 30 | # Удвойте число 15 = 30. 31 | # Утроите число 15 = 45. 32 | # Увеличьте число 15 в четыре раза = 60. 33 | # Увеличьте число в пять раз. 15 = 75. 34 | 35 | 36 | # def nums(nums): 37 | # a = nums * 2 38 | # b = nums * 3 39 | # c = nums * 4 40 | # d = nums * 5 41 | # print (f"Удвойте число {nums} = {a}\nУтроите число {nums} = {b}\nУвеличьте число {nums} в четыре раза = {c}\nУвеличьте число в пять раз {nums} = {d}") 42 | # nums(15) 43 | 44 | # ↓↓↓↓↓↓↓ This task with lambda ↓↓↓↓↓↓↓ 45 | # def func_compute(n): 46 | # return lambda x : x * n 47 | # result = func_compute(2) 48 | # print("Double the number of 15 =", result(15)) 49 | # result = func_compute(3) 50 | # print("Triple the number of 15 =", result(15)) 51 | # result = func_compute(4) 52 | # print("Quadruple the number of 15 =", result(15)) 53 | # result = func_compute(5) 54 | # print("Quintuple the number 15 =", result(15)) 55 | 56 | #====================================================================== 57 | 58 | # 3. Write a Python program to sort a list of tuples using Lambda. 59 | # Original list of tuples: 60 | # [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)] 61 | # Sorting the List of Tuples: 62 | # [('Social sciences', 82), ('English', 88), ('Science', 90), ('Maths', 97)] 63 | 64 | 65 | # list = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)] 66 | # print("Original list :") 67 | # print(list) 68 | # list.sort(key = lambda x: x[1]) 69 | # print("\nSorted:") 70 | # print(list) 71 | #====================================================================== 72 | 73 | 74 | # 6. Write a Python program to square and cube every number in 75 | # a given list of integers using Lambda. 76 | # Original list of integers: 77 | # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 78 | # Square every number of the said list: 79 | # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 80 | # Cube every number of the said list: 81 | # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 82 | 83 | # list_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 84 | # print(f"Original list: {list_nums}") 85 | # square_nums = list(map(lambda x: x ** 2, list_nums)) 86 | # print (f"Square nums: {square_nums}") 87 | # cube_nums = list(map(lambda x: x ** 3, list_nums)) 88 | # print(f"Cube nums: {cube_nums}") 89 | #====================================================================== 90 | 91 | # 7. Write a Python program to find if a given string starts with a given 92 | # character using Lambda. 93 | # Sample Output: 94 | # True 95 | # False 96 | 97 | # word = "ISTAM" 98 | # true_func = lambda word: True if word.startswith('I') else False 99 | # false_func = lambda word: True if word.startswith('P') else False 100 | # print(true_func(word)) 101 | # print(false_func(word)) 102 | 103 | 104 | 105 | # f1 = 0 106 | # f2 = 1 107 | # n = 10 108 | # print(f1, f2, end = " ") 109 | # while n > 1: 110 | # f1,f2 = f2, f1+f2 111 | # print(f2, end=" ") 112 | # n -= 1 113 | 114 | 115 | 116 | 117 | # f1 = 0 118 | # f2 = 1 119 | # n = 10 120 | # print(f1, f2, end = " ") 121 | # for i in range(2, n): 122 | # f1,f2 = f2, f1+f2 123 | # print(f2, end=" ") 124 | 125 | 126 | 127 | # f1 = 0 128 | # f2 = 1 129 | # n = 100 130 | # print(f1, f2, end = " ") 131 | # while f2 {x':1, 'y':2, 'a':3} 39 | 40 | # def remove_duplicates(dict): 41 | # result = {} 42 | # values = [] 43 | # for k, v in dict.items(): 44 | # if v not in values: 45 | # result[k] = v 46 | # values.append(v) 47 | # return result 48 | # new_dict = remove_duplicates({'x':1, 'y':2, 'z':2, 'a':3, 'b':1, 'c':3}) 49 | # print(new_dict) 50 | 51 | # ============================================================== 52 | # 12. Write a function that takes a dict as first argument and number as second argument. 53 | # Return a list of all the keys that have values greater than the number passed as second argument. 54 | # RU: Напишите функцию, которая принимает словарь в качестве первого аргумента и число в 55 | # качестве второго аргумента. Верните список всех ключей, у которых значения больше, чем число, 56 | # переданное в качестве второго аргумента. 57 | # Input: {'a': 100, 'b': 200, 'c': 300, 'd': "Hello world", 'e': True}, 150 58 | # Output: {'b': 200, 'c': 300} 59 | 60 | # def get_keys_greater_than(dict, num): 61 | # a = {k:v for k,v in dict.items() if isinstance(v, int) and v > num} 62 | # return a 63 | # print(get_keys_greater_than({'a': 100, 'b': 200, 'c': 300, 'd': "Hello world", 'e': True}, 150)) 64 | 65 | # ============================================================== 66 | # 14. Write a function that takes a dictionary as an argument and returns 67 | # a new dictionary with the keys and values reversed. 68 | # RU: Напишите функцию, которая принимает словарь в качестве аргумента 69 | # и возвращает новый словарь с обратными ключами и значениями. 70 | 71 | # def reverse_dict(d): 72 | # a = {v:k for k,v in d.items()} 73 | # return a 74 | # print(reverse_dict({'a': 1, 'b': 2, 'c': 3, 'd': 4})) 75 | 76 | # ============================================================== 77 | # 15. Write a function that takes a list of dictionaries as an argument 78 | # and returns a sum of numeric values of all dicts 79 | # RU: Напишите функцию, которая принимает список словарей в качестве аргумента 80 | # и возвращает сумму числовых значений всех словарей 81 | # x = {'a': 1, 'b': "2", "c": "Hello"} 82 | # z = {'d': "4", 'e': 3, "f": "World"} 83 | # a = {'g': 5, 'h': "!!!", "i": "6"} 84 | # arr = [x, z, a] 85 | # # test(arr) # 21 86 | # def sum_numeric_values(arr_of_dicts: list[dict]) -> int: 87 | # pass 88 | 89 | # ============================================================== 90 | # 16. Write a function that takes a dictionary as an argument and returns a new 91 | # dictionary that contains only the key-value pairs where the value is a string. 92 | # RU: Напишите функцию, которая принимает словарь в качестве аргумента и возвращает 93 | # новый словарь, который содержит только пары ключ-значение, где значение - строка. 94 | 95 | # x = {1: 1, 2: 2, 3: "Hello"} 96 | # a = {v for v in x.values() if isinstance(v, str)} 97 | # print(a) -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson13.py: -------------------------------------------------------------------------------- 1 | # 1. Write a Python program to create a set. 2 | 3 | #1 4 | # a = 1,2,3,4,5,5,5,1,1 5 | # print(set(a)) 6 | #2 7 | # a = (set({1,2,3,4,5,6,7,1,1,1,1})) 8 | # print(a) 9 | # print(type(a)) 10 | 11 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson3.py: -------------------------------------------------------------------------------- 1 | # 1. Напишите программу на Python для вычисления 2 | # суммы списка чисел. 3 | 4 | # def summa(*arr): 5 | # return (sum(arr)) 6 | # print(summa(1,2,3,4,5,6,7,8,9,10)) 7 | #--------------------------------------------------------------------------------------- 8 | 9 | #2. Напишите программу на Python для получения факториала неотрицательного 10 | #целого числа. 11 | 12 | # def factorial(n): 13 | # if n == 1: 14 | # return n 15 | # return factorial(n-1) * n 16 | # print(factorial(5)) 17 | #--------------------------------------------------------------------------------------- 18 | 19 | # 3. Напишите программу на Python для 20 | # решения последовательности Фибоначчи с использованием рекурсии. 21 | 22 | # def fibonachi(n): 23 | # if n <= 0 or n==1: 24 | # return 1 25 | # else: 26 | # return fibonachi(n-1) + fibonachi(n-2) 27 | # n = 10 28 | # fib = [fibonachi(i) for i in range(n+1)] 29 | # print(fib) 30 | #--------------------------------------------------------------------------------------- 31 | 32 | #CALCULATOR 33 | 34 | # a = int(input(">>1 ")) 35 | # b = int(input(">>2 ")) 36 | # c = input('* / - + ') 37 | # if c == "*": 38 | # print(a * b) 39 | # if c == "/": 40 | # print(a / b) 41 | # if c == "+": 42 | # print(a + b) 43 | # if c == "-": 44 | # print(a - b) 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson4.py: -------------------------------------------------------------------------------- 1 | #HOMEWORK 2 | 3 | 4 | #1 LAST LETTER BEFORE 5 | 6 | # def last_l_before(string, stop=1): 7 | # if stop == 0: 8 | # return 9 | # elif len(string) == 1: 10 | # print(string) 11 | # else: 12 | # print(string) 13 | # last_l_before(string[-1] + string[:-1], stop=stop-1) 14 | # last_l_before("Hello world", stop=len("Hello world")+1) 15 | 16 | 17 | #2 PYRAMID WITH RECURSION 18 | 19 | # def pyramida(n, current=1): 20 | # if current >= n: 21 | # return 22 | # else: 23 | # print(' ' * (n - current) + '*' * (2 * current - 1)) 24 | # pyramida(n, current + 1) 25 | 26 | # n = int(input('>>>: ')) 27 | # pyramida(n) 28 | 29 | 30 | # x = lambda string1, string2: string1 + string2 31 | # print(x("Istam", "jamshed")) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson6.py: -------------------------------------------------------------------------------- 1 | #1 2 | # def first_and_last_twins (arr): 3 | # arr = list(arr) 4 | # for items in arr: 5 | # if items[0] == items[-1]: 6 | # print(f"first_last_twins: {items}") 7 | # else: 8 | # print(f"No: {items}") 9 | # first_and_last_twins(['aziza', 'istam', 'sass']) 10 | 11 | 12 | #2 13 | # def delete_duplicates(arr): 14 | # x = list(arr) 15 | # for i in x: 16 | # if x.count(i) > 1: 17 | # x.remove(i) 18 | # return x 19 | # print(delete_duplicates("IIssttaamm")) 20 | 21 | 22 | #3 23 | # def first_vowels(arr): 24 | # vowels = ["a","e","i","o","u","y"] 25 | # for i in arr: 26 | # if i[0] in vowels: 27 | # print(f"VOWEL_WORD: {i}") 28 | # first_vowels(["istam", "rustam","qodirali" ,"es", "eeeee"]) 29 | 30 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson7.py: -------------------------------------------------------------------------------- 1 | # HOMEWORK 2 | 3 | # 1. Create a tuple with numbers and print one last item. 4 | # RU: Создайте кортеж с числами и выведите один последный элемент. 5 | 6 | # def last_element (arr:list): 7 | # return arr[-1::] 8 | # print(last_element(list(range(1,11)))) 9 | 10 | # ================================================================ 11 | 12 | # 2. Create a tuple with numbers and check if a given element exists in the tuple. 13 | # RU: Создайте кортеж с числами и проверьте, существует ли в кортеже заданный элемент. 14 | 15 | # def check_if_exists(tup, items_arr): 16 | # if items_arr in tup: 17 | # print("yes") 18 | # else: 19 | # print("no") 20 | # check_if_exists((1,2,3,4,5,6,7,8,9,100), (100)) 21 | 22 | # ================================================================ 23 | 24 | # 3. Create a tuple with numbers and find the index of a given element in the tuple. 25 | # RU: Создайте кортеж с числами и найдите индекс заданного элемента в кортеже. 26 | 27 | # def get_index(tup, item): 28 | # a = tup.index(item) 29 | # return (f"index of item {item} in tup: {a}") 30 | # print(get_index((1,2,3,4,5,6,7), (3))) 31 | 32 | # ================================================================ 33 | 34 | # 4. Create a tuple with numbers and find the number of occurrences 35 | # of a given element in the tuple. 36 | # RU: Создайте кортеж с числами и найдите количество вхождений заданного 37 | # элемента в кортеж. 38 | 39 | # def count_item(tup, item): 40 | # return tup.count(item) 41 | # print(count_item((1,2,3,4,5,6,1,1,1,1,7), (1))) 42 | 43 | # ================================================================ 44 | 45 | # Write a Python function that takes a tuple of integers as input 46 | # and returns a new tuple with the same integers sorted in descending 47 | # order, but with the even numbers before the odd numbers. 48 | # RU: Напишите функцию Python, которая принимает в качестве входных данных 49 | # кортеж целых чисел и возвращает новый кортеж с теми же целыми числами, 50 | # отсортированными в порядке убывания, но с четными числами перед нечетными. 51 | # INPUT: => (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) 52 | # OUTPUT: => (6, 4, 2, 9, 5, 5, 5, 3, 3, 1, 1) 53 | 54 | # def sort_tuple(numbers): 55 | # even = [x for x in numbers if x % 2 == 0] 56 | # odd = [x for x in numbers if x % 2 != 0] 57 | # even.sort(reverse=True) 58 | # odd.sort(reverse=True) 59 | # return tuple(even + odd) 60 | # numbers = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) 61 | # result = sort_tuple(numbers) 62 | # print(list(result)) 63 | # ================================================================ 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /LessonsExersisesAll/ExLesson8.py: -------------------------------------------------------------------------------- 1 | # BEGINNER LEVEL 2 | # ========================================================================================== 3 | 4 | # 1. Create a function that gets only numbers from given sentence and 5 | # separates them into two lists: evens and odds 6 | # RU: Создайте функцию, которая получает только числа из данного предложения и 7 | # разделяет их на два списка: четные и нечетные 8 | # Use at least one built-in function 9 | # RU: Используйте по крайней мере одну встроенную функцию 10 | 11 | # INPUT: "Hello 7th World in 2023 year 2nd time" 12 | # [7, 3] [2, 0, 2] 13 | 14 | # def even_odd(sentence): 15 | # numbers = [int(x) for x in sentence if x.isnumeric()] 16 | # even = [x for x in numbers if x % 2 == 0] 17 | # odd = [x for x in numbers if x not in even] 18 | # return even, odd 19 | # even, odd = even_odd("This is a test sentence with 1 2 3 numbers 45 6") 20 | # print("Evens:", even) 21 | # print("Odds:", odd) 22 | 23 | # ========================================================================================== 24 | 25 | # 2. Create a function that accepts a string and counts the number of 26 | # upper and lower case letters. 27 | # Sample String : 'The quick Brow Fox' 28 | # Expected Output : 29 | # No. of Upper case characters : 3 30 | # No. of Lower case Characters : 12 31 | # --------------------------------- 32 | # RU: Создайте функцию, которая принимает строку и подсчитывает количество 33 | # прописных и строчных букв. 34 | # Пример строки: 'The quick Brow Fox' 35 | # Ожидаемый результат: 36 | # Количество прописных букв: 3 37 | # Количество строчных букв: 12 38 | 39 | # def upper_lower(sentence): 40 | # upper = 0 41 | # lower = 0 42 | 43 | # for char in sentence: 44 | # if char.isupper(): 45 | # upper += 1 46 | # elif char.islower(): 47 | # lower += 1 48 | # return f"Количество прописных букв: {upper} \nКоличество строчных букв: {lower}" 49 | # print(upper_lower('The quick Brow Fox')) 50 | 51 | # ========================================================================================== 52 | 53 | # 3. Create a function that counts vowel and consonant letters in a string. 54 | # RU: Создайте функцию, которая подсчитывает гласные и согласные буквы в строке. 55 | 56 | # def vowels_and_constants(sentence): 57 | # vowels = 0 58 | # constants = 0 59 | # vowels1 = 'A', 'E', 'I', 'O', 'U', 'Y' 60 | # constants1 = list('BCDFGHJKLMNPQRSTVWXYZ') 61 | 62 | # for letter in sentence: 63 | # if letter.upper() in vowels1: 64 | # vowels += 1 65 | # elif letter.upper() in constants1: 66 | # constants += 1 67 | # return f"Гласные буквы в тексте: {vowels} \nСогласные буквы в тексте: {constants}" 68 | # sentence = "ABCDEFG" 69 | # print(vowels_and_constants(sentence)) 70 | 71 | # ========================================================================================== 72 | # 4. Write a program that takes a list of numbers as input and 73 | # returns the sum of the even numbers. 74 | # RU: Напишите программу, которая принимает список чисел в качестве входных 75 | # данных и возвращает сумму четных чисел. 76 | 77 | # def sum_even_nums(nums): 78 | # even_nums = 0 79 | 80 | # for num in nums: 81 | # if num % 2 == 0: 82 | # even_nums += num 83 | # return even_nums 84 | 85 | # nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 86 | # print(sum_even_nums(nums)) 87 | 88 | # ========================================================================================== 89 | # 5. Write a Python program to find those numbers which are 90 | # divisible by 7 and multiples of 5, between 1500 and 2700 91 | # (both included). 92 | # RU: Напишите программу на Python для поиска тех чисел, 93 | # которые делятся на 7 и кратны 5, в диапазоне от 1500 до 2700 94 | # (включительно). 95 | 96 | # 7 and 5 97 | # 1500 and 2700 98 | 99 | # def find_numbers(): 100 | # result=[] 101 | # for i in range(1500,2701): 102 | # if i %35==0: 103 | # result.append(i) 104 | # return result 105 | # print(find_numbers()) 106 | 107 | # ========================================================================================== 108 | # INTERMEDIATE LEVEL 109 | 110 | # 1. Find an average number of given numbers of the list 111 | # and return nearest integer from given list 112 | # RU: Найти среднее число данного списка и вернуть ближайшее 113 | # целое число из данного списка. 114 | # INPUT: [1, 10, 40, 35, 20, 30, 50, 60, 70] 115 | # OUTPUT: 37.777... => 35 => index-3 116 | 117 | 118 | # def blizko_average(lst): 119 | # srz = sum(lst) / len(lst) 120 | # blizko = round(srz) 121 | # index = lst.index(blizko) 122 | # return blizko, index 123 | 124 | # lst = [1, 10, 40, 35, 20, 30, 50, 60, 70] 125 | # blizko, index = blizko_average(lst) 126 | # print('Среднее значнеие:', sum(lst) / len(lst)) 127 | # print('Ближайший:', blizko) 128 | # print('Индекс:', index) 129 | 130 | 131 | # ========================================================================================== 132 | 133 | # 2. Print stars (*) in the shape of a pyramid with N number of steps. 134 | # pyramid(4) => 135 | # * 136 | # *** 137 | # ***** 138 | # ******* 139 | 140 | # def pyramid(n): 141 | # i = 1 142 | # while i <= n: 143 | # print(" "*(n-i) + "*"*(2*i-1)) 144 | # i += 1 145 | # print(" "*(n-1)) 146 | # pyramid(10) 147 | 148 | 149 | # ========================================================================================== 150 | # 4. Write a Python program to construct the following pattern, 151 | # using a nested for loop. 152 | # RU: Напишите программу на Python для построения следующего узора, 153 | # используя вложенный цикл for. 154 | # * 155 | # * * 156 | # * * * 157 | # * * * * 158 | # * * * * * 159 | # * * * * 160 | # * * * 161 | # * * 162 | # * 163 | 164 | # def pattern(n): 165 | # for i in range(n): 166 | # print('* '*i) 167 | # for i in range(n): 168 | # print('* '*(n-i)) 169 | 170 | # pattern(5) 171 | # ========================================================================================== 172 | 173 | 174 | 175 | # 5. Write a program that takes a range of 100 numbers 176 | # and checks if the number is dividible to 3, 5 or both. 177 | # Then takes these numbers and sums them all together 178 | # ---------------------------------------------------- 179 | # RU: Программа принимает диапазон 100 чисел и проверяет, 180 | # делится ли число на 3, 5 или на оба. Затем возмите эти числа 181 | # и суммируйте их всех вместе и скажите какое число ЧЁТНОЕ ИЛИ НЕТ. 182 | def сумма_кратных_чисел(): 183 | pass 184 | 185 | # ========================================================================================== 186 | 187 | # 6. Write a program that prints out the first 100 prime numbers. 188 | # RU: Напишите программу, которая выводит первые 100 простых чисел. 189 | # prime_numbers = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ... 190 | def n_prime_numbers(n): 191 | pass 192 | 193 | # ========================================================================================== 194 | 195 | # 7. Write a program that calculates the sum of the first 1000 Fibonacci numbers. 196 | # RU: Напишите программу, которая вычисляет сумму первых 1000 чисел Фибоначчи. 197 | def sum_fibonacci(n): 198 | pass 199 | 200 | # ========================================================================================== 201 | 202 | # 8. Write a program that generates a random password of length 20. 203 | 204 | # import random 205 | 206 | # def create_password_of_length(): 207 | # letters = "abcdefghijklmnopqrstuvwxyz" 208 | # letters_ru = "абвгдеёжз" 209 | # numbers = "1234567890" 210 | # symbols = "!@#$%^&()_+<>?/;:" 211 | # total_sybols_for_password = 20 212 | 213 | # everything_includes = letters + letters_ru + numbers + symbols 214 | # created_password = "" 215 | 216 | # for i in range(total_sybols_for_password): 217 | # random_int = random.randint(0, len(everything_includes)-1) 218 | # created_password += everything_includes[random_int] 219 | # print(created_password) 220 | # create_password_of_length() 221 | # ========================================================================================== 222 | 223 | # * 224 | # * * 225 | # * * * 226 | # * * * * 227 | # * * * * * 228 | 229 | # def pattern(n): 230 | # i = 1 231 | # while i <= n: 232 | # print ("* "*(1*i-1)) 233 | # i += 1 234 | # print ("* "*(1*i-1)) 235 | # pattern(5) 236 | # ========================================================================================== 237 | -------------------------------------------------------------------------------- /LessonsExersisesAll/PythonList280EX.py: -------------------------------------------------------------------------------- 1 | ##PYTHON ##LIST ##EXERSISES 2 | # ================================================================ 3 | 4 | # 1. Write a Python program to sum all the items in a list. 5 | #RU: 1. Напишите программу на Python для суммирования всех элементов списка. 6 | 7 | # a = [1,2,3,4,5,6,7,8,9,10] 8 | # c = 0 9 | # for i in a: 10 | # c += i 11 | # print (c) 12 | 13 | # or 14 | 15 | # a = [1,2,3,4,5,6,7,8,9,10] 16 | # print(sum(a)) 17 | # ================================================================ 18 | 19 | # 2. Write a Python program to multiply all the items in a list. 20 | #RU: 2. Напишите программу на Python для умножения всех элементов списка. 21 | 22 | # a = [1,2,3,4] 23 | # b = 1 24 | # for items in a: 25 | # b *= items 26 | # print(b) 27 | # ================================================================ 28 | 29 | # 3. Write a Python program to get the largest number from a list. 30 | # RU: 3.Напишите программу на Python, чтобы получить наибольшее число из списка. 31 | 32 | # a = [1,2,3,4,5] 33 | # largest = a[0] 34 | # for items in a: 35 | # if items > largest: 36 | # largest = items 37 | # print(largest) 38 | 39 | #or 40 | 41 | # a = [1,2,3,4,5] 42 | # print(max(a)) 43 | # ================================================================ 44 | 45 | # 4. Write a Python program to get the smallest number from a list. 46 | # RU: 4. Напишите программу на Python, чтобы получить наименьшее число из списка. 47 | 48 | # a = [1,2,3,4,5] 49 | # smallest = a[1] 50 | # for items in a: 51 | # if items < smallest: 52 | # smallest = items 53 | # print(smallest) 54 | 55 | #or 56 | 57 | # a = [1,2,3,4,5] 58 | # print(min(a)) 59 | # ================================================================ 60 | 61 | # 5. Write a Python program to count the number of strings from a given list of strings. The string length is 2 or more and the first and last characters are the same. 62 | # Sample List : ['abc', 'xyz', 'aba', '1221'] 63 | # Expected Result : 2 64 | # RU: 5. Напишите программу на Python для подсчета количества строк из заданного списка строк. 65 | # Длина строки составляет 2 или более, а первый и последний символы совпадают. 66 | # Список образцов: ['abc', 'xyz', 'aba', '1221'] 67 | # Ожидаемый результат: 2 68 | 69 | # a = ['istam', 'shaxa', 'av', 'aba'] 70 | # for i in a: 71 | # if len(i) >= 2: 72 | # if i == i[::-1]: 73 | # print(a.index(i)) 74 | 75 | #or with function (def) 76 | 77 | # def count_strings(strings): 78 | # for i in strings: 79 | # if len(i) >= 2 and i[0] == i[-1]: 80 | # return strings.index(i) 81 | # print(count_strings(['abc', 'xyz','qwert', '1221', 'aba'])) 82 | # ================================================================ 83 | 84 | # 6. Write a Python program to get a list, sorted in increasing order by the last element in 85 | # each tuple from a given list of non-empty tuples. 86 | # Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] 87 | # Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] 88 | # RU: 6. Напишите программу на Python, чтобы получить список, отсортированный в порядке 89 | # возрастания по последнему элементу в каждом кортеже из заданного списка непустых кортежей. 90 | # Список образцов: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] 91 | # Ожидаемый результат: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] 92 | 93 | 94 | # tuples = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] 95 | # sorted_tuples = sorted(tuples, key=lambda у: у[-1]) 96 | # print(sorted_tuples) 97 | # ================================================================ 98 | 99 | # 7. Write a Python program to remove duplicates from a list. 100 | # RU: 7. Напишите программу на Python для удаления дубликатов из списка. 101 | 102 | # a = ['a','b','c','a'] 103 | # print(sorted(set(a))) 104 | 105 | #or 106 | 107 | # a = [10,20,30,20,10,50,60,40,80,50,40] 108 | # dup_i = set() 109 | # uniq_i = [] 110 | # for x in a: 111 | # if x not in dup_i: 112 | # uniq_i.append(x) 113 | # dup_i.add(x) 114 | # print(sorted(dup_i)) 115 | # ================================================================ 116 | 117 | # 8. Write a Python program to check if a list is empty or not. 118 | #RU : 8. Напишите программу на Python, проверяющую, пуст ли список или нет 119 | 120 | # l = [13] 121 | # if not l: 122 | # print("Список пуст") 123 | # else: 124 | # print("список полный") 125 | # ================================================================ 126 | 127 | # 9. Write a Python program to clone or copy a list. 128 | # RU: 9. Write a Python program to clone or copy a list. 129 | 130 | # list1 = ['a','b','c'] 131 | # copy_list = list(list1.copy()) 132 | # copy_list.insert(0,'s') 133 | 134 | # print(f"original_list: {list1}") 135 | # print(f"copy_list: {copy_list}") 136 | # ================================================================ 137 | 138 | # 10. Write a Python program to find the list 139 | # of words that are longer than n from a given list of words. 140 | #RU: 10. Напишите программу на Python, 141 | # чтобы найти список слов длиной более n из заданного списка слов. 142 | 143 | # def find_list(n,lis:list): 144 | # for i in lis: 145 | # if len(i) == n: 146 | # print(i) 147 | # find_list(5, ['istam','rusik',"shax"]) 148 | # ================================================================ 149 | 150 | # 11. Write a Python function that takes two lists and 151 | # returns True if they have at least one common member. 152 | # RU: 11. Напишите функцию Python, которая принимает два списка и возвращает True, 153 | # если у них есть хотя бы один общий член. 154 | 155 | # def common_members(list1,list2): 156 | # result = '' 157 | # for i in list1: 158 | # for x in list2: 159 | # if i == x: 160 | # result = 'Есть одинаковый' 161 | # return result 162 | # print(common_members([1,2,3,4,5], [5,6,7,8,9])) 163 | # print(common_members([1,2,3,4,5], [6,7,8,9])) 164 | # ================================================================ 165 | 166 | # 12. Write a Python program to print a specified 167 | # list after removing the 0th, 4th and 5th elements. 168 | # Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] 169 | # Expected Output : ['Green', 'White', 'Black'] 170 | # RU:12. Напишите программу на Python для печати указанного списка после удаления 171 | # 0-го, 4-го и 5-го элементов. 172 | # Список образцов: ['Красный', 'Зеленый', 'Белый', 'Черный', 'Розовый', 'Желтый'] 173 | # Ожидаемый результат: ['Зеленый', 'Белый', 'Черный'] 174 | 175 | # a = ['Красный', 'Зеленый', 'Белый', 'Черный', 'Розовый', 'Желтый'] 176 | # print(f"original list: {a}") 177 | # b = a.copy() 178 | # b.remove(a[0]) 179 | # b.remove(a[4]) 180 | # b.remove(a[5]) 181 | # print(f"copy list: {b}") 182 | 183 | #or with LIST COMPREHENSION 184 | 185 | # a = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] 186 | # print(f"before: {a}") 187 | # a = [x for (i,x) in enumerate(a) if i not in (0,4,5)] 188 | # print(f"after: {a}") 189 | # ================================================================ 190 | 191 | # 13. Напишите программу на Python для печати чисел указанного 192 | # списка после удаления из него четных чисел. 193 | 194 | # a = [1,2,3,4,5,6,7,8,9,10] 195 | # a = [i for i in a if i %2 != 0] 196 | # print(a) 197 | # ================================================================ 198 | 199 | # 15. Напишите программу на Python для перетасовки и печати указанного списка. 200 | 201 | # from random import shuffle 202 | # a = ["apple", "orange", "istam", "rustam", "shaxa"] 203 | # print(f"original {a}") 204 | # shuffle(a) 205 | # print(f"shuffle {a}") 206 | # ================================================================ 207 | -------------------------------------------------------------------------------- /LessonsExersisesAll/PythonString113EX.py: -------------------------------------------------------------------------------- 1 | #1. Напишите программу на Python для вычисления длины строки. 2 | 3 | # def calculate_string (string): 4 | # return(len(string)) 5 | # print(calculate_string('istam')) 6 | #--------------------------------------------------------------------------------------- 7 | 8 | #2. Напишите программу на Python для подсчета количества символов (частоты символов) в строке. 9 | # Пример строки: google.com. 10 | # Ожидаемый результат: {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm' : 1} 11 | 12 | # def count_characters (string): 13 | # dict = {} 14 | # for i in string: 15 | # keys = dict.keys() 16 | # if i in keys: 17 | # dict[i] += 1 18 | # else: 19 | # dict[i] = 1 20 | # return dict 21 | # print(count_characters('Istam_122')) 22 | #--------------------------------------------------------------------------------------- 23 | 24 | #3. Напишите программу на Python, чтобы получить строку, состоящую из первых двух и последних двух символов заданной строки. Если длина строки меньше 2, вместо этого верните пустую строку. 25 | # Пример строки: 'w3resource' 26 | # Ожидаемый результат: 'w3ce' 27 | # Пример строки: 'w3' 28 | # Ожидаемый результат: 'w3w3' 29 | # Пример строки: 'w' 30 | # Ожидаемый результат: пустая строка 31 | 32 | #1 33 | # def string_first_and_last_two_letters (string): 34 | # return(string[:2:] + string[5::]) 35 | # print(string_first_and_last_two_letters('i3stam3')) 36 | 37 | #2 38 | # def string_first_and_last_two_letters(string): 39 | # if len(string) < 2: 40 | # return '' 41 | # return string[0:2] + string[-2:] 42 | 43 | # print(string_first_and_last_two_letters('Istam')) 44 | # print(string_first_and_last_two_letters('I2')) 45 | # print(string_first_and_last_two_letters('I')) 46 | #--------------------------------------------------------------------------------------- 47 | 48 | # 4. Напишите программу на Python, чтобы получить строку из заданной строки, в которой все вхождения ее первого символа были изменены на «$», за исключением самого первого символа. 49 | # Пример строки: «restart». 50 | # Ожидаемый результат: «resta$t». 51 | 52 | # def update_character(string): 53 | # char = string[0] 54 | # string = string.replace(char, '$') 55 | # string = char + string[1::] 56 | # return string 57 | # print(update_character('istaiimii')) 58 | #--------------------------------------------------------------------------------------- 59 | 60 | # 5. Напишите программу на Python, чтобы получить одну строку из двух заданных строк, разделенных пробелом, и поменять местами первые два символа каждой строки. 61 | # Пример строки: «abc», «xyz». 62 | # Ожидаемый результат: «xyc abz». 63 | 64 | # def fifth_ex (string, string1): 65 | # new_string = string1[:2] + string[2:] 66 | # new_string1 = string[:2] + string1[2:] 67 | # return new_string + ' ' +new_string1 68 | 69 | # print(fifth_ex('abc','der')) 70 | #--------------------------------------------------------------------------------------- 71 | 72 | # 6. Напишите программу на Python, добавляющую «ing» в конец заданной строки 73 | # (длина должна быть не менее 3). Если данная строка уже заканчивается на «ing», 74 | # добавьте вместо нее «ly». Если длина данной строки меньше 3, оставьте ее без изменений. 75 | # Пример строки: 'abc' 76 | # Ожидаемый результат: 'abcing' 77 | # Пример строки: 'string' 78 | # Ожидаемый результат: 'stringly' 79 | 80 | # def last_ing (string): 81 | # simb = len(string) 82 | # if simb < 3: 83 | # return string 84 | # elif string[-3:]== 'ing': 85 | # return string + 'ly' 86 | # else: 87 | # return string + 'ing' 88 | # print(last_ing('istam')) 89 | #--------------------------------------------------------------------------------------- 90 | 91 | # 8. Напишите функцию Python, которая принимает 92 | # список слов и возвращает самое длинное слово и длину самого длинного слова. 93 | # Пример вывода: 94 | # Самое длинное слово: Упражнения 95 | # Длина самого длинного слова: 9. 96 | 97 | # def max_word (string_list): 98 | # a = [] 99 | # for i in string_list: 100 | # a.append((len(i), i)) 101 | # a.sort() 102 | # return a[-1][0], a[-1][1] 103 | # result = max_word(["shaxa", "istam", "pythonnomberone"]) 104 | # print("max:",result[1]) 105 | # print("len_max:",result[0]) 106 | #--------------------------------------------------------------------------------------- 107 | 108 | # 9. Напишите программу на Python для удаления n-го 109 | # индексного символа из непустой строки. 110 | 111 | # def remove_nth_index(string, index): 112 | # return(string [:index] + string[index +1:]) 113 | # print(remove_nth_index('istam',2)) 114 | #--------------------------------------------------------------------------------------- 115 | 116 | # 10. Напишите программу Python для изменения заданной строки на новую строку, 117 | # в которой первый и последний символы поменялись местами. 118 | 119 | # numbers = [1, 2, 3, 4, 5] 120 | # numbers[0], numbers[-1] = numbers[-1], numbers[0] 121 | # print(numbers) 122 | #--------------------------------------------------------------------------------------- 123 | 124 | # 11. Напишите программу на Python для удаления символов, 125 | # имеющих нечетные индексные значения в данной строке. 126 | 127 | # string = "123456789" 128 | # string1 = "" 129 | # for i in range(len(string)): 130 | # if i % 2: 131 | # string1 += string[i] 132 | # print(string1) 133 | #--------------------------------------------------------------------------------------- 134 | 135 | # 12. Напишите программу на Python для подсчета вхождений 136 | # каждого слова в заданном предложении. 137 | 138 | # def count_characters (string): 139 | # dict={} 140 | # for i in string.split(' '): 141 | # dict=dict|{i:string.split(' ').count(i)} 142 | # return dict 143 | # print(count_characters('Istam12 fdgfg fgdd fgdd')) 144 | #--------------------------------------------------------------------------------------- 145 | 146 | # 13. Напишите сценарий Python, который принимает вводимые пользователем 147 | # данные и отображает их обратно в верхнем и нижнем регистре. 148 | 149 | # def cases (string): 150 | # user_input = input('please write text: ') 151 | # a = user_input.lower() 152 | # b = user_input.upper() 153 | # return (f"lower text {a} , Upper text {b}") 154 | # print(cases('string')) 155 | #--------------------------------------------------------------------------------------- 156 | 157 | # 14. Напишите программу на Python, которая принимает на вход 158 | # последовательность слов, разделенных запятыми, 159 | # и печатает отдельные слова в отсортированной форме (буквенно-цифровом формате). 160 | # Примеры слов: red, black, pink, green. 161 | # Ожидаемый результат: black, green, pink, red. 162 | 163 | # def sort_words(): 164 | # items = input("напишите слова с запятой: ") 165 | # words = [word for word in items.split(",")] 166 | # sorted_words = sorted(list(set(words))) 167 | # return ",".join(sorted_words) 168 | # print(sort_words()) 169 | #--------------------------------------------------------------------------------------- 170 | 171 | # 16. Напишите функцию Python для вставки строки в середину строки. 172 | # Пример функции и результат: 173 | # Insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]] 174 | # Insert_sting_middle('{{}}', 'PHP') -> {{PHP}} 175 | 176 | # def center_text(str, word): 177 | # return str[:3] + word + str[3:]\ 178 | # print(center_text('[[[]]]', 'Python')) 179 | # print(center_text('{{{}}}', 'C++')) 180 | # print(center_text('<<<>>>', 'HTML')) 181 | #--------------------------------------------------------------------------------------- 182 | 183 | # 17. Напишите функцию Python, чтобы получить строку, состоящую из 4 184 | # копий последних двух символов указанной строки (длина должна быть не менее 2). 185 | # Пример функции и результата: 186 | # Insert_end('Python') -> onononon 187 | # Insert_end('Упражнения') -> eseseses 188 | 189 | # def string_last_two(string): 190 | # return string + string[-2::] *4 191 | # print(string_last_two('Python')) 192 | #--------------------------------------------------------------------------------------- 193 | 194 | # 18. Напишите функцию Python для получения строки, 195 | # состоящей из первых трех символов указанной строки. 196 | # Если длина строки меньше 3, верните исходную строку. 197 | # Пример функции и результата: 198 | # first_three('ipy') -> ipy 199 | # first_three('python') -> pyt 200 | 201 | # def first_three(string): 202 | # if len(string) < 3: 203 | # return string 204 | # else: 205 | # return string + string[:3] * 3 206 | # print(first_three("Python")) 207 | #--------------------------------------------------------------------------------------- 208 | 209 | # 20. Напишите функцию Python для переворачивания строки, 210 | # если ее длина кратна 4. 211 | 212 | # def revers_text(string): 213 | # if len(string) % 4 == 0: 214 | # return ''.join(reversed(string)) 215 | # return string 216 | # print(revers_text("ista")) 217 | # print(revers_text("istam")) 218 | #--------------------------------------------------------------------------------------- 219 | -------------------------------------------------------------------------------- /Mini_Games_And_Projects/GuessNumber.py: -------------------------------------------------------------------------------- 1 | # NUMBER GUESSING GAME => Угадай число 2 | 3 | wants_again = True 4 | 5 | while wants_again: 6 | import random 7 | lives = 7 8 | random_number = random.randint(1, 50) 9 | guessed_number = int(input("Enter a number from 1 to 50: ")) 10 | 11 | while random_number != guessed_number: 12 | lives -= 1 13 | 14 | if guessed_number < random_number: 15 | print("Your number is too low!!!") 16 | elif guessed_number > random_number: 17 | print("Your number is too high!!!") 18 | 19 | if lives > 0: 20 | print(f"You have {lives} lives left.") 21 | guessed_number = int(input("Guess again: ")) 22 | else: 23 | break 24 | 25 | def show_result(type): 26 | match type: 27 | case "win": 28 | print(f"You win!!!") 29 | case "lose": 30 | print(f"You lose!!!") 31 | 32 | 33 | if lives == 0: 34 | if random_number == guessed_number: 35 | show_result("win") 36 | else: 37 | show_result("lose") 38 | print(f'The number was {random_number}') 39 | elif random_number == guessed_number: 40 | show_result("win") 41 | else: 42 | show_result("lose") 43 | print(f'The number was {random_number}') 44 | 45 | print(f"You have {lives} lives left.") 46 | 47 | 48 | if input("Would you like to play again? (y/n): ") == "y": 49 | wants_again = True 50 | else: 51 | print("Game Over Goodbye!!!") 52 | wants_again = False -------------------------------------------------------------------------------- /Mini_Games_And_Projects/HelloWorld_with_cycle.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def printCharacter(text = "Hello World", interval = 100): 4 | alp = "1234567890!@#$%^&*()_+-=QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnmАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя " 5 | i = 0 6 | result = "" 7 | while True: 8 | print(result + alp[i]) 9 | if alp[i] == text[len(result)]: 10 | result += alp[i] 11 | i += 1 12 | if i == len(alp): 13 | i = 0 14 | if len(result) == len(text): 15 | break 16 | time.sleep(interval / 500) 17 | 18 | printCharacter("Istam", 10) -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/__init__.py -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/__pycache__/app.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/__pycache__/app.cpython-312.pyc -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/__pycache__/constructor.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/__pycache__/constructor.cpython-311.pyc -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/__pycache__/constructor.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/__pycache__/constructor.cpython-312.pyc -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/app.py: -------------------------------------------------------------------------------- 1 | from constructor import Quiz 2 | import random 3 | import playsound 4 | import msvcrt 5 | 6 | 7 | # Questions in a list for first level 8 | level_one = [ 9 | '>>>>\n\nThere are 17-floors in apartmant. On the first floor there are only 4 people living,\nbut the more you gohigher, the more the number of people is increasing in double. \nSo, which number of the elevator is being pushed the most each day? \na) Last floor \nb) First floor \nc) Middle floor \nd) All floors are equal\n\n', 10 | '>>>>\n\nIn the lake there are 30 hungry Sharks that eat each other constantly. \nA Shark is full when he ate 3 other sharks hungry or full. What number of sharks will have eaten totally 3 of them in the end? \na) 9 \nb) 7 \nc) 2 \nd) 0\n\n', 11 | '>>>>\n\nGeorge, Andrey and Sasha - friends. George is real brother of Andrey. \nAndrey is real brother of Sasha. But is not their brother. Why? \na) He is UFO \nb) He hates them both \nc) She is girl \nd) It was a trick \n\n', 12 | '>>>>\n\n100 students learned English and German languages simultoneously. \nAt the end of course they give an exam which showed that 10 of them could not pass neither English \nnor German subject. From others who left, 75 passed German and 83 passed English. How many of students know both languages? \na) 75 \nb) 68 \nc) 88 \nd) 10 \n\n', 13 | '>>>>\n\nThere are a group of Caterpillars going on. One is ahead, two are behind. \nOne is behind, two are ahead and one is between. How many of them in a group? \na) 2 \nb) 3 \nc) 4 \nd) 5\n\n', 14 | '>>>>\n\nWhich one is heavier, 1kg of Cotton or 1kg of Iron? \na) Iron \nb) Cotton \nc) None \nd) Equal \n\n', 15 | '>>>>\n\nThree huge Chickens can eat three fattest Caterpillars in three minutes. \nHow much time would it take if thirty Chickens were about to eat thirty Caterpillars? \na) 3 \nb) 5 \nc) 10 \nd) 30 \n\n', 16 | '>>>>\n\nThe treasure hunter made his way to an uninhabited island in the Caribbean using an old map. \nHe wandered for several hours in the dense tropics, untill he came across a tribe of local Aborigens. \nThe tribal elder decided to kill the intruder immediately, but first decided to mock him. \nThe treasure hunter could only say the last phrase in his life. If it turns out to be true, \nthen he will be thrown from the mountain onto rocky shore. If the phrase turns out to be lie, \nthe wanderer will be torn apart by lions. However, the treasur hunter managed to escape. \nWhat was his phrase after which the elder was forced to release the treasure hunter??? \n\na) I am being torn apart by lions \nb) I want to jump from mountains to rocky shore \nc) I am sorry \nd) I do not want to die \n\n', 17 | '>>>>\n\nIn the room there are four corners and at each corner there is a cat. \nIn front of each cat there are 3 cats. How many cats are there in total? \na) 16 \nB) 12 \nc) 3 \nd) 4 \n\n', 18 | ">>>>\n\nAlex's grandfather was going home on foot on a sunny and beautiful day. And suddenly rain started pouring and he went home soaking wet. But when he got home not a single hair on his head got wet, Why? \na) He was ill \nb) He ran too fast \nc) He met a friend \nd) He had't any \n\n", 19 | '>>>>\n\nTwo children can create two bicycles in two hours. How many children required to create 12 bicycles in 6 hours? \na) 2 \nb) 3 \nc) 4 \nd) 5 \n\n', 20 | '>>>>\n\nYou were given this, and it belongs to you now. You have never passed it on to anyone, but all your friends use it. What is it? \na) Skill \nb) Age \nc) Ability \nd) Name \n\n', 21 | '>>>>\n\nI never was, am always to be. Noone ever saw me, nor ever will, and yet i am the confidence of all, Who am I ??? \na) Earth \nb) Sun \nc) Air \nd) Future \n\n' 22 | ] 23 | # Questions in a list for second level 24 | level_two = [ 25 | "\n>>Lelvel-2>>\n -In what part of the body do you find Fibula? \na) Head \nb) Arms \nc) Legs \nd) Everywhere in the body \n\n", 26 | "\n>>Lelvel-2>>\n -If you have Crypthofhobia, what are you afraid of? \na) Crypto Currency \nb) Hot Weather \nc) Nature \nd) Ice and Cold \n\n", 27 | "\n>>Lelvel-2>>\n -According to ONS, What was the most popular boy's name in the UK in 2018? \na) Jozeph \nb) George \nc) Oliver \nd) Stephen \n\n", 28 | "\n>>Lelvel-2>>\n -Which popular video game franchise has released games with the subtitles -World At War- and -Black Ops- ? \na) World Of Warcraft \nb) Call of Duty \nc) Darksiders \nd) Alice in Wonderland \n\n", 29 | "\n>>Lelvel-2>>\n -What is chemical symbol for Silver? \na) Ag \nb) h2o \nc) Ac \nd) Al \n\n", 30 | "\n>>Lelvel-2>>\n -What is the capital city of Switzerland? \na) Regensdorf \nb) Zofingen \nc) Geneva \nd) Bern \n\n", 31 | "\n>>Lelvel-2>>\n -What is the smallest planet in our solar system? \na) Mercury \nb) Venus \nc) Earth \nd) Mars \n\n", 32 | "\n>>Lelvel-2>>\n -What does the Latin Tempus mean in English? \na) Hello \nb) Time \nc) Ruler \nd) Future \n\n", 33 | "\n>>Lelvel-2>>\n -What is seven cubed? \na) 343 \nb) 49 \nc) 250 \nd) 7+7+7 \n\n", 34 | "\n>>Lelvel-2>>\n -How many sonnets did Shakespeare write? \na) 117 \nb) 154 \nc) 300+ \nd) He did not write any \n\n" 35 | ] 36 | 37 | def make_questions(): 38 | questions = [ 39 | Quiz(level_one[0], 'b'), 40 | Quiz(level_one[1], 'a'), 41 | Quiz(level_one[2], 'c'), 42 | Quiz(level_one[3], 'b'), 43 | Quiz(level_one[4], 'b'), 44 | Quiz(level_one[5], 'd'), 45 | Quiz(level_one[6], 'a'), 46 | Quiz(level_one[7], 'a'), 47 | Quiz(level_one[8], 'd'), 48 | Quiz(level_one[9], 'd'), 49 | Quiz(level_one[10], 'c'), 50 | Quiz(level_one[11], 'd'), 51 | Quiz(level_one[12], 'd')] 52 | 53 | 54 | questions_lv_two = [ 55 | Quiz(level_two[0], 'c'), 56 | Quiz(level_two[1], 'd'), 57 | Quiz(level_two[2], 'c'), 58 | Quiz(level_two[3], 'b'), 59 | Quiz(level_two[4], 'a'), 60 | Quiz(level_two[5], 'd'), 61 | Quiz(level_two[6], 'a'), 62 | Quiz(level_two[7], 'b'), 63 | Quiz(level_two[8], 'a'), 64 | Quiz(level_two[9], 'b'), 65 | ] 66 | return questions, questions_lv_two 67 | 68 | def run_code(questions): # First level start-code 69 | score = 0 70 | for question in questions: 71 | answer = input(question.prompt + 'Answer: ').lower() 72 | if answer == question.answer: 73 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\right.mp3') 74 | score += 1 #you must specify the path to the folder on your computer 75 | else: 76 | print("Oh no, Wrong...") 77 | print(f"The answer is (({question.answer}))") 78 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\wrong.mp3') 79 | #you must specify the path to the folder on your computer 80 | print(f"\n\n\n\n You got {score} / {len(questions)} correnct!") 81 | 82 | 83 | 84 | if score > 7: # Finish 1st level with some comment 85 | random.shuffle(questions_lv_two) # And get to the 2nd level-code 86 | lev_two_score = 0 87 | print(" You got right more than half of questions and can get on to next level...") 88 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\lv_up.mp3') 89 | #you must specify the path to the folder on your computer 90 | 91 | for quiz_two in questions_lv_two: # Loop through second ques.-list 92 | answer = input(quiz_two.prompt + 'Answer: ').lower() 93 | if answer == quiz_two.answer: 94 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\right.mp3') 95 | score += 1 #you must specify the path to the folder on your computer 96 | lev_two_score += 1 97 | else: 98 | print("Bad luck...try next>>>") 99 | print(f"The answer is (({quiz_two.answer}))") 100 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\wrong.mp3') 101 | #you must specify the path to the folder on your computer 102 | 103 | 104 | 105 | if score > 12: # Demonstration of the result 106 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\triumph.mp3') 107 | #you must specify the path to the folder on your computer 108 | print(f'You got {lev_two_score} / {len(questions_lv_two)}, ---WELL DONE---, You are very smart person...') 109 | elif score <= 10: 110 | print(f"You got {lev_two_score} / {len(questions_lv_two)}. In total you earned {score} scores.") 111 | 112 | 113 | 114 | 115 | while True: 116 | print("\n If you would like to try again press --ENTER--\n") # Ask for one more time 117 | key = ord(msvcrt.getch()) 118 | if key == 13: 119 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\sweet.mp3') 120 | random.shuffle(questions) 121 | run_code(questions) 122 | else: 123 | print("Thank you for playing ... Hope to see you again...") 124 | playsound.playsound('D:\\Pythonres\\Mini_Games_And_Projects\\Quiz-Game-main\\sweet.mp3') 125 | break 126 | 127 | if __name__ == '__main__': 128 | questions, questions_lv_two = make_questions() 129 | random.shuffle(questions) 130 | run_code(questions) 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/constructor.py: -------------------------------------------------------------------------------- 1 | class Quiz: 2 | def __init__(self, prompt, answer): 3 | self.prompt = prompt 4 | self.answer = answer 5 | 6 | -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/lv_up.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/lv_up.mp3 -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/right.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/right.mp3 -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/sweet.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/sweet.mp3 -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from app import make_questions 3 | 4 | class TestQuiz(unittest.TestCase): 5 | 6 | def test_questions_contstructor(self): 7 | questions, _ = make_questions() 8 | self.assertTrue( isinstance(questions, list) ) 9 | 10 | def test_question_attributes(self): 11 | # we will test that each question has a prompt and an answer 12 | questions, _ = make_questions() 13 | for entry in questions: 14 | self.assertIsNotNone(entry.prompt) 15 | self.assertIsNotNone(entry.answer) 16 | 17 | if __name__ == '__main__': 18 | unittest.main() -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/triumph.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/triumph.mp3 -------------------------------------------------------------------------------- /Mini_Games_And_Projects/Quiz-Game-main/wrong.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/Mini_Games_And_Projects/Quiz-Game-main/wrong.mp3 -------------------------------------------------------------------------------- /POSTGRES/1-First-lesson.md: -------------------------------------------------------------------------------- 1 | 1. Introduction and Creating first table 2 | 3 | # Create table 4 | ```sql 5 | CREATE TABLE users ( 6 | id SERIAL PRIMARY KEY, 7 | name VARCHAR(255), 8 | email VARCHAR(255), 9 | password VARCHAR(255) NOT NULL UNIQUE DEFAULT '12345' 10 | ); 11 | ``` 12 | ___ 13 | # Insert data 14 | ```sql 15 | INSERT INTO users (name, email, password) 16 | VALUES ('John Doe', 'test@gmail.com', '12345'); 17 | ``` 18 | ___ 19 | # Select data 20 | ```sql 21 | SELECT * FROM users; 22 | ``` 23 | ___ 24 | # Update data 25 | ```sql 26 | UPDATE users SET name = 'Jane Doe' WHERE id = 1 27 | ``` 28 | ___ 29 | # Alter table 30 | ```sql 31 | ALTER TABLE users ADD COLUMN age INT 32 | ``` 33 | ___ 34 | # Delete data 35 | ```sql 36 | DELETE FROM users WHERE id = 1 37 | ``` 38 | ___ 39 | # 40 | ```sql 41 | VARCHAR => is used to store strings and text 42 | INT => is used to store integers 43 | SERIAL => is used to auto increment the value 44 | PRIMARY KEY => is used to set the primary key (it is identical to normal id) 45 | NULL => is used to set the field as empty 46 | NOT NULL => is used to set the field as required 47 | UNIQUE => is used to set the field as unique 48 | DEFAULT => is used to set the default value (ex: DEFAULT '...') 49 | ``` -------------------------------------------------------------------------------- /POSTGRES/3-Third-lesson.md: -------------------------------------------------------------------------------- 1 | 3. Syntax items - Continue of the second lesson 2 | 3 | 4 | ```sql 5 | CREATE TABLE Customers ( 6 | id SERIAL PRIMARY KEY, 7 | name VARCHAR(255) NOT NULL, 8 | email VARCHAR(255) NOT NULL 9 | ); 10 | CREATE TABLE Orders ( 11 | id SERIAL PRIMARY KEY, 12 | order_date DATE NOT NULL, 13 | total DECIMAL(10,2) NOT NULL, 14 | customer_id INTEGER NOT NULL, 15 | FOREIGN KEY (customer_id) REFERENCES Customers (id) 16 | ); 17 | INSERT INTO Customers (name, email) 18 | VALUES ('John Doe', 'test@mail.com'); 19 | 20 | INSERT INTO Orders (order_date, total, customer_id) 21 | VALUES ('2022-01-01', 100.00, 1); 22 | 23 | INSERT INTO Orders (order_date, total, customer_id) 24 | VALUES ('2022-02-01', 150.00, 1); 25 | 26 | SELECT * FROM Customers; 27 | SELECT * FROM Orders; 28 | ``` 29 | 30 | 31 | 32 | 33 | ```sql 34 | -- Let's say we have two tables: Students and Courses. 35 | -- Each student can enroll in multiple courses, so we want to create a 36 | -- relationship between the two tables using the FOREIGN KEY constraint. 37 | 38 | CREATE TABLE Students ( 39 | id SERIAL PRIMARY KEY, 40 | name VARCHAR(255) NOT NULL, 41 | email VARCHAR(255) NOT NULL 42 | ); 43 | 44 | CREATE TABLE Courses ( 45 | id SERIAL PRIMARY KEY, 46 | name VARCHAR(255) NOT NULL, 47 | instructor VARCHAR(255) NOT NULL 48 | ); 49 | 50 | CREATE TABLE Enrollments ( 51 | id SERIAL PRIMARY KEY, 52 | student_id INTEGER NOT NULL, 53 | course_id INTEGER NOT NULL, 54 | FOREIGN KEY (student_id) REFERENCES Students (id), 55 | FOREIGN KEY (course_id) REFERENCES Courses (id) 56 | ); 57 | 58 | INSERT INTO Courses (name, instructor) 59 | VALUES ('Math', 'Mr. Smith'), 60 | ('Science', 'Mrs. Smith'), 61 | ('English', 'Mr. Jones'); 62 | 63 | INSERT INTO Students (name, email) 64 | VALUES ('John Smith', 'test@mail.com'), 65 | ('Matthew', 'test2@mail.com'); 66 | 67 | SELECT * FROM students; 68 | 69 | INSERT INTO Enrollments (student_id, course_id) 70 | VALUES 71 | (1, 1), 72 | (1, 2), 73 | (1, 3); 74 | SELECT * FROM Enrollments; 75 | 76 | -- This means that the student with an id of 1 is enrolled in the course with an id of 1 77 | ``` 78 | 79 | 80 | **MONEY** 81 | Working with money 82 | In postgres, the money type is a fixed-point number with two decimal places. It is useful for storing monetary amounts. The money type is not precise, because it rounds to the nearest cent. For example, 83 | 1.005 is stored as 1.01. 84 | 85 | To use the money type, you must specify the amount in the following format: '$100.00'. The dollar sign is required. You can also use the following format: '100.00 USD'. The currency code is optional. 86 | 87 | To create a table with the money type, you use the following syntax: 88 | ```sql 89 | -- 1.000001 => 1.01 90 | 91 | INSERT INTO laptops (id, ip_address, price) 92 | VALUES ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd312a11', '192.168.0.138', '$200'); 93 | 94 | SELECT * FROM laptops; 95 | -- [==============================================================================] 96 | 97 | **SUBSTRING()** - Extracts a substring from a string 98 | ```sql 99 | SYNTAX: SELECT SUBSTRING(column_name, start_position, length) FROM table_name; 100 | 101 | SELECT SUBSTRING(name, 1, 3) AS FirstName FROM students; 102 | This will return the first 3 characters of the first name column 103 | So if: first_name = 'John' 104 | The result will be: 'Joh' 105 | ``` 106 | 107 | **MAX()** - Returns the maximum value in a set of values 108 | ```sql 109 | SELECT MAX(price) FROM products; 110 | ``` 111 | 112 | **MIN()** - Returns the minimum value in a set of values 113 | ```sql 114 | SELECT MIN(price) FROM products; 115 | ``` 116 | 117 | **AVG()** - Returns the average value in a set of values 118 | ```sql 119 | SELECT AVG(price) FROM products; 120 | ``` 121 | 122 | **SUM()** - Returns the sum of all or distinct values in a set of values 123 | ```sql 124 | SELECT SUM(price) FROM products; 125 | ``` 126 | 127 | **COUNT()** - Returns the number of rows that matches a specified criteria 128 | **COUNT(DISTINCT)** - Returns the number of distinct rows that matches a specified criteria 129 | ```sql 130 | SELECT COUNT(*) FROM products; 131 | SELECT COUNT(DISTINCT price) FROM products; 132 | ``` 133 | 134 | **ROUND()** - Rounds a number to a specified number of decimal places 135 | ```sql 136 | SYNTAX: SELECT ROUND(column_name, number_of_decimal_places) FROM table_name; 137 | 138 | SELECT ROUND(price, 2) FROM products; 139 | -- This will return the price column rounded to 2 decimal places 140 | -- ex: 141 | -- price = 10.1234 142 | -- result = 10.12 143 | ``` 144 | 145 | **CONCAT()** - Adds two or more expressions together 146 | ```sql 147 | SELECT CONCAT(first_name, ' ', last_name) AS Full_Name FROM customers; 148 | ``` 149 | 150 | **UNION** - Combines the result of two or more SELECT statements 151 | 152 | The queries in the union must follow these rules: 153 | They must have the same number of columns 154 | The columns must have the same data types 155 | The columns must be in the same order 156 | 157 | NOTE: The UNION operator selects only distinct values by default. 158 | To allow duplicate values, use the UNION ALL operator. 159 | ```sql 160 | -- SELECT * FROM customers; 161 | -- SELECT * FROM students; 162 | 163 | SELECT name, email FROM customers 164 | UNION 165 | SELECT name, email FROM students; 166 | ``` 167 | 168 | **UNION ALL** - Combines the result of two or more SELECT statements, 169 | but it does not remove duplicate rows 170 | ```sql 171 | SELECT first_name, last_name FROM customers 172 | UNION ALL 173 | SELECT first_name, last_name FROM employees; 174 | ``` 175 | 176 | **ORDER BY** - Sorts the result set in ascending or descending order 177 | ```sql 178 | SELECT * FROM customers ORDER BY first_name; 179 | SELECT * FROM customers ORDER BY first_name DESC; 180 | ``` 181 | 182 | **GROUP BY** - Groups rows that have the same values into summary rows 183 | ```sql 184 | SELECT * FROM customers GROUP BY first_name; 185 | 186 | 187 | *Merging two or more columns* 188 | 189 | ```sql 190 | -- Lets say we have a table with the following data: 191 | 192 | -- Customers TABLE 193 | -- ___________________________________________________ 194 | -- -- id | name | surname | full_name | email 195 | -- -- 1 | John | test1 | | John@test.com 196 | -- -- 2 | Mary | test2 | | Mary@test.com 197 | -- -- 3 | Peter | test3 | | Peter@test.com 198 | -- ___________________________________________________ 199 | 200 | -- We want to add a new column called full_name and populate it with the first name and last name 201 | -- We can do this using the CONCAT() function 202 | 203 | -- ALTER TABLE customers ADD COLUMN full_name VARCHAR(255); 204 | -- UPDATE customers SET full_name = CONCAT(name, ', email: ', email); 205 | 206 | ``` -------------------------------------------------------------------------------- /POSTGRES/Task 1.txt: -------------------------------------------------------------------------------- 1 | # 1st exercise of 'postgresql' 2 | 3 | # - Create a table called 'cars' with the following columns: 4 | # it should have unique id always 5 | # RU: уникальный идентификатор 6 | # it should have a Model of the car (as text no more than 20 characters) 7 | # RU: модель автомобиля 8 | # it should have a Year of the car (as integer) 9 | # RU: год выпуска автомобиля 10 | # it should have a Price of the car (as integer) 11 | # RU: цена автомобиля 12 | # it should have color of the car (as text no more than 20 characters) 13 | # RU: цвет автомобиля 14 | # it should have an origin of the car (where it is from ... etc...) 15 | # RU: страна производитель автомобиля 16 | ================================================================================= 17 | # ADD - Добавить в таблицу новую запись 18 | # add at least 5 cars to the table 19 | # each should be unique 20 | ================================================================================= 21 | # UPDATE - Обновить запись в таблице 22 | # update the price of the car with id 3 to 12345 23 | # RU: обновить цену автомобиля с id 3 на 12345 24 | ================================================================================= 25 | # ALTER - Изменить структуру таблицы 26 | # add a column to the table called 'sold' 27 | # RU: добавить в таблицу колонку 'sold' (продано) *BOOLEAN* 28 | # тип данных - boolean (логический тип данных) 29 | ================================================================================= 30 | # UPDATE again - Обновить запись в таблице 31 | # update the sold status of the car with id 4 to True 32 | # RU: обновить статус продажи автомобиля с id 4 на True 33 | ================================================================================= 34 | # DELETE - Удалить запись из таблицы 35 | # delete the car with id 5 from the table 36 | # RU: удалить автомобиль с id 5 из таблицы 37 | 38 | 39 | 40 | # To change the column data type we use ALTER COLUMN 41 | # ALTER COLUMN cars TYPE boolean USING sold::boolean; 42 | 43 | # ALTER TABLE table_name 44 | # ALTER COLUMN column_name [SET DATA] TYPE new_data_type; 45 | 46 | ================================================================================== 47 | ================================================================================== 48 | ================================================================================== -------------------------------------------------------------------------------- /POSTGRES/Task 2.txt: -------------------------------------------------------------------------------- 1 | SECOND EXERCISE. 2 | 3 | 4 | --------------------------------------------------------------------------- 5 | CREATE A TABLE called orders with the following columns: 6 | 7 | order_id, 8 | order_date, 9 | order_cost, 10 | order_status, 11 | shipping_address => CREATE ADDRESS TYPE => (RU: создаем тип адреса) 12 | 13 | ====----> CREATE TYPE address AS (street TEXT, city TEXT, zip INTEGER) <----===== 14 | --------------------------------------------------------------------------- 15 | INSERT INTO orders 5 elements 16 | RU: добавляем 5 элементов 17 | --------------------------------------------------------------------------- 18 | ADD a new column called customer_id 19 | RU: добавляем новую колонку customer_id 20 | --------------------------------------------------------------------------- 21 | CREATE CUSTOMERS TABLE with the following columns: 22 | RU: создаем таблицу customers с колонками: 23 | id 24 | name 25 | email 26 | --------------------------------------------------------------------------- 27 | UPDATE two of the orders' ids with random customer ids that you have created 28 | RU: обновляем два id заказов с рандомными id клиентов, которые вы создали 29 | --------------------------------------------------------------------------- -------------------------------------------------------------------------------- /POSTGRES/Task 3.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/POSTGRES/Task 3.txt -------------------------------------------------------------------------------- /POSTGRES/Task 4.txt: -------------------------------------------------------------------------------- 1 | # Create 2 users and save them into db 2 | 3 | # Ask 3rd time through input to login 4 | # If the email of the user and password the user 5 | # math with the db info, the print "You are logged in" 6 | # Otherwise, print "You entered wrong email or password" 7 | # ====================================================== 8 | # RU: Запросите у пользователя почту и пароль. 9 | # Создайте 2 пользователя и сохраните их в БД 10 | 11 | # Спросите 3-ий раз через input логин 12 | # Если почта пользователя и пароль пользователя 13 | # совпадают с информацией из БД, то напечатать "You are logged in" 14 | # В противном случае, напечатать "You entered wrong email or password" -------------------------------------------------------------------------------- /POSTGRES/create-file.psql: -------------------------------------------------------------------------------- 1 | You can use the pg_dump command to create a backup of your PostgreSQL database as a file. 2 | The pg_dump command is a shell command and should be run in a terminal or command prompt. 3 | 4 | Here"s an example command: 5 | SYNTAX: 'pg_dump -U postgres -h localhost -p 5432 -F c -f база.psql postgres' 6 | 7 | 8 | Replace , , , , and 9 | with the appropriate values for your database. This command will create a backup of your 10 | database as a SQL file. 11 | 12 | -- ===================================================================================== 13 | -- ===================================================================================== 14 | 15 | You can then restore the database from the backup file using the psql command. 16 | 17 | Here"s an example command: 18 | 'pg_restore -U postgres -h localhost -p 5432 -d postgres база.psql' 19 | 20 | Again, replace , , , , and 21 | with the appropriate values for your database. This command will restore the 22 | database from the SQL file. 23 | 24 | NOTE: 25 | By restoring the database from the backup file, you will overwrite any existing data in the database. 26 | The database you have currently selected in psql will be the one overwritten by the restore command. 27 | 28 | -- ===================================================================================== 29 | -- ===================================================================================== 30 | 31 | You can also use the pg_dumpall command to create a backup of all your PostgreSQL databases as a file. -------------------------------------------------------------------------------- /POSTGRES/exam.md: -------------------------------------------------------------------------------- 1 | # We create an input application using input() function in python and use postgresql to store the data. 2 | 3 | 4 | 5 | 6 | 7 | 8 | ## The application is as follows: 9 | 1. **Create psql db to connect (at least 2 more)** 10 | RU: *Создать psql db для подключения (как минимум 2)* 11 | UZ: `Ulanish uchun psql db yaratish (kamida 2 ta)` 12 | 13 | 2. **Ask from user to which db to connect** 14 | RU: *Спросить у пользователя к какой db подключиться* 15 | UZ: `Foydalanuvchidan qaysi db ga ulanishini so'rang` 16 | 17 | 3. **Create class User to hold all user related methods and info** 18 | RU: *Создать класс для хранения всех методов и информации о пользователе* 19 | UZ: `Foydalanuvchi bilan bog'liq metodlarni va ma'lumotlarni saqlash ` 20 | `uchun klass yaratish` 21 | 22 | 4. **Create 2 function to register and login into account (separate from Class)** 23 | RU: *Создать 2 функции для регистрации и входа в аккаунт (Отдельно от Class-а)* 24 | UZ: `Ro'yxatdan o'tish va hisobga kirish uchun 2 ta funksiya yaratish (Class dan ajratilgan holda)` 25 | 26 | 5. **Each time, for new user, create new instance of class and store** 27 | **it in psql db** 28 | RU: *Каждый раз, для нового пользователя, создавать новый экземпляр* 29 | *класса и хранить его в psql db* 30 | UZ: `Har bir yangi foydalanuvchi uchun klassning yangi misolini yaratib,` 31 | `uni psql db da saqlang` 32 | 33 | 6. **Class should have 5 informations about user:** 34 | **- first_name - last_name - email - password - record_points** 35 | RU: *Класс должен иметь 5 информаций о пользователе:* 36 | *- имя - фамилия - почта - пароль - рекорд очков* 37 | UZ: `Klass foydalanuvchi haqida 5 ta ma'lumotlarni saqlash kerak:` 38 | `- ism - familiya - email - parol - rekord baho` 39 | 40 | 7. **Create 4 methods for class:** 41 | **- get_my_points - get my points from db** 42 | **- update_my_points - update my points in db (called if new record)** 43 | **- start_game - start game** 44 | **- end_game - e 45 | nd game** 46 | RU: *Создать 4 метода для класса:* 47 | *- get_my_points - получить мои очки из db* 48 | *- update_my_points - обновить мои очки в db (вызывается если новый рекорд)* 49 | *- start_game - начать игру* 50 | *- end_game - закончить игру* 51 | UZ: `Klass uchun 4 ta metod yaratish:` 52 | `- get_my_points - db dan o'z bahoimni olish` 53 | `- update_my_points - db da o'z bahoimni yangilash (yangi rekord bo'lsa)` 54 | `- start_game - o'yinni boshlash` 55 | `- end_game - o'yinni tugatish` 56 | 57 | 8. **Create number guessing game:** 58 | **- user should guess number from 1 to 100** 59 | **- user should have 6 attempts** 60 | **- each time for incorrect answer, user should be notified** 61 | **and number of attempts should be decreased and shown to the user** 62 | **- if user guessed the number, he should be notified and** 63 | **his record should be updated if he has less attempts than before** 64 | RU: *Создать игру угадывания чисел:* 65 | *- пользователь должен угадать число от 1 до 100* 66 | *- пользователь должен иметь 6 попыток* 67 | *- каждый раз при неправильном ответе, пользователь должен быть уведомлен* 68 | *и количество попыток должно быть уменьшено и показано пользователю* 69 | *- если пользователь угадал число, он должен быть уведомлен и* 70 | *его рекорд должен быть обновлен, если у него меньше попыток, чем раньше* 71 | UZ: `Sonni topish o'yini yaratish:` 72 | `- foydalanuvchi 1 dan 100 gacha bo'lgan sonni topishga harakat qilishi kerak` 73 | `- foydalanuvchining 6 ta urinishi bo'lishi kerak` 74 | `- har bir noto'g'ri javob uchun foydalanuvchi xabardor qilinishi kerak` 75 | `va urinishlar soni kamayishi va foydalanuvchiga ko'rsatilishi kerak` 76 | `- foydalanuvchi sonni topgan bo'lsa, u xabardor qilinishi kerak va` 77 | `agar avvalgi urinishlar sonidan kam bo'lsa, uning rekordi yangilanishi kerak` 78 | 79 | 9. **Every user related info should be stored in psql db** 80 | RU: *Вся информация о пользователе должна храниться в psql db* 81 | UZ: `Foydalanuvchi haqida ma'lumotlar psql db da saqlanishi kerak` 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | > When Terminal starts it shows options of databases and asks the user to select one of them. 90 | ```python 91 | # Get all available databases from postgresql 92 | **import** psycopg2 93 | 94 | conn = psycopg2.connect(host="localhost", database="postgres", 95 | user="postgres", password="...") 96 | 97 | cur = conn.cursor() 98 | cur.execute("SELECT datname FROM pg_database WHERE datistemplate = false;") 99 | databases = cur.fetchall() 100 | print("Available databases:") 101 | for i in range(len(databases)): 102 | print(f"{i+1}. {databases[i][0]}") 103 | 104 | db = input("Enter the database you want to use: ") 105 | print(f"Using database - {db.upper()}") 106 | 107 | # or 108 | # To add new database 109 | # cur.execute("CREATE DATABASE ") 110 | # # To delete database 111 | # cur.execute("DROP DATABASE ") 112 | ``` 113 | 114 | > After selecting the database you have to connect to db. 115 | > We use psycopg2 library to connect to postgresql database. 116 | ```python 117 | import psycopg2 118 | 119 | def connect_db(db:str, user:str, password:str, host:str, port:str): 120 | # ... Your code here 121 | return conn 122 | 123 | 124 | conn = connect_db(db, user, password, host, port) 125 | conn.autocommit = True 126 | cur = conn.cursor() 127 | ``` 128 | 129 | > After connecting to db we have to ask to register or login. 130 | > Based on the answer we call the respective function (login() or register()). 131 | ```python 132 | print("1. Register") 133 | print("2. Login") 134 | answer = input("Enter your choice (1) or (2): ") 135 | if answer == "1": 136 | register() 137 | # Remember to use login function after registering a new user 138 | elif answer == "2": 139 | login() 140 | else: 141 | print("Invalid choice") 142 | ``` 143 | 144 | > register() => should use a class named User to store the data of user. 145 | > - 1. Create a class instance and store the data in it. 146 | > - 2. Insert the data into the table. 147 | ```python 148 | ``` -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | faker = "*" 8 | requests = "*" 9 | selenium = "*" 10 | playsound = "*" 11 | 12 | [dev-packages] 13 | 14 | [requires] 15 | python_version = "3.12" 16 | -------------------------------------------------------------------------------- /Test.md: -------------------------------------------------------------------------------- 1 |

PYTHON ASSERTION TYPES

2 | 3 | --- 4 | 5 | - `assert` => allows us to check if the condition is true 6 | 7 | ```python 8 | assert 1 == 1 9 | ``` 10 | --- 11 | 12 | - `assert_never` => allows us to check if two values are equal 13 | 14 | ```python 15 | from typing import Union, assert_never 16 | 17 | def handle_value(value: Union[int, str, float]): 18 | if isinstance(value, int): 19 | print("Handling an integer...") 20 | elif isinstance(value, str): 21 | print("Handling a string...") 22 | elif isinstance(value, float): 23 | print("Handling a float...") 24 | else: 25 | assert_never(value) 26 | 27 | handle_value([]) 28 | ``` 29 | --- 30 | 31 | 32 | ## unittest.TestCase assertions 33 | 34 |
35 | NOTE: Please note that 36 | assertNotEqual, assertTrue, assertFalse, assertIs, assertIsNone, assertIn, and sertIsInstance 37 | are part of the unittest module in Python and are not built-in assertions like assert. 38 | They need to be used within the context of a unittest.TestCase class. 39 |
40 | 41 | 1. `assertNotEqual(a, b)`: This assertion checks if a is not equal to b. 42 | 43 | 2. `assertTrue(x)`: This assertion checks if the value of x is True. 44 | 45 | 3. `assertFalse(x)`: This assertion checks if the value of x is False. 46 | 47 | 4. `assertIs(a, b)`: This assertion checks if a is b. 48 | 49 | 5. `assertIsNone(x)`: This assertion checks if the value of x is None. 50 | 51 | 6. `assertIn(a, b)`: This assertion checks if a is in b. 52 | 53 | 7. `assertIsInstance(a, b)`: This assertion checks if a is an instance of b. -------------------------------------------------------------------------------- /chromedriver.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Istam0808/PythonCourse/94d146b299b03ccac0bf786277aa2db49c1fca92/chromedriver.exe -------------------------------------------------------------------------------- /www. ISTAM_COMPANY: -------------------------------------------------------------------------------- 1 | 2 | _________ _______ _________ ________ 3 | | | | | | |\ /| 4 | | | | | | | \ / | 5 | | |_____ | |______| | \ / | _____ 6 | | | | | | | | | | __\\_ COMPANY 7 | | | | | | | \ / | 8 | ____|____ _____| | / \ / \/ \ 9 | 10 | 11 | 12 | 13 | 14 | ███ ███████████ ████████████ ████████████ ██████ ██████ 15 | ███ ███ ████ ████ ████ ████████ ████████ 16 | ███ ███ ████ ████ ████ ██ █████ █████ ██ 17 | ███ ███ ████ ████ ████ ████ ██████████ ████ 18 | ███ ███ ████ ████ ████ ████ ███ ████ 19 | ███ ███████████ ████ ████████████████ ████ ███ ████ 20 | ███ ███████████ ████ ████ ████ ████ ███ ████ 21 | ███ ███ ████ ████ ████ ████ ███ ████ 22 | ███ ███ ████ ████ ████ ████ ███ ████ 23 | ███ ███ ████ ████ ████ ████ ███ ████ 24 | ███ ███ ████ ████ ████ ████ ███ ████ 25 | ███ ███████████ ████ ████ ████ ████ ███ ████ 26 | --------------------------------------------------------------------------------