diff --git a/9_Hackerrank_Challenges_2024.ipynb b/9_Hackerrank_Challenges_2024.ipynb deleted file mode 100644 index 36033d6..0000000 --- a/9_Hackerrank_Challenges_2024.ipynb +++ /dev/null @@ -1,1266 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [], - "collapsed_sections": [ - "3BTL73oqyncu", - "y8Oenp7nR4bj", - "OskLPH3AowZO", - "QYGLqy6yxgfo", - "UdRk3RZ-EK9y" - ] - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "markdown", - "source": [ - "## 1. Hacker Rank Challenge\n", - "\n", - "he provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.\n", - "\n", - "[Hacker Link](https://www.hackerrank.com/challenges/finding-the-percentage/problem?isFullScreen=true)" - ], - "metadata": { - "id": "3BTL73oqyncu" - } - }, - { - "cell_type": "code", - "source": [ - " marks = {'Krishna': [67.0, 68.0, 69.0], 'Arjun': [70.0, 78.0, 79.0],'Shankar': [87.0, 88.0, 89.0]}\n", - " print(marks)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "m59Q0lOkyG6P", - "outputId": "1373ad0d-cd1f-4656-8a72-921e7d5c480b" - }, - "execution_count": 4, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "{'Krishna': [67.0, 68.0, 69.0], 'Arjun': [70.0, 78.0, 79.0], 'Shankar': [87.0, 88.0, 89.0]}\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "for key,value in marks.items():\n", - " if key == 'Arjun':\n", - " print(sum(value)/3)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "J0UyfC18yU60", - "outputId": "3f1d208a-ed89-4e78-887e-849f5b687f5b" - }, - "execution_count": 5, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "75.66666666666667\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "\n", - "if __name__ == '__main__':\n", - " n = int(input())\n", - " student_marks = {}\n", - " for _ in range(n):\n", - " name, *line = input().split()\n", - " scores = list(map(float, line))\n", - " student_marks[name] = scores\n", - " query_name = input()\n", - "\n", - "def calculate(student_marks, name):\n", - " print('Marks and Name', student_marks, query_name)\n", - " result = 0\n", - " for key,value in student_marks.items():\n", - " print('Within For Loop - Key and Value', key, value)\n", - " if key == query_name:\n", - " result = sum(value)/3\n", - " break\n", - " return result\n", - "\n", - "a = calculate(student_marks, query_name)\n", - "print(format(a,'.2f'))\n" - ], - "metadata": { - "id": "zllxhXOV-EH2", - "colab": { - "base_uri": "https://localhost:8080/" - }, - "outputId": "aa77447d-622c-4f4a-d80d-ef6a6d709045" - }, - "execution_count": 7, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "3\n", - "Krishna 67 68 69\n", - "Arjun 70 98 63\n", - "Malika 52 56 60\n", - "Malika\n", - "Marks and Name {'Krishna': [67.0, 68.0, 69.0], 'Arjun': [70.0, 98.0, 63.0], 'Malika': [52.0, 56.0, 60.0]} Malika\n", - "Within For Loop - Key and Value Krishna [67.0, 68.0, 69.0]\n", - "Within For Loop - Key and Value Arjun [70.0, 98.0, 63.0]\n", - "Within For Loop - Key and Value Malika [52.0, 56.0, 60.0]\n", - "56.00\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "x = 1\n", - "n = int(input())\n", - "while x <=n:\n", - " print(x, end='')\n", - " x += 1" - ], - "metadata": { - "id": "SyZ8mSdkRuj5" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "markdown", - "source": [ - "## 2. Hackerrank Numpy Arrays\n", - "\n", - "Print the reverse NumPy array with type float.\n", - "\n", - "[Hack Link](https://www.hackerrank.com/challenges/np-arrays/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign%5Blink)" - ], - "metadata": { - "id": "y8Oenp7nR4bj" - } - }, - { - "cell_type": "code", - "source": [ - "import numpy\n", - "\n", - "def arrays(arr):\n", - " # complete this function\n", - " # use numpy.array\n", - " toarr = numpy.array(arr, dtype=numpy.float32)\n", - " return(toarr[::-1])\n", - "\n", - "arr = input().strip().split(' ')\n", - "result = arrays(arr)\n", - "print(result)\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "aB-VDu23SOSZ", - "outputId": "fc2fa996-a2fd-4043-c619-c13dc122a3f1" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "1 2 3 4 -8 -10\n", - "[-10. -8. 4. 3. 2. 1.]\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "import numpy\n", - "# Enter your code here. Read input from STDIN. Print output to STDOUT\n", - "\n", - "data = list(map(int, input().split()))\n", - "data = numpy.array(data, int)\n", - "return(numpy.reshape(data, (3,3)))\n", - "\n", - "data.shape = (3,3)\n", - "print (data)\n", - "\n", - "\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "pXRZt58Jn1ui", - "outputId": "f760a8a0-11e2-4577-f2ef-83cb807fffbc" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "1 2 3 4 5 6 7 8 9\n", - "[[1 2 3]\n", - " [4 5 6]\n", - " [7 8 9]]\n", - "[[1 2 3]\n", - " [4 5 6]\n", - " [7 8 9]]\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "import numpy\n", - "\n", - "my__1D_array = numpy.array([1, 2, 3, 4, 5, 6])\n", - "print (my__1D_array.shape)\n", - "my__1D_array.shape = (3, 3)\n", - "print (my__1D_array)\n", - "\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "obJuGSrNzBqB", - "outputId": "d055163c-fd59-45ec-86a2-042904e55da2" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "(6,)\n", - "[[1 2]\n", - " [3 4]\n", - " [5 6]]\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##3. Hackerrank Transpose and Flatten\n", - "Hackerrank Challenge [here](https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign)" - ], - "metadata": { - "id": "OskLPH3AowZO" - } - }, - { - "cell_type": "code", - "source": [ - "string = \" hello world is the first code of first every programmer\"\n", - "print(string.find(\"first\"))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "8DfBBDURo6Rr", - "outputId": "3458b4c6-5d7d-4ddd-9846-91e2919433e0" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "20\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "list1 = [[1, 2],[3,4],[5,6]]\n", - "list2 = [[7],[8],[9],[10],[11],[12]]\n", - "\n", - "new_list = []\n", - "\n", - "for item1 in list1:\n", - " for item2 in list2:\n", - " new_list.append([item1, item2])\n", - "\n", - "print(new_list)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "el11mLDBSart", - "outputId": "e2b9d2e7-067c-4ae9-c311-7f5073b23104" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##4. Hackerrank Zeros and Ones\n", - "\n", - "[Hack Link](https://www.hackerrank.com/challenges/np-zeros-and-ones/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign)" - ], - "metadata": { - "id": "QYGLqy6yxgfo" - } - }, - { - "cell_type": "code", - "source": [ - "import numpy as np\n", - "\n", - "shape = list(map(int, input().split()))\n", - "print(shape)\n", - "\n", - "print(np.zeros(shape, dtype=int))\n", - "print(np.ones(shape, dtype=int))" - ], - "metadata": { - "id": "qwwpeqoAxrFH" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "def addition(n):\n", - " return n + n\n", - "\n", - "# We double all numbers using map()\n", - "numbers = (1, 2, 3, 4)\n", - "result = map(addition, numbers)\n", - "#print(list(result))\n", - "print(list(result))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "_7kuOyv63hIy", - "outputId": "ce077501-4429-4eb4-94ef-5d35cff074cb" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "(2, 4, 6, 8)\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "engagement = {'acct': '0', 'utc_date': '2015-01-09', 'num_courses_visited': '1.0', 'total_minutes_visited': '11.6793745', 'lessons_completed': '0.0', 'projects_completed': '0.0'}\n", - "print(engagement) #{'Ghana', 'USA', 'Ukraine', 'Nigeria'}" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "7GBCkv4ttavb", - "outputId": "52477afa-9093-4d9f-d51a-4f74e07caee9" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "{'acct': '0', 'utc_date': '2015-01-09', 'num_courses_visited': '1.0', 'total_minutes_visited': '11.6793745', 'lessons_completed': '0.0', 'projects_completed': '0.0'}\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "List_Of_Games = [\n", - " {\n", - " \"Name\":\"CyberPunk 2077\",\n", - " \"Username\": \"iDontPlayCyberPunk\"\n", - " },\n", - " {\n", - " \"Name\": \"Call Of Duty: Warzone\",\n", - " \"Username\": \"minininja\"\n", - " },\n", - " {\n", - " \"Name\": \"Counter Strike: Global Offensive\",\n", - " \"Username\": \"the_brave_gamer\"\n", - " },\n", - " {\n", - " \"Name\": \"Valorant\",\n", - " \"Username\": \"thebravegamer#askmeforusername\"\n", - " },\n", - " {\n", - " \"Name\": \"Assassin's Creed Valhalla\",\n", - " \"Username\": \"CompetetiveNahiKhelta\"\n", - " },\n", - "]\n", - "# if List_Of_Games[\"Name\"] == \"CyberPunk 2077\":\n", - "# print(\"It's full of bugs but still I Play Pirated Game.\")\n", - "\n", - "for i in range(len(List_Of_Games)):\n", - " if List_Of_Games[i][\"Name\"] == \"CyberPunk 2077\":\n", - " print(\"It's full of bugs but still I Play Pirated Game.\")" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "z56m_1NStvAU", - "outputId": "65eff690-91e3-4b9e-cb64-73b0f5d2117c" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "It's full of bugs but still I Play Pirated Game.\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Random Phrase Generator" - ], - "metadata": { - "id": "gYC-1Pbiizsw" - } - }, - { - "cell_type": "code", - "source": [ - "import random\n", - "\n", - "# Take from the 50 of the least used english words from https://www.yourdictionary.com/articles/rare-words-useful-know\n", - "# Make them into set of 4 tuples. Feel free to create any number of tuples\n", - "\n", - "lest_used_words_1 = (\"2\", \"4\", \"8\", \"6\", \"5\", \"3\")\n", - "lest_used_words_2 = (\"runs\", \"hits\", \"jumps\", \"drives\", \"barfs\")\n", - "lest_used_words_3 = (\"crazily.\", \"dutifully.\", \"foolishly.\", \"merrily.\", \"occasionally.\")\n", - "lest_used_words_4 = (\"adorable\", \"clueless\", \"dirty\", \"odd\", \"stupid\")\n", - "\n", - "num = random.randrange(0,6)\n", - "print(num)\n", - "print (nouns[num] + ' ' + verbs[num] + ' ' + adv[num] + ' ' + adj[num])" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "opRrJiFejRa-", - "outputId": "d7992a37-4819-4780-d91f-6e09bc70785f" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "4\n", - "monkey barfs occasionally. stupid\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "from wonderwords import RandomWord\n", - "\n", - "r = RandomWord()\n", - "\n", - "# generate a random word\n", - "r.word()\n", - "print('Simple Random Word', r)\n", - "\n", - "# random word that starts with a and ends with en\n", - "#r.word(starts_with=\"a\", ends_with=\"en\")\n", - "print(\"Start with 'a' end with 'en':- \", r.word(starts_with=\"a\", ends_with=\"en\"))\n", - "\n", - "# generate a random noun or adjective, by default all\n", - "print(\"Word with parts of speech are included :- \",r.word(sinclude_parts_of_speech=[\"nouns\", \"adjectives\"]))\n", - "\n", - "\n", - "# you can combine multiple filtering options\n", - "r.word(starts_with=\"ru\", word_max_length=10, include_parts_of_speech=[\"verbs\"])" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "88lAILHimMzO", - "outputId": "9397f4e8-966d-4e99-abf7-81637fd09c0c" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Simple Random Word \n", - "Start with 'a' end with 'en':- abdomen\n", - "Word with parts of speech are included :- chick\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "# generate a random word between the length of 3 and 8 characters\n", - "print(\"Random word between the length of 3 and 8 characters :- \",r.word(word_min_length=8, word_max_length=12))\n", - "\n", - "# generate a random word with a custom regular expression\n", - "print(\"Random word with a custom regular expression :- \",r.word(regex=\".*a\"))\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "CRBT206pqCJM", - "outputId": "906d53b3-c3ee-435e-c910-94a938a3bb73" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Random word between the length of 3 and 8 characters :- endorsement\n", - "Random word with a custom regular expression :- tiara\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "# you can combine multiple filtering options\n", - "print(\"Random word by combining multiple filtering options :- \",r.word(starts_with=\"s\", word_min_length=5, word_max_length=10, include_parts_of_speech=[\"nouns\", \"adjectives\",\"verbs\"]))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "gbnb1Gm5qg6n", - "outputId": "e74d3ec8-c811-4631-ba19-8944547c4157" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Random word by combining multiple filtering options :- strength\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##5. The-minion-game\n", - "\n", - "\n", - "---\n", - "*Solved*.\n", - "\n", - "[Hackerrank Challenge](https://www.hackerrank.com/challenges/the-minion-game/problem?isFullScreen=true )" - ], - "metadata": { - "id": "pBIEcnKIqeoe" - } - }, - { - "cell_type": "code", - "source": [ - "## INITIAL TRIES ##\n", - "\n", - "string = \"JAPAN\"\n", - "kevin_vow= ([char for char in string if char.lower() in {'a','e','i','o','u'}])\n", - "stuart_con = ([char for char in string if char.isalpha() and char.lower() not in {'a','e','i','o','u'}])\n", - "print(kevin_vow)\n", - "print(stuart_con)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "AMh4zsobqn-E", - "outputId": "42bc9119-e961-44f2-808f-319d11de1123" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "['A', 'A']\n", - "['J', 'P', 'N']\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "string[::-1]" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 35 - }, - "id": "QXtfZPvGDXqr", - "outputId": "20c210fc-1ddf-4a3c-c801-d764b9e4d4db" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "'ANANAB'" - ], - "application/vnd.google.colaboratory.intrinsic+json": { - "type": "string" - } - }, - "metadata": {}, - "execution_count": 43 - } - ] - }, - { - "cell_type": "code", - "source": [ - "vowels = [\"A\",\"E\",\"I\",\"O\",\"U\"]\n", - "stuart = 0\n", - "kevin = 0\n", - "for pos,letter in enumerate(string,start=1):\n", - " print('pos', pos)\n", - " if letter in vowels:\n", - " print('Vowel Pos', pos)\n", - " kevin+=pos\n", - " else:\n", - " stuart+=pos\n", - "if stuart > kevin:\n", - " print(f\"Stuart {stuart}\")\n", - "elif kevin > stuart:\n", - " print(f\"Kevin {kevin}\")\n", - "else:\n", - " print(\"Draw\")\n", - "\n", - "\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "VGxEPVk07yX_", - "outputId": "331dffab-c4ec-48e1-c7b9-bfc402a1e973" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "pos 1\n", - "pos 2\n", - "Vowel Pos 2\n", - "pos 3\n", - "pos 4\n", - "Vowel Pos 4\n", - "pos 5\n", - "Stuart 9\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##6. 'Merge the Tools' Challenge\n", - "\n", - "Consider the following:\n", - "\n", - "A string, , of length where .\n", - "An integer, , where is a factor of .\n", - "We can split into substrings where each subtring, , consists of a contiguous block of characters in . Then, use each to create string such that:\n", - "\n", - "The characters in are a subsequence of the characters in .\n", - "Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string\n", - "Given and , print lines where each line denotes string .\n", - "\n", - "\n", - "*Solved*.\n", - "[Challenge Link](https://www.hackerrank.com/challenges/merge-the-tools/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign\n", - ")" - ], - "metadata": { - "id": "UdRk3RZ-EK9y" - } - }, - { - "cell_type": "code", - "source": [ - "string = 'AABCAAADA'\n", - "n = 3\n", - "u = 0\n", - "\n", - "parts = [string[i:i+n] for i in range(0, len(string), n)]\n", - "\n", - "for part in parts:\n", - " new_part = \"\"\n", - " for j in range(len(part)):\n", - " # print(\"j\", j)\n", - " # print(\"part[j] =\",part[j])\n", - " # print('part[j-1] =',part[j-1])\n", - " if j == 0 or part[j] != part[j-1] and part[j] not in new_part:\n", - " new_part += part[j]\n", - " print(new_part)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "gu2E7HWTESkW", - "outputId": "f2e8b7fa-45f7-4e4e-b099-1eda14c77ecf" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "AB\n", - "CA\n", - "AD\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "input_numbers = input('Please provide input values : ')\n", - "#Input example -- 1 5 6 7 9 -9 or 5 5 5 5\n", - "val = list(map(int, input_numbers.split()))\n", - "#val = val = [1, 2, 3, 4, 5, -9] # Smple Values\n", - "if all([True if i>0 else False for i in val]):\n", - " res=any([True if str(i)==str(i)[::-1] else False for i in val])\n", - "else:\n", - " res=False\n", - "print(res)\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "NkOc5XqYvC7g", - "outputId": "1883b8c8-3b0f-42ca-8a01-a5cf952f4156" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Please provide input values : 5 5 5 5 5\n", - "True\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "#PYTHON eval() function\n", - "x=str(print(2 + 3))\n", - "eval(x)\n", - "eval(str((2+58)))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 233 - }, - "id": "OOW8iUyQyCby", - "outputId": "ac360f3d-3855-4793-d74e-5944fe93ccbc" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "5\n" - ] - }, - { - "output_type": "error", - "ename": "NameError", - "evalue": "name 'apple' is not defined", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0meval\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0meval\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m58\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0meval\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'a'\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;34m'pple'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n", - "\u001b[0;31mNameError\u001b[0m: name 'apple' is not defined" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##7. Plus Minus\n", - "\n", - "Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.\n", - "[Hacker Rank Link](https://www.hackerrank.com/challenges/plus-minus/problem?isFullScreen=false)" - ], - "metadata": { - "id": "aKQoe0HE2I-Y" - } - }, - { - "cell_type": "code", - "source": [ - "arr=[-4, 3, -9, 0, 4, 1]\n", - "p,n,z=0,0,0\n", - "for i in arr:\n", - " if i >=1:\n", - " p +=1\n", - " elif i <= 1 and i != 0:\n", - " n +=1\n", - " else:\n", - " z +=1\n", - "print(\"{:.6f}\".format(p/len(arr)))\n", - "print(\"{:.6f}\".format(n/len(arr)))\n", - "print(\"{:.6f}\".format(z/len(arr)))\n", - "\n", - "## *********************************************\n", - "## USING LIST COMPREHENSIONS\n", - "## *********************************************\n", - "arr = [-4, 3, -9, 0, 4, 1]\n", - "\n", - "p = sum(1 for i in arr if i > 0)\n", - "n = sum(1 for i in arr if i < 0)\n", - "z = sum(1 for i in arr if i == 0)\n", - "\n", - "print(\"{:.6f}\".format(p / len(arr)))\n", - "print(\"{:.6f}\".format(n / len(arr)))\n", - "print(\"{:.6f}\".format(z / len(arr)))\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "OQ0OgMmk2V2c", - "outputId": "2f8b0a32-26da-4c05-8409-e87b3c738eb4" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "3 2 1\n", - "0.5\n", - "0.500000\n", - "0.333333\n", - "0.166667\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##8. Hackerrank Nested Lists\n", - "Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.\n", - "\n", - "[Hack Link](https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=false)" - ], - "metadata": { - "id": "-jdtAsVMoB7I" - } - }, - { - "cell_type": "code", - "source": [ - "## FIRST LET US LEARN HOW TO CREATE NESTED LIST\n", - "\n", - "# Initialize an empty list to store the final output\n", - "my_list = []\n", - "\n", - "# Initialize an empty temporary list to store each sub-list\n", - "temp_list = []\n", - "\n", - "# Take input from the user for the number of sub-lists\n", - "n = int(input('Enter the number of sub-lists: '))\n", - "\n", - "# Loop over the range of n to take input for each sub-list\n", - "for i in range(n):\n", - "\n", - " # Loop over the range of 2 to take input for each element in the sub-list\n", - " for j in range(2):\n", - "\n", - " # Take input from the user for the current element\n", - " temp_list.append(input())\n", - "\n", - " # Append the current sub-list to the final list\n", - " my_list.append(temp_list)\n", - "\n", - " # Reset the temporary list to an empty list for the next iteration\n", - " temp_list = []\n", - "\n", - "# Print the final output\n", - "print(my_list)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "eTnf6X5VpQV8", - "outputId": "c4959304-d4dc-4247-c784-3f609ea55eda" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Enter the number of sub-lists: 3\n", - "3\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "[['3', '3'], ['4', '5'], ['6', '7']]\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "records =[['A', 20],['B',50],['C', 50]]\n", - "records.sort(key=lambda x:x[1])\n", - "print(records)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "o1jn8qyIzwtb", - "outputId": "67d200a9-151e-46dc-ab5f-52fc74cbeb79" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[['A', 20], ['B', 50], ['C', 50]]\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Fibonacci Series" - ], - "metadata": { - "id": "NVVUygAD8t0B" - } - }, - { - "cell_type": "code", - "source": [ - "num = 10\n", - "n1, n2 = 0, 1\n", - "fib_l=[n1,n2]\n", - "#print(\"Fibonacci Series:\", n1, n2, end=\" \")\n", - "for i in range(2, num):\n", - " n3 = n1 + n2\n", - " n1 = n2\n", - " n2 = n3\n", - " #print(n3, end=\" \")\n", - " fib_l.append(n3)\n", - "#print(\"\\n\")\n", - "print(fib_l)\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "d-6QgNTN8wRx", - "outputId": "95c8b3c2-4a45-4fc1-ffa2-73fdf6831216" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "l = list(range(10))\n", - "l = list(map(lambda x:x*x, l))\n", - "print(l)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "qH-jhdSkJrKe", - "outputId": "c45f587e-2a5a-4af3-bcf6-a619052c46fe" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "l = list(filter(lambda x: x > 10 and x < 80, l))\n", - "print(l)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "X83QqpO6KA5j", - "outputId": "338d4b4b-1218-42ee-94f7-17aba2e6fb36" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[16, 25, 36, 49, 64]\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Validating Email Addresses : Use Regex pkg" - ], - "metadata": { - "id": "MtleXHErOg9o" - } - }, - { - "cell_type": "code", - "source": [ - "import re\n", - "\n", - "def is_valid_email(email):\n", - " # Define a regular expression for basic email validation\n", - " regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{3,}$'\n", - " return re.match(regex, email) is not None\n", - "\n", - "# Example usage\n", - "email = \"example@example.com\"\n", - "print(f\"Is the email '{email}' valid? {is_valid_email(email)}\")\n", - "\n", - "# Testing with various email addresses\n", - "emails = [\n", - " \"user@example.com\",\n", - " \"user.name+tag+sorting@example.com\",\n", - " \"user_name@example.com\",\n", - " \"user-name@example.co.uk\",\n", - " \"user.name@sub.example.com\",\n", - " \"user@example\", # Invalid\n", - " \"user@.com\", # Invalid\n", - " \"user@com\", # Invalid\n", - " \"@example.com\", # Invalid\n", - " \"user@\", # Invalid\n", - " \"user@ example.com\", # Invalid\n", - "]\n", - "\n", - "for email in emails:\n", - " print(f\"Is the email '{email}' valid? {is_valid_email(email)}\")\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "GnshC3hFOi9S", - "outputId": "9955d1a9-779e-456c-c621-4da5f83ee36d" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Is the email 'example@example.com' valid? True\n", - "Is the email 'user@example.com' valid? True\n", - "Is the email 'user.name+tag+sorting@example.com' valid? True\n", - "Is the email 'user_name@example.com' valid? True\n", - "Is the email 'user-name@example.co.uk' valid? False\n", - "Is the email 'user.name@sub.example.com' valid? True\n", - "Is the email 'user@example' valid? False\n", - "Is the email 'user@.com' valid? False\n", - "Is the email 'user@com' valid? False\n", - "Is the email '@example.com' valid? False\n", - "Is the email 'user@' valid? False\n", - "Is the email 'user@ example.com' valid? False\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "##9. Text Wrap\n", - "You are given a string *s* and width *w*.\n", - "Your task is to wrap the string into a paragraph of width *w*.\n", - "\n", - "[Hack Link](https://www.hackerrank.com/challenges/text-wrap/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign)" - ], - "metadata": { - "id": "8Xjsi8CLS6VZ" - } - }, - { - "cell_type": "code", - "source": [ - "import textwrap\n", - "\n", - "string = \"ABCDEFGHIJKLIMNOQRSTUVWXYZ\"\n", - "max_width = 4\n", - "\n", - "for i in range(0,len(string),max_width):\n", - " result = (string[i:i+max_width])\n", - " print(result)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "OzoVlBTpTRC-", - "outputId": "b7027b38-e025-4abd-83ac-3195fad0ae2b" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "ABCD\n", - "EFGH\n", - "IJKL\n", - "IMNO\n", - "QRST\n", - "UVWX\n", - "YZ\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "def wrap(string, max_width):\n", - " return (textwrap.fill(string,max_width))\n", - "\n", - "print(wrap('ABCDEFGHIJKLIMNOQRSTUVWXYZ',4))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "lkD34CkgX0Xv", - "outputId": "46844416-2181-45c8-b94d-ede458194e45" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "ABCD\n", - "EFGH\n", - "IJKL\n", - "IMNO\n", - "QRST\n", - "UVWX\n", - "YZ\n" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/Pandas_Problems.ipynb b/Pandas_Problems.ipynb deleted file mode 100644 index dac24ca..0000000 --- a/Pandas_Problems.ipynb +++ /dev/null @@ -1,1007 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [], - "authorship_tag": "ABX9TyPCk1jCrF5J8oFtiuXv2i2W", - "include_colab_link": true - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "view-in-github", - "colab_type": "text" - }, - "source": [ - "\"Open" - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Find Nth Salary\n", - "Find the nth highest salary from the Employee table. If there is no nth highest salary, return null." - ], - "metadata": { - "id": "_ckK9EKxp6iQ" - } - }, - { - "cell_type": "code", - "source": [ - "import pandas as pd" - ], - "metadata": { - "id": "sqIn4ho3p6NM" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "dJFhUtdSpvYO" - }, - "outputs": [], - "source": [ - "data = [[1, 100], [2, 200], [3, 300]]\n", - "employee = pd.DataFrame(data, columns=['Id', 'salary']).astype({'Id':'Int64', 'salary':'Int64'})" - ] - }, - { - "cell_type": "code", - "source": [ - "employee" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 143 - }, - "id": "LcsGz920p3-A", - "outputId": "9065bbf8-9164-4030-9044-0023a696314b" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - " Id salary\n", - "0 1 100\n", - "1 2 200\n", - "2 3 300" - ], - "text/html": [ - "\n", - "
\n", - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
Idsalary
01100
12200
23300
\n", - "
\n", - "
\n", - "\n", - "
\n", - " \n", - "\n", - " \n", - "\n", - " \n", - "
\n", - "\n", - "\n", - "
\n", - " \n", - "\n", - "\n", - "\n", - " \n", - "
\n", - "\n", - "
\n", - " \n", - " \n", - " \n", - "
\n", - "\n", - "
\n", - "
\n" - ], - "application/vnd.google.colaboratory.intrinsic+json": { - "type": "dataframe", - "variable_name": "employee", - "summary": "{\n \"name\": \"employee\",\n \"rows\": 3,\n \"fields\": [\n {\n \"column\": \"Id\",\n \"properties\": {\n \"dtype\": \"Int64\",\n \"num_unique_values\": 3,\n \"samples\": [\n 1,\n 2,\n 3\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"salary\",\n \"properties\": {\n \"dtype\": \"Int64\",\n \"num_unique_values\": 3,\n \"samples\": [\n 100,\n 200,\n 300\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" - } - }, - "metadata": {}, - "execution_count": 4 - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "### Solution" - ], - "metadata": { - "id": "b6G1_3F3qZCH" - } - }, - { - "cell_type": "code", - "source": [ - "def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame:\n", - "\n", - " #Create a list of uniuqe salary records. Drop duplicate salary\n", - " unique_salary = employee['salary'].drop_duplicates()\n", - "\n", - " #Sort unique_salary in descending order and get 2nd highest salary\n", - " nth_highest = unique_salary.nlargest(N).iloc[-1] if len(unique_salary) >=N and N >=1 else None\n", - "\n", - " #Create a dataframe returning SecondHighestSalary value\n", - " if nth_highest is None:\n", - " return pd.DataFrame({f'getNthHighestSalary({N})' : [None]})\n", - " else:\n", - " return pd.DataFrame({f'getNthHighestSalary({N})' : [nth_highest]})\n", - "\n" - ], - "metadata": { - "id": "_MOdIGEEqYQ9" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "result = nth_highest_salary(employee, -1)\n", - "print(result)\n", - "\n", - "result = nth_highest_salary(employee, 2)\n", - "print(result)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "maKaDDpSqf1O", - "outputId": "301de11d-078c-45ed-94dd-537b8a7d2b8a" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - " getNthHighestSalary(-1)\n", - "0 None\n", - " getNthHighestSalary(2)\n", - "0 200\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Consecutive Numbers\n", - "Find all numbers that appear at least three times consecutively.\n", - "Return the result table in any order." - ], - "metadata": { - "id": "HQuNhs2qKUZj" - } - }, - { - "cell_type": "code", - "source": [ - "## Test case DF #1\n", - "data = [[1, 1], [2, 1], [3, 1], [4, 2], [5, 1], [6, 2], [7, 2]]\n", - "logs = pd.DataFrame(data, columns=['id', 'num']).astype({'id':'Int64', 'num':'Int64'})\n", - "\n", - "## Test case DF #2\n", - "data2 = [[1, 1]]\n", - "logs2 = pd.DataFrame(data2, columns=['id', 'num']).astype({'id':'Int64', 'num':'Int64'})\n", - "logs2\n", - "\n", - "## Test case DF #3\n", - "data3 = [[1, 3], [2, 3], [3, 3], [4, 3]]\n", - "logs3 = pd.DataFrame(data3, columns=['id', 'num']).astype({'id':'Int64', 'num':'Int64'})\n", - "logs3\n", - "\n", - "## Test case DF #4\n", - "data4 = [[1, 1], [2, 1], [4, 1], [5, 1],[6, 2], [7, 1]]\n", - "logs4 = pd.DataFrame(data4, columns=['id', 'num']).astype({'id':'Int64', 'num':'Int64'})\n", - "logs4" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/", - "height": 238 - }, - "id": "JjvnUzavKefK", - "outputId": "908fb3b1-4e22-42a9-fb3f-8e496a127372" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - " id num\n", - "0 1 1\n", - "1 2 1\n", - "2 4 1\n", - "3 5 1\n", - "4 6 2\n", - "5 7 1" - ], - "text/html": [ - "\n", - "
\n", - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
idnum
011
121
241
351
462
571
\n", - "
\n", - "
\n", - "\n", - "
\n", - " \n", - "\n", - " \n", - "\n", - " \n", - "
\n", - "\n", - "\n", - "
\n", - " \n", - "\n", - "\n", - "\n", - " \n", - "
\n", - "\n", - "
\n", - " \n", - " \n", - " \n", - "
\n", - "\n", - "
\n", - "
\n" - ], - "application/vnd.google.colaboratory.intrinsic+json": { - "type": "dataframe", - "variable_name": "logs4", - "summary": "{\n \"name\": \"logs4\",\n \"rows\": 6,\n \"fields\": [\n {\n \"column\": \"id\",\n \"properties\": {\n \"dtype\": \"Int64\",\n \"num_unique_values\": 6,\n \"samples\": [\n 1,\n 2,\n 7\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"num\",\n \"properties\": {\n \"dtype\": \"Int64\",\n \"num_unique_values\": 2,\n \"samples\": [\n 2,\n 1\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" - } - }, - "metadata": {}, - "execution_count": 98 - } - ] - }, - { - "cell_type": "code", - "source": [ - "import pandas as pd\n", - "\n", - "def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:\n", - "\n", - " #Let us sort the list first\n", - " logs.sort_values(by=[\"id\"], inplace=True)\n", - "\n", - " #create a list of id and num values\n", - " id_list = logs[\"id\"].values\n", - " num_list = logs[\"num\"].values\n", - "\n", - " # Initialize an empty DataFrame for results\n", - " result = pd.DataFrame(columns=['ConsecutiveNums'])\n", - "\n", - " # Check for edge cases: empty or single-row DataFrame\n", - " if len(num_list) < 3:\n", - " return result # Return an empty DataFrame if no consecutive triplets are possible\n", - "\n", - " #Now, let us loop over the lists and compare if 3 consecutive num values are the same\n", - " for i in range(len(id_list)-2):\n", - " if num_list[i] == num_list[i+1] == num_list[i+2] and id_list[i] + 1 == id_list[i+1] and id_list[i] + 2 == id_list[i+2]:\n", - " print(num_list[i])\n", - " #return the value as a Dataframe\n", - " result = result._append({'ConsecutiveNums': num_list[i]}, ignore_index=True)\n", - " result = pd.DataFrame(result['ConsecutiveNums'].unique(), columns=['ConsecutiveNums'])\n", - " return result" - ], - "metadata": { - "id": "DjXGHT2_NLFL" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "print(consecutive_numbers(logs4))" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "pKcWoCI4KjXu", - "outputId": "080ca186-d6d7-48dd-de3c-3e5b7b551bc1" - }, - "execution_count": null, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Empty DataFrame\n", - "Columns: [ConsecutiveNums]\n", - "Index: []\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "## Largest Number\n", - "\n", - "Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.\n", - "\n", - "Since the result may be very large, so you need to return a string instead of an integer.\n", - "\n", - "\n", - "*Example 1:*\n", - "\n", - "Input: nums = [10,2]\n", - "\n", - "Output: \"210\"\n", - "\n", - "\n", - "*Example 2:*\n", - "\n", - "Input: nums = [3,30,34,5,9]\n", - "\n", - "Output: \"9534330\"\n", - "\n", - "[Leet Code link](https://leetcode.com/problems/largest-number/description/?lang=pythondata)" - ], - "metadata": { - "id": "ugWspSI52rkk" - } - }, - { - "cell_type": "code", - "source": [ - "from functools import cmp_to_key\n", - "\n", - "\n", - "def largestNumber(nums) -> str:\n", - " nums_str = [str(x) for x in nums]\n", - " print('num_str=',nums_str )\n", - "\n", - " def compare(a, b):\n", - " print('value of a & b =', a,b)\n", - " if a + b > b + a:\n", - " return -1\n", - " elif a + b < b + a:\n", - " return 1\n", - " else:\n", - " return 0\n", - "\n", - " nums_str.sort(key=cmp_to_key(compare))\n", - "\n", - " if nums_str[0] == \"0\":\n", - " return \"0\"\n", - "\n", - " return \"\".join(nums_str)\n", - "\n", - "result = largestNumber([3,30,34,5,9])\n", - "print(result)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "iVC3qvcgX3XO", - "outputId": "06cf5fd0-74ac-45c4-ab91-2cd8be1a1385" - }, - "execution_count": 65, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "num_str= ['3', '30', '34', '5', '9']\n", - "value of a & b = 30 3\n", - "value of a & b = 34 30\n", - "value of a & b = 34 30\n", - "value of a & b = 34 3\n", - "value of a & b = 5 3\n", - "value of a & b = 5 34\n", - "value of a & b = 9 3\n", - "value of a & b = 9 34\n", - "value of a & b = 9 5\n", - "9534330\n" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 11ec33e..0000000 --- a/README.md +++ /dev/null @@ -1,9 +0,0 @@ -**Python Tiny Tricks** - -Python scripts that contain tips and tricks that are helpful in daily programming - -1. Import one of your .py file into another script. - useful_functions.py is a script that is being imported into import_local_scripts.py - -2. 9_Hackerrank_Challenges_2024.ipynb contains some of the neat solutions for hackerrank challenges. -3. I didn't code everyday and when I started my python jurney, it was bit of a mix-up I had with range, enumerate and zip function. This file explains all fhat --> range_vs_enumerate_vs_zip.ipynb diff --git a/exception_n_function_in_for_loop.py b/exception_n_function_in_for_loop.py new file mode 100755 index 0000000..0ed7ce5 --- /dev/null +++ b/exception_n_function_in_for_loop.py @@ -0,0 +1,21 @@ +def create_groups(items, n): + try: + size = len(items) // n + except ZeroDivisionError as e: + print("WARNING: Please use a nonzero number. Error returned is {}".format(e)) + return [] + else: + groups = [] + for i in range(0, len(items), size): + groups.append(items[i:i + size]) + return groups + finally: + print("{} groups returned.".format(n)) + +print("Creating 6 groups...") +for group in create_groups(range(64), 6): + print(list(group)) + +print("\nCreating 0 groups...") +for group in create_groups(range(32), 0): + print(list(group)) \ No newline at end of file diff --git a/flying_circus_cast.txt b/flying_circus_cast.txt new file mode 100755 index 0000000..7c813d7 --- /dev/null +++ b/flying_circus_cast.txt @@ -0,0 +1,64 @@ +Graham Chapman, Various / ... (46 episodes, 1969-1974) +Eric Idle, Various / ... (46 episodes, 1969-1974) +Terry Jones, Various / ... (46 episodes, 1969-1974) +Michael Palin, It's Man / ... (46 episodes, 1969-1974) +Terry Gilliam, Various / ... (46 episodes, 1969-1974) +John Cleese, Announcer / ... (40 episodes, 1969-1973) +Carol Cleveland, Various / ... (34 episodes, 1969-1974) +Ian Davidson, Algy Braithwaite / ... (8 episodes, 1969-1970) +John Hughman, Alfred Lord Tennyson / ... (8 episodes, 1970-1974) +The Fred Tomlinson Singers, Amantillado Chorus / ... (7 episodes, 1969-1973) +Connie Booth, Animated Mother / ... (6 episodes, 1969-1974) +Bob Raymond, 'Dad' / ... (5 episodes, 1974) +Lyn Ashley, Algon Girl / ... (5 episodes, 1970-1972) +Rita Davies, Argument Secretary / ... (4 episodes, 1969-1972) +Stanley Mason, Clapper Man / ... (4 episodes, 1970-1971) +David Ballantyne, Ivan the Terrible / ... (3 episodes, 1970-1971) +Donna Reading, Girl in Bikini with Its Man / ... (3 episodes, 1969) +Peter Brett, Door-to-Door Martial Arts Salesman (2 episodes, 1974) +Maureen Flanagan, Anona Winn / ... (2 episodes, 1969-1970) +Katya Wyeth, Elsie / ... (2 episodes, 1969) +Frank Lester, The Late Professor Thynne (2 episodes, 1972-1974) +Neil Innes, Hesitant guitarist / ... (2 episodes, 1974) +Dick Vosburgh, Van der Berg (1 episode, 1969) +Sandra Richards, 'Semprini' Girl / ... (1 episode, 1970) +Julia Breck, Puss In Boots / ... (1 episode, 1972) +Nicki Howorth, Miss Bladder (1 episode, 1972) +Jimmy Hill, Himself (1 episode, 1974) +Barry Cryer, Herman Rodrigues (1 episode, 1969) +Jeannette Wild, Second Secretary (1 episode, 1970) +Marjorie Wilde, Dear Old Lady (1 episode, 1970) +Marie Anderson, Girl interviewing the announcer (1 episode, 1972) +Caron Gardner, Mary (1 episode, 1973) +Nosher Powell, Jack Bodell (1 episode, 1973) +Carolae Donoghue, Vera's Husband's Mistress (1 episode, 1969) +Vincent Wong, Mr. Kamikaze (1 episode, 1970) +Helena Clayton, Various Roles (1 episode, 1971) +Nigel Jones, Various (1 episode, 1972) +Roy Gunson, (1 episode, 1970) +Daphne Davey, Various Roles (1 episode, 1971) +Stenson Falke, (1 episode, 1974) +Alexander Curry, Various (1 episode, 1970) +Frank Williams, Clerk of the Court (1 episode, 1972) +Ralph Wood, (1 episode, 1970) +Rosalind Bailey, Elizabethan Girl (1 episode, 1972) +Marion Mould, (1 episode, 1974) +Sheila Sands, Stripper / ... (uncredited) (2 episodes, 1969) +Richard Baker, Himself - BBC News Anchor (uncredited) (3 episodes, 1972-1973) +Douglas Adams, Dr. Emile Koning - Surgeon / ... (uncredited) (2 episodes, 1974) +Ewa Aulin, Harrassed Woman (uncredited) (1 episode, 1969) +Reginald Bosanquet, Himself (uncredited) (1 episode, 1970) +Barbara Lindley, Bride (uncredited) (1 episode, 1970) +Roy Brent, Armoured Knight (uncredited) (1 episode, 1972) +Jonas Card, Armoured Knight (uncredited) (1 episode, 1972) +Tony Christopher, Armoured Knight (uncredited) (1 episode, 1972) +Beulah Hughes, (uncredited) (1 episode, 1972) +Peter Kodak, Armoured Knight (uncredited) (1 episode, 1972) +Lulu, Herself (uncredited) (1 episode, 1972) +Jay Neill, Armoured Knight (uncredited) (1 episode, 1972) +Graham Skidmore, Armoured Knight (uncredited) (1 episode, 1972) +Ringo Starr, Himself (uncredited) (1 episode, 1972) +Fred Tomlinson, Superintendent McGough (uncredited) (1 episode, 1972) +David Hamilton, Himself - Thames TV Announcer (uncredited) (1 episode, 1973) +Suzy Mandel, German Girl (uncredited) (1 episode, 1974) +Peter Woods, BBC Presenter (uncredited) (1 episode, 1974) \ No newline at end of file diff --git a/import_local_scripts.py b/import_local_scripts.py old mode 100644 new mode 100755 diff --git a/range_vs_enumerate_vs_zip.ipynb b/range_vs_enumerate_vs_zip.ipynb deleted file mode 100644 index acb71da..0000000 --- a/range_vs_enumerate_vs_zip.ipynb +++ /dev/null @@ -1,246 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "markdown", - "source": [ - "## Python range vs enumerate vs zip\n", - "\n", - "1. Python functions range(), enumerate() seems to be similar in the beginning but they serve a different purposes\n", - "\n", - "2. Where as the zip() function returns a zip object, which is an iterator of tuples. For example, we can use it to create a list of tuples by zipping in two or more separate lists together\n" - ], - "metadata": { - "id": "IcxFD6BuVD3D" - } - }, - { - "cell_type": "markdown", - "source": [ - "### range()\n", - "Generates a sequence of numbers within a specified range.\n", - "\n", - "Useful when you need to iterate a fixed number of times or access specific indices.\n", - "\n", - "Returns an iterable object." - ], - "metadata": { - "id": "2LFNq_fMXPmp" - } - }, - { - "cell_type": "code", - "source": [ - "for i in range(5):\n", - " print(i) # prints 0, 1, 2, 3, 4" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "2R3ppXCBV5Aq", - "outputId": "985469cc-fb76-43de-afe2-0a1633c1d9fe" - }, - "execution_count": 1, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "0\n", - "1\n", - "2\n", - "3\n", - "4\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "### enumerate()\n", - "\n", - "Iterates over an iterable (like a list or string) and returns both the index and the corresponding value at each step.\n", - "\n", - "Useful when you need both the index and the value during iteration.\n", - "\n", - "Returns an enumerate object, which can be easily converted to a list of tuples." - ], - "metadata": { - "id": "AhpoMXKvXlds" - } - }, - { - "cell_type": "code", - "source": [ - "# enumerate list items\n", - "cars = ['Audi','BMW','Tesla','Ford','Toyota']\n", - "for i, car in enumerate(cars):\n", - " print(i,car) #" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "T_7CcpDBXtDI", - "outputId": "29db8ebd-1278-49ba-ffb8-e028a076447b" - }, - "execution_count": 2, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "0 Audi\n", - "1 BMW\n", - "2 Tesla\n", - "3 Ford\n", - "4 Toyota\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [ - "# enumerate a string\n", - "string = 'love cars'\n", - "for i, l in enumerate(string):\n", - " print(i,l)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "oMy0jHUuX9gV", - "outputId": "6eec0d0c-4273-404d-9f94-c201bec2ae41" - }, - "execution_count": 4, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "0 l\n", - "1 o\n", - "2 v\n", - "3 e\n", - "4 \n", - "5 c\n", - "6 a\n", - "7 r\n", - "8 s\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "### zip()\n", - "\n", - "The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it." - ], - "metadata": { - "id": "mYw4KEeFYY4t" - } - }, - { - "cell_type": "code", - "source": [ - "languages = ['Java', 'Python', 'JavaScript']\n", - "versions = [14, 3, 6]\n", - "\n", - "result = zip(languages, versions)\n", - "print(list(result))\n", - "\n", - "# Output: [('Java', 14), ('Python', 3), ('JavaScript', 6)] ## Which is list of tuples" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "V6oUhvVpYeX1", - "outputId": "f122edf7-8307-442b-adbd-71cb9d72d42c" - }, - "execution_count": 5, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[('Java', 14), ('Python', 3), ('JavaScript', 6)]\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "source": [ - "### Combine all these function into a single code snippet" - ], - "metadata": { - "id": "1jiUQVu9Y9wy" - } - }, - { - "cell_type": "code", - "source": [ - "# create a list of names\n", - "names = ['Arjun', 'Shiva', 'Artha', 'Karna', 'Rajesh']\n", - "\n", - "# create a list of subjects\n", - "subjects = ['Python', 'Go', 'C++', 'Javascript', 'SQL']\n", - "\n", - "# create a list of marks\n", - "grade = [99, 78, 97, 92, 80]\n", - "\n", - "## Zip them together\n", - "result = zip(names, subjects,grade)\n", - "print(list(result))\n", - "#[('Arjun', 'Python', 99), ('Shiva', 'Go', 78), ('Artha', 'C++', 97), ('Karna', 'Javascript', 92), ('Rajesh', 'SQL', 80)]\n", - "\n", - "# use enumerate() and zip() function\n", - "# to iterate the lists\n", - "for i, (names, subjects, grade) in enumerate(zip(names, subjects, grade)):\n", - " print(i, names, subjects, grade)" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "NDp_DzK4ZBR4", - "outputId": "9aff87c3-c9de-4659-a07c-9df107f3bf80" - }, - "execution_count": 10, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "[('Arjun', 'Python', 99), ('Shiva', 'Go', 78), ('Artha', 'C++', 97), ('Karna', 'Javascript', 92), ('Rajesh', 'SQL', 80)]\n", - "0 Arjun Python 99\n", - "1 Shiva Go 78\n", - "2 Artha C++ 97\n", - "3 Karna Javascript 92\n", - "4 Rajesh SQL 80\n" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/read_string_from_file.py b/read_string_from_file.py new file mode 100755 index 0000000..96b7354 --- /dev/null +++ b/read_string_from_file.py @@ -0,0 +1,17 @@ +## Function to read string from a plain text file +## This file refers the text file flying_circus_cast.txt file in the execution + +def create_cast_list(filename): + cast_list = [] + #use with to open the file filename + with open (filename) as f: + for line in f: + cast_list.append(line.split(',')[0]) + #use the for loop syntax to process each line + #and add the actor name to cast_list + + return cast_list + +c_list = create_cast_list('../python-programming/flying_circus_cast.txt') +for actor in c_list: + print(actor) \ No newline at end of file diff --git a/useful_functions.py b/useful_functions.py old mode 100644 new mode 100755