{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# asynchronous code in python" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A\n", "!\n", "B\n", "@\n", "Hey\n" ] } ], "source": [ "import asyncio\n", "\n", "async def main():\n", " task= asyncio.create_task(other())\n", " print(\"A\")\n", " await asyncio.sleep(1)\n", " print(\"B\")\n", " return_val = await task\n", " print(return_val)\n", "\n", "async def other():\n", " print(\"!\")\n", " await asyncio.sleep(2)\n", " print(\"@\")\n", " return \"Hey\"\n", "# asyncio.run(main()) --> this is for python >= 3.7\n", "await main()" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Counter in collection in python" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Counter({'x': 4, 'y': 2, 'z': 2})\n", "Counter({'a': 3, 'A': 3, 'r': 3, 'e': 2, 'c': 1, 'd': 1})\n", "Counter({'x': 4, 'y': 2, 'z': 2})\n", "Counter : Counter({'x': 4, 'y': 2, 'z': 2})\n", "\n", "\n", "u : 0\n", "\n", "\n", "G : 1\n", "n : 2\n", "a : 1\n", "n : 2\n", "i : 1\n", "Counter({'e': 2, 'o': 2, ' ': 2, 'n': 2, 'W': 1, 'l': 1, 'c': 1, 'm': 1, 't': 1, 'a': 1, 'i': 1})\n" ] } ], "source": [ "from collections import Counter\n", "\n", "# Counter with list -------> \n", "list1 = ['x','y','z','x','x','x','y', 'z']\n", "print(Counter(list1))\n", "\n", "# Counter with String ------->\n", "s = \"aaaAAAcdeerrr\"\n", "print(Counter(s))\n", "\n", "# Counter with tuple ------->\n", "tuple1 = ('x','y','z','x','x','x','y','z')\n", "print(Counter(tuple1))\n", "\n", "# initialize empty counter and assign value to it ------>\n", "_count = Counter()\n", "\n", "_count.update(list1)\n", "print(f\"Counter : {_count}\")\n", "\n", "\n", "\n", "# Accessing Counter -------->\n", "print(\"\\n\")\n", "_count = Counter()\n", "_count.update('Welcome to Gnani')\n", "print('%s : %d' % ('u', _count['u']))\n", "print(\"\\n\")\n", "for char in 'Gnani':\n", " print('%s : %d' % (char, _count[char]))\n", "\n", "\n", "\n", "# Deleting an Element from Counter ----->\n", "\n", "del _count[\"G\"]\n", "print(_count)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmatic operation on counter" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Counter({'y': 7, 'z': 2})\n", "Counter({'x': 16})\n", "Counter({'y': 2})\n", "Counter({'y': 5, 'x': 4, 'z': 4})\n" ] } ], "source": [ "from collections import Counter\n", "\n", "counter1 = Counter({'x': 4, 'y': 2, 'z': -2})\n", "counter2 = Counter({'x': -12, 'y': 5, 'z':4 })\n", "\n", "# Addition\n", "counter3 = counter1 + counter2 # only the values that are positive will be returned.\n", "print(counter3)\n", "\n", "# Substarction\n", "counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output\n", "print(counter4)\n", "\n", "#Intersection\n", "counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2\n", "print(counter5)\n", "\n", "#Union\n", "counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2\n", "print(counter6)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Methods\n", "- elements() : This method will return you all the elements with count >0. Elements with 0 or -1 count will not be returned.\n", "- most_common(value): This method will return you the most common elements from Counter list.\n", "- subtract(): This method is used to deduct the elements from another Counter.\n", "- update(): This method is used to update the elements from another Counter.\n" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "x\n", "x\n", "x\n", "x\n", "x\n", "y\n", "y\n", "\n", "\n", "\n", "Most_common with given n(n=2) : [('x', 5), ('y', 2)]\n", "Most commen : [('x', 5), ('y', 2), ('x1', 0), ('z', -2)]\n", "\n", "\n", "\n", "Subtract : Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})\n", "\n", "\n", "\n", "Update : Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})\n", "\n", "\n", "\n", "We can update the value of any key:\n", "Counter({'x': 50, 'y': 17, 'x1': 0, 'z': -2})\n" ] } ], "source": [ "counter1 = Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})\n", "print(\"\\n\\n\")\n", "\n", "for a in counter1.elements():\n", " print(a)\n", "\n", "print(\"\\n\\n\")\n", "\n", "most_2_common_element = counter1.most_common(2)\n", "print(\"Most_common with given n(n=2) :\",most_2_common_element)\n", "print(\"Most commen :\",counter1.most_common())\n", "\n", "print(\"\\n\\n\")\n", "\n", "counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})\n", "counter2 = Counter({'x': 2, 'y':5})\n", "counter1.subtract(counter2)\n", "print(\"Subtract :\",counter1)\n", "\n", "print(\"\\n\\n\")\n", "\n", "counter1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})\n", "counter2 = Counter({'x': 2, 'y':5})\n", "counter1.update(counter2)\n", "print(\"Update :\",counter1)\n", "\n", "print(\"\\n\\n\")\n", "\n", "print(\"We can update the value of any key:\")\n", "counter1['x'] = 50\n", "print(counter1)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Map fucntion\n", "- Create simple itereator for function, instead of writing loop" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "[2, 4, 6, 8]\n" ] } ], "source": [ "# Return double of n\n", "def addition(n):\n", "\treturn n + n\n", "\n", "# We double all numbers using map()\n", "numbers = (1, 2, 3, 4)\n", "result = map(addition, numbers)\n", "print(type(result))\n", "print(result)\n", "print(list(result))\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6, 8]\n" ] } ], "source": [ "numbers = (1,2,3,4)\n", "output = list(map(lambda x: x+x,numbers))\n", "print(output)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[11, 11, 11, 11, 11]\n" ] } ], "source": [ "n1 = [1,2,3,4,5]\n", "n2 = [10,9,8,7,6]\n", "\n", "output = list(map(lambda x,y:x+y,n1,n2))\n", "print(output)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]\n" ] } ], "source": [ "l = ['sat', 'bat', 'cat', 'mat']\n", "output = list(map(list,l))\n", "print(output)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Lambda" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GA\n", "GFEDCBA\n" ] } ], "source": [ "str1 = 'abcdefg'\n", "\n", "# lambda returns a function object\n", "l = -(len(str1)-1)\n", "rev_upper = lambda string: string.upper()[::l]\n", "print(rev_upper(str1))\n", "rev_upper = lambda string: string.upper()[::-1]\n", "print(rev_upper(str1))\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Int formatting: 1.000000e+06\n", "float formatting: 999,999,999,999.79\n" ] } ], "source": [ "format_numeric = lambda num: f\"{num:e}\" if isinstance(num, int) else f\"{num:,.2f}\"\n", "\n", "print(\"Int formatting:\", format_numeric(1000000))\n", "print(\"float formatting:\", format_numeric(999999999999.789541235))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## usecase" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "20\n", "30\n", "40\n" ] } ], "source": [ "is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]\n", "\n", "# iterate on each lambda function\n", "# and invoke the function to get the calculated value\n", "for item in is_even_list:\n", "\tprint(item())" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "# Example of lambda function using if-else\n", "Max = lambda a, b : a if(a > b) else b\n", "print(Max(1, 2))\n" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 9, 9]\n" ] } ], "source": [ "List = [[2,4,3],\n", " [1, 4, 9, 16],\n", " [3, 6, 9, 12]\n", " ]\n", "\n", "# Sort each sublist\n", "sortList = lambda x: (sorted(i) for i in x)\n", "\n", "# Get the second largest element\n", "secondLargest = lambda x, f : [y[-2] for y in f(x)]\n", "res = secondLargest(List, sortList)\n", "\n", "print(res)\n" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5, 7, 97, 77, 23, 73, 61]\n" ] } ], "source": [ "li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]\n", "\n", "final_list = list(filter(lambda x: (x % 2 != 0), li))\n", "print(final_list)\n" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[90, 59, 21, 60]\n" ] } ], "source": [ "# Python 3 code to people above 18 yrs\n", "ages = [13, 90, 17, 59, 21, 60, 5]\n", "\n", "adults = list(filter(lambda age: age > 18, ages))\n", "\n", "print(adults)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]\n" ] } ], "source": [ "# Python code to illustrate\n", "# map() with lambda()\n", "# to get double of a list.\n", "li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]\n", "\n", "final_list = list(map(lambda x: x*2, li))\n", "print(final_list)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['DOG', 'CAT', 'PARROT', 'RABBIT']\n" ] } ], "source": [ "# Python program to demonstrate\n", "# use of lambda() function\n", "# with map() function\n", "animals = ['dog', 'cat', 'parrot', 'rabbit']\n", "\n", "# here we intend to change all animal names\n", "# to upper case and return the same\n", "uppered_animals = list(map(lambda animal: animal.upper(), animals))\n", "\n", "print(uppered_animals)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "193\n" ] } ], "source": [ "# Python code to illustrate\n", "# reduce() with lambda()\n", "# to get sum of a list\n", "\n", "from functools import reduce\n", "li = [5, 8, 10, 20, 50, 100]\n", "sum = reduce((lambda x, y: x + y), li)\n", "print(sum)\n", "# (((((5+8)+10)+20)+50)+100)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The maximum element of the list is : 6\n" ] } ], "source": [ "# python code to demonstrate working of reduce()\n", "# with a lambda function\n", "\n", "# importing functools for reduce()\n", "import functools\n", "\n", "# initializing list\n", "lis = [1, 3, 5, 6, 2, ]\n", "\n", "# using reduce to compute maximum element from list\n", "print(\"The maximum element of the list is : \", end=\"\")\n", "print(functools.reduce(lambda a, b: a if a > b else b, lis))\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Decorators" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "@gfg_decorator\n", "def hello_decorator():\n", " print(\"Gfg\")\n", "\n", "'''Above code is equivalent to -\n", "\n", "def hello_decorator():\n", " print(\"Gfg\")\n", " \n", "hello_decorator = gfg_decorator(hello_decorator)'''" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HELLO\n", "HELLO\n" ] } ], "source": [ "# Python program to illustrate functions\n", "# can be treated as objects\n", "def shout(text):\n", "\treturn text.upper()\n", "\n", "print(shout('Hello'))\n", "\n", "yell = shout\n", "\n", "print(yell('Hello'))\n" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.\n", "hi, i am created by a function passed as an argument.\n" ] } ], "source": [ "# Python program to illustrate functions\n", "# can be passed as arguments to other functions\n", "def shout(text):\n", "\treturn text.upper()\n", "\n", "def whisper(text):\n", "\treturn text.lower()\n", "\n", "def greet(func):\n", "\t# storing the function in a variable\n", "\tgreeting = func(\"Hi, I am created by a function passed as an argument.\")\n", "\tprint (greeting)\n", "\n", "greet(shout)\n", "greet(whisper)\n" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25\n" ] } ], "source": [ "# Python program to illustrate functions\n", "# Functions can return another function\n", "\n", "def create_adder(x):\n", "\tdef adder(y):\n", "\t\treturn x+y\n", "\n", "\treturn adder\n", "\n", "add_15 = create_adder(15)\n", "\n", "print(add_15(10))\n" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "This is inside the function !!\n", "10\n" ] } ], "source": [ "# defining a decorator\n", "def hello_decorator(func):\n", "\n", "\t# inner1 is a Wrapper function in\n", "\t# which the argument is called\n", "\t\n", "\t# inner function can access the outer local\n", "\t# functions like in this case \"func\"\n", "\tdef inner1():\n", "\t\tprint(\"1\")\n", "\n", "\t\t# calling the actual function now\n", "\t\t# inside the wrapper function.\n", "\t\tfunc()\n", "\n", "\t\tprint(\"10\")\n", "\t\t\n", "\treturn inner1\n", "\n", "\n", "# defining a function, to be called inside wrapper\n", "def function_to_be_used():\n", "\tprint(\"This is inside the function !!\")\n", "\n", "\n", "# passing 'function_to_be_used' inside the\n", "# decorator to control its behaviour\n", "function_to_be_used = hello_decorator(function_to_be_used)\n", "\n", "\n", "# calling the function\n", "function_to_be_used()\n" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "120\n", "Total time taken in : factorial 2.0022339820861816\n" ] } ], "source": [ "# importing libraries\n", "import time\n", "import math\n", "\n", "# decorator to calculate duration\n", "# taken by any function.\n", "def calculate_time(func):\n", "\t\n", "\t# added arguments inside the inner1,\n", "\t# if function takes any arguments,\n", "\t# can be added like this.\n", "\tdef inner1(*args, **kwargs):\n", "\n", "\t\t# storing time before function execution\n", "\t\tbegin = time.time()\n", "\t\t\n", "\t\tfunc(*args, **kwargs)\n", "\n", "\t\t# storing time after function execution\n", "\t\tend = time.time()\n", "\t\tprint(\"Total time taken in : \", func.__name__, end - begin)\n", "\n", "\treturn inner1\n", "\n", "\n", "\n", "# this can be added to any function present,\n", "# in this case to calculate a factorial\n", "@calculate_time\n", "def factorial(num):\n", "\n", "\t# sleep 2 seconds because it takes very less time\n", "\t# so that you can see the actual difference\n", "\ttime.sleep(2)\n", "\tprint(math.factorial(num))\n", "\n", "# calling the function.\n", "factorial(5)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "MAIN function\n", "10\n", "Sum = 3\n" ] } ], "source": [ "def hello_decorator(func):\n", "\tdef inner1(*args, **kwargs):\n", "\t\t\n", "\t\tprint(\"1\")\n", "\t\t\n", "\t\t# getting the returned value\n", "\t\treturned_value = func(*args, **kwargs)\n", "\t\tprint(\"10\")\n", "\t\t\n", "\t\t# returning the value to the original frame\n", "\t\treturn returned_value\n", "\t\t\n", "\treturn inner1\n", "\n", "\n", "# adding decorator to the function\n", "@hello_decorator\n", "def sum_two_numbers(a, b):\n", "\tprint(\"MAIN function\")\n", "\treturn a + b\n", "\n", "a, b = 1, 2\n", "\n", "# getting the value through return of the function\n", "print(\"Sum =\", sum_two_numbers(a, b))\n" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "400\n", "200\n" ] } ], "source": [ "# code for testing decorator chaining\n", "def decor1(func):\n", "\tdef inner():\n", "\t\tx = func()\n", "\t\treturn x * x\n", "\treturn inner\n", "\n", "def decor(func):\n", "\tdef inner():\n", "\t\tx = func()\n", "\t\treturn 2 * x\n", "\treturn inner\n", "\n", "@decor1\n", "@decor\n", "def num():\n", "\treturn 10\n", "\n", "@decor\n", "@decor1\n", "def num2():\n", "\treturn 10\n", "\n", "print(num())\n", "print(num2())\n" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5\n", "2.0\n", "divide has exception : division by zero\n" ] } ], "source": [ "def error_handler(func):\n", " \n", " def innner_function(*args, **kwargs):\n", " \n", " try:\n", " result = func(*args, **kwargs)\n", " \n", " return result\n", " except Exception as e:\n", " return f\"{func.__name__} has exception : {e}\"\n", " return innner_function\n", "\n", "\n", "@error_handler\n", "def divide(a,b):\n", " return a/b\n", "\n", "a,b = 5,10\n", "print(divide(a,b))\n", "a,b = 10,5\n", "print(divide(a,b))\n", "a,b = 10,0\n", "print(divide(a,b))" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "result saved in memory\n", "result saved in memory\n", "result saved in memory\n", "result saved in memory\n", "result saved in memory\n", "120\n", "returning result from saved memory\n", "120\n" ] } ], "source": [ "# Factorial program with memoization using\n", "# decorators.\n", "\n", "# A decorator function for function 'f' passed\n", "# as parameter\n", "memory = {}\n", "def memoize_factorial(f):\n", "\t\n", "\t# This inner function has access to memory\n", "\t# and 'f'\n", "\tdef inner(num):\n", "\t\tif num not in memory:\n", "\t\t\tmemory[num] = f(num)\n", "\t\t\tprint('result saved in memory')\n", "\t\telse:\n", "\t\t\tprint('returning result from saved memory')\n", "\t\treturn memory[num]\n", "\n", "\treturn inner\n", "\t\n", "@memoize_factorial\n", "def facto(num):\n", "\tif num == 1:\n", "\t\treturn 1\n", "\telse:\n", "\t\treturn num * facto(num-1)\n", "\n", "print(facto(5))\n", "print(facto(5)) # directly coming from saved memory\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Generator in python" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "# A generator function that yields 1 for first time,\n", "# 2 second time and 3 third time\n", "def simpleGeneratorFun():\n", "\tyield 1\t\t\n", "\tyield 2\t\t\n", "\tyield 3\t\t\n", "\n", "# Driver code to check above generator function\n", "for value in simpleGeneratorFun():\n", "\tprint(value)\n" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "# A Python program to demonstrate use of\n", "# generator object with next()\n", "\n", "# A generator function\n", "def simpleGeneratorFun():\n", "\tyield 1\n", "\tyield 2\n", "\tyield 3\n", "\n", "# x is a generator object\n", "x = simpleGeneratorFun()\n", "\n", "# Iterating over the generator object using next\n", "print(next(x)) # In Python 3, __next__()\n", "print(next(x))\n", "print(next(x))\n" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "1\n", "2\n", "3\n", "\n", "Using for in loop\n", "0\n", "1\n", "1\n", "2\n", "3\n" ] } ], "source": [ "# A simple generator for Fibonacci Numbers\n", "def fib(limit):\n", "\t\n", "\t# Initialize first two Fibonacci Numbers\n", "\ta, b = 0, 1\n", "\n", "\t# One by one yield next Fibonacci Number\n", "\twhile a < limit:\n", "\t\tyield a\n", "\t\ta, b = b, a + b\n", "\n", "# Create a generator object\n", "x = fib(5)\n", "\n", "# Iterating over the generator object using next\n", "print(next(x)) # In Python 3, __next__()\n", "print(next(x))\n", "print(next(x))\n", "print(next(x))\n", "print(next(x))\n", "\n", "# Iterating over the generator object using for\n", "# in loop.\n", "print(\"\\nUsing for in loop\")\n", "for i in fib(5):\n", "\tprint(i)\n" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "5\n", "7\n", "11\n", "13\n", "17\n", "19\n", "23\n", "29\n", "31\n", "37\n", "41\n", "43\n", "47\n", "53\n" ] } ], "source": [ "def primeFunction():\n", "\tprime = None\n", "\tnum = 1\n", "\twhile True:\n", "\t\tnum = num + 1\n", "\n", "\t\tfor i in range(2, num):\n", "\t\t\tif(num % i) == 0:\n", "\t\t\t\tprime = False\n", "\t\t\t\tbreak\n", "\t\t\telse:\n", "\t\t\t\tprime = True\n", "\n", "\t\tif prime:\n", "\t\t\t\n", "\t\t\t# yields the value to the caller\n", "\t\t\t# and halts the execution\n", "\t\t\tyield num\n", "\n", "def main():\n", "\t\n", "\t# returns the generator object.\n", "\tprime = primeFunction()\n", "\t\n", "\t# generator executes upon request\n", "\tfor i in prime:\n", "\t\tprint(i)\n", "\t\tif i > 50:\n", "\t\t\tbreak\n", "\n", "if __name__ == \"__main__\":\n", "\tmain()\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Thread\n", "- https://www.geeksforgeeks.org/multithreading-python-set-1/" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Square: 100\n", "Cube: 1000\n", "Done!\n" ] } ], "source": [ "# Python program to illustrate the concept\n", "# of threading\n", "# importing the threading module\n", "import threading\n", "\n", "\n", "def print_cube(num):\n", "\t# function to print cube of given num\n", "\tprint(\"Cube: {}\" .format(num * num * num))\n", "\n", "\n", "def print_square(num):\n", "\t# function to print square of given num\n", "\tprint(\"Square: {}\" .format(num * num))\n", "\n", "\n", "if __name__ ==\"__main__\":\n", "\t# creating thread\n", "\tt1 = threading.Thread(target=print_square, args=(10,))\n", "\tt2 = threading.Thread(target=print_cube, args=(10,))\n", "\n", "\t# starting thread 1\n", "\tt1.start()\n", "\t# starting thread 2\n", "\tt2.start()\n", "\n", "\t# wait until thread 1 is completely executed\n", "\tt1.join()\n", "\t# wait until thread 2 is completely executed\n", "\tt2.join()\n", "\n", "\t# both threads completely executed\n", "\tprint(\"Done!\")\n" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ID of process running main program: 371152\n", "Main thread name: MainThread\n", "Task 1 assigned to thread: t1\n", "ID of process running task 1: 371152\n", "Task 2 assigned to thread: t2\n", "ID of process running task 2: 371152\n" ] } ], "source": [ "# Python program to illustrate the concept\n", "# of threading\n", "import threading\n", "import os\n", "\n", "def task1():\n", "\tprint(\"Task 1 assigned to thread: {}\".format(threading.current_thread().name))\n", "\tprint(\"ID of process running task 1: {}\".format(os.getpid()))\n", "\n", "def task2():\n", "\tprint(\"Task 2 assigned to thread: {}\".format(threading.current_thread().name))\n", "\tprint(\"ID of process running task 2: {}\".format(os.getpid()))\n", "\n", "if __name__ == \"__main__\":\n", "\n", "\t# print ID of current process\n", "\tprint(\"ID of process running main program: {}\".format(os.getpid()))\n", "\n", "\t# print name of main thread\n", "\tprint(\"Main thread name: {}\".format(threading.current_thread().name))\n", "\n", "\t# creating threads\n", "\tt1 = threading.Thread(target=task1, name='t1')\n", "\tt2 = threading.Thread(target=task2, name='t2')\n", "\n", "\t# starting threads\n", "\tt1.start()\n", "\tt2.start()\n", "\n", "\t# wait until all threads finish\n", "\tt1.join()\n", "\tt2.join()\n" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Worker thread running\n", "Worker thread running\n", "Main thread continuing to run\n" ] } ], "source": [ "import concurrent.futures\n", "\n", "def worker():\n", "\tprint(\"Worker thread running\")\n", "\n", "# create a thread pool with 2 threads\n", "pool = concurrent.futures.ThreadPoolExecutor(max_workers=2)\n", "\n", "# submit tasks to the pool\n", "pool.submit(worker)\n", "pool.submit(worker)\n", "\n", "# wait for all tasks to complete\n", "pool.shutdown(wait=True)\n", "\n", "print(\"Main thread continuing to run\")\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Regular Expressions\n", "- https://www.geeksforgeeks.org/regular-expression-python-examples-set-1/ " ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Start Index: 34\n", "End Index: 40\n" ] } ], "source": [ "import re\n", "\n", "s = 'GeeksforGeeks: A computer science portal for geeks'\n", "\n", "match = re.search(r'portal', s)\n", "\n", "print('Start Index:', match.start())\n", "print('End Index:', match.end())\n" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] } ], "source": [ "\"\"\"\n", "\\ ==> Backslash\n", "\n", "The backslash (\\) makes sure that the character is not treated in a special way. This can be considered a way of escaping metacharacters. For example, \n", "if you want to search for the dot(.) in the string then you will find that dot(.) will be treated as a special character as is one of the metacharacters . \n", "So for this case, we will use the backslash(\\) just before the dot(.) so that it will lose its specialty. See the below example for a better understanding.\n", "\n", "\"\"\"\n", "\n", "import re\n", "\n", "s = 'geeks.forgeeks'\n", "\n", "# without using \\\n", "match = re.search(r'.', s)\n", "print(match)\n", "\n", "# using \\\n", "match = re.search(r'\\.', s)\n", "print(match)" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['b', 'c', 'd', 'e', 'e', 'e', 'f', 'g', 'h', 'h', 'i', 'j', 'k', 'l', 'm']\n" ] } ], "source": [ "\"\"\"\n", "[] ==> Square Brackets\n", "\n", "Square Brackets ([]) represent a character class consisting of a set of characters that we wish to match. For example, the character class [abc] will match any single a, b, or c. \n", "\n", "We can also specify a range of characters using - inside the square brackets. For example, \n", "\n", "[0, 3] is sample as [0123]\n", "[a-c] is same as [abc]\n", "We can also invert the character class using the caret(^) symbol. For example, \n", "\n", "[^0-3] means any number except 0, 1, 2, or 3\n", "[^a-c] means any character except a, b, or c\n", "\"\"\"\n", "\n", "import re\n", "\n", "string = \"The quick brown fox jumps over the lzy dog\"\n", "pattern = \"[a-m]\"\n", "result = sorted(re.findall(pattern, string))\n", "\n", "print(result)\n" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matched: The quick brown fox\n", "Matched: The lazy dog\n", "Not matched: A quick brown fox\n" ] } ], "source": [ "\"\"\"\n", "^ ==> Caret\n", "\n", "Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given character(s) or not. For example - \n", "\n", "^g will check if the string starts with g such as geeks, globe, girl, g, etc.\n", "^ge will check if the string starts with ge such as geeks, geeksforgeeks, etc.\n", "\n", "\"\"\"\n", "\n", "import re\n", "\n", "# Match strings starting with \"The\"\n", "regex = r'^The'\n", "strings = ['The quick brown fox', 'The lazy dog', 'A quick brown fox']\n", "for string in strings:\n", "\tif re.match(regex, string):\n", "\t\tprint(f'Matched: {string}')\n", "\telse:\n", "\t\tprint(f'Not matched: {string}')" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Match found!\n" ] } ], "source": [ "\"\"\"\n", "$ - Dollar\n", "\n", "Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given character(s) or not. For example – \n", "\n", "s$ will check for the string that ends with a such as geeks, ends, s, etc.\n", "ks$ will check for the string that ends with ks such as geeks, geeksforgeeks, ks, etc.\n", "\"\"\"\n", "\n", "import re\n", "\n", "string = \"Hello World!\"\n", "pattern = r\"World!$\"\n", "\n", "match = re.search(pattern, string)\n", "if match:\n", "\tprint(\"Match found!\")\n", "else:\n", "\tprint(\"Match not found.\")\n" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Match found!\n" ] } ], "source": [ "\"\"\"\n", ". - Dot\n", "\n", "Dot(.) symbol matches only a single character except for the newline character (\\n). For example -\n", "\n", "a.b will check for the string that contains any character at the place of the dot such as acb, acbd, abbb, etc\n", ".. will check if the string contains at least 2 characters.\n", "\n", "\"\"\"\n", "\n", "import re\n", "\n", "string = \"The quick brown fox jumps over the lazy dog.\"\n", "pattern = r\"brown.fox\"\n", "\n", "match = re.search(pattern, string)\n", "if match:\n", "\tprint(\"Match found!\")\n", "else:\n", "\tprint(\"Match not found.\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'''\n", "| – Or\n", "Or symbol works as the or operator meaning it checks whether the pattern before or after the or symbol is present in the string or not. For example -\n", "a|b will match any string that contains a or b such as acd, bcd, abcd, etc.\n", "\n", "? – Question Mark\n", "Question mark(?) checks if the string before the question mark in the regex occurs at least once or not at all. For example - \n", "ab?c will be matched for the string ac, acb, dabc but will not be matched for abbc because there are two b. Similarly, it will not be matched for abdc because b is not followed by c.\n", "\n", "* – Star\n", "Star (*) symbol matches zero or more occurrences of the regex preceding the * symbol. For example -\n", "ab*c will be matched for the string ac, abc, abbbc, dabc, etc. but will not be matched for abdc because b is not followed by c.\n", "\n", "+ – Plus\n", "Plus (+) symbol matches one or more occurrences of the regex preceding the + symbol. For example -\n", "ab+c will be matched for the string abc, abbc, dabc, but will not be matched for ac, abdc because there is no b in ac and b is not followed by c in abdc.\n", "\n", "{m, n} – Braces \n", "Braces match any repetitions preceding regex from m to n both inclusive. For example -\n", "a{2, 4} will be matched for the string aaab, baaaac, gaad, but will not be matched for strings like abc, bc because there is only one a or no a in both the cases.\n", "\n", "() – Group\n", "Group symbol is used to group sub-patterns. For example -\n", "(a|b)cd will match for strings like acd, abcd, gacd, etc.\n", "\n", "'''" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10 (default, Nov 14 2022, 12:59:47) \n[GCC 9.4.0]" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1" } } }, "nbformat": 4, "nbformat_minor": 2 }