See More

{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "metadata": { "id": "2wTTQga3iIQ4" }, "source": [ "#Basic programings in python\n" ] }, { "cell_type": "markdown", "metadata": { "id": "cb-WOTrln57T" }, "source": [ "##Print Hello world!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QTok4bFlnQpd", "outputId": "c8d520a6-7c19-4a2a-8eb6-8d5bd9d9af90" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello_World!" ] } ], "source": [ "print(\"Hello\", \"World\", sep=\"_\", end=\"!\")" ] }, { "cell_type": "markdown", "metadata": { "id": "Rhk4Ugn3ovja" }, "source": [ "##Add Two numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "LNx1FjGPos2B", "outputId": "23cc62c2-1492-4663-a305-4aa23156ebbf" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter 1st number:4\n", "Enter 2nd number:66\n", "Addition of num1 and num2 are:70\n" ] } ], "source": [ "def add(n, m):\n", " return n+m\n", "num1 = int(input(\"Enter 1st number:\"))\n", "num2 = int(input(\"Enter 2nd number:\"))\n", "result = add(num1, num2)\n", "print(\"Addition of num1 and num2 are: {}\".format(result))" ] }, { "cell_type": "markdown", "metadata": { "id": "4UUFY_mwqYId" }, "source": [ "##Find square root" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "_VwXVBItqek8", "outputId": "583e316b-c931-45a1-dbce-29b9a2e1076c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number to find square root:5\n", "Square root of 5 is 25\n", "Cube root of 5 is 125\n" ] } ], "source": [ "def square(n):\n", " return n*n\n", "def cube(n):\n", " return n**3\n", "\n", "number = int(input(\"Enter number to find square root:\"))\n", "print(\"Square root of {1} is {0}\".format(square(number), number))\n", "print(\"Cube root of {num} is {num_cube}\".format(num_cube=cube(number), num=number))" ] }, { "cell_type": "markdown", "metadata": { "id": "ou8geTW8jml5" }, "source": [ "##Check a number is +ve, -ve or 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "I4ju51n7j1za", "outputId": "17543e97-03bc-4dc1-936c-4b35b5a76e13" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number to check: +3455\n", "3455 is a Positive number\n" ] } ], "source": [ "number= int(input(\"Enter a number to check: \"))\n", "if number > 0:\n", " print(\"{} is a Positive number\".format(number))\n", "elif number < 0:\n", " print(\"{} is a Negetive number\".format(number))\n", "else:\n", " print(\"{} is simply a Zero.\".format(number))" ] }, { "cell_type": "markdown", "metadata": { "id": "9UBAdnxe71Xb" }, "source": [ "##largest among 3 numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6n60aXw28AH9", "outputId": "f9d5e905-0328-4b14-c7a2-c8113e4ce7a7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A: 3\n", "B: 6\n", "C: 9\n", "9 is a largest number.\n" ] } ], "source": [ "a = int(input(\"A: \"))\n", "b = int(input(\"B: \"))\n", "c = int(input(\"C: \"))\n", "\n", "if a>b and a>c:\n", " print(f\"{a} is a largest number.\")\n", "elif b>c:\n", " print(f\"{b} is a largest number.\")\n", "else:\n", " print(f\"{c} is a largest number.\")" ] }, { "cell_type": "markdown", "metadata": { "id": "A_g9HJ-nQZbc" }, "source": [ "##Multiplication table" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7fsnh1GARR9E", "outputId": "070302de-4e47-42e6-80fe-529bba577b7f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter which number table do you want: 2\n", "1 * 2 = 2\n", "2 * 2 = 4\n", "3 * 2 = 6\n", "4 * 2 = 8\n", "5 * 2 = 10\n", "6 * 2 = 12\n", "7 * 2 = 14\n", "8 * 2 = 16\n", "9 * 2 = 18\n", "10 * 2 = 20\n" ] } ], "source": [ "table = int(input(\"Enter which number table do you want: \"))\n", "upto= 10\n", "\n", "for i in range(1, upto+1):\n", " print(f\"{i} * {table} = {i*table}\")\n" ] }, { "cell_type": "markdown", "metadata": { "id": "NhYzbg66YfXa" }, "source": [ "##Simple calculator" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "jNe2EWwcYksf", "outputId": "4f64e444-3451-4a46-bd24-9bbebd19058d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter calculator symbol + - * / // %:-\n", "Enter the numbers seperated by space:456 56\n", "Subtraction: 400\n" ] } ], "source": [ "operation = input(\"Enter calculator symbol + - * / // %:\")\n", "\n", "def add(num):\n", " result = 0\n", " for i in num:\n", " result += i\n", " return result\n", "def sub(num):\n", " return num[0] - num[1]\n", "def mul(num):\n", " result = 1\n", " for i in num:\n", " result*= i\n", " return result\n", "def div(num):\n", " return num[0] // num[1]\n", "def fdiv(num):\n", " return num[0]/num[1]\n", "def mod(num):\n", " return num[0]%num[1]\n", "\n", "if operation == '+' or operation == '-' or operation == '*' or operation =='/' or operation =='//' or operation =='%':\n", " operands = list(map(int, input(\"Enter the numbers seperated by space:\").split(\" \")))\n", " if operation =='+':\n", " print(\"Addition:\", add(operands))\n", " elif operation == '-':\n", " print('Subtraction:', sub(operands))\n", " elif operation =='*':\n", " print('Multiplication:', mul(operands))\n", " elif operation =='//':\n", " print('Division:', div(operands))\n", " elif operation =='/':\n", " print(\"Floor division:\", fdiv(operands))\n", " else:\n", " print('Modulus:', mod(operands))\n", "else:\n", " print(\"Enter invalid operation...\")\n", " " ] }, { "cell_type": "markdown", "metadata": { "id": "1H1BkUyZUSho" }, "source": [ "##Swap two variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "vDmTZTGNVUD0", "outputId": "b7e2dc1f-0931-4eef-fdaa-7ce5f2baa11c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before swapping a has 10 and b has 20\n", "After swapping a has 20 and b has 10\n" ] } ], "source": [ "a = 10\n", "b = 20\n", "print(f\"Before swapping a has {a} and b has {b}\")\n", "a, b = b, a\n", "print(f\"After swapping a has {a} and b has {b}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ZuGfttYwQALF", "outputId": "91bf27e7-391d-4cb7-9f26-e4408f455ee4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before swapping x has 100 and y has 150\n", "After swapping x has 150 and y has 100\n" ] } ], "source": [ "x = 100\n", "y = 150\n", "print(f\"Before swapping x has {x} and y has {y}\")\n", "x = x+y\n", "y = x-y\n", "x = x-y\n", "print(f\"After swapping x has {x} and y has {y}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5eCq9XhGWbix", "outputId": "a5dfc416-e199-4ab4-9142-d7db253bf531" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before swapping p has 5 and q has 15\n", "After swapping p has 15 and q has 5\n" ] } ], "source": [ "p = 5\n", "q = 15\n", "print(f\"Before swapping p has {p} and q has {q}\")\n", "p = p ^ q\n", "q = p^q\n", "p = p^ q\n", "print(f\"After swapping p has {p} and q has {q}\")" ] }, { "cell_type": "markdown", "metadata": { "id": "zuCMYneRt3yc" }, "source": [ "##Calculate the area of triangle" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OxaebxqHuBrF", "outputId": "3734eef9-62e3-4af4-bec6-6fdda2254590" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter base of the triangle:5\n", "Enter height of the triangle:10\n", "Area of triangle is 25.0\n" ] } ], "source": [ "\n", "selection = int(input(\"Apply 1 if it is right angle triangle else 0: \"))\n", "def right_angled(b, h):\n", " area = 0.5 * b * h\n", " return area\n", "def equilateral(side):\n", " area = ((3**0.5)/4) * side *side\n", " return area\n", "if selection == 1:\n", " height = int(input(\"Enter Height of the triangle:\"))\n", " base = int(input(\"Enter Base of the triangle:\"))\n", " print(f\"Area of right angled triangle is: {right_angled(base, height)}\")\n", "else:\n", " side = int(input(\"Enter side of the Equilateral triangle: \"))\n", " print(\"Area of Equilateral triangle is {}\".format(equilateral(side)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KZa76aJvUN4k" }, "outputs": [], "source": [ "\n", "try:\n", " base = int(input(\"Enter base of the triangle:\"))\n", " height = int(input(\"Enter height of the triangle:\"))\n", " area = 0.5 * base * height\n", "except:\n", " area = ((3**0.5)/4) * base *base\n", "finally:\n", " print(f\"Area of triangle is {area}\")\n", " " ] }, { "cell_type": "markdown", "metadata": { "id": "KyxRw6A51pd9" }, "source": [ "##Solve Quadratic equation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-1tNT2OC1_gH", "outputId": "83b3925e-912b-4389-b1e5-360408598b2e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "1\n", "Complex roots\n", "Roots are: -0.5 +i and -0.5 -i11\n" ] } ], "source": [ "a = int(input())\n", "b = int(input())\n", "c = int(input())\n", "\n", "if a == 0:\n", " print(\"Invalid Quadrilateral equation.\")\n", "else:\n", " discriminant = b * b - 4 * a * c\n", " square_dis = discriminant **0.5\n", " denominator = 2*a\n", " if discriminant > 0:\n", " # If b*b > 4*a*c, then roots are real and different; roots of x2 - 7x - 12 are 3 and 4\n", " print(\"Real and different roots\")\n", " print(\"Roots: \", -b-square_dis/denominator, \" and \", -b+square_dis/denominator )\n", "\n", "\n", " elif discriminant == 0:\n", " # b*b == 4*a*c, then roots are real and both roots are same; roots of x2 - 2x + 1 are 1 and 1\n", " print(\"Real and same roots\")\n", " print(\"Roots are: \", -b/denominator)\n", "\n", " else:\n", " # If b*b < 4*a*c, then roots are complex; x2 + x + 1 roots are -0.5 + i1.73205 and -0.5 - i1.73205\n", " print(\"Complex roots\")\n", " print(\"Roots are: \", -b/denominator,\"+i and \", -b/denominator,\"-i\")\n" ] }, { "cell_type": "markdown", "metadata": { "id": "xssNXpIgXbVn" }, "source": [ "##convert Kilometers to miles" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OUI1JwEmXpvO", "outputId": "84f1fc8e-403b-4802-cb61-686a1e5cf3a6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter kilometer to convert into miles: 1\n", "1.0 kilometers are equal to 0.6215040397762586 miles\n" ] } ], "source": [ "#1 kilometer = 0.6215 miles\n", "kilometers = float(input(\"Enter kilometer to convert into miles: \"))\n", "miles = kilometers / 1.609\n", "print(f\"{kilometers} kilometers are equal to {miles} miles\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "2rfkHwqkdmDx", "outputId": "981b4900-db10-4a27-9c46-c37bbace764e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter miles to convert into kilometers: 5\n", "5.0 miles are equal to 8.045 kilometers\n" ] } ], "source": [ "##1mile = 1.609 kilometers\n", "miles = float(input(\"Enter miles to convert into kilometers: \"))\n", "kilometers = miles * 1.609\n", "print(f\"{miles} miles are equal to {kilometers} kilometers\")" ] }, { "cell_type": "markdown", "metadata": { "id": "5rcZvRC8Xrhc" }, "source": [ "##Convert Celsius to Fahrenheit" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GzGd-f1UX2XQ", "outputId": "c4a3a2ef-d6c3-4881-d957-4d4982ad109b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter celsius to convert of Fahrenheit: 37\n", "Fahrenheit : 98.6\n" ] } ], "source": [ "#(C*1.8) + 32 = F\n", "\n", "celsius = float(input(\"Enter celsius to convert: \"))\n", "fahrenheit = (celsius * 1.8) + 32\n", "print(f\"Fahrenheit : {round(fahrenheit, 2)}\") " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-e0TLHkThqYL", "outputId": "2659d2dc-4110-47be-8551-12390aa66bf3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter Fahrenhei: 98\n", "Celsius : 36.67\n" ] } ], "source": [ "# C = (F-32)/1.8\n", "\n", "fahrenheit = float(input(\"Enter Fahrenhei: \"))\n", "celsius = (fahrenheit - 32) / 1.8\n", "print(f\"Celsius : {round(celsius, 2)}\") " ] }, { "cell_type": "markdown", "metadata": { "id": "MAzjTbDpk-p2" }, "source": [ "##Check a number is Even or Odd" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SdpHOx0BlId-", "outputId": "f276521c-56d1-4022-ac53-7fb9f04b06ad" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number:2\n", "Even number!\n" ] } ], "source": [ "num = int(input(\"Enter a number:\"))\n", "\n", "def isEven(n):\n", " return n%2 == 0 \n", " # return 1 if n%2 == 0 else 0\n", " # return True if n%2 == 0 else False\n", " \n", "if isEven(num):\n", " print(\"Even number!\")\n", "else: \n", " print(\"Odd number!\")" ] }, { "cell_type": "markdown", "metadata": { "id": "UCduvwyJn9Er" }, "source": [ "##Check Leap Year or not" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "B5EcT-nBlIkT", "outputId": "d952af96-7fc2-464a-db57-04639ba6157d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter year: 2023\n", "Non leap year\n" ] } ], "source": [ "year = int(input(\"Enter year: \"))\n", "\n", "def leap(year):\n", " return year%4==0\n", "print(\"Leap Year\" if leap(year) else \"Non leap year\")" ] }, { "cell_type": "markdown", "metadata": { "id": "GYMGjPFSzgh_" }, "source": [ "##Sum of natural numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "WQvB3XT2zo_O", "outputId": "6bf6a2d4-e357-4de6-fc8d-82aae10e71b9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number upto: 15\n", "Sum: 120\n" ] } ], "source": [ "number = int(input('Number upto: '))\n", "sum = 0 \n", "for i in range(number+1):\n", " sum += i\n", "print(\"Sum:\", sum)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "v80e6uFx0Kno", "outputId": "ae5fe2fe-c7c3-4828-8bdd-bb6162443cac" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number upto: 15\n", "Sum: 120\n" ] } ], "source": [ "number = int(input('Enter number upto: '))\n", "sum = 0\n", "while number > 0:\n", " sum += number\n", " number-=1\n", "print('Sum:', sum)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "g-7JkX_h08rp", "outputId": "63b4ed26-fc17-4dba-d658-1545a5c3a2e3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number:15\n", "sum of 15 natural numbers are: 120\n" ] } ], "source": [ "number = int(input('Enter number:'))\n", "\n", "def sum(n):\n", " if n == 1:\n", " return 1\n", " else:\n", " return n + sum(n-1)\n", "print(\"sum of {} natural numbers are: {}\".format(number, sum(number)))" ] }, { "cell_type": "markdown", "metadata": { "id": "PM9I2-oQNQrf" }, "source": [ "##Factorial of a number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8vh4KbRjNUi3", "outputId": "825aa965-8aca-45e1-f57b-ec94f68cca80" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number: 5\n", "factorial of 5 is 120\n" ] } ], "source": [ "number = int(input('Enter number: '))\n", "factorial = 1\n", "for i in range(1, number+1):\n", " factorial *= i\n", "print(f\"factorial of {number} is {factorial}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4afAy94f8imk", "outputId": "ebca230a-1f5f-47f3-81f7-8a03e7a4df59" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "120\n" ] } ], "source": [ "def factorial(n):\n", " # return 1 if n ==0 else n*factorial(n-1)\n", " if n == 1:\n", " return 1\n", " else:\n", " return n * factorial(n-1)\n", " \n", "if __name__ == \"__main__\":\n", " number = int(input())\n", " print(factorial(number))" ] }, { "cell_type": "markdown", "metadata": { "id": "LGWJ0SwPXa2d" }, "source": [ "##Factors of a number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uXVe2j0eXgCU", "outputId": "d6081de3-8486-4490-85c1-a5e5b4fe86a3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "number:18\n", "1 2 3 6 9 18 " ] } ], "source": [ "number = int(input(\"number:\"))\n", "\n", "for i in range(1,number+1):\n", " if number%i== 0:\n", " print(i, end= ' ')" ] }, { "cell_type": "markdown", "metadata": { "id": "vEmVzdEb9Db-" }, "source": [ "##Prime number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9XzHR_GJ9Jqo", "outputId": "3abb7bef-cc76-43ba-f1b8-b1dc7d55e5bf" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Any number:21\n", "21 is not a prime number\n" ] } ], "source": [ "number = int(input(\"Any number:\"))\n", "def isPrime(number):\n", " for i in range(2, (number//2)+1):\n", " if number%i == 0:\n", " return False\n", " break\n", " return True\n", "\n", "if isPrime(number):\n", " print(\"{} is a prime number\".format(number))\n", "else:\n", " print(\"{} is not a prime number\".format(number))" ] }, { "cell_type": "markdown", "metadata": { "id": "EBtWIvn-AeTZ" }, "source": [ "##Prime number in an interval" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X6l76H_qAkYD", "outputId": "25785bc3-23fc-4332-fe55-7cc4b3666430" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter start:2\n", "Enter stop:100\n", "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 " ] } ], "source": [ "start = int(input(\"Enter start:\"))\n", "stop = int(input(\"Enter stop:\"))\n", "\n", "def isPrime(n):\n", " for j in range(2, (n//2)+1):\n", " if i%j == 0:\n", " return False\n", " return True\n", "\n", "for i in range(start, stop+1):\n", " if isPrime(i):\n", " print(i, end=\" \")" ] }, { "cell_type": "markdown", "metadata": { "id": "-VZsY_49RSm8" }, "source": [ "##Fabinacci series" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "j6qSlAOYRaZd", "outputId": "8df0ca75-0ad0-4738-9fdf-0ac7b66f6607" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fabinacci sequence upto: 1\n", "Fabinacci sequence: 0 1 1 " ] } ], "source": [ "upto = int(input('Fabinacci sequence upto: '))\n", "\n", "print(\"Fabinacci sequence:\", end= \" \")\n", "n = 0\n", "m = 1\n", "if upto ==0:\n", " print(n)\n", "elif upto == 1:\n", " print(n,m)\n", "else:\n", " print(n, m, end=' ')\n", " for i in range(2, upto+1):\n", " o = m\n", " m = m + n\n", " n = o\n", " print(m, end = ' ')\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Vd6BA7vIvRrs", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ffc6bf6d-5dc2-4c08-f7d1-daa636bb948f" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter the number: 9\n", "Fabbinocci sequence : 0 1 1 2 3 5 8 13 21 " ] } ], "source": [ "num = int(input(\"Enter the number: \"))\n", "def fabbinocci(n):\n", " if n < 2:\n", " return n\n", " else:\n", " return fabbinocci(n-1)+fabbinocci(n-2)\n", "print(\"Fabbinocci sequence :\", end =\" \")\n", "for i in range(num):\n", " print(fabbinocci(i), end=\" \")" ] }, { "cell_type": "markdown", "metadata": { "id": "gQUtbks1RbtB" }, "source": [ "##Armstrong number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Hq9NxXUFRkRF", "outputId": "01cd5f01-4763-4f55-bdb5-afe4e7bfcc73" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "153\n", "153 is an Armstrong number.\n" ] } ], "source": [ "number = int(input())\n", "copy = number\n", "armstrong = 0\n", "count = len(str(number))\n", "\n", "while number >0:\n", " remainder = number % 10\n", " armstrong += remainder**count\n", " number //= 10\n", "\n", "if armstrong == copy:\n", " print(f\"{copy} is an Armstrong number.\")\n", "else:\n", " print(\"not an armstrong number\")" ] }, { "cell_type": "markdown", "metadata": { "id": "LU0llexFRlAp" }, "source": [ "##Armstrong number in an interval" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HzMoU3bZRsik", "outputId": "79d0d8b9-7083-4f01-e5c7-01750b6b06a9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter first number: 1\n", "Enter final number:500\n", "1 2 3 4 5 6 7 8 9 153 370 371 407 " ] } ], "source": [ "start = int(input(\"Enter first number: \"))\n", "stop = int(input('Enter final number:'))\n", "\n", "def isArmstrong(n):\n", " str_n = str(n)\n", " count = len(str_n)\n", " armstrong = 0\n", " for j in str_n:\n", " armstrong += int(j)**count\n", " if armstrong == n:\n", " return n\n", "for i in range(start, stop+1):\n", " if isArmstrong(i):\n", " print(i, end = \" \")" ] }, { "cell_type": "markdown", "metadata": { "id": "lqhIyPS1Zg-p" }, "source": [ "##Power of 2 by anonumous function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "q5AK8C9PZjNS", "outputId": "62dc4c7c-eee3-4cac-a478-ba24572acbe4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number5\n", "2 power 0 is 1\n", "2 power 1 is 2\n", "2 power 2 is 4\n", "2 power 3 is 8\n", "2 power 4 is 16\n", "2 power 5 is 32\n" ] } ], "source": [ "number= int(input(\"Enter number\"))\n", "a = list(map(lambda x: 2**x, range(number+1)))\n", "for i in range(number+1):\n", " print(f'2 power {i} is {a[i]}')\n" ] }, { "cell_type": "markdown", "metadata": { "id": "pDB5wXJLj41m" }, "source": [ "##Find numbers divisible by another number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ng0biN0PkKCN", "outputId": "2a508092-3359-45e3-8bd6-15855e1b8b4d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter number: 5\n", "enter a number upto we have to check: 80\n", "The list of numbers which are divisible by 5 are [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80]\n" ] } ], "source": [ "number = int(input(\"Enter number: \"))\n", "upto = int(input('enter a number upto we have to check: '))\n", "divisible = list(filter(lambda y: y%number ==0, list(range(1,upto+1))))\n", "print(f\"The list of numbers which are divisible by {number} are {divisible}\")" ] }, { "cell_type": "markdown", "metadata": { "id": "BWwBjlnfnZ2Y" }, "source": [ "##Find HCF or GCD" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nuICAm7coEB6", "outputId": "6cb4a587-57e2-4621-86da-e0b6ef1ad16f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HCf_1:24\n", "HCF_2:54\n", "6\n" ] } ], "source": [ "hcf1 = int(input('HCf_1:'))\n", "hcf2 = int(input('HCF_2:'))\n", "\n", "def gcd(hcf1, hcf2):\n", " small = hcf1 if hcf2 > hcf1 else hcf2\n", " for i in range(small+1,1,-1):\n", " if ((hcf1 % i == 0) and (hcf2 % i == 0)):\n", " return i\n", "\n", "print(gcd(hcf1, hcf2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "G4K-_dM6ufEx", "outputId": "c28d17ac-a5f7-4b8c-8b8e-cebfe6816219" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10,5,65,40,20\n", "5\n" ] } ], "source": [ "nums = [int(x) for x in list(input().split(','))]\n", "\n", "def gcd(nums):\n", " nums = sorted(nums)\n", " for j in range(nums[0],1,-1):\n", " boolean = False\n", " for i in nums:\n", " if i%j ==0:\n", " boolean = True\n", " else:\n", " boolean = False\n", " if boolean== True:\n", " return j\n", "print(gcd(nums))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ld1ompySmYCx", "outputId": "bcc34077-36da-471f-d25c-9cf79ad4aec3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "##Euclidean algorithm\n", "n = 27\n", "m = 24\n", "def Euclidean(m, n):\n", " while n:\n", " m,n = n, m%n\n", " return m\n", "print(Euclidean(m,n))" ] }, { "cell_type": "markdown", "metadata": { "id": "qzzgPLk-nr9J" }, "source": [ "##LCM" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nO899ac7nvrw", "outputId": "7ea0f62a-9deb-4fcc-e448-db56a9d336e8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Primary:4\n", "Second:6\n", "LCM 12\n" ] } ], "source": [ "m = int(input('Primary:'))\n", "n = int(input(\"Second:\"))\n", "large = ref = m if m>n else n\n", "small = n if m>n else m\n", "count = 2\n", "while large % small != 0:\n", " large = ref\n", " large *= count\n", " count +=1\n", "print(\"LCM\", large)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "VSCfjlwxq6Bb", "outputId": "aa46aeb6-f82c-4075-bc11-46e9957a281f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Primary:4\n", "Second:6\n", "LCM: 12\n" ] } ], "source": [ "m = m1 = int(input('Primary:'))\n", "n = n1 = int(input(\"Second:\"))\n", "while n:\n", " m, n = n, m%n\n", "lcm = (m1*n1)//m\n", "print(\"LCM:\", lcm)" ] }, { "cell_type": "markdown", "source": [ "##Reverse a Number" ], "metadata": { "id": "D8PDiZxYGldM" } }, { "cell_type": "code", "source": [ "num = 12345\n", "rev_num = 0\n", "while num > 0:\n", " rem = num % 10\n", " rev_num = rem + (rev_num * 10)\n", " num //=10\n", "print(rev_num)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "hh_rlG2mGpkb", "outputId": "3c65989b-90af-467d-d0ca-c3824c6e5439" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "54321\n" ] } ] }, { "cell_type": "code", "source": [ "num = 12345\n", "print(int(str(num)[::-1]))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HVhy1jvff0eT", "outputId": "ef087489-1180-4af2-86f6-c5bac63cf413" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "54321\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Count number of digits in a number" ], "metadata": { "id": "5-Vl-Pd5ih-S" } }, { "cell_type": "code", "source": [ "num = 123\n", "count = 0\n", "while num:\n", " num//=10\n", " count +=1\n", "print(count) " ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "UR1K-Uvco4Ia", "outputId": "a74f1012-af66-4b50-d4ce-209a5dfcf1c0" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "3\n" ] } ] }, { "cell_type": "code", "source": [ "num=1234\n", "print(len(str(num)))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7_x2Tbg3qImT", "outputId": "159e3c74-a849-4f86-877f-3ad5efbf2a01" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "4\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Compute the power of a number" ], "metadata": { "id": "b4DnmeGakBB2" } }, { "cell_type": "code", "source": [ "num = 4\n", "pwr = 2\n", "def power(num, pwr):\n", " return num ** pwr\n", "print(power(num,pwr))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "n2fI9_K1npsW", "outputId": "897dd480-f308-4a35-85cf-53eb41151e82" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "16\n" ] } ] }, { "cell_type": "code", "source": [ "print(int(pow(4,3)))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "RdMZbspXoVFe", "outputId": "7856f627-3790-4abc-b850-5b07bd074f59" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "64\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "nsPt1qAhtTsf" }, "source": [ "##Decimal to Binary, Octal Hexadecimal" ] }, { "cell_type": "markdown", "metadata": { "id": "Wn_mZIvBw14L" }, "source": [ "####Decimal to binary" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "y2bUh4uN68bm", "outputId": "b35127dd-f1cc-4689-c444-8649044230d1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Decimal: 15\n", "With functions: 1111\n", " binary is 1111 without functions\n" ] } ], "source": [ "decimal = int(input(\"Decimal: \"))\n", "\n", "print('With functions:', bin(decimal).replace(\"0b\",\"\"))\n", "\n", "binary = ''\n", "while decimal>0:\n", " binary = str(decimal%2) + binary\n", " decimal //=2\n", "print(f'binary is {binary} without functions')\n" ] }, { "cell_type": "markdown", "metadata": { "id": "sDMwRb8-CmWd" }, "source": [ "####Decimal to octal" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dXmBVO9jCp2Q", "outputId": "bfaffc46-7021-4b0e-aabd-d7e28d02d380" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Decimal:12\n", "with functions 14\n", "Octal without functions: 14\n" ] } ], "source": [ "decimal = int(input(\"Decimal:\"))\n", "\n", "print(\"with functions\", oct(decimal).replace(\"0o\", ''))\n", "\n", "octal = ''\n", "while decimal>0:\n", " octal = str(decimal%8) + octal\n", " decimal //= 8\n", "print('Octal without functions:', octal)" ] }, { "cell_type": "markdown", "metadata": { "id": "FrBxSnFHEJOp" }, "source": [ "####Decimal to hexadecimal" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "UrdSFLAVEP1T", "outputId": "120c1b79-4c39-48b2-ac49-c2e2f01eda68" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Decimal: 15\n", "with functions: f\n", "Hexadecimal without function: f\n" ] } ], "source": [ "decimal = int(input('Decimal: '))\n", "print('with functions:', hex(decimal).replace('0x', ''))\n", "hexadecimal = ''\n", "hexa = '0123456789abcdef'\n", "while decimal>0:\n", " hexadecimal = hexa[decimal%16] + hexadecimal\n", " decimal //= 16\n", "print(\"Hexadecimal without function:\", hexadecimal)" ] }, { "cell_type": "markdown", "metadata": { "id": "uUsvTHmTIOFK" }, "source": [ "####Binary to decimal" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4-ip7ZvPIU0n", "outputId": "92106df7-b436-4482-ded9-e43aa9586fee" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Binary:1011\n", "Decimal: 11\n", "Decimal without function: 11\n" ] } ], "source": [ "binary = input(\"Binary:\")\n", "print(\"Decimal:\", int(binary,2))\n", "decimal = 0\n", "for i in binary:\n", " decimal = decimal * 2 + int(i) \n", "print('Decimal without function:', decimal)" ] }, { "cell_type": "markdown", "metadata": { "id": "bu26vbrWKq3Y" }, "source": [ "####Octal to decimal\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aKJgsacOKwcV", "outputId": "c3c095f7-b672-4383-c551-647a8bf734d8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Octal:17\n", "Decimal: 15\n", "Decimal without function: 15\n" ] } ], "source": [ "octal = input(\"Octal:\")\n", "print('Decimal:', int(octal, 8))\n", "\n", "decimal = 0\n", "for i in octal:\n", " decimal = decimal*8 + int(i)\n", "print(\"Decimal without function:\", decimal)" ] }, { "cell_type": "markdown", "metadata": { "id": "N7qeCQnLL97H" }, "source": [ "####Hexadecimal to decimal" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bTlznukdMB9T", "outputId": "d05f16b3-635f-4ba9-e60e-33808f675ed7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hexadecimal:51\n", "decimal: 81\n", "deciamal without function: 81\n" ] } ], "source": [ "hexa = input(\"Hexadecimal:\")\n", "print(\"decimal:\", int(hexa, 16))\n", "\n", "decimal = 0\n", "hex_map = {'0':0, '1':1, '2':2, '3':3, '4':4,'5':5,'6':6, '7':7, '8':8, '9':9, 'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15}\n", "for i in hexa:\n", " decimal = 16*decimal + hex_map[i]\n", "print(\"deciamal without function:\",decimal)" ] }, { "cell_type": "markdown", "source": [ "###Decimal to Binary with Reccursion" ], "metadata": { "id": "Q2HfZM_MHJXY" } }, { "cell_type": "code", "source": [ "dec = int(input(\"Enter Decimal number:\"))\n", "def decToBin(dec):\n", " if dec>0:\n", " decToBin(dec//2)\n", " print(dec%2, end = \"\")\n", "decToBin(dec)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "iql0nRa7HTR6", "outputId": "d5808de3-ed03-4afc-d78a-4171b478963f" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter Decimal number:9\n", "01001" ] } ] }, { "cell_type": "markdown", "source": [ "## Creating pyramid patterns" ], "metadata": { "id": "qCW4WVOzyM41" } }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n):\n", " print(\"* \", end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1AkBjoDVzL3C", "outputId": "ea836f5b-896e-42d9-a308-765bfa7b8804" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", "* * * * * \n", "* * * * * \n", "* * * * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(i+1):\n", " print(\"* \", end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "U8YRjY4I0pmB", "outputId": "82a5b458-fb03-4fc6-c514-685470f68401" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* \n", "* * \n", "* * * \n", "* * * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i):\n", " print(\"* \", end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DiVa-5H41N2k", "outputId": "5cc18711-1c6c-467d-fec6-4ed9047f89a8" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", "* * * * \n", "* * * \n", "* * \n", "* \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(\" \", end=\"\")\n", " for k in range(i+1):\n", " print(\"* \", end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1Cd0LNLA1rPz", "outputId": "0164a096-7f0e-471f-ac87-c844467c783c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " * \n", " * * \n", " * * * \n", " * * * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(i):\n", " print(\" \", end= \"\")\n", " for k in range(n-i):\n", " print('* ',end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "WCXQl0CO2mBE", "outputId": "549ec514-ac3a-4f3b-a327-33ff0ea69a2a" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", " * * * * \n", " * * * \n", " * * \n", " * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(\" \", end = \"\")\n", " for k in range(i+1):\n", " print(\"* \", end=\"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "J-P7GH4ZrBML", "outputId": "398d9406-cc7c-4b3b-eec8-292b232e3347" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " * \n", " * * \n", " * * * \n", " * * * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(i):\n", " print(\" \", end=\"\")\n", " for k in range(n-i):\n", " print(\"* \", end = \"\")\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Xb8a0POdtIix", "outputId": "0a4463f3-e521-40f2-db4f-eb8f7a9185af" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", " * * * * \n", " * * * \n", " * * \n", " * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(\" \", end=\"\")\n", " for k in range(i+1):\n", " print(\"* \", end = \"\")\n", " print()\n", "for i in range(n):\n", " for j in range(i+1):\n", " print(' ', end = '')\n", " for k in range(n-i-1):\n", " print(\"* \", end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8HbSBkFLuBrP", "outputId": "456d97e4-5e13-4193-edb2-942cee14e65f" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " * \n", " * * \n", " * * * \n", " * * * * \n", "* * * * * \n", " * * * * \n", " * * * \n", " * * \n", " * \n", " \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n-1):\n", " for j in range(i):\n", " print(\" \", end = '')\n", " for k in range(n-i):\n", " print(\"* \", end = '')\n", " print()\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(\" \", end = \"\")\n", " for k in range(i+1):\n", " print('* ', end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "o61zUnjRwG-l", "outputId": "9c7fc65b-0b75-454f-e94d-398a897f33fd" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", " * * * * \n", " * * * \n", " * * \n", " * \n", " * * \n", " * * * \n", " * * * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n-1):\n", " for j in range(i):\n", " print(' ', end = \"\")\n", " for k in range(n-i):\n", " if k ==0 or k == n-i-1:\n", " print('* ', end = '')\n", " else:\n", " print(\" \",end = '')\n", " print()\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(' ', end = '')\n", " for k in range(i+1):\n", " if k == 0 or k == i:\n", " print(\"* \", end='')\n", " else:\n", " print(' ', end='')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QnT_50gmwurp", "outputId": "aa74ab6e-8119-4932-d0f5-c9a80aeec6d9" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * \n", " * * \n", " * * \n", " * * \n", " * \n", " * * \n", " * * \n", " * * \n", "* * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n):\n", " if i == 0 or j ==0 or i == n-1 or j == n-1:\n", " print('* ',end = '')\n", " else:\n", " print(' ', end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4RRtTVFR13YK", "outputId": "0b1aa879-11af-48de-e769-d049bb6fab7a" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", "* * \n", "* * \n", "* * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n+1):\n", " for j in range(i):\n", " if j == 0 or i ==n or i == j+1:\n", " print('* ', end = '')\n", " else:\n", " print(' ',end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "BuwLW0ty4M1I", "outputId": "a49f9e29-4be0-420c-e77b-a5229b988114" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "* \n", "* * \n", "* * \n", "* * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(i):\n", " print(' ',end ='')\n", " for k in range(n-i):\n", " if i == 0 or k == 0 or k ==n-i-1:\n", " print('* ',end='')\n", " else:\n", " print(' ',end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "erz7c8-W5nzW", "outputId": "454a963c-e816-4300-a183-d3bc6e2a5d09" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", " * * \n", " * * \n", " * * \n", " * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i):\n", " if i == 0 or j == 0 or j == n-i-1:\n", " print('* ', end='')\n", " else:\n", " print(' ', end = '')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X7ME_zH3618H", "outputId": "3e05c909-040b-49c8-ac48-a46d37cf918c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", "* * \n", "* * \n", "* * \n", "* \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(n-i-1):\n", " print(' ',end='')\n", " for k in range(i+1):\n", " if k == 0 or k ==i or i ==n-1:\n", " print('* ', end = '')\n", " else:\n", " print(' ',end='')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "a-GQnPU-7akb", "outputId": "0117d452-0f10-44f1-e40c-20508433dc31" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " * \n", " * * \n", " * * \n", " * * \n", "* * * * * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n):\n", " for j in range(i):\n", " print(' ',end='')\n", " for k in range(n-i):\n", " if i == 0 or k == 0 or k == n-i-1:\n", " print('* ', end='')\n", " else:\n", " print(' ',end='')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lk-Dm6ls8lAh", "outputId": "ea78d5f5-e7be-430c-a51d-88c1e39dfcbb" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "* * * * * \n", " * * \n", " * * \n", " * * \n", " * \n" ] } ] }, { "cell_type": "code", "source": [ "n = 5\n", "for i in range(n-1):\n", " for j in range(n-i-1):\n", " print(\" \",end='')\n", " for k in range(i+1):\n", " if k == 0 or k == i:\n", " print(\"* \",end='')\n", " else:\n", " print(' ',end='')\n", " print()\n", "for i in range(n):\n", " for j in range(i):\n", " print(' ',end='')\n", " for k in range(n-i):\n", " if k == 0 or k ==n-i-1:\n", " print('* ',end='')\n", " else:\n", " print(' ',end='')\n", " print()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "CKT4NaX89Wk6", "outputId": "4ffce69a-b704-4333-d1b5-5a555b7d7d1a" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " * \n", " * * \n", " * * \n", " * * \n", "* * \n", " * * \n", " * * \n", " * * \n", " * \n" ] } ] }, { "cell_type": "markdown", "source": [ "##Check if list is empty" ], "metadata": { "id": "FXq7r6Bb19HQ" } }, { "cell_type": "code", "source": [ "list1 = [21,3,9,54,3,24]\n", "list2=[]\n", "if len(list1) == 0:\n", " print('List1 is empty')\n", "else:\n", " print(f'List1 has {len(list1)} elements')\n", "\n", "if not list2:\n", " print('List is Empty')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "m9lsa65AGY7O", "outputId": "b58e810d-d98c-4f7c-87f8-a805f7cb8599" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "List1 has 6 elements\n", "List is Empty\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Get the last Element of the list" ], "metadata": { "id": "40klYLAt7MFA" } }, { "cell_type": "code", "source": [ "my_list = [1,2,3,4,5,6]\n", "print(my_list[len(my_list)-1])\n", "print(my_list[-1])" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "B2nlg07-Cs4S", "outputId": "bd130bd8-b5f6-48b3-9676-903339c1f75f" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "6\n", "6\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Index of list using For loop" ], "metadata": { "id": "M7BjhsSuVAx2" } }, { "cell_type": "code", "source": [ "num = ['zero','one','two','three']\n", "for i in num:\n", " ind = num.index(i)\n", " print(ind, 'index of', i)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "t4SYbCcxVGRd", "outputId": "bbc8e578-d649-49b4-e507-5e161aee1be3" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "0 index of zero\n", "1 index of one\n", "2 index of two\n", "3 index of three\n" ] } ] }, { "cell_type": "code", "source": [ "num = ['zero','one','two','three']\n", "for i,j in enumerate(num):\n", " print(i,'index of', j)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "APRehIkaWLBP", "outputId": "031fdeb6-a1d8-482c-e90f-3ec4a8c1a87c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "0 index of zero\n", "1 index of one\n", "2 index of two\n", "3 index of three\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Count the occurance of an Item in a List" ], "metadata": { "id": "HE-A5Gc28g-n" } }, { "cell_type": "code", "source": [ "List = [1,2,3,4,2,4,1,4,5,2,6,72,7,8]\n", "search = 2\n", "print(List.count(search))" ], "metadata": { "id": "doyrLOtX8ssM", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d73c0760-9738-40d7-c8e9-0d71d95c5558" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "3\n" ] } ] }, { "cell_type": "code", "source": [ "search = 1\n", "count = 0\n", "for i in List:\n", " if search == i:\n", " count +=1\n", "print(count)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0RAp_WTTWjZE", "outputId": "12fb93d1-4e06-4cc7-a630-d20b7df2ce63" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "2\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Slice lists" ], "metadata": { "id": "hi5miv5M1p5P" } }, { "cell_type": "code", "source": [ "my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "\n", "# Get the first three items\n", "slice1 = my_list[:3]\n", "print(slice1) # Output: [1, 2, 3]\n", "\n", "# Get the last three items\n", "slice2 = my_list[-3:]\n", "print(slice2) # Output: [8, 9, 10]\n", "\n", "# Get every other item starting from the second item\n", "slice3 = my_list[1::2]\n", "print(slice3) # Output: [2, 4, 6, 8, 10]\n", "\n", "# Reverse the list\n", "slice4 = my_list[::-1]\n", "print(slice4) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "wtEROPdl7Jks", "outputId": "0dc74fa0-a87e-4924-acc4-bf2cbf19bb75" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1, 2, 3]\n", "[8, 9, 10]\n", "[2, 4, 6, 8, 10]\n", "[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Concatenate Two lists" ], "metadata": { "id": "gPUDqU3Q2P0k" } }, { "cell_type": "code", "source": [ "list1 = [1,2,3,4]\n", "list2 = [5,6,7,8]\n", "\n", "print(list1+list2)\n", "\n", "list1.extend(list2)\n", "print(list1)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ZdPiXxWJMqnO", "outputId": "73c2df38-9ac5-425b-ac66-f110f64f1987" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1, 2, 3, 4, 5, 6, 7, 8]\n", "[1, 2, 3, 4, 5, 6, 7, 8]\n" ] } ] }, { "cell_type": "code", "source": [ "str1 = \"Hello\"\n", "str2 = \"World\"\n", "\n", "total = '_'.join((str1,str2))\n", "print(total)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "gREEvsFYNdlq", "outputId": "526dd553-9b55-4c57-832b-281f35f93085" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello_World\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Split a list into evenly sized chuncks" ], "metadata": { "id": "zXOrCJqY2fJs" } }, { "cell_type": "code", "source": [ "my_list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14]\n", "size = 2\n", "lists= [my_list[i:i+size] for i in range(0,len(my_list),size)]\n", "print(lists)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "KQ_nBOum2rfT", "outputId": "5dbfd4c6-776a-4ea8-9953-06aa880b42fa" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14]]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Flattened list from nested list" ], "metadata": { "id": "Qyz5rkkd1Z0X" } }, { "cell_type": "code", "source": [ "nested_list = [0.1,0.2,[3.1,4.2,[5,6,[70,80,[900,1000]]]]]\n", "def flattened(num):\n", " flattened_list = []\n", " for i in num:\n", " if isinstance(i, list):\n", " flattened_list.extend(flattened(i))\n", " else:\n", " flattened_list.append(i)\n", " return flattened_list\n", "print(flattened(nested_list))\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PWgZZSV_3GnE", "outputId": "ab1b83c7-214e-4a59-e894-72e6bcda89cf" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[0.1, 0.2, 3.1, 4.2, 5, 6, 70, 80, 900, 1000]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Iterate through two lists in parallel" ], "metadata": { "id": "rxMoYCELF6UJ" } }, { "cell_type": "code", "source": [ "my_list = [1,2,3,4]\n", "my_list2 = my_list[::-1]\n", "for i, j in zip(my_list, my_list2):\n", " print(i,j)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Sw5Lw9mFZEVe", "outputId": "a750a43d-2b6d-4de2-88cb-d74c36d7ad4d" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "1 4\n", "2 3\n", "3 2\n", "4 1\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Remove duplicate element from a list" ], "metadata": { "id": "zgWt459ynUcE" } }, { "cell_type": "code", "source": [ "my_list = [1,1,2,7,3,4,4,5,5,3,3,5,4,1,6]\n", "print(list(set(my_list)))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "91FsCujM4F7K", "outputId": "87955b2e-2506-4e71-8d40-30ca19ca4049" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1, 2, 3, 4, 5, 6, 7]\n" ] } ] }, { "cell_type": "code", "source": [ "my_list = [1,1,2,7,3,4,4,5,5,3,3,5,4,1,6]\n", "new_list = []\n", "for i in my_list:\n", " if i not in new_list:\n", " new_list.append(i)\n", "new_list.sort()\n", "print(new_list)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "iUbvuneG4Urq", "outputId": "0d670fad-e500-4926-db75-e7a2e0cba378" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1, 2, 3, 4, 5, 6, 7]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Del, remove,and pop on a list" ], "metadata": { "id": "7iiFPwKZEWX3" } }, { "cell_type": "code", "source": [ "my_list = [1,2,3,4,5,6,7,8,9]\n", "print('Actual list:', my_list)\n", "del my_list[1] #delete the 1st index item \n", "print('Del index 1:',my_list)\n", "my_list.remove(3) #remove element which we passed as an argument\n", "print(my_list)\n", "popped_item = my_list.pop(5) #pop item in 5th index\n", "print(f'{popped_item} is fetched which locates as 5th index of {my_list}')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6hpVb4OuM4YN", "outputId": "37bf2967-6995-4403-c9ab-da7e6dabb12e" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Actual list: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "Del index 1: [1, 3, 4, 5, 6, 7, 8, 9]\n", "[1, 4, 5, 6, 7, 8, 9]\n", "8 is fetched which locates as 5th index of [1, 4, 5, 6, 7, 9]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Add 2 matrices" ], "metadata": { "id": "rEvaCGJ6Gll5" } }, { "cell_type": "code", "source": [ "m,n= map(int,input('Enter matrix structure in M*N:').split())\n", "print('Enter the elements:')\n", "matrix1 = []\n", "for i in range(m):\n", " row = []\n", " for j in range(n):\n", " k = int(input())\n", " row.append(k)\n", " matrix1.append(row)\n", "\n", "print('Enter elements of second matrix:')\n", "matrix2 = [[int(input()) for i in range(m)] for j in range(n)]\n", "\n", "major = []\n", "for i in range(m):\n", " minor = []\n", " for j in range(n):\n", " k = matrix1[i][j]+matrix2[i][j]\n", " minor.append(k)\n", " major.append(minor)\n", " \n", "for minor in major:\n", " print(minor)\n", "for i in range(m):\n", " for j in range(n):\n", " print(major[i][j], end=' ')\n", " print()\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "k90L1dL-DHBt", "outputId": "ebbf3467-539f-482c-fa5f-2a52ed400cf8" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter matrix structure in M*N:2 2\n", "Enter the elements:\n", "2\n", "4\n", "6\n", "8\n", "Enter elements of second matrix:\n", "8\n", "6\n", "4\n", "2\n", "[10, 10]\n", "[10, 10]\n", "10 10 \n", "10 10 \n" ] } ] }, { "cell_type": "markdown", "source": [ "##Transpose a Matrix\n" ], "metadata": { "id": "GK7Icr5uekzC" } }, { "cell_type": "code", "source": [ "# Example matrix\n", "matrix = [ [1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]\n", "]\n", "transpose = []\n", "for i in range(len(matrix[0])):\n", " row = []\n", " for j in range(len(matrix)):\n", " row.append(matrix[j][i])\n", " transpose.append(row)\n", "\n", "# Using the zip function\n", "# transpose = list(map(list, zip(*matrix)))\n", "\n", "print(\"Transposed matrix:\")\n", "for row in transpose:\n", " print(row)\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bEBeG6LmepYr", "outputId": "72a318b2-9dee-41f4-9a6f-8af16089855c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Transposed matrix:\n", "[1, 4, 7]\n", "[2, 5, 8]\n", "[3, 6, 9]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Multiply two matrices" ], "metadata": { "id": "MowlcNu5S5qX" } }, { "cell_type": "code", "source": [ "matrix = [[2, 2, 2],\n", " [4, 5, 6],\n", " [7, 8, 9]]\n", "matrix2 = [[1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]]\n", "matrixB = []\n", "for i in range(len(matrix[0])):\n", " row = []\n", " for j in range(len(matrix)):\n", " k = matrix[j][i]\n", " row.append(k)\n", " matrixB.append(row)\n", "\n", "mul = [[0 for i in range(len(matrixB[0]))]for j in range(len(matrix))]\n", "\n", "for i in range(len(matrix)):\n", " for j in range(len(matrixB[0])):\n", " for k in range(len(matrixB)):\n", " mul[i][j]= matrix[i][k]*matrixB[k][j]\n", "for i in mul:\n", " print(i)\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "oJH_mSqvS-uw", "outputId": "4a939b89-9417-4f1c-fba9-26b2f7d136bc" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[4, 12, 18]\n", "[12, 36, 54]\n", "[18, 54, 81]\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Parse a string to a float or int" ], "metadata": { "id": "bpuCwpn66w9E" } }, { "cell_type": "code", "source": [ "string_in = '3.14'\n", "# string_in = '3.14pi'\n", "try:\n", " float_in = float(string_in)\n", " print(float_in)\n", "except ValueError as e:\n", " print(\"Exception raised on \", e)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "h-25863A692d", "outputId": "48357c52-cb5e-48c7-fb07-4294172ed1ef" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Exception raised on could not convert string to float: '3.14pi'\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Create a Long Multiline String" ], "metadata": { "id": "U4k6wgOYWvHz" } }, { "cell_type": "code", "source": [ "long_string = '''This is a long multiline string. It spans across multiple lines.\n", "You can include line breaks and formatting within the string.\n", "\n", "Here's an example of a bulleted list:\n", "- Item 1\n", "- Item 2\n", "\n", "Just make sure to enclose the string in triple quotes.'''\n", "\n", "print(long_string)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "2ACliXH3ifV4", "outputId": "fd72ee64-7684-40ff-a95b-c11e49847525" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "This is a long multiline string. It spans across multiple lines.\n", "You can include line breaks and formatting within the string.\n", "\n", "Here's an example of a bulleted list:\n", "- Item 1\n", "- Item 2\n", "\n", "Just make sure to enclose the string in triple quotes.\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "ipk9lF4xgXGP" }, "source": [ "##Ascii value of a character" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "TZ0mhT3vgcD5", "outputId": "41814c22-ffad-4f36-998c-a5c57fa705b9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a character:7\n", "Unicode value of 7 is 55\n" ] } ], "source": [ "character = input(\"Enter a character:\")\n", "ascii_value = ord(character)\n", "chr_value = chr(ascii_value)\n", "print(f'Unicode value of {chr_value} is {ascii_value}')" ] }, { "cell_type": "markdown", "source": [ "##String is Palindrome or Not" ], "metadata": { "id": "JH4ObQHTdMht" } }, { "cell_type": "code", "source": [ "string = input(\"Enter String: \")\n", "\n", "if string == string[::-1]:\n", " print(\"string is palindrome\")\n", "else:\n", " print(\"Not pallindrome\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "NpEPsguwdhlZ", "outputId": "52d9f569-ffd7-4c54-d0c2-bb869ba158fd" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter String: madam\n", "string is palindrome\n" ] } ] }, { "cell_type": "code", "source": [ "string = input(\"Enter string: \")\n", "rev = ''\n", "for i in string:\n", " rev = i + rev\n", "if string == rev:\n", " print(\"Pallindrome\")\n", "else:\n", " print(\"Not pallindrome\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "mjq3gZE7d8qC", "outputId": "f984a09b-e048-45a5-db30-90ab83e2eb25" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter string: haiah\n", "Pallindrome\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Count the number of each vowel" ], "metadata": { "id": "5cw4EVwxcwGf" } }, { "cell_type": "code", "source": [ "words = input().upper()\n", "A = E = I = O = U = 0\n", "\n", "for i in words:\n", " if i =='A':\n", " A += 1\n", " elif i =='E':\n", " E += 1\n", " elif i =='I':\n", " I += 1\n", " elif i =='O':\n", " O += 1\n", " elif i =='U':\n", " U += 1\n", " else:\n", " pass\n", " \n", "print('A:', A , 'E: ', E,' I: ',I,' O: ',O,' U: ',U)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9k0UYKJhf8Hx", "outputId": "da439ad2-7d2b-477f-c6c7-713869a19902" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Sai Praveen\n", "A: 2 E: 2 I: 1 O: 0 U: 0\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Get Substing of a String" ], "metadata": { "id": "pmVTqMgk7kLL" } }, { "cell_type": "code", "source": [ "s = 'Ande Sai Praveen'\n", "s1 = s[4:8]\n", "s2= s[5:]\n", "s3 = s[:8:-1]\n", "print('S1:', s1)\n", "print('S2:', s2)\n", "print('S3:', s3)" ], "metadata": { "id": "GlovNyf8DIgo", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ab4929e3-7fd7-4b19-c8a6-87048fbef1b2" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "S1: Sai\n", "S2: Sai Praveen\n", "S3: neevarP\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Sort words with alphabetical order" ], "metadata": { "id": "0mHqMIJ_-lhv" } }, { "cell_type": "code", "source": [ "alphabets = ['hai','i', 'had', 'many', 'hopes', 'on','ttec', 'company', 'for', 'that', 'i', 'had', 'prepared','very', 'much.', 'still','i', 'didn\"t','get','it', 'due', 'to', 'having', 'pooor', 'communication', 'skills.']\n", "sorted_one = sorted(alphabets)\n", "print(sorted_one)\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "mV4V6XGN-quL", "outputId": "9c5faa16-219b-4c9c-d2d5-6dffe9b2c684" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['communication', 'company', 'didn\"t', 'due', 'for', 'get', 'had', 'had', 'hai', 'having', 'hopes', 'i', 'i', 'i', 'it', 'many', 'much.', 'on', 'pooor', 'prepared', 'skills.', 'still', 'that', 'to', 'ttec', 'very']\n" ] } ] }, { "cell_type": "code", "source": [ "words = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n", "for i in range(len(words)):\n", " for j in range(len(words)-i-1):\n", " if words[j]>words[j+1]:\n", " words[j], words[j+1]= words[j+1], words[j]\n", "print(words)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "C5Z2LPhOBkkJ", "outputId": "8db17313-11a0-4721-c396-f1d8c9eb28f8" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['apple', 'banana', 'cherry', 'date', 'elderberry']\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Trim whitespace from a string" ], "metadata": { "id": "xa_i_0Wee_GN" } }, { "cell_type": "code", "source": [ "string = 'Hai Sai Praveen'\n", "trim = ''\n", "for i in string:\n", " if i != \" \":\n", " trim = trim+i\n", "print(trim)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "G7fEbdgurQsG", "outputId": "73e741a2-e5ec-4b09-b52d-9c8c9c51cd99" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "HaiSaiPraveen\n" ] } ] }, { "cell_type": "code", "source": [ "string = ' Hai sai Praveen '\n", "print(string.strip())\n", "print(string.rstrip())\n", "print(string.lstrip())" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "xk09_Lx_shod", "outputId": "fc243ed4-9643-41be-af28-014361fc91ea" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hai sai Praveen\n", " Hai sai Praveen\n", "Hai sai Praveen \n" ] } ] }, { "cell_type": "markdown", "source": [ "##convert bytes to a string" ], "metadata": { "id": "EtjE8MnznbyY" } }, { "cell_type": "code", "source": [ "byte_code = b'Hai Praveen'\n", "decode_code = byte_code.decode()\n", "print(decode_code)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aoP1H4Ghnn02", "outputId": "28c7bb2c-699e-466a-b455-9d8226ee51e7" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hai Praveen\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Check if two strings are Anagram" ], "metadata": { "id": "hw7mcPRuij3w" } }, { "cell_type": "code", "source": [ "string1='listen'\n", "string2 = 'silent'\n", "string1 = string1.replace(\" \",\"\").lower()\n", "string2 = string2.replace(\" \",\"\").lower()\n", "if sorted(string1) == sorted(string2):\n", " print(\"Strings are Anagrams\")\n", "else:\n", " print(\"Not Anagrams\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "C_upRSqDq1yv", "outputId": "1915135e-1490-4c44-837f-81343f4d8330" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Strings are Anagrams\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Capitalise the First Character of a string" ], "metadata": { "id": "UYwyStwpilRB" } }, { "cell_type": "code", "source": [ "text = \"hai my name is praveen. now i am going to create a capitalised text.\"\n", "words = text.split()\n", "Text = [word[0].upper() + word[1:] for word in words]\n", "text = \" \".join(Text)\n", "print(text)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "yjKewO32slkr", "outputId": "922ba94f-bd92-4b6a-dee2-2be8140af1c1" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hai My Name Is Praveen. Now I Am Going To Create A Capitalised Text.\n" ] } ] }, { "cell_type": "code", "source": [ "name= 'sai praveen'\n", "print(name[0].upper() + name[1:])" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nyVPu2yoy8jL", "outputId": "42850677-35eb-4753-860e-62ff380efedf" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Sai praveen\n" ] } ] }, { "cell_type": "code", "source": [ "text = \"hai my name is praveen. now i am going to create a capitalised text.\"\n", "print(text.capitalize())\n", "print(text.title())" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uK_35fx1wphT", "outputId": "cda36b14-dd5f-43d3-c66c-fa40dc3d2fea" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hai my name is praveen. now i am going to create a capitalised text.\n", "Hai My Name Is Praveen. Now I Am Going To Create A Capitalised Text.\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Check if a string is a Number(Float)" ], "metadata": { "id": "oxN0q-Yd8UnZ" } }, { "cell_type": "code", "source": [ "\n", "def is_num(input):\n", " return isinstance(input, str)\n", "\n", "def is_num1(input):\n", " return input.isdigit()\n", "\n", "def is_num2(input):\n", " return input.isnumeric()\n", "\n", "def is_num3(input):\n", " try:\n", " float(input)\n", " return True\n", " except:\n", " return False\n", "print(is_num3('5'))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lk0ETkg-Sz6F", "outputId": "562d6400-c361-42c2-e106-e776c3896d72" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "True\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Count the number of occurance of a character in a string" ], "metadata": { "id": "JOiL9TFPnJlg" } }, { "cell_type": "code", "source": [ "text = 'Sai praveen'.lower()\n", "ch = 'a'.lower()\n", "print(text.count(ch))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "BF20K-Nl3N20", "outputId": "a86c6616-4bc7-421b-edca-86d811c19cae" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "2\n" ] } ] }, { "cell_type": "code", "source": [ "text = 'Sai praveen'\n", "ch = 'e'\n", "count = 0\n", "for i in text:\n", " if ch == i:\n", " count += 1\n", "print(count)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PBdhVs3d3l8o", "outputId": "16027604-ca0a-4685-fdd8-e6618b7d96c3" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "2\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Remove punctuation from a string" ], "metadata": { "id": "qMAoPMBSe07u" } }, { "cell_type": "code", "source": [ "import string\n", "string_input = 'Hai! my name is Praveen: Im working in D.X.C. Technologies!'\n", "new = str.maketrans('','',string.punctuation)\n", "string_input = string_input.translate(new)\n", "print(string_input)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GQup11wde72x", "outputId": "cf361f29-0c82-481b-e840-38784cf38c9f" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hai my name is Praveen Im working in DXC Technologies\n" ] } ] }, { "cell_type": "code", "source": [ "import string\n", "string_input = 'Hai! my name is Praveen: Im working in D.X.C. Technologies!'\n", "s = ''\n", "for i in string_input:\n", " if i not in string.punctuation:\n", " s += i\n", "print(s)" ], "metadata": { "id": "YX4czPn1h5ex" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Illustrate different set operations" ], "metadata": { "id": "dBcYYR4bCv4Y" } }, { "cell_type": "code", "source": [ "a = {1,2,3,4,5,6}\n", "b = {4,5,6,7,8,9}\n", "\n", "union_set = a.union(b) #returns unique elements from both sets\n", "union_set= a | b\n", "print(union_set)\n", "\n", "intersection_set = a.intersection(b) # return common elements in both sets\n", "intersection_set=a & b\n", "print(intersection_set)\n", "\n", "difference_set = a.difference(b)\n", "difference_set = a - b #returns elements present in A but not in B\n", "print(difference_set)\n", "\n", "s\n", "ymmetric_difference_set = a.symmetric_difference(b)\n", "symmetric_difference_set = a ^ b # returns the elements present in either of the sets but not in both\n", "print(symmetric_difference_set) \n", "\n", "subset_check = a.issubset(b)\n", "subset_check = a <= b #returns True if all the elements in the first set are present in the second\n", "print(subset_check) \n", "\n", "superset_check = b.issuperset(a)\n", "superset_check = a >= b #returns True if all the elements in the second set are present in the first\n", "print(superset_check)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1I2ugnVnDm1M", "outputId": "33a93476-c456-48d6-b39f-81c4a1d1f1fd" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{1, 2, 3, 4, 5, 6, 7, 8, 9}\n", "{4, 5, 6}\n", "{1, 2, 3}\n", "{1, 2, 3, 7, 8, 9}\n", "False\n", "False\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Create nested dictionary" ], "metadata": { "id": "2zNT78RWTeva" } }, { "cell_type": "code", "source": [ "Details = {'Name':'Sai Praveen Ande',\n", " 'Age' :22,\n", " 'Qualification': 'B.Tech',\n", " 'Branch' : 'ECE',\n", " 'Address':{'Door No':'1-96',\n", " 'Street':'Shivalayam Street',\n", " 'Village':'Chintaparru',\n", " 'State': 'Andhra Pradhesh',\n", " 'Pin':534250}}\n", "print(Details)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Sb-OwFdCTkmo", "outputId": "753e2ce1-36b8-4664-fa0a-4c1f6165c14d" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{'Name': 'Sai Praveen Ande', 'Age': 22, 'Qualification': 'B.Tech', 'Branch': 'ECE', 'Address': {'Door No': '1-96', 'Street': 'Shivalayam Street', 'Village': 'Chintaparru', 'State': 'Andhra Pradhesh', 'Pin': 534250}}\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Convert two lists into a Dictionary" ], "metadata": { "id": "Aco1c3lAezO8" } }, { "cell_type": "code", "source": [ "list1 = [1,2,3,4,5]\n", "list2 = [1,4,9,16,25]\n", "\n", "my_dict = {}\n", "for index,value in enumerate(list1):\n", " my_dict[value] = list2[index]\n", "\n", "my_dict2 = {k:v for k, v in zip(list2, list1) }\n", "\n", "my_dict3 = dict(zip(list1, list2))\n", "\n", "print(my_dict)\n", "print(my_dict2)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "cxbZ6LZuoQfG", "outputId": "65a7c712-583a-4f03-8dfd-b5d472c0fca3" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}\n", "{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Iterate over Dictionaries using for loop" ], "metadata": { "id": "tfvBuEC51toO" } }, { "cell_type": "code", "source": [ "my_dict = {'A':'Append', 'B':'BaseClass', 'C':'Cassendra','D':'Database','E':'Efficient'}\n", "for item, value in my_dict.items():\n", " print(item, 'for', value)\n", "for item in my_dict.keys():\n", " print(item, end = ' ')\n", "print()\n", "for value in my_dict.values():\n", " print(value, end = ' ')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "a2nLbq997jmn", "outputId": "1adc73b4-8bb7-48bc-c192-04e248ba6742" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "A for Append\n", "B for BaseClass\n", "C for Cassendra\n", "D for Database\n", "E for Efficient\n", "A B C D E \n", "Append BaseClass Cassendra Database Efficient " ] } ] }, { "cell_type": "markdown", "source": [ "##Sort a dictionary by value" ], "metadata": { "id": "8tC2rYdK13al" } }, { "cell_type": "code", "source": [ "my_dict = {2:\"pineapple\",3: \"banana\", 4:\"orange\", 11:'papaya'}\n", "\n", "sorted_dict = dict(sorted(my_dict.items(), key=lambda x:x[1]))#sort values\n", "print(sorted_dict)\n", "\n", "print(dict(sorted(my_dict.items(), key = lambda x:x[1], reverse = True))) # sort values in reverse order\n", "\n", "will_sorted = list(my_dict.items()) #covert dict to list\n", "will_sorted.sort(key=lambda x: x[1])#sort the values\n", "print({key:value for key,value in will_sorted}) #covert list to dict" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "yEiqMjS2AGgE", "outputId": "df911831-0110-49db-b399-c641fcde6e80" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{3: 'banana', 4: 'orange', 11: 'papaya', 2: 'pineapple'}\n", "{2: 'pineapple', 11: 'papaya', 4: 'orange', 3: 'banana'}\n", "{3: 'banana', 4: 'orange', 11: 'papaya', 2: 'pineapple'}\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Check if a key is present in a dictionary" ], "metadata": { "id": "1cKvry7f2X8s" } }, { "cell_type": "code", "source": [ "my_dict = {'A':'Append', 'B':'BaseClass', 'C':'Cassendra','D':'Database','E':'Efficient'}\n", "ele = 'F'\n", "if ele in my_dict.keys():\n", " print(f'{ele} Key exist with {my_dict[ele]}')\n", "else:\n", " print('Element not found')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tPE7GTQoOAvD", "outputId": "8842a9e5-d621-4216-ffb4-5bbc5ad91224" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Element not found\n" ] } ] }, { "cell_type": "code", "source": [ "ele = 'C'\n", "if my_dict.get(ele) is not None:\n", " print(f'{ele} is present in dictionary with {my_dict.get(ele)}')\n", "else:\n", " print(f'{ele} not in dictionary')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "cpzhMqeOPL_v", "outputId": "5feffc6d-5aad-4209-c93e-98b58931f1c9" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "C is present in dictionary with Cassendra\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Delete an Item from a Dictionary" ], "metadata": { "id": "F6xSl_gyWupG" } }, { "cell_type": "code", "source": [ "my_dict = {'a':'Append', 'b':'BredthFirstSearch', 'c':'concat', 'd':'Developing'}\n", "del my_dict['b']\n", "my_dict.pop('c')\n", "print(my_dict)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rldkHmZog2u3", "outputId": "c2f52b76-9abd-4136-f25b-e315e7d2535b" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{'a': 'Append', 'd': 'Developing'}\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Merge Two Dictionaries" ], "metadata": { "id": "xGalkFt6SwI7" } }, { "cell_type": "code", "source": [ "one = {1:'sai Praveen', 2:'vamsi', 3: 'nazir', 4: 'jagadhish'}\n", "two = {3:'Raja Blessing', 6:'peta subhramanyam', 7:'Pavan Putram'}\n", "one.update(two)\n", "merged = {**one, **two}\n", "print(one)\n", "print(merged)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "yqPmBZe2R0ZQ", "outputId": "baf11ac3-fdbc-40ac-9055-fa043284fb0c" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{1: 'sai Praveen', 2: 'vamsi', 3: 'Raja Blessing', 4: 'jagadhish', 6: 'peta subhramanyam', 7: 'Pavan Putram'}\n", "{1: 'sai Praveen', 2: 'vamsi', 3: 'Raja Blessing', 4: 'jagadhish', 6: 'peta subhramanyam', 7: 'Pavan Putram'}\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Catch multiple exceptions in one line" ], "metadata": { "id": "cvtuC3Sb2GIM" } }, { "cell_type": "code", "source": [ "my_list = [1,2,3]\n", "try:\n", " print(my_list[3]/0)\n", "except (IndexError, ZeroDivisionError, ValueError) as e:\n", " print('Exception Raise', str(e))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "kMvPoknhH0sh", "outputId": "d73e4336-ef79-41e2-fece-d4a28d0c443f" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Exception Raise list index out of range\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Print output without a new line" ], "metadata": { "id": "qcWq7erU7uxk" } }, { "cell_type": "code", "source": [ "print(\"I am a python\", end = \" \")\n", "print(\"Programmer!\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "G_EvZg5WOXS0", "outputId": "a0ba986e-5bd8-44d8-d6b7-f8fe2307aa43" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "I am a pyton Programmer!\n" ] } ] }, { "cell_type": "code", "source": [ "import sys\n", "sys.stdout.write(\"Hello \")\n", "sys.stdout.write(\"Praveen!\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "n-QXfZS_O3cG", "outputId": "0a9aaba6-f81e-48ab-8a40-2bc33cb3cd10" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello Praveen!" ] } ] }, { "cell_type": "markdown", "source": [ "##Get the class name of an Instance" ], "metadata": { "id": "pb83CpTAepG1" } }, { "cell_type": "code", "source": [ "class MyClass:\n", " pass\n", "obj = MyClass()\n", "\n", "class_name = type(obj).__name__\n", "class_Name = obj.__class__.__name__\n", "\n", "print(class_name)\n", "print(class_Name)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "p3H80OKUnKU1", "outputId": "dafc74d0-9dd9-4244-f144-6a621af10129" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "MyClass\n", "MyClass\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Represent Enum" ], "metadata": { "id": "BdVKEb6RD0lx" } }, { "cell_type": "code", "source": [ "from enum import Enum\n", "\n", "class Color(Enum): #Define Color Enum\n", " RED = 1\n", " GREEN = 2\n", " YELLOW = 3\n", "\n", "print(Color.RED) #Accessing Enum member\n", "\n", "print(Color.GREEN.value) #print Enum value\n", "\n", "for colors in Color: #accessing Enum through iteration\n", " print(colors) \n", "\n", "print(Color.RED == Color.RED) #Comparision Enum values\n", "print(Color.RED == Color.GREEN)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-bqHFKljGuoC", "outputId": "a1687e66-a0b9-4051-d60a-d9e8070f7cbc" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Color.RED\n", "2\n", "Color.RED\n", "Color.GREEN\n", "Color.YELLOW\n", "True\n", "False\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "OORpgoNqXowO" }, "source": [ "##Generate a random number random lib\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "K7ScBQw4X00z", "outputId": "aa15957e-429a-4bcb-8341-37a80511f920" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "1\n", "3.204923201970927\n", "E\n", "['N']\n" ] } ], "source": [ "import random as r\n", "\n", "print(r.randint(1,90)) #returns an integer between an interval\n", "print(r.random()) #returns a floating number from 0 to 1\n", "print(r.uniform(3,6)) #return a floating number in an interval\n", "print(r.choice(\"PRAVEN\")) #returns an element in a sequence\n", "print(r.choices(\"ANDE BHASKARA NAGA SAI PRAVEEN\")) #returns a list of elements in a sequence" ] }, { "cell_type": "markdown", "source": [ "##Randomly Select an element from the list" ], "metadata": { "id": "I0nJPktK8Kmt" } }, { "cell_type": "code", "source": [ "import random\n", "lis = [1,2,3,4,5,6,7,8]\n", "print(random.choice(lis))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Nys3hnaxRrHW", "outputId": "3934ebdf-e2d7-42ea-f640-bb189e60beb3" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "1\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "qlFPK30xzwe2" }, "source": [ "##Shuffle deck of cards" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "E3lVpFOgvF47", "outputId": "cb4ec1b3-891b-4785-f07f-75986b67b61a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Spades of 4\n", "Spades of 10\n", "Diamonds of 10\n", "Spades of 7\n", "Clubs of 2\n" ] } ], "source": [ "import itertools, random\n", "suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n", "ranks= ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'K', 'Q']\n", "cords = [(suit, rank) for suit in suits for rank in ranks]\n", "# chords = list(itertools.product(suits, ranks))\n", "random.shuffle(cords)\n", "for i in range(5):\n", " print(cords[i][0],'of', cords[i][1])" ] }, { "cell_type": "markdown", "source": [ "##Compute all the permutations of the string" ], "metadata": { "id": "la7yH6XgimuY" } }, { "cell_type": "code", "source": [ "from itertools import permutations\n", "text = 'abc'\n", "letters = permutations(text)\n", "words = [''.join(letter) for letter in letters]\n", "for word in words:\n", " print(word, end = ' ')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uolBp_OOz2H0", "outputId": "ca95f121-bc6d-4cb4-dbd7-eb36d559afd9" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "abc acb bac bca cab cba " ] } ] }, { "cell_type": "markdown", "source": [ "##Copy a File" ], "metadata": { "id": "fp6VARMo2MAl" } }, { "cell_type": "code", "source": [ "from shutil import copy\n", "src_file = 'path/source/file.txt'\n", "dst_file = 'path/destination/file.txt'\n", "copy(src_file, dst_file)" ], "metadata": { "id": "0MD9oLzuJIXK" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "with('path/source/file.txt', 'rb') as src_file:\n", " with('path/destination/file.txt', 'wb') as dst_file:\n", " while True:\n", " data = src_file.read(1024)\n", " if not data:\n", " break\n", " dst_file.write(data)" ], "metadata": { "id": "P8J11zEiLLxX" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Append to a File" ], "metadata": { "id": "5BShsG5DWt_9" } }, { "cell_type": "code", "source": [ "File_path = 'path/source/file.txt'\n", "with open(File_path, 'a') as file:\n", " content = \"This is the Text that I should have to append to file.txt file.\\n\"\n", " file.write(content)" ], "metadata": { "id": "muBjI9S7fkry" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Read a File Line by line into a list" ], "metadata": { "id": "e-2ix7m073pz" } }, { "cell_type": "code", "source": [ "path_file = \"path/source/file.txt\"\n", "\n", "with open(path_file, 'r') as file:\n", " lines = [line.strip() for line in file.readlines()]\n", "print(lines)" ], "metadata": { "id": "16B4dIbKPIph" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Get Line Count of a File\n" ], "metadata": { "id": "a8pXHr-YEQqx" } }, { "cell_type": "code", "source": [ "file_path= 'path/source/file.txt'\n", "with open(file_path, 'r') as file:\n", " count = 0\n", " for line in file:\n", " count += 1\n", "print(count)" ], "metadata": { "id": "ElkNV8a0K1p9" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Get the file name from the file path" ], "metadata": { "id": "uRvizGxPfNll" } }, { "cell_type": "code", "source": [ "import os\n", "file_path = 'path/source/file.txt'\n", "file_name = os.path.basename(file_path)\n", "print(file_name)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6tvSJX4MfTja", "outputId": "1f196839-3257-4ee1-a64d-a41828d9f394" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "file.txt\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Extra extension from a file name" ], "metadata": { "id": "uFactB5QWv6y" } }, { "cell_type": "code", "source": [ "import os\n", "file_name = 'file.exe'\n", "file_exe = os.path.splitext(file_name)[1]\n", "print(file_exe)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0iMJIz3rjQwY", "outputId": "8f8437c9-9711-4108-8710-e04c52e98a31" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ ".exe\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Find All File with .txt Extension Present inside a Directory" ], "metadata": { "id": "BnwIL6IJEwlT" } }, { "cell_type": "code", "source": [ "import os\n", "\n", "files= 'path/source/'\n", "for file in files:\n", "\n", " if os.path.splitext(files)[1] == '.txt':\n", " print(os.path.basename(file))\n" ], "metadata": { "id": "fxfrAPMbQLqM" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from glob import glob\n", "txt_files = glob(\"path/source/*.txt\")\n", "\n", "for file in txt_files:\n", " print(file)" ], "metadata": { "id": "b3CBIuTjRpvy" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Get the full path of the current working directory" ], "metadata": { "id": "ipKwLs8iFwTD" } }, { "cell_type": "code", "source": [ "from os import getcwd\n", "print(getcwd())" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EGBhiPSYYqgz", "outputId": "f854e395-6a4e-4421-cb1c-7b9b71bb4851" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "/content\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Check the file size" ], "metadata": { "id": "UtBK3xILGhTI" } }, { "cell_type": "code", "source": [ "from os import path\n", "\n", "file_path = 'path/to/source/file.txt'\n", "print('File size:', path.getsize(file_path), 'bytes')" ], "metadata": { "id": "q65iVXVNaHxB" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "qXJDVnpoIXvX" }, "source": [ "##Display calender" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "mF1xcl3zJBya", "outputId": "eeca042b-84ff-44b0-8625-a862eb8fabcf" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "enter year: 2001\n", "Enter month 1-12: 10\n", "\n", " October 2001\n", "Mo Tu We Th Fr Sa Su\n", " 1 2 3 4 5 6 7\n", " 8 9 10 11 12 13 14\n", "15 16 17 18 19 20 21\n", "22 23 24 25 26 27 28\n", "29 30 31\n", "\n" ] } ], "source": [ "import calendar\n", "yy = int(input('enter year: '))\n", "month = int(input('Enter month 1-12: '))\n", "print()\n", "print(calendar.month(yy, month))" ] }, { "cell_type": "markdown", "source": [ "##Convert String to dateTime" ], "metadata": { "id": "Xd54zBNO7GOk" } }, { "cell_type": "code", "source": [ "from datetime import datetime\n", "str_time = \"22-10-2001 02:30:12\"\n", "Dtime = datetime.strptime(str_time, '%d-%m-%Y %H:%M:%S')\n", "print(Dtime)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bVqsHt66A9iq", "outputId": "e75c375d-da2b-4911-bf01-fe09362dfa1e" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "2001-10-22 02:30:12\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Get file creation and modification date" ], "metadata": { "id": "85yFpP2fFk07" } }, { "cell_type": "code", "source": [ "import os, datetime\n", "\n", "file_path = 'path/to/source/file.txt'\n", "\n", "creation_time = os.path.getctime(file_path)\n", "creation_date = datetime.datetime.fromtimestamp(creation_time)\n", "print(f'File is created at {creation_time} on {creation_date}')\n", "\n", "modify_time = os.path.getmtime(file_path)\n", "modify_date = datetime.datetime.fromtimestamp(modify_time)\n", "print(f'File recently modified at {modify_time} on {modify_date}')\n" ], "metadata": { "id": "c_u0rpLoSEay" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Create a countdown timer" ], "metadata": { "id": "0dC0J8AGipYU" } }, { "cell_type": "code", "source": [ "import time\n", "\n", "def timer(minutes):\n", " seconds = minutes * 60\n", " while seconds>0:\n", " minute_remaining = seconds // 60\n", " second_remaining = seconds % 60\n", " print(f'{minute_remaining:02d} : {second_remaining:02d}')\n", " time.sleep(1)\n", " seconds -=1\n", " print(\"Time is UP!\")\n", "timer(1)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "wyrWKvqjifYx", "outputId": "3a26fbb6-1013-45f6-d1ab-c2a70b87b501" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "01 : 00\n", "00 : 59\n", "00 : 58\n", "00 : 57\n", "00 : 56\n", "00 : 55\n", "00 : 54\n", "00 : 53\n", "00 : 52\n", "00 : 51\n", "00 : 50\n", "00 : 49\n", "00 : 48\n", "00 : 47\n", "00 : 46\n", "00 : 45\n", "00 : 44\n", "00 : 43\n", "00 : 42\n", "00 : 41\n", "00 : 40\n", "00 : 39\n", "00 : 38\n", "00 : 37\n", "00 : 36\n", "00 : 35\n", "00 : 34\n", "00 : 33\n", "00 : 32\n", "00 : 31\n", "00 : 30\n", "00 : 29\n", "00 : 28\n", "00 : 27\n", "00 : 26\n", "00 : 25\n", "00 : 24\n", "00 : 23\n", "00 : 22\n", "00 : 21\n", "00 : 20\n", "00 : 19\n", "00 : 18\n", "00 : 17\n", "00 : 16\n", "00 : 15\n", "00 : 14\n", "00 : 13\n", "00 : 12\n", "00 : 11\n", "00 : 10\n", "00 : 09\n", "00 : 08\n", "00 : 07\n", "00 : 06\n", "00 : 05\n", "00 : 04\n", "00 : 03\n", "00 : 02\n", "00 : 01\n", "Time is UP!\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Measure the Elapsed time" ], "metadata": { "id": "VCI-CxpEWwlE" } }, { "cell_type": "code", "source": [ "import time\n", "start = time.time()\n", "\n", "time.sleep(3)#delay for 3seconds\n", "\n", "end = time.time()\n", "elapsed_time = end -start\n", "\n", "print(f'{elapsed_time:.2f}')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Whq8e3w3kYpt", "outputId": "3339adce-ede6-4df5-f096-fce8204b757e" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "3.01\n" ] } ] }, { "cell_type": "markdown", "source": [ "##Merge mails" ], "metadata": { "id": "th6bzthKk_-D" } }, { "cell_type": "code", "source": [ "import email\n", "import mailbox\n", "\n", "# create a new mailbox file\n", "merged_mailbox = mailbox.mbox('merged.mbox')\n", "\n", "# list of email messages to merge\n", "messages = ['message1.eml', 'message2.eml', 'message3.eml']\n", "\n", "# loop through each message and add it to the merged mailbox\n", "for msg_file in messages:\n", " with open(msg_file, 'r') as f:\n", " msg = email.message_from_file(f)\n", " merged_mailbox.add(msg)\n", "\n", "# close the merged mailbox file\n", "merged_mailbox.close()\n" ], "metadata": { "id": "4-J12l7SlFLp" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##size of an Image" ], "metadata": { "id": "K7T93qW-vs-M" } }, { "cell_type": "code", "source": [ "from PIL import Image\n", "\n", "pic = Image.open(\"picture.jpg\")\n", "width, height = pic.size\n", "print('Image resolution: ', width, \"*\", height)" ], "metadata": { "id": "8J6SbzBBvwN1" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Print color text to the terminal" ], "metadata": { "id": "NCdNIfrm7PJp" } }, { "cell_type": "code", "source": [ "# install the colorama library first by running pip install colorama\n", "\n", "from colorama import Back, Style, Fore\n", "#Fore and Back has BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE\n", "\n", "# Style has NORMAL, BRIGHT, DIM, RESET_ALL\n", "\n", "print(Fore.RED + 'Text is in RED color')\n", "print(Back.LIGHTBLACK_EX + 'Text background is in light black')\n", "print(Style.DIM + 'Text style is changed to DIM')\n", "print(Style.RESET_ALL + \"Text style can be r\")" ], "metadata": { "id": "J1vSuSMC7QUD" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "##Find hash the file" ], "metadata": { "id": "o_cgIYutyGAS" } }, { "cell_type": "code", "source": [ "import hashlib\n", "\n", "# open the file to hash\n", "with open('example.txt', 'rb') as f:\n", " # read the contents of the file\n", " contents = f.read()\n", "\n", " # generate the hash value\n", " md5_hash = hashlib.md5(contents)\n", " sha256_hash = hashlib.sha256(contents)\n", "\n", " # print the hash values\n", " print(\"MD5 hash:\", md5_hash.hexdigest())\n", " print(\"SHA256 hash:\", sha256_hash.hexdigest())\n" ], "metadata": { "id": "_N0ZIfT-yKdh" }, "execution_count": null, "outputs": [] } ], "metadata": { "colab": { "provenance": [], "toc_visible": true, "collapsed_sections": [ "cb-WOTrln57T", "Rhk4Ugn3ovja", "4UUFY_mwqYId", "ou8geTW8jml5", "9UBAdnxe71Xb", "A_g9HJ-nQZbc", "NhYzbg66YfXa", "1H1BkUyZUSho", "zuCMYneRt3yc", "KyxRw6A51pd9", "xssNXpIgXbVn", "5rcZvRC8Xrhc", "MAzjTbDpk-p2", "UCduvwyJn9Er", "GYMGjPFSzgh_", "PM9I2-oQNQrf", "LGWJ0SwPXa2d", "vEmVzdEb9Db-", "EBtWIvn-AeTZ", "-VZsY_49RSm8", "gQUtbks1RbtB", "LU0llexFRlAp", "lqhIyPS1Zg-p", "pDB5wXJLj41m", "BWwBjlnfnZ2Y", "qzzgPLk-nr9J", "D8PDiZxYGldM", "5-Vl-Pd5ih-S", "b4DnmeGakBB2", "nsPt1qAhtTsf", "qCW4WVOzyM41", "FXq7r6Bb19HQ", "40klYLAt7MFA", "M7BjhsSuVAx2", "HE-A5Gc28g-n", "hi5miv5M1p5P", "gPUDqU3Q2P0k", "zXOrCJqY2fJs", "Qyz5rkkd1Z0X", "rxMoYCELF6UJ", "zgWt459ynUcE", "7iiFPwKZEWX3", "rEvaCGJ6Gll5", "GK7Icr5uekzC", "MowlcNu5S5qX", "bpuCwpn66w9E", "U4k6wgOYWvHz", "ipk9lF4xgXGP", "JH4ObQHTdMht", "5cw4EVwxcwGf", "pmVTqMgk7kLL", "0mHqMIJ_-lhv", "xa_i_0Wee_GN", "EtjE8MnznbyY", "hw7mcPRuij3w", "UYwyStwpilRB", "oxN0q-Yd8UnZ", "JOiL9TFPnJlg", "qMAoPMBSe07u", "dBcYYR4bCv4Y", "2zNT78RWTeva", "Aco1c3lAezO8", "tfvBuEC51toO", "8tC2rYdK13al", "1cKvry7f2X8s", "F6xSl_gyWupG", "xGalkFt6SwI7", "cvtuC3Sb2GIM", "qcWq7erU7uxk", "pb83CpTAepG1", "BdVKEb6RD0lx", "OORpgoNqXowO", "I0nJPktK8Kmt", "qlFPK30xzwe2", "la7yH6XgimuY", "fp6VARMo2MAl", "5BShsG5DWt_9", "e-2ix7m073pz", "a8pXHr-YEQqx", "uRvizGxPfNll", "uFactB5QWv6y", "BnwIL6IJEwlT", "ipKwLs8iFwTD", "UtBK3xILGhTI", "qXJDVnpoIXvX", "Xd54zBNO7GOk", "85yFpP2fFk07", "0dC0J8AGipYU", "VCI-CxpEWwlE", "th6bzthKk_-D", "K7T93qW-vs-M", "NCdNIfrm7PJp", "o_cgIYutyGAS" ], "authorship_tag": "ABX9TyNc8GeyYI72/rxV3IZv62+2", "include_colab_link": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }