Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AhmedAlhallag/95e3b14a1ed9c2acd001f52abd1d9b1d to your computer and use it in GitHub Desktop.
Save AhmedAlhallag/95e3b14a1ed9c2acd001f52abd1d9b1d to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"hideCode": true,
"init_cell": true
},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'notebook_autorun'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-54ab3a830350>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'reload_ext'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'autoreload'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'autoreload'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'2'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0mnotebook_autorun\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mAutorun\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mcells\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m15\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m13\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m11\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m9\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m7\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mAutorun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcells\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcells\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mverbose\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_js\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;31mModuleNotFoundError\u001b[0m: No module named 'notebook_autorun'"
]
}
],
"source": "%reload_ext autoreload\n%autoreload 2\nfrom notebook_autorun import Autorun\ncells = [-15,-13,-11,-9,-7,-5,-3,-1]\nAutorun(cells=cells,verbose=False).add_js()"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "# Questions for the Programming module\n## Topics Covered: Strings, Lists, Dictionaries, sets, starred expressions, recursion, searching, sorting\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Nested Lists\n## **1)**\nGiven 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\nNote: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.\n\n##### Example\n\nrecords = [[\"chi\",20.0],[\"beta\",50.0],[\"alpha\",50.0]]\n\nThe ordered list of scores is [20.0,50.0], so the second lowest score is 50.0 . There are two students with that score: . [\"beta\",\"alpha\"]Ordered alphabetically, the names are printed as:\n```python\n>> alpha\n>> beta\n```\n##### Input format\nThe first line contains an integer,N, the number of students.\nThe 2N subsequent lines describe each student over 2 lines.\n- The first line contains a student's name.\n- The second line contains their grade.\n\n##### Constraints\n* 2 <= N <= 5\n* There will always be one or more students having the second lowest grade.\n\n##### Output format\nPrint the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.\n\n###### Sample input 0\n```python\n5\nHarry\n37.21\nBerry\n37.21\nTina\n37.2\nAkriti\n41\nHarsh\n39\n```\n\n###### Sample Output 0 \n```python\n>> Berry\n>> Harry\n```\n\n#### Note: This'll probably be implemented via VPL, since it has 6 test cases."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# Answer: (does not have to be exactly like mine)\nif __name__ == '__main__':\n list = []\n scores = []\n n = int(input())\n while not (2<=n<= 5):\n n = int(input())\n for _ in range(0,n):\n name = input()\n score = float(input())\n scores.append(score)\n list.append([name,score])\n second_lowests = []\n min = list[0][1]\n for inner_list in list:\n if inner_list[1] < min:\n min = inner_list[1]\n scores.sort()\n second_lowest = None\n for num in scores:\n if num > min:\n second_lowest = num\n break\n names =[]\n for i in range(0,len(list)):\n if list[i][1] == second_lowest:\n names.append(list[i][0])\n names.sort()\n for s in names:\n print(s)\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Writing functions\n## **2)**\nAn extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.\n\nIn the Gregorian calendar, three conditions are used to identify leap years:\n\n* The year can be evenly divided by 4, is a leap year, unless:\n* The year can be evenly divided by 100, it is NOT a leap year, unless:\n* The year is also evenly divisible by 400. Then it is a leap year.\n\nThis means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. <a href=\"http://www.timeanddate.com/date/leapyear.html\"> Source </a>\n\n\nTask\n\nGiven a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.\n\nNote that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function.\n\n##### Input Format\n\nRead *year*, the year to test.\n\n##### Constraints\n\n$ 1900 <= year <= 10^5 $\n\nOutput Format\n\nThe function must return a Boolean value (True/False). Output is handled by the provided code stub.\n\n##### Sample Input 0\n```python\n1990\n```\n\n##### Sample Output 0\n```python\nFalse\n```\n\n#### Note: This'll probably be implemented via VPL, since it has 5 test cases.\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# Answer: (does not have to be exactly like mine)\ndef is_leap(year):\n leap = False\n while not (1900 <= year <= 10**5):\n year = int(input())\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n leap = True\n else:\n leap = True\n return leap\n\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### List methods \n## **3)**\nConsider a list (list = []). You can perform the following commands:\n\n1. insert i e: Insert integer at position .\n2. print: Print the list.\n3. remove e: Delete the first occurrence of integer .\n4. append e: Insert integer at the end of the list.\n5. sort: Sort the list.\n6. pop: Pop the last element from the list.\n7. reverse: Reverse the list.\n8. Initialize your list and read in the value of followed by lines of commands where each command will be of the types \n9. listed above. Iterate through each command in order and perform the corresponding operation on your list.\n\n##### Example\n\n**N = 4**\n\n*append 1*\n\n*append 2*\n\n*insert 3 1*\n\n*print*\n\n* append 1: append 1 to the list, arr=[1]\n* append 2: append 2 to the list, arr=[1,2]\n* insert 3 1: insert 3 at index 1, arr=[1,3,2]\n* print: Print the array\n\n##### Output\n```python\n[1,3,2]\n````\n\n##### Input Format\n\nThe first line contains an integer, , denoting the number of commands.\nEach line of the subsequent lines contains one of the commands described above.\n\n##### Constraints\n\nThe elements added to the list must be integers.\nOutput Format\n\nFor each command of type print, print the list on a new line.\n\n##### Sample Input 0\n``` python\n12\ninsert 0 5\ninsert 1 10\ninsert 0 6\nprint\nremove 6\nappend 9\nappend 1\nsort\nprint\npop\nreverse\nprint\n```\n\n##### Sample Output 0\n```python\n[6, 5, 10]\n[1, 5, 9, 10]\n[9, 5, 1]\n```\n#### Note: This'll probably be implemented via VPL, since it has 5 test cases.\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# Answer: (does not have to be exactly like mine)\nif __name__ == '__main__':\n N = int(input())\n list = []\n\n for _ in range(N):\n data = input().split()\n cmd = data[0]\n vals = data[1:]\n if cmd == \"print\":\n print(list)\n else:\n exp = \"list.\"+ cmd +\"(\" + \",\".join(vals) + \")\"\n eval(exp)\n "
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### [Optional; >> regex]\n## **4)**\nA valid postal code **P** have to fullfil both below requirements:\n\n 1. **P** must be a number in the range from **100000** to **999999** inclusive.\n 2. **P** must not contain more than one alternating repetitive digit pair.\n \nAlternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them.\n\nFor example:\n```python\n121426 # Here, 1 is an alternating repetitive digit.\n523563 # Here, NO digit is an alternating repetitive digit.\n552523 # Here, both 2 and 5 are alternating repetitive digits.\n```\nYour task is to provide two regular expressions ```regex_integer_in_range``` and ```regex_alternating_repetitive_digit_pair```. Where:\n\n```regex_integer_in_range``` should match only integers range from **100000** to **999999** inclusive\n\n```regex_alternating_repetitive_digit_pair``` should find alternating repetitive digits pairs in a given string.\n\nBoth these regular expressions will be used by the provided code template to check if the input string is a valid postal code using the following expression:\n\n```python\n(bool(re.match(regex_integer_in_range, P)) \nand len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)\n```\n##### Input Format\n\nLocked stub code in the editor reads a single string denoting **P** from stdin and uses provided expression and your regular expressions to validate if **P** is a valid postal code.\n\n##### Output Format\n\nYou are not responsible for printing anything to stdout. Locked stub code in the editor does that.\n\n##### Sample Input 0\n\n```python\n110000\n```\n\n##### Sample Output 0\n\n```python\nFalse\n```\n\n###### Explanation 0\n\n1 1 0**0**0**0** : (0, 0) and (**0**, **0**) are two alternating digit pairs. Hence, it is an invalid postal code.\n\n###### Note:\nA score of **0** will be awarded for using 'if' conditions in your code.\nYou have to pass all the testcases to get a positive score.\n\n### You are given the following Code:\n```python\nimport re\nP = input()\n\nregex_integer_in_range = r\"_________\"\t# Write down the regex in place of the underscore. Do not delete 'r'.\nregex_alternating_repetitive_digit_pair = r\"_________\"\t# Write down the regex in place of the underscore. Do not delete 'r'.\n\nprint (bool(re.match(regex_integer_in_range, P)) \nand len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)\n```\n#### Note: This'll probably be implemented via VPL, since it has 6 test cases."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "# Answer: (does not have to be exactly like mine)\n\n\nimport re\n\nP = input()\n\nregex_integer_in_range = r\"\\b[1-9]([0-9]){5}\\b\"\nregex_alternating_repetitive_digit_pair = r\"(\\d)(?=\\d\\1)\"\n\nprint (bool(re.match(regex_integer_in_range, P)) \nand len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### [Optional; >> regex]\n## **5)**\nNeo has a complex matrix script. The matrix script is a X grid of strings. It consists of alphanumeric characters, spaces and symbols \\(!,@,#,\\$,\\%,\\&\\).\n\n<img src=\"https://s3.amazonaws.com/hr-challenge-images/12524/1442753362-1075bd12d9-Capture.JPG\">\n\n\nTo decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column.\n\nIf there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability.\n\nNeo feels that there is no need to use 'if' conditions for decoding.\n\nAlphanumeric characters consist of: [A-Z, a-z, and 0-9].\n\n#### Input Format\n\nThe first line contains space-separated integers N (rows) and M (columns) respectively.\nThe next N lines contain the row elements of the matrix script.\n\nConstraints\n\n$ 0 < N , M < 100 $\n\nNote: A 0 score will be awarded for using 'if' conditions in your code.\n\n##### Output Format\n\nPrint the decoded matrix script.\n\n##### Sample Input 0\n\n```\n7 3\nTsi\nh%x\ni #\nsM \n$a \n#t%\nir!\n```\n\n##### Sample Output 0\n```\nThis is Matrix# %!\n```\n\n##### Explanation 0\n\nThe decoded script is:\n\n```\nThis$#is% Matrix# %!\n```\n\nNeo replaces the symbols or spaces between two alphanumeric characters with a single space ' ' for better readability.\n\nSo, the final decoded script is:\n\n```\nThis is Matrix# %!\n```\n#### Note: This'll probably be implemented via VPL, since it has 6 test cases."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# Answer: (does not have to be exactly like mine)\nimport re\n\nfirst_multiple_input = input().rstrip().split()\nn = int(first_multiple_input[0])\nm = int(first_multiple_input[1])\n\nwhile not (n > 0 and m < 100):\n first_multiple_input = input().rstrip().split()\n n = int(first_multiple_input[0])\n m = int(first_multiple_input[1])\n\nmatrix = []\n\nfor _ in range(n):\n matrix_item = input()\n matrix.append(matrix_item)\ncol = []\nbigger = []\n\nfor column in range(0,m):\n for string in matrix:\n col.append(string[column])\n bigger.append(col)\n col = []\n\n\nfor elem in bigger:\n index = bigger.index(elem)\n elem = \"\".join(elem)\n bigger[index] = elem\n\nnew = \"\".join(bigger)\n\nc = re.sub(\"(?<=\\w)[^a-zA-Z0-9]+(?=\\w)\",\" \",new)\nprint(c)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## **6)**\nGiven the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given **n** scores. Store them in a list and find the score of the runner-up.\n\nInput Format\n\nThe first line contains . The second line contains an array A[] of n integers each separated by a space.\n\nConstraints\n* $ 2 <= n <= 100 $\n* $ -100<=A[i]<=100 $\n\n##### Output Format\n\nPrint the runner-up score.\n\n##### Sample Input 0\n```\n5\n2 3 6 6 5\n```\n\n##### Sample Output 0\n```\n5\n```\n\n##### Explanation 0\n\nGiven list is **[2,3,6,6,5]** . The maximum score is 6 , second maximum is 5. Hence, we print 5 as the runner-up score. "
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\n \nif __name__ == '__main__':\n # constraints\n n = int(input())\n while not (2<=n<=10):\n print(\"N scores should be between 2-10 inclusive\")\n n = int(input())\n \n arr = list(map(int, input().split()))\n \n while len(arr) != n:\n print(f\"You should enter {n} white-spaced values.\\nEnter the scores seperated by spaces:\\n\")\n arr = list(map(int, input().split()))\n\n for i in range(0,len(arr)):\n while not (-100 <= arr[i] <= 100):\n arr[i] = int(input(f\"Between -100 to 100. Enter Elem No.{i+1}: \"))\n \n# A detailed solution\n secondm_max = 0\n arr.sort(reverse = True)\n max = arr[0]\n for x in arr:\n if x < max:\n secondm_max = x \n break\n print(secondm_max) \n \n \n# Or a pythonic Solution\n# dist = list(set(arr))\n# dist.pop(dist.index(max(dist)))\n# print(max(dist))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Dictionaries\n## **7)**\nThe 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##### Example\n* $ marks key:value pairs are $\n* 'alpha': [20,30,40]\n* 'beta': [30,50,70]\n* query_name = 'beta'\n\n\nThe **query_name** is 'beta'. beta's average score is (30+50+70)/3 = 50.0.\n\n##### Input Format\n\nThe first line contains the integer , the number of students' records. The next lines contain the names and marks obtained by a student, each value separated by a space. The final line contains **query_name**, the name of a student to query.\n\n##### Constraints\n* 2<= n <= 10\n* 0 <= marks[i] <= 100\n* length of marks = 3\n\n##### Output Format\n\nPrint one line: The average of the marks obtained by the particular student correct to 2 decimal places.\n\n##### Sample Input 0\n```python\n3\nKrishna 67 68 69\nArjun 70 98 63\nMalika 52 56 60\nMalika\n```\n\n##### Sample Output 0\n```python\n56.00\n```\n\n##### Sample Input 1\n```python\n2\nHarsh 25 26.5 28\nAnurag 26 28 30\nHarsh\n```\n##### Sample Output 1\n```python\n26.50\n```\n#### Note: This'll probably be implemented via VPL, since it has 6 test cases."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nif __name__ == '__main__':\n n = int(input())\n student_marks = {}\n for _ in range(n):\n name, *line = input().split()\n\n scores = list(map(float, line))\n for i in range(0,len(scores)) :\n while not (0<= scores[i] <= 100):\n print(\"Mark: 0-100.\",end=\"\")\n scores[i] = float(input(f\"Enter score no.{i+1}/{len(scores)}: \"))\n\n student_marks[name] = scores\n\n query_name = input()\n marks = student_marks[query_name]\n print(f\"{sum(marks)/len(marks):.2f}\")\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## **8)**\nYou are given a patient. Every patient has a unique amount of teeth. Each tooth is either healthy 1, rotten 0 or pulled out -. Pull out any rotten teeth you find.\n##### Input\nLine 1: Integer N for the amount of rows of teeth in a mouth\nNext N lines: Rows of teeth\n##### Output\nOutput the entire mouth of the patient after you have pulled out all the rotten teeth.\n###### Constraints\n2 \u2264 N \u2264 10\nExample\n###### Input Sample 0\n```python\n2\n----------1---------\n----------0---------\n```\n##### Output Sample 0\n\n```python\n----------1---------\n--------------------\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nteeth = []\nfor i in range(n):\n row = input()\n if row.find(\"0\"):\n teeth.append(row.replace(\"0\",\"-\"))\n else:\n teeth.append(row)\n\n\nfor i in teeth:\n print(i)\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## **9)**\n\nNo statements are given in this question. Observe the input and the expected output and try to formulte your code.\n\n\n| Input | Output \n| :- | :- \n| **```13:05```** | **```785```** \n| **```11:35```** | **```695```**\n| **```00:42```** | **```42```**"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "#Answer:\n\nduration = input()\n\ncolIdx = duration.find(\":\")\n\nh = int(duration[:colIdx])\nm = int(duration[colIdx+1:])\nconv = (h*60) + m\nprint(conv)\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Dictionaries: Histograms\n## **10)**\n\nYou have two lists:\n* <u>**First Part:**<u/>\n \n```python\n# First list is called vals, which contains some values, lets say 7 elements\nvals = [1, 3, 4, 6, 8, 9, 10]\n# Second List is called random_nums:\nrandom_nums = []\n```\nYou will stuff the second list with 7 (same length as the first list) random integers from 5 to 15, using the ```random.randint(5,15)```, so each time you run this program you should have different 7 random integers. (Do not play with the seed function)\n\n##### Explanation \nSay for domenstration the resultant second list, random_nums is said to be (for one run) :\n```python\n>> random_nums\n[14, 13, 9, 8, 8, 15, 15] \n ```\n* <u>**Second Part:**<u/>\n\nMap each random integer that you generated in the random_nums list to the element of the same index from the vals list, to create a new list of pairs, in each pair the one element is an integer from the vals list and the other element is an integer from the random_nums list (order does not really matter here)\n```python\n# For example:\n#Say that first list is shown before: \nvals = [1, 3, 4, 6, 8, 9, 10]\n# And the random list of integers is (for a specific run)\nrandom_nums = [9, 11, 11, 7, 10, 9, 13]\n# The mapped list now is:\nmapped_list = [(9, 1), (11, 3), (11, 4), (7, 6), (10, 8), (9, 9), (13, 10)] \n```\nNow treat each pair\u2019s elements as the following, one is the number (taken from vals list), and the other is the count of that number (count is the random integer taken from the random_nums list)\n\n##### Explanation:\n\nFor example : the first pair (9,1) :- \n-\t1 is the number, and 9 is the count of that number (1 is repeated 9 times, hypothetically)\n-\tThe second pair (11,3):- 3 is the number, and 11 is it\u2019s count (3 is repeated 11 times, hypothetically)\nCreate a new list using the mapped_list that we created, call it \u2018data\u2019, that has the numbers from each pair (second element in this example) repeated a number of times which equals the first element of the same pair.\nFor example: The list would have 1 repeated 9 times, then 3 repeated 11 time, then 4 repeated 11 times, etc .. \n```python\n# The list should look like this :\ndata = [1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]\n```\n\n* <u>**Third Part: (creating the histogram)**<u/>:\n\n***(Without using the Counter() from the collections module)***\n\nCreate a function and call it count_elems(a_list), that take as a list as an argument, and retuns a dictionary, the key from that dictionary is the element of the passed list, and the value to that key is the count of the element itself (which is the same as the key)\n\n#### Explanation\n```python\nFor Example: \n# The function definition\ndef count_elems(a_list):\n # your code goes here\n return count_in_dict\n\n# Recall the data list:\ndata = [1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]\n# The dictionary returned after the function call (passing the \u2018data\u2019 list) should be like this:\n>> counted = count_elems(data)\n{1: 9, 3: 11, 4: 11, 6: 7, 8: 10, 9: 9, 10: 13} \n# in each key-value pair in this dictionary: the key is the element in the data list, and the value is how many times its repeated, in other words: it\u2019s count.\n```\n\n* <u>**Fourth Part**<u/>:\n \nCreate a function and call it represent_counted(a_dict), that takes a dictionary, and prints:\n1) The Dictionary itself\n2) A table that has: the Element in that dictionary (the key), the Count of that element (the value to the key), and a Symbolic Representation for that count (using any symbolic character as tallies)\n\n##### Run Exmaple :\n\n<img src=\"https://ahmedhallag-media.s3.amazonaws.com/pic1.png\" width=400 height=400>\n\nThe Output should be like this:\n<img src=\"https://ahmedhallag-media.s3.amazonaws.com/pic2.png\" width=500 height=400>\n \n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "#answer\n# +------------Definitions-------------+\n\n# same as the Counter() function\n# Note: the \"-> dict:\" is just to indicate that it will return a dictionary; can be discarded\ndef count_elements(seq) -> dict:\n \"\"\"Tally elements from `seq`.\"\"\"\n hist = {}\n for i in seq:\n hist[i] = hist.get(i, 0) + 1 # creats a dictionary out of the redundant list (seq)\n print(hist)\n return hist\n\n# horizontal histogram :produces plus tallies for the count of each number\n# produces plus tallies for the count of each number\ndef ascii_histogram_2(count_dict) -> None:\n print(\"Number: Count: Symbols That represent each count:\")\n for k in sorted(count_dict):\n print('{0} \\t ({1}) \\t {t}'.format(k,count_dict[k] ,t = '+' * count_dict[k])) #thats multiplication not UNPACKING\n\n\n# +------------Imports-------------+\n\nimport random\n# random.seed(3) # to make the reuslt the same everytime\n\n# +------------Part 1-------------+\nvals = [1, 3, 4, 6, 8, 9, 10]\n# Each number in `vals` will occur between 5 and 15 times.\nfr = [random.randint(5,15) for v in vals ]\n# print(vals)\n# print(fr)\n\n# +------------Part 2-------------+\nziiped_list = zip(fr,vals)\ndata = []\n\nfor f, v in zip(fr, vals):\n data.extend([v] * f) # for example : [2]*3 = [2,2,2] and extenc because you cant you cant append a list\n # Note : append does not accept multiple values\n # Note: extend does not except inidividual multiple or single elements ; only accepts iterables (lists,tuples,sets)\n\n# for elem in zip(fr,vals):\n# print(elem)\n\n# print(data)\n\n# +------------Part 3:Creating the histogram-------------+\n# print(fr)\n# print(data)\ncounted_dict = count_elements(data)\n# print(counted_dict)\nascii_histogram_2(counted_dict)\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Searching & Replacing\n## **11)**\nYou are a given a string that may contain different forms of the word \"chocolate\".\nAnd since you hate chocolate for some reason, you will replace this word with any other replacement of your choice (you can prompt it as well or define it locally).\n\n##### Constraint:\nYou will have different test cases. All of these will have the word \"chocolate\", sometimes in a readable way, and sometimes with some interefering in the middle of the word.\n\n* Special characters such as: (,),[,],\",',&,#,@,!,$,^,*,~,`\n* Special Characters should be replaced with white spaces.\n\n- Replacement rules:\n * if the replacement word was of the same number of characters as the found 'chocolate' instance from the given string (after replacing the special characters with white spaces, if existed); then it will be replaced with it directly with no added talies to the right of left.\n * if the replacement word's number of characters was smaller than the found 'chocolate' instance from the given string (after replacing the special characters with white spaces, if existed); then additional (+) tallies should be added to the right/left of the replaced word to cover the span of the extracted 'chocolate' instance, note also that the replacement should be justified in the middle.\n\n#### Input/Output Samples: \n\n```python\nrep = \"IHATETHIS\"\nw = \"chocolate\" # this will be taken from user input\n```\n\n#### Test Case 1: ```len(rep)==len(w)```\n```python\n(Original)>> Chocolate! Is this what you said?\n(Reduced.)>> IHATETHIS Is this what you said\n(Replaced)>> IHATETHIS Is this what you said\n```\n#### Test Case 2: ```len(rep) < len(w)```\n```python\n(Original)>> C%h__=_=o_c-o.l,,a..t-*\\e c-h-o-c-o-l-a-t-e Enough of that!!\n(Reduced.)>> C h o c o l a t e c h o c o l a t e Enough of that\n(Replaced)>> ++++++++IHATETHIS++++++++ ++++IHATETHIS++++ Enough of that\n```\n#### Test Case 3:\n```python\n(Original)>> chari, c-h-a-s-i-s cholo c-h-o-l-o-l-o-l-o OH I can't even spell it!\n(Reduced.)>> chari c h a s i s cholo c h o l o l o l o OH I can t even spell it\n(Replaced)>> chari c h a s i s cholo c h o l o l o l o OH I can t even spell it #**[SAME, No instance found]**\n```\n#### Test Case 4: ```len(rep) < len(w)```\n```python\n(Original)>> This line does not contain c-h-o-c-o-l-a-t-e\n(Reduced.)>> This line does not contain c h o c o l a t e\n(Replaced)>> This line does not contain ++++IHATETHIS++++\n```\n#### Test Case 5: ```len(rep) < len(w)```\n```python\n(Original)>> I hate C&*^H#@OC**O@@!LATE!!!\n(Reduced.)>> I hate C H OC O LATE\n(Replaced)>> I hate +++++IHATETHIS+++++\n```\n\n#### Test Case 6: ```len(rep) < len(w)```\n```python\n(Original)>> Yeah YEAH C&*^H#@OC**O@@!LATE C H ocolate HA!\n(Reduced.)>> Yeah YEAH C H OC O LATE C H ocolate HA\n(Replaced)>> Yeah YEAH +++++IHATETHIS+++++ +IHATETHIS++ HA\n```\n\n\n\n \n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "# answer\nimport re\n\n\ndef srch_and_replace_chocolate_v2(str, replacement):\n original_reduced = re.sub(\"[^a-zA-Z0-9]\", \" \", str)\n word = [\"c\", \"h\", \"o\", \"c\", \"o\", \"l\", \"a\", \"t\", \"e\"]\n list_of_tuples = []\n for currIDX in range(0, len(original_reduced)):\n nextIDX = currIDX + 1\n if nextIDX == len(original_reduced):\n break\n if original_reduced[currIDX].lower() == \"c\":\n i = 1\n count = 1\n while((nextIDX < len(original_reduced))):\n\n if (original_reduced[nextIDX].lower() == \"c\") and (count == 1):\n break\n if original_reduced[nextIDX].lower() == word[i]:\n count += 1\n nextIDX += 1\n i += 1\n else:\n if original_reduced[nextIDX] == \" \":\n nextIDX += 1\n continue\n else:\n break\n if count == 9:\n finIDX = nextIDX - 1\n list_of_tuples.append((currIDX, finIDX))\n break\n for elem in list_of_tuples:\n i = 1\n index = list_of_tuples.index(elem)\n list_of_tuples[index] = original_reduced[elem[0]:elem[1]+1]\n\n preFinalExp = \"\"\n for i in range(len(list_of_tuples)):\n substrLen = len(list_of_tuples[i])\n tempExp = f'.replace(\"{list_of_tuples[i]}\", \"{replacement}\".center({substrLen},\"+\") )'\n preFinalExp = preFinalExp + tempExp\n\n finalExp = f'\"{original_reduced}\"{preFinalExp}'\n subbed = eval(finalExp)\n subbed = subbed.rstrip()\n print(subbed)\n return list_of_tuples, original_reduced, subbed\n\n\nlist_strings = [\n \"Chocolate! Is this what you said?\",\n \"C%h__=_=o_c-o.l,,a..t-*\\e c-h-o-c-o-l-a-t-e Enough of that!!\",\n \"chari, c-h-a-s-i-s cholo c-h-o-l-o-l-o-l-o OH I can't even spell it!\",\n \"This line does not contain c-h-o-c-o-l-a-t-e\",\n \"I hate C&*^H#@OC**O@@!LATE!!!\",\n \"Yeah YEAH C&*^H#@OC**O@@!LATE C H ocolate HA!\"\n]\n\nword = input()\n\nfor string in list_strings:\n srch_and_replace_chocolate_v2(string, word)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Smallest positive \n## **12)**\nWrite a program that finds the smallest positive number in a list.\n\n##### Sample Input 0\n```python\n[4, -6, 7, 2, -4, 10]\n```\n\n##### Sample Output 0\n```python\n2\n```\n\n##### Sample Input 1\n```python\n[.2, 5, 3, -.1, 7, 7, 6]\n```\n##### Sample Output 1\n```python\n0.2\n```\n"
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "2\n"
}
],
"source": "#answer\nl = [.2, 5, 3, -.1, 7, 7, 6]\nl = [4, -6, 7, 2, -4, 10]\n\ndef smallest_pos_v2(l):\n temp = None\n for a in l:\n if a >= 0:\n if temp == None or a < temp:\n temp = a\n return temp\n\nprint(smallest_pos_v2(l))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Dictionaries [Recursion]\n## **13)**\n\n\nGiven the following nested dictionaries:\n```python\ncourses = {\n 'spring2020': {'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Peter C.'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian',\n 'assistant': 'Andy'}},\n 'fall2020': {'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Sarah'},\n 'cs212': {'name': 'The Design of Computer Programs',\n 'teacher': 'Peter N.',\n 'assistant': 'Andy',\n 'prereq': 'cs101'},\n 'cs253': {'name': 'Web Application Engineering - Building a Blog',\n 'teacher': 'Steve',\n 'prereq': 'cs101'},\n 'cs262': {'name': 'Programming Languages - Building a Web Browser',\n 'teacher': 'Wes',\n 'assistant': 'Peter C.',\n 'prereq': 'cs101'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian'},\n 'cs387': {'name': 'Applied Cryptography',\n 'teacher': 'Dave'}},\n 'spring2044': {'cs001': {'name': 'Building a Quantum Holodeck',\n 'teacher': 'Dorina'},\n 'cs003': {'name': 'Programming a Robotic Robotics Teacher',\n 'teacher': 'Jasper'},\n }\n}\n```\n* Write a recursive function that uses one loop only to traverses and prints this nested dictionary. \n\n##### Expected Output:\n\n```python\n+-----------------------------------+\n+ Semester: spring2020 +\n+-----------------------------------+\nCourse No.: 'cs101' | name: Building a Search Engine\n | teacher: Dave\n | assistant: Peter C.\n\nCourse No.: 'cs373' | name: Programming a Robotic Car\n | teacher: Sebastian\n | assistant: Andy\n\n\n+-------------------------------+\n+ Semester: fall2020 +\n+-------------------------------+\nCourse No.: 'cs101' | name: Building a Search Engine\n | teacher: Ahmed\n | assistant: Sarah\n\nCourse No.: 'cs212' | name: The Design of Computer Programs\n | teacher: Hady\n | assistant: Micheal\n | prereq: cs101\n\nCourse No.: 'cs253' | name: Web Application Engineering - Building a Blog\n | teacher: Ashraf\n | prereq: cs101\n\nCourse No.: 'cs262' | name: Programming Languages - Building a Web Browser\n | teacher: Miral\n | assistant: Nada.\n | prereq: cs101\n\nCourse No.: 'cs373' | name: Programming a Robotic Car\n | teacher: Salma\n\nCourse No.: 'cs387' | name: Applied Cryptography\n | teacher: Roba\n\n\n+-----------------------------------+\n+ Semester: spring2044 +\n+-----------------------------------+\nCourse No.: 'cs001' | name: Building a Quantum Holodeck\n | teacher: Dina\n\nCourse No.: 'cs003' | name: Programming a Robotic Robotics Teacher\n | teacher: Sameh\n\n```\n\nNote: your function should work on **any dictionary of any depth of nesting** not only the one given in this example. "
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "#answer\n\ncourses = {\n 'spring2020': {'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Peter C.'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian',\n 'assistant': 'Andy'}},\n 'fall2020': {'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Sarah'},\n 'cs212': {'name': 'The Design of Computer Programs',\n 'teacher': 'Peter N.',\n 'assistant': 'Andy',\n 'prereq': 'cs101'},\n 'cs253': {'name': 'Web Application Engineering - Building a Blog',\n 'teacher': 'Steve',\n 'prereq': 'cs101'},\n 'cs262': {'name': 'Programming Languages - Building a Web Browser',\n 'teacher': 'Wes',\n 'assistant': 'Peter C.',\n 'prereq': 'cs101'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian'},\n 'cs387': {'name': 'Applied Cryptography',\n 'teacher': 'Dave'}},\n 'spring2044': {'cs001': {'name': 'Building a Quantum Holodeck',\n 'teacher': 'Dorina'},\n 'cs003': {'name': 'Programming a Robotic Robotics Teacher',\n 'teacher': 'Jasper'},\n }\n}\n\nlevels_deep = 0\n\ndef printme(val, n):\n if n == 1:\n var = \"Semester\"\n l = (len(var) + len(val)) * 2\n exp1 = \"+\"+\"-\"*(l-1)+\"+\"\n print(exp1)\n exp2 = f\"+ {var}: {val}\"\n diff = len(exp1) - (len(exp2)-1)\n print(exp2+\" \"*(diff-2)+\"+\")\n print(\"+\"+\"-\"*(l-1)+\"+\")\n lenFirstLabel = len(exp1)\n return lenFirstLabel\n elif n == 2:\n var = \"Course No.\"\n exp2 = f\"{var}: '{val}'\"\n lenSecondLabel = len(exp2)\n print(f\"{exp2} \", end=\"\")\n return lenSecondLabel\n\n\n\ndef goDeeper_v2(dict):\n global levels_deep, l\n is_dict = False\n elem = 0\n for key in dict:\n val = dict[key]\n if type(val).__name__ == \"dict\":\n is_dict = True\n if is_dict:\n levels_deep += 1\n l = printme(key, levels_deep)\n goDeeper_v2(val)\n else:\n if elem == 0:\n print(f\"| {key}: {dict[key]}\")\n else:\n print(f\"{' '*l} | {key}: {dict[key]}\")\n elem += 1\n\n levels_deep -= 1\n print()\n\ngoDeeper_v2(courses)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **14)**\n\nSeems like the consonants are a bit sensitive to the vowels in your string inputs.\n\n##### Constraints:\n* if a consonant was found to be followed by a vowel (or vice versa); a white space should be added between them. \n* if two sequential vowels or consonants were found, no space will be added between them, and if white spaces found to be between them, they'll be taken away.\n\n##### Sample input 1:\n```python\nbc a e k l \n```\n\n##### Sample output 1:\n```python\nbc ae kl\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nv, statement = \"aieou\", input()\nnw_char = statement[0] # -> non white space character\nfor char in statement: # bc a e k l -> here we will fixate a pointer on the current 'non-white space' character while the loop's counter will go through them all anyway\n if char != \" \":\n ZeroOrOne = (nw_char in v) != (char in v)\n print(int(ZeroOrOne)*\" \" + char, end=\"\")\n nw_char = char"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **15)**\nNo statements are given in this question. Observe the input and the expected output to figure out the problem.\n\n\n##### Input 1:\n```python\nThis sentence is long\n```\n##### Expected output 1:\n```python\nThis sentence is\nhis sentence is \nis sentence is l\ns sentence is lo\n sentence is lon\nsentence is long\n```\n\n\n##### Input 2:\n```python\nHello world\n```\n##### Expected output 2:\n```python\n Hello world\n```\n###### Input 3:\n```python\nSixteen is magic\n```\n##### Expected Output 3:\n```python\nSixteen is magic\n```\n\n##### Input 4:\n```python\nDAY NINE! GIVE IT UP FOR DAY NINE! DAY FIFTEEN! GIVE IT FOR DAY FIFTEEN!\n```\n\n##### Expected Output 4:\n```python\nDAY NINE! GIVE I\nAY NINE! GIVE IT\nY NINE! GIVE IT \n NINE! GIVE IT U\nNINE! GIVE IT UP\nINE! GIVE IT UP \nNE! GIVE IT UP F\nE! GIVE IT UP FO\n! GIVE IT UP FOR\n GIVE IT UP FOR \nGIVE IT UP FOR D\nIVE IT UP FOR DA\nVE IT UP FOR DAY\nE IT UP FOR DAY \n IT UP FOR DAY N\nIT UP FOR DAY NI\nT UP FOR DAY NIN\n UP FOR DAY NINE\nUP FOR DAY NINE!\nP FOR DAY NINE! \n FOR DAY NINE! D\nFOR DAY NINE! DA\nOR DAY NINE! DAY\nR DAY NINE! DAY \n DAY NINE! DAY F\nDAY NINE! DAY FI\nAY NINE! DAY FIF\nY NINE! DAY FIFT\n NINE! DAY FIFTE\nNINE! DAY FIFTEE\nINE! DAY FIFTEEN\nNE! DAY FIFTEEN!\nE! DAY FIFTEEN! \n! DAY FIFTEEN! G\n DAY FIFTEEN! GI\nDAY FIFTEEN! GIV\nAY FIFTEEN! GIVE\nY FIFTEEN! GIVE \n FIFTEEN! GIVE I\nFIFTEEN! GIVE IT\nIFTEEN! GIVE IT \nFTEEN! GIVE IT F\nTEEN! GIVE IT FO\nEEN! GIVE IT FOR\nEN! GIVE IT FOR \nN! GIVE IT FOR D\n! GIVE IT FOR DA\n GIVE IT FOR DAY\nGIVE IT FOR DAY \nIVE IT FOR DAY F\nVE IT FOR DAY FI\nE IT FOR DAY FIF\n IT FOR DAY FIFT\nIT FOR DAY FIFTE\nT FOR DAY FIFTEE\n FOR DAY FIFTEEN\nFOR DAY FIFTEEN!\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "#answer\ns = input()\nl = len(s)\n\n\nif l <= 16:\n diff = 16 - l \n print(diff*\" \"+s)\nelse:\n start = 0\n end = 16\n for i in range(l):\n if end <= l:\n print(s[start:end])\n start += 1\n end += 1"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **16)**\nNo statements are given in this question. Observe the input and the expected output to figure out the problem.\n\n\n\n##### Input 1: &emsp;&emsp;&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Expected output 1:\n\n\n**```! | o V - \\_/```** &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; **```!!!!!\n |o o| \n | V | \n | - | \n \\_/```** \n\n\n##### Input 2: &emsp;&emsp;&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Expected output 2:\n\n**```~ I - . O '-+-'```** &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; **```~~~~~\n I- -I \n I . I \n I O I \n '-+-'```** \n\n\n\n##### Input 3: &emsp;&emsp;&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Expected output 3:\n**```_ l 0 o = U```** &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&nbsp;&nbsp;&nbsp; **```_____\n l0 0l \n l o l \n l = l \n U ```** \n\n\n##### Input 4: &emsp;&emsp;&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Expected output 4:\n**```^ ^ ^ ^ ^ ^^^^^```** &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; **```^^^^^\n ^^ ^^ \n ^ ^ ^ \n ^ ^ ^ \n ^^^^^```** \n\n\nYou are given the following code to start with:\n```python\nhair, cheek, eye, nose, mouth, chin = input().split()\n\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nhair, cheek, eye, nose, mouth, chin = input().split()\n\nprint(hair*5)\nprint(cheek+eye+\" \"+eye+cheek)\nprint(cheek+\" \"+ nose+\" \"+cheek)\nprint(cheek+\" \"+mouth+\" \"+cheek)\nif len(chin) == 5:\n print(chin)\nelif len(chin) == 3:\n print(\" \"+ chin)\nelse:\n print(\" \"*2+chin)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **17)**\nNo statements are given in this question. Observe the input and the expected output to figure out the problem.\n\n##### Constraints:\n* **n**: number of integers to be entered.\n\n##### Sample Input 0\n```python\n5\n5 4 9 2 7\n```\n\n##### Sample Output 0\n```python\n2 4 5 7 9\n```\n\n##### Sample Input 1\n```python\n8\n5 4 1 8 9 3 7 2\n```\n##### Sample Output 1\n```python\n1 2 3 4 5 7 8 9\n```\n\n##### Sample Input 2\n```python\n10\n-38 190 180 170 160 150 140 130 120 110\n```\n##### Sample Output 2\n```python\n-38 110 120 130 140 150 160 170 180 190\n```\n\n##### Sample Input 3\n```python\n8\n-1 1 -1 1 -1 1 -1 0\n```\n##### Sample Output 3\n```python\n-1 -1 -1 -1 0 1 1 1\n```\n\n##### Sample Input 4\n```python\n3\n5 12 8\n```\n##### Sample Output 4\n```python\n5 8 12 \n```\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "#answer:\nvals=[]\nfor i in input().split():\n vals.append(int(i))\nprint(*sorted(vals))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## Slicing/Sets\n\n### **18)**\nTurns out you accidently removed a full drive from your linux machine, but thankfully you had a snapshot of your operating system so you managed to bring everything back...but you're not entirely sure if the retreavied folders were \"everything\" that existed on that drive. As a safety check you decided to write a program that count all directories from the retrieved paths.\n\n##### Constraints:\n* parent/root directories that are common should not be repeated\n* **n**: number of paths to be entered.\n\n\n\n##### Sample Input 1\n```python\n1\n/a/b/c/d/e/f\n```\n##### Sample Output 1\n```python\n6\n```\n\n##### Sample Input 2\n```python\n2\n/a/b/c/\n/d/g/k/\n\n```\n##### Sample Output 2\n```python\n6\n```\n\n##### Sample Input 3\n```python\n5\n/a/b/c/d/e\n/a/b/c/d/e/f\n/a/b/c/g\n/a/b/c/h\n/a/b/c/m/h/a/b\n```\n##### Sample Output 3\n```python\n12\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# Answer\nn = int(input())\nf = set()\nfor i in range(n):\n path = input().strip(\"/\").lstrip(\"/\")\n while path.count(\"/\"):\n f.add(path)\n path=path[:len(path)-path[::-1].index(\"/\")-1]\n f.add(path)\nprint(len(f))\n\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **19)**\nNo statements are given in this question. Observe the input and the expected output to figure out the problem.\n##### Sample Input & Output 1 \n```python\n(in1)>>e\n(in2)>>Hello World!\n(out)>>1\n```\n##### Sample Input & Output 1\n```python\n(in1)>>e\n(in2)>>welcome\n(out)>>7\n```\n##### Sample Input & Output 1\n```python\n(in1)>>a\n(in2)>>What About UPPER - and lowercase?\n(out)>>50\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "#answer\n# Expalnation: adding up all indices of a given character\nc, s = (input() for _ in range(2))\nprint(sum(i for i, v in enumerate(s)if v == c))\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "\n### **20)**\nYou and one of your colleguoes decided to have a competition.\nYou and him a given a string, you and him need to form the greatest number of substrings possible out of that string.\nBut you need something to differentiate how both of you will start off couting down the subtrings possibilites.\nSo you flip a coin, and who ever happens to have heads will create substrings that starts with a consonant, and whoever gets a tail will create substrings that starts with a vowel.\nYou end up having heads, you will create substrings starting with a consonant.\nand your collegue ends up having tails, he will create substrings starting with a vowel. \n\nWhen all possible substrings are created, the competition is called off.\n\n* Rules:\n\nA compititor gets +1 point for each occurrence of the substring in the string .\n\n###### Explanation (image):\n\n<img src=\"https://ahmedhallag-media.s3.amazonaws.com/min_1.png\">\n\nThe winner obviusly who gets his subtrings to score more points than the other.\n\n* Input Format\n * A single line of input containing the string .\n\n\n* Output Format\n * Print one line that has the name of the winner and their score separated by a space, If the game is a draw, print Draw.\n\n###### Sample Input 0\n```\nHavana\n```\n###### Sample Output 0 \n```\nYou 12\n```\n\n###### Sample Input 1\n```\nBanana\n```\n###### Sample Output 1\n```\nYou 12\n```\n\n###### Sample Input 2\n```\nBAANANAS\n```\n###### Sample Output 2\n```\nColleague 19\n```\n\n###### Sample Input 3\n```\nHAAVAANAA\n```\n###### Sample Output 3\n```\nColleague 27\n```\n\n\n###### Sample Input 4\n```\nBANANANAAAS\n```\n###### Sample Output 4\n```\nDraw\n```\n\n\n\n* Note :\nVowels are defined as \"aieou\" In this problem."
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "banana\nYou 12\n"
}
],
"source": "# answer\n\ndef competition_result(s):\n cnt_c = 0 \n cnt_v = 0 \n s=s.upper()\n for i in range(len(s)):\n if s[i] in \"aieou\".upper():\n cnt_v += (len(s)-i)\n else:\n cnt_c += (len(s)-i)\n if cnt_c > cnt_v:\n print(\"You\",cnt_c)\n elif cnt_v > cnt_c:\n print(\"Colleague\",cnt_v)\n else:\n print(\"Draw\")\n\n\n\n\nif __name__ == '__main__':\n s = input()\n competition_result(s)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "\n### **21)**\n\nWrite a program that takes two inputs, a string and a substring in that string. Your program should count how many times that substring appears in the original string.\n\n\n* Input Format\n\nThe first line of input contains the original string. The next line contains the substring.\n\n\n\n* Output Format\n\nOutput the integer number indicating the total number of occurrences of the substring in the original string.\n\n###### Sample Input\n```python\nHJKMLMLM\nMLM\n```\n###### Sample Output\n```python\n2\n```\n\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nstring, sub = (input().strip() for _ in range(2))\ncnt = 0\nfor i in range(len(string)-len(sub)+1):\n if string[i:i+len(sub)] == sub:\n cnt += 1\nprint(cnt)\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **22)**\n\nUsing **one print statement** , print the word \"Hello\" \"World\" on two seperate lines via **4 different techniques**.\n###### Output:\n```python\nHello\nWorld\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "# asnwer\n# m1\nprint(\"Hello\", \"World\", sep=\"\\n\")\n# m2\nprint(\"Hello\\nWorld\")\n# m3\nlist = [\"Hello\", \"World\"]\nprint(\"\\n\".join(list))\n# m4\ndict = {\"Hello\": \"somestuff1\", \"World\": \"somestuff2\"}\nprint(*dict, sep=\"\\n\")"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **23)**\n\nUser enters a string, and your program will output all lowercase letters converted to uppercase and vice versa.\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# A pythonic answer:\n[print(i.swapcase(), end=\"\") for i in input()]\n\n# detailed answer:\n# l = list(s)\n# for i in range(len(l)):\n# if l[i].isalpha:\n# if l[i] == l[i].lower():\n# l[i] = l[i].upper()\n# elif l[i] == l[i].upper():\n# l[i] = l[i].lower()\n# print(\"\".join(l))\n#Note: you can also use isupper() and islower()"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## List comprehensions\n\n### **24)**\nIn this problem a cubid's dimension is represented in 3 integers, Px, Py, Pz. Anotther integer n will be present to add a simple constraint.\nPrint all the possible coordinates given by (x,y,z) on 3D grid where the sum(x+y+z) != n.\nNote that:\n```python\n0 <= x <= Px\n0 <= y <= Py\n0 <= z <= Pz\n```\nHint: Try using List comprehensions.\n\n* Input Format\n\n 4 integers, 1 integer a line.\n\n###### Constraints\n\nPrint the list in lexicographic increasing order.\n\n###### Sample Input 0\n```\n(x)>> 1\n(y)>> 1\n(z)>> 1\n(n)>> 2\n```\n###### Sample Output 0\n```\n[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]\n```\n\n###### Sample Input 1\n```\n(x)>> 2\n(y)>> 2\n(z)>> 2\n(n)>> 2\n```\n###### Sample Output 1\n```\n[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 2], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 2], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]\n```\n\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Coord_planes_color.svg/1200px-Coord_planes_color.svg.png\" width=540 height=450>"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nx,y,z,n = (int(input()) for _ in range(4))\nprint([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != n])"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **25)**\nWrite a program that calculates the *absolute* difference between the sums of its diagonals.\n\n* Input Format\n\n * The first input, n, is the number of rows and columns in the square matrix .\n * Next n lines describes a horizontal vecor (a row of the matrix) that is 1*n. \n\n###### Sample Input\n```\n3\n11 2 4\n4 5 6\n10 8 -12\n```\n\n###### Sample Output\n```\n15\n```\n\n###### Explanation\n```\nSum of primary diagonal: 11 + 5 - 12 = 4\nSum of the secondary diagonal: 4 + 5 + 10 = 19\nDifference: |4 - 19| = 15\n```\n\n\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\ndef diagonalDifference(arr):\n lr,rl = 0,0\n for i in range(len(arr)):\n lr += arr[i][i]\n rl += arr[i][(len(arr)-1)-i]\n return abs(lr-rl)\n\nint(input())"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **26)**\nYour program should take in a couple of words, each word is taken in a sperate line, a words can occur twice. Print the number of occurences of each word in the order they appear in.\n\n\n* Input Format\n\n N, number of words to be entred.\n A word each line of N.\n\n* Output Format.\n First print: number if distinct words.\n Second print: Number of occurences of each word as of their appearance order.\n\n##### Sample Input\n```python\n4\nafgd\nklmno\nafgd\nlamana\n```\n###### Sample Output\n```python\n3\n2 1 1\n```\n\n###### Explanation\n\n* 3 are distinct words.\n* \"afgd\" appeared twice, each of the other words appeared once.\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nfrom collections import Counter\nwords = []\nfor _ in range(int(input())):\n words.append(input())\n \nc = Counter(words)\ndist = set(words)\nfor v in c.values():\n print(v, \"\", end=\"\")\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "# Binary to decimal\n### **27)**\n\n* The program:\nYour program must output the binary representation of each number given as input.\nEach number will be given on a separate line, you must output the binary result followed by a newline character in the same order.\nThe binary representation must always start with a 1, except for the number 0 (no zero-padding).\n\n##### Input Format:\n* Line 1: N, an integer for the amount of numbers to test.\n* N next lines: X, an integer.\n\n##### Output Format:\n* N lines: The binary representation of X.\n\n\n###### Input Example 0:\n```python\n6\n0\n1\n2\n3\n9\n256\n```\n\n###### Output Example 0:\n```python\n0\n1\n10\n11\n1001\n100000000\n```\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# a pythonic answer\n'''\nexec(\"print(f'{int(input()): b}');\" * int(input(\"How many numbers do you want to transform? \")))\n'''\n\n# a less pythonic answer:\nn = int(input())\nfor i in range(n):\n x = int(input().strip())\n print(bin(x).replace(\"0b\",\"\"))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **28)**\nWrite a program that count x if it wasn't followed by y in either directions in a string where x and y are characters. \nCase sensitive.\n\n###### Test case 1:\n```pyhton\n>> z\n>> Q\n>> zqqaiz\n2\n```\n\n###### Test case 2:\n```pyhton\n>> a\n>> b\n>> ababacak\n1\n```\n\n###### Test case 3:\n```pyhton\n>> m\n>> e\n>> elmemeee\n0\n```\n\n###### Test case 4:\n```pyhton\n>> k\n>> H\n>> khHkhokhlkHh\n2\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nx,y,text = input(), input(), input()\nc = 0 \nif text[len(text)-1] == x and text[len(text)-2] != y:\n c += 1\nif text[0] == x and text[1] != y:\n c += 1\nfor i in range(1,len(text)-1):\n if text[i] == x and (text[i+1] != y and text[i-1] != y):\n c += 1\nprint(c) \n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **29)**\nNo statements are given in this question. Observe the input and the expected output and try to formulate your code.\n\n###### Test Cases:\n```python\n>> {0:90,1:78,6:188}\n6 \n\n>> {\"Age\":23,\"Dept.No.\":3,\"YrsExp\":10}\nAge\n\n>> {\"10\":70,\"20\":71,\"30\":72}\n30\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nd2 = eval(input())\nprint(*[key for key,val in d2.items() if val == max(d2.values())])"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **30)**\nWrite a program that converts strings that represent numbers to actual numerical values using **Four different techniques**.\n###### Examples:\n```python\n>> \"12534\"\n12534\n```\n###### Guidelines:\n1) **First technique**: int() can be partially used in your code\n\n2) **Second technique**: int() cannot be used. You may use dictionaries as a data structure.\n\n3) **Third technique**: int() cannot be used nor any built in data structure (dictionaries, lists, sets, tuples)\n\n4) **Fourth technique**: int() cannot be used nor any built in data structure (dictionaries, lists, sets, tuples)"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\n# +----------Method 1: int() is partially used-----------+\nn = \"12534\"\nnum = 0 \nfor i in range(len(n)):\n num = int(n[i]) + num * 10\nprint(num)\n\n# +----------Method 2: Dictionaries-----------+\nn = \"12534\"\nnum_value_dict = {\n \"0\":0,\n \"1\":1,\n \"2\":2,\n \"3\":3,\n \"4\":4,\n \"5\":5,\n \"6\":6,\n \"7\":7,\n \"8\":8,\n \"9\":9\n}\nresult = 0 \nplace = 1\nfor digit in n[::-1]:\n result += num_value_dict[digit] * place \n temp = 0 \n place *= 10\nprint(result)\n\n# +----------Method 3: No int() v1-----------+\na = \"12534\"\nplace = 1\nresult = 0 \ntemp = 0 \nfor digit in a[::-1]:\n for d in '0123456789':\n temp += digit > d\n \n result += temp * place\n place *= 10\n temp = 0 \n\nprint(result)\n\n# +----------Method 3: No int() v2; ascii and some math-----------+\nnm = \"12534\"\n# Explanation:=============================\n# if we know that digit \"5\" --> ascii = 53\n# and \"0\" --> ascii = 48\n# we can say:\n# 53 - 48 = 5 --> for \"5\" and so on for the rest of the digits\n\n# +++ terms of a poly\n# 546: 500 + 40 + 6 == 5 * (10^2) + 4 * (10^1) + 6 * (10^0)\n\nres = 0 \nfor i in range(len(nm)):\n d = ord(nm[i]) - ord(\"0\")\n res += d * (10**((len(nm)-1)-i)) \nprint(res)\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Formatting\n### **31)**\nWrite a program that creates a right justified **binary staircase** that shows binary numbers up to a given decimal input.\n\n###### Examples:\n```python\n>> 10\n\n 0\n 1\n 10\n 11\n 100\n 101\n 110\n 111\n1000\n1001\n1010\n\n>> 5\n\n 0\n 1\n 10\n 11\n100\n101\n\n>> 16\n\n 0\n 1\n 10\n 11\n 100\n 101\n 110\n 111\n 1000\n 1001\n 1010\n 1011\n 1100\n 1101\n 1110\n 1111\n10000\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "n = int(input())\nl = len(f\"{n:b}\")\nfor i in range(n+1): print(f\"{i:{l}b}\")"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Formatting\n### **32)**\n\nDisplay a pretty tree depending on its height N given on standard input.\nThe tree is made of **N + 1: N for its branches and a one for its trunk**.\n\nTo get your tree correctly centered, each stage of the tree must be composed of an **odd number of stars**.\nFill in the empty space with points.\n\n* Input Format:\n * Line 1: an integer N (number of stages of the tree).\n\n* Output Format:\n * N lines: the tree branches (as many lines as the tree height).\n * Last line: the tree trunk.\n\nThese lines must only be made of points and stars.\n\n###### EXAMPLES:\n```python\n\n>> 3\n\n...*...\n..***..\n.*****.\n...*...\n\n>> 4\n\n....*....\n...***...\n..*****..\n.*******.\n....*....\n\n>> 7\n\n.......*.......\n......***......\n.....*****.....\n....*******....\n...*********...\n..***********..\n.*************.\n.......*.......\n\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nx = 1\nl = []\nfor i in range(n):\n l.append(x)\n x += 2\n \nw = l[len(l)-1]+2\ny = 1\nfor i in range(n):\n print(f\"{'*'*y:.^{w}}\")\n y += 2\n\nprint(f\"{'*'*1:.^{w}}\")\n "
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Sets\n### **33)**\nA program takes multiple numbers. if one of the 0123456789 digits were not found a given number, it should be printed out.\n\n* Input format:\n * n: number of lines to be entered.\n * line(s): the number(s).\n* Outout format:\n * space seperated digits that didn't appear in the given number.\n \n###### Example 1:\n```python\n>> 2\n\n>> 1275421\n6 8 0 3 9\n\n>> 89231675 \n4 0\n\n```\n\n###### Example 2:\n```python\n>> 1\n\n>> 0234567289\n1\n```\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nsA = set('0123456789')\nfor i in range(n):\n line = input()\n sB= set(line)\n print(*sA.difference(sB))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Hamming Numbers: Recursion\n### **34)**\nYou must determine which of the input list are Hamming Numbers.\n\nHamming numbers are those integers whose only prime factors are 2, 3 and 5.\n\n*'Smooth'* enough?\n\nNote: Use recursion in your solution.\n\n* Input format:\n * Line 1: the number N of integers\n * Next N lines: an integer I\n* Output format:\n * N lines: HAMMING or OTHER\n \n###### Inputs:\n```python\n10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n```\n\n###### Output:\n```python\nHAMMING\nHAMMING\nHAMMING\nHAMMING\nHAMMING\nHAMMING\nOTHER\nHAMMING\nHAMMING\nHAMMING\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "def ham(x):\n if x == 1:\n return 1\n if x % 2 == 0:\n return ham(x/2)\n if x % 3 == 0:\n return ham(x/3)\n if x % 5 == 0:\n return ham(x/5)\n return 0\n\nn = int(input())\nfor i in range(n):\n if ham(int(input())):\n print(\"HAMMING\")\n else:\n print(\"OTHER\")"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **35)**\n\nYou must convert given binary into hexadecimal.\n\n* Input format:\n * A single binary number T (0b followed by a string of 1's and 0's). The string length is N.\n* Output format:\n * A hexadecimal representation of the binary number (0x followed by a string of chars in 0123456789abcdef)\n\n###### Examples:\n```python\n>> 0b1010\n0xa\n\n>> 0b101\n0x5\n```\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **36)**\nNo statements are given in this question. Observe the input and the expected output and try to formulate your code.\n\n```python\n# Test Case 1:\n(input) >> 4\n(input) >> 1\n\n(output) > 4\n\n\n# Test Case 2:\n(input) >> 50\n(input) >> 9\n\n(output) > 1 4 16 25 36 49\n\n\n# Test Case 3:\n(input) >> 63\n(input) >> 1 4 9 16 25 36 49\n\n(output) > None # Empty string\n```\n\n\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nm = int(input())\nl = list(map(int,input().split()))\n\ns = []\nfor i in range(1,m):\n if i**2 > m:\n break\n elif i**2 in l:\n continue \n s.append(i**2)\n\ns = list(map(str,s))\nprint(\" \".join(s))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **37)**\n\nA **Harshad number** is an integer that is divisible by the sum of its own digits.\n\nFor example, 1729 is a Harshad number because 1 + 7 + 2 + 9 = 19 and 1729 = 19 \u00d7 91.\n\n* Input format:\n * A positive integer N.\n* Output format:\n\n * **true** if the integer is a Harshad number.\n \n * **false** If the integer is not a Harshad number.\n \n###### Input >> Output Examples:\n```python\n\n1229 >> false\n18 >> true\n154 >> false\n45665 >> false\n5 >> true\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nplace = 1\nds = []\nfor d in str(n)[::-1]:\n ds.append(int(d))\n place *= 10\nif (n/sum(ds)) % 1 == 0: print(\"true\")\nelse: print(\"false\")\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **38)**\n\nA **palindrome** is a piece of text where the order of the letters stay the same whether you read from left to right or right to left.\n\nYour program must output whether, for each word given on the standard input, where it is a palindrome or not.\n\nA single letter is considered to be a palindrome.\n\n* Input format:\n * Line 1: the number N of words\n * N next lines: a word W to analyze\n* Output format:\n * For each word, true if W is a palindrome, false otherwise.\n \n###### Constraints\nInput W should only contain alphabetic letters in lowercase.\n\n###### Examples:\n```python\n# inputs\n>> 2\n>> abcba\n>> crab\n\n# outputs\ntrue\nfalse\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nfor i in range(n):\n w = input()\n if w == w[::-1]:\n print(\"true\")\n else:\n print(\"false\")\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **39)**\n\nNo statements are given in this question. Observe the input and the expected output and try to formulate your code.\n\n###### Test case 1:\n```python\n# inputs\n>> 10 2 12 3 7\n>> Print the smallest number\n\n# output\n2\n```\n\n###### Test case 2:\n```python\n# inputs\n>> 5 12 11 2\n>> Print the largest number\n\n# output\n12\n```\n###### Test case 3:\n```python\n# inputs\n>> 1 2 4 3\n>> Print the 3rd number\n\n# output\n4\n```\n###### Test case 4:\n```python\n# inputs\n>> 5 4 6 2 3 7 8\n>> Print the smallest odd number\n\n# output\n3\n```\n###### Test case 5:\n```python\n# inputs\n>> 14 8 9 12 3\n>> Print the largest even number\n\n# output\n14\n```\n###### Test case 6:\n```python\n# inputs\n>> 2 3 4 5 6 7 8\n>> Print the 2nd odd number\n\n# output\n5\n```\n###### Test case 7:\n```python\n# inputs\n>> 54 27 7 28 53 36 14 5 15 30 46 60 39 61 24 3 41 86 1 31 25 11 55 2 12 97 98 99 34 64 52 20 75 96 21 101 67 102 59 85 87 22 88 50 89 100 62 69 35 70 13 37 47 103 95 79 44 19 74 4 38 77 84 40 65 90 56 48 6849 57 94 58 42 18 80 72 63 73 6 83 10 76 91 78 92 29 93 105 51 17 8 9 16 32 66 23 26 81 45 82 33 43 71 104 999\n>> Print the 101st number\n\n# output\n33\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nn = int(input())\nl = list(map(int,input().split()))\ninstruction = input().split()[2:-1]\nins = \" \".join(instruction)\nif ins == \"smallest\":\n print(min(l))\nelif ins == \"largest\":\n print(max(l))\nelif ins == \"3rd\":\n print(l[2])\nelif ins == \"smallest odd\":\n print(min([x for x in l if x % 2 != 0]))\nelif ins == \"largest even\":\n print(max([x for x in l if x % 2 == 0]))\nelif ins == \"2nd odd\":\n print([x for x in l if x % 2 != 0][1])\nelse:\n print(l[100])\n\n\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **40)**\n\nNo statements are given in this question. Observe the input and the expected output and try to formulate your code.\n\n###### Test Case 1:\n```python\n# inputs\n>> 2 \n>> 4\n\n# output\n16\n```\n\n###### Test Case 2:\n```python\n# inputs\n>> 7 \n>> 11\n\n# output\n539\n```\n\n###### Test Case 3:\n```python\n# inputs\n>> 456 \n>> 54\n\n# output\n11228544\n```\n\n###### Test Case 4:\n```python\n# inputs\n>> 1111 \n>> 79\n\n# output\n97511359\n```\n\n###### Test Case 5:\n```python\n# inputs\n>> 0 \n>> 6\n\n# output\n0\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nm = int(input())\nn = int(input())\nprint(n*(m**2))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### List methods\n### **41)**\n\nYour program must output the biggest number that is writtable by using the given digits.\n\n* Input Format:\n * Line 1: An integer N, the number of digits.\n * Line 2: N space separated digits.\n\n* Output format:\n * Line 1: The biggest number that is writtable using all the given digits.\n\n###### Test Case(s):\n```python\n# Input\n>> 1 2 3 4 5 6 7 8 9\n\n# Output\n987654321\n```"
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "9 1 2 3 4 5 6 7 8 9\n9987654321\n"
}
],
"source": "# answer\nn3 = []\nfor i in input().split():\n n3.append(int(i))\n \nn3.sort(reverse=True)\n\nn4 = list(map(str, n3))\nn5 = \"\".join(n4)\nprint(int(n5))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Formatting\n### **42)**\n\nConstruct a square using '+' characters with width and height as 'n'.\n\n###### Examples:\n```python\n>> 3\n+++\n+++\n+++\n\n>> 6\n++++++\n++++++\n++++++\n++++++\n++++++\n++++++\n\n>> 5\n+++++\n+++++\n+++++\n+++++\n+++++\n```\n"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": [
0
]
},
"outputs": [],
"source": "# answer\ns = int(input())\nfor i in range(s):\n print(\"+\"*s)\n"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **43)**\n\n\nA ball is dropped and bounces. At each rebound, the ball reaches half the height of the previous rebound.\n\nHow high the ball must be dropped so it reaches exactly the height H after the sixth rebound?\n\n* Input format:\n * An integer H, the height reached by the ball after the sixth rebound.\n\n* Output format:\n * The height at which we must drop the ball.\n###### Examples\n\n```python\n\n(input)>> 5\n(output)> 320\n\n(input)>> 120\n(output)> 7680\n\n(input)>> 3\n(output)> 192\n```\n\n"
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "5\n320\n"
}
],
"source": "# answer\nfinal = int(input())\nfor i in range(6):\n final = final * 2\nprint(final)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **44)**\nGiven two angles of a triangle, calculate the third angle.\n\n* INPUT Format:\n * A single line containing the two angles a et b separated by a space.\n\n* OUTPUT Format:\n * A single line containing the last angle c.\n\n\n###### EXAMPLE:\n\n```python\n>> 1 1\n178\n```\n"
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "1 1\n178\n"
}
],
"source": "# answer\nprint(180-sum(map(int,input().split()))) "
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **45)**\nYour program must read two numbers and output the concatenation of their difference and sum.\n\n* INPUT Format:\n * Two positive integers A and B.\n\n* OUTPUT Format:\n * The concatenated results of A-B and A+B.\n\n###### EXAMPLE:\n```python\n>> 6 4\n210\n```"
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "6 4\n210\n"
}
],
"source": "a,b = input().split()\nprint(str(int(a)-int(b))+str(int(a)+int(b)))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **46)**\n\nYou have two values, a sum and a difference, using these values find the original two numbers out of them.\n\n* INPUT Format:\n * s: the sum.\n * d: The difference.\n\n* OUTPUT Format:\n * A single line (space-seperated) that contains thw two number. Smallest number is printed first.\n\n\n##### Test Case 1:\n```python\n(s)>> 92 \n(d)>> 16\n38 54\n```\n\n##### Test Case 2:\n```python\n(s)>> 139\n(d)>> -7\n66 73\n```\n\n\n\n\n\n\n"
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"code_folding": [],
"collapsed": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "92\n16\n38 54\n"
}
],
"source": "# answer\ns,d = int(input()), int(input())\nprint(*sorted([(d+s)//2, (s-d)//2]))"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### **47)**\n\nA six-sided die is tossed by both of John and Frank for three times. Each of John and Frank wrote down a triplet of their own tosses.\n\nFor example, John's 3 tosses in a row is described by the triplet j = (j[0], j[1], j[2]), where Frank's triplet f = (f[0], f[1], f[2]).\n\nWrite some lines that compares the tosses: j[0] with f[0], j[1] with f[1], and j[2] with f[2].\n\nIf j[i] > f[i], then John is awarded 1 point.\n\nIf j[i] < f[i], then Frank is awarded 1 point.\n\nIf j[i] = f[i], then neither person receives a point.\n\nComparison points is the total points a person earned.\n\nGiven j and f, determine their respective comparison points.\n\n* Example\n\n j = [1, 2, 3]\n \n f = [3, 2, 1]\n\n * For elements *0*, Frank is awarded a point because j[0] .\n\n * For the equal elements j[1] and f[1], no points are earned.\n\n * Finally, for elements 2, j[2] > f[2] so John receives a point.\n\n * The return array is [1, 1] with John's score first and Frank's second.\n\n* Function Description\n\n * Complete the function compareTriplets in the editor below.\n\n * compareTriplets has the following parameter(s):\n\n * j: John's tosses triplet.\n * f: Frank's tosses triplet.\n\n* Return\n\n * John's score is in the first position, and Frank's score is in the second.\n\n* Input Format:\n\n * The first line contains 3 space-separated integers, j[0], j[1], and j[2], the respective values in triplet j.\n * The second line contains 3 space-separated integers, f[0], f[1], and f[2], the respective values in triplet f.\n\n\n###### Sample Input 0\n```python\n>> 5 6 7 # john's tosses\n>> 3 6 10 # frank's tosses\n```\n\n###### Sample Output 0\n```python\n1 1 # john's score, frank's score\n```\n\n###### Sample Input 1\n```python\n>> 17 28 30 # john's tosses\n>> 99 16 8 # frank's tosses\n```\n\n###### Sample Output 1\n```python\n2 1 # john's score, frank's score\n```\n"
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "99 16 8\n17 28 30\n1 2\n"
}
],
"source": "# answer\ndef compareTriplets(j, f):\n fr = 0\n jo = 0\n\n for jj, ff in zip(j, f):\n if jj > ff:\n jo += 1\n elif jj < ff:\n fr += 1\n return [jo, fr]\n\nj = list(map(int, input().rstrip().split()))\nf = list(map(int, input().rstrip().split()))\nresult = compareTriplets(j, f)\nprint(*result)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### [Advanced :: optional]\n### **48)**\n\n<b>The user hits the jackpot when he/she enters an input that equals The number 777 of any base starting base 8.</b>\n\nWrite a program that prints \"You hit the jackpot at base ```<B>```\", when a user's input is found equal to 777 of any base staring base 8.\n \nOtherwise the program should print \"No jackpot found\"\n\n* INPUT Format:\n * n: a number that can be of value 777 in any base, or any other value.\n\n* OUTPUT Format:\n * A single line stating whether the entered number is a jackpot (and of which base) or not.\n\n\n###### Test Cases:\n```python\n\n>> 777\nA jackpot found in base 10\n\n>> 1911\nA jackpot found in base 16\n\n>> 511\nA jackpot found in base 8\n\n>> 7399\nA jackpot found in base 32\n\n```"
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"code_folding": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "222\nNot a jackpot\n"
}
],
"source": "# answer\nn = int(input())\n\nfound = False\n\nfor i in range(8, 37):\n\n if 7*(1+i+i*i) == n:\n print(\"A jackpot found in base\", i)\n found = True\n break\n\nif not found:\n print(\"Not a jackpot\")"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Cryptography: Caesar Cipher [ASCII::optional]\n### **49)**\n\nEvery upper case alphabet shifts to the left, for example if the alphabet D was left shifted by 3, it will become A, and E would become B, and so on..\n\n* INPUT Format:\n * sh: shift value.\n * s: string to be encrypted (shifted). Has to be uppercase.\n\n* OUTPUT Format:\n * shifted string.\n\n\n**Test case 1:**\n```python\n(in1)>> 3\n(in2)>> H3LL0 W0RLD\n(out)>> E3II0 T0OIA\n```\n\n**Test case 2:**\n```python\n(in1)>> 6\n(in2)>> THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\n(out)>> NBY KOCWE VLIQH ZIR DOGJM IPYL NBY FUTS XIA\n```"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"code_folding": []
},
"outputs": [],
"source": "# answer\nsh = int(input())\ns = input()\nn = \"\"\nfor char in s:\n val = ord(char)-sh\n if char != \" \":\n if 65 <= val <= 90:\n n += chr(val)\n else:\n if val < 65:\n if '0' <= char <= '9':\n n += char\n else:\n n += chr(90 - (65 - val - 1))\n else:\n n += char\nprint(n)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "### Cryptography: Atbash cipher [ASCII::optional]\n### **50)**\n\nYour program must decrypt a text with Atbash cipher -- *a simple substitution cipher*.\n\nIt consists in substituting a (the first letter) for z (the last), b (the second) for y (one before last), and so on, reversing the alphabet.\n\n* INPUT Format:\n * Line 1: an encrypted word. Contains only lowercase.\n\n* OUTPUT Format:\n * Line 1: the decrypted word.\n\n**Test cases:**\n```python\n>> zyxabc\nabczyx\n\n>> svool\nhello\n\n>> abcdefghijklmnopqrstuvwxyz\nzyxwvutsrqponmlkjihgfedcba\n\n>> xlwrmtrhiformt\ncodingisruling\n```\n\n"
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"code_folding": [],
"collapsed": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "xlwrmtrhiformt\ncodingisruling\n"
}
],
"source": "# answer\ns = input()\nprint( *(chr(122-abs(97-ord(c))) for c in s), sep=\"\" )"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "\n#### MCQ [Debugging]\n\n### **01)**\n\nThe following was a humble trial of a non pythonista to write progam that will that counts all the possible substrings that that starts with a vowel in s string.\n\n###### Explanation:\n```python\nstring = \"banana\"\n# List of all substrings:\nsubs = ['anana', 'an', 'anan', 'a', 'ana']\n# substring count that starts with a vowel: -> \"aieou\"\n# a --> count: 3\n# an --> count: 2\n# ana --> count: 2\n# anan --> count: 1\n# anana --> count: 1\n# Total Count of all substrings: 9 \n>> 9\n```\n###### Problem:\nThere is a mistake in this code where instead of having the result of 9, the program hangs and goes into an infinite loop.\nChoose from the choices the fix for this problem.\nNote: the fix sould work on the following **string variations**:\n\n###### test case 1:\n```python\ns = \"banana\" # count: 9\nsubs = ['ana', 'an', 'anan', 'anana', 'a']\n>> 9\n```\n###### test case 2:\n```python\ns = \"BAANANAS\" # count: 19\nsubs = ['aa', 'as', 'aananas', 'aana', 'anana', 'anan', 'an', 'ananas', 'aan', 'ana', 'anas', 'aanan', 'a', 'aanana']\n>> 19\n```\n###### test case 3: \n```python\ns = \"ANANAS\" # count: 12\nsubs = ['a', 'anan', 'anas', 'anana', 'as', 'ana', 'ananas', 'an']\n>> 12\n```\n###### test case 4:\n```python\ns = \"BANANANAAAS\" # count: 33 \nsubs = ['anan', 'anananaaa', 'ananaa', 'anaa', 'anana', 'aaa', 'ananaaa', 'anananaaas', 'ananana', 'anaaas', 'ananaaas', 'as', 'an', 'aaas', 'anananaa', 'ana', 'a', 'aas', 'ananan', 'aa', 'anaaa']\n>> 33\n```\n###### test case 5:\n```python\ns = \"BANAASA\" # count: 14\nsubs = ['asa', 'anaas', 'an', 'anaa', 'aas', 'anaasa', 'as', 'aasa','ana', 'a', 'aa']\n>> 14\n```\n\n###### Code:\n```python\nimport re\ndef countSubs(list, s):\n cnt = 0\n s = s.lower()\n for elem in list:\n if len(elem) == 1:\n cnt += s.count(elem)\n else:\n idxs = re.search(elem, s)\n if idxs:\n idxs = idxs.span()[0]\n cnt += 1\n temp = s\n while True:\n temp = s[idxs+1:] \n idxs = re.search(elem, temp)\n if idxs:\n idxs = idxs.span()[0]\n cnt += 1\n else:\n break\n return cnt\n\nlist = ['anana', 'an', 'anan', 'a', 'ana']\ns = \"banana\"\nprint(countSubs(list,s))\n```\n\n###### Required knowledge:\nThe ```re.search()``` method takes two arguments, a pattern or a sub-string to be searched for, and a string to be searched in. It returns the first match object if there were matches. The match object contains a span attribute that has the starting and ending indices of that match. \n**Example:**\n```python\n>> import re\n>> s = \"havaana\"\n>> fmatch = re.search(\"a\",s)\n>> fmatch\n<re.Match object; span=(1, 2), match='a'>\n>> fmatch_span = fmatch.span()\n(1,2)\n>> fmatch_span[0] # starting index\n1\n>> fmatch_span[1] # ending index\n2\n```\n"
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a297d8dd551d4bbfb50ba9661a27f829",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='80px', width='100%'), options=(('Replace the \"whil\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='80px'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"danger\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\ns1 =\"Replace the \\\"while True:\\\" with \\\"while idxs:\\\"\"\n\ns2 =\"Replace 'temp = s[idxs+1:]' with 'temp = temp[idxs+1:]'\"\ns3 =\"Replace the \\\"temp = temp[idxs+1:]\\\" with \\\"temp = temp[idxs-1:]\\\" and Replace every \\\"idxs = idxs.span()[0]\\\" with \\\"idxs = idxs.span()[1]\\\"\\n\"\n\n# s4 = \"Replace every \\\"re.search()\\\" with \\\"s.count()\\\"\"\n# __.\nQ1 = create_multipleChoice_widget('Choose the fix to this problem:',[s1,s2,s3,],s2) \ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {
"hideCode": false
},
"source": "#### MCQ\n### **02)**\nWhat would be the output of the foloowing code:\n```python\nmy_dict = {'a':[0, 1, 2, 3], 'b':[0, 1, 2, 3], 'c':[0, 1, 2, 3], 'd':[0, 1, 2, 3]}\ni = 0\noutput = []\nfor key in my_dict:\n output.append(my_dict[key][i])\n i += 1\nprint(output)\n```\n\n"
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "159fbe8a74bf457698a351daaed01cf1",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='80px', width='100%'), options=(('[0, 1, 2, 3, 0, 1\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='80px'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"success\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\ns1 = \"[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]\"\ns2 = \"['a', 'b', 'c', 'd']\"\ns3 = \"[0, 1, 2, 3]\"\n\n# __.\nQ1 = create_multipleChoice_widget('Choose the fix to this problem:',[s1,s2,s3,],s3)\n# Q2 = create_multipleChoice_widget('lalalalal',['cat','dog','mouse'],'dog')\n# Q3 = create_multipleChoice_widget('jajajajaj',['blue','white','red'],'white')\n\n \ndisplay(Q1)\n# display(Q2)\n# display(Q3)"
},
{
"cell_type": "markdown",
"metadata": {
"hideCode": false
},
"source": "#### MCQ\n### **03)**\nWhat is the output of the following line:\n```python\nl = [2,3,4,5]\nprint(l[len(l)-abs(-1-len(l))]) \n```\n\n\n"
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f49d0fb8474443f183a208a05794a5bd",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='80px', width='100%'), options=(('2', 0), ('5', 1),\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='80px'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"info\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\ns1 = \"2\"\ns2 = \"5\"\ns3 = \"[4, 5]\"\ns4 = \"Index out of range\"\n\n# __.\nQ1 = create_multipleChoice_widget('Choose your answer:',[s1,s2,s3,s4],s2)\ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {
"hideCode": false
},
"source": "#### MCQ [Debuggeing]\n### **04)**\nA Classless view of an ip address can be given in a format like this:\n```python\nxxx.xxx.xxx.xxx/ROUTING_PREFIX\n>> Examples:\n192.168.0.0/16 -> ROUTING PREFIX: 16\n10.0.0.0/24 -> ROUTING PREFIX: 24\n```\nI was trying to write code that prints the routing prefix part of an ip address, but without success. Find out which of the following fixes does the job.\n\n##### Code:\n```python\nip = \"192.168.1.0/24\"\nip[len(ip) - ip[::].find(\"/\")] # A problem here ...\n```\n\n"
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "03c051ebf1c146b1bf6fd7e5ee77d8b8",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='80px', width='100%'), options=(('add : (a colon) t\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='80px'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"warning\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\n\ns1 = \"add : (a colon) to form a slice instead of the index\"\ns2 = \"add : (a colon) to form a slice instead of the index and replace the len(ip) with (len(ip)-1)\"\ns3 = \"add : (a colon) to form a slice instead of the index and a step of -1 to the inner slice\"\ns4 = \"add a start of -1, step of -1 to the inner slice \"\n\n# __.\nQ1 = create_multipleChoice_widget('Choose your fix:',[s1,s2,s3,s4],s3)\ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {
"hideCode": false
},
"source": "#### MCQ \n### **05)**\nWould the following the statement yeild true or false?\n\n```python\n(\"51\" < \"6\" and \"50\" <= \"5\" and \"6\" <= \"6\" and \"90\" == 90) or (\"True\" >= \"False\")\n```"
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "6517f95e7dc146489bd74ae12a38ebd6",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='100%', width='100%'), options=(('(False and False \u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='100%'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"info\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\n\ns1 = \"(False and False and True and False) or (True) --> True\"\ns2 = \"(True and False and True and False) or (False) --> False\"\ns3 = \"(True and False and True and False) or (True) --> True\"\ns4 = \"(True and True and True and False) or (True) --> True\"\ns5 = \"Error rasied; incomparable types.\"\n\n# (\"51\" < \"6\" and \"50\" <= \"5\" and \"6\" <= \"6\" and \"90\" == 90) or (\"True\" >= \"False\")\n\n \n# __.\nQ1 = create_multipleChoice_widget('Choose your answer:',[s1,s2,s3,s4,s5],s3)\ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "#### MCQ \n### **06)**\nWhich of the following statements will raise an error?\n\nGiven:\n\n```python\nl = [2,3,4,5]\nstring = \"Getting warmer?\"\nd = {\"name\":\"Ahmed\",\"age\":23,\"dept\":\"CS\"}\ny = 5,6\n```\n\na) \n\n```python\nl[len(l)-len(l)-1]\n```\n\nb)\n\n```python\nstring[1000:10002]\n```\n\nc)\n\n```python\nd.get(\"Name\")\n```\n\nd)\n```python\nprint(y[3:]) \n```"
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ed624e48d9174ed4bc75cb88092ce796",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='100%', width='100%'), options=(('a', 0), ('b', 1),\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='100%'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"info\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\n\ns1 = \"a\"\ns2 = \"b\"\ns3 = \"c\"\ns4 = \"d\"\ns5 = \"None of the above\"\n\n# (\"51\" < \"6\" and \"50\" <= \"5\" and \"6\" <= \"6\" and \"90\" == 90) or (\"True\" >= \"False\")\n\n \n# __.\nQ1 = create_multipleChoice_widget('Choose your answer:',[s1,s2,s3,s4,s5],s5)\ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "#### MCQ \n### **07)**\n\nGiven:\n```python\nd = {\"name\":\"Ahmed\",\"age\":23}\n```\n\nWill the followig two lines print the same result?\n\n```python\nprint(\"{name} {age}\".format(**d))\nprint(\"{a} {n}\".format(a=d[\"name\"],n=d[\"age\"])) \n```"
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8e9d647fa9c44cdc9effdec970baa252",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='100%', width='100%'), options=(('True', 0), ('Fals\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='100%'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"danger\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\n\ns1 = \"True\"\ns2 = \"False\"\n# s3 = \"c\"\n# s4 = \"d\"\n# s5 = \"None of the above\"\n\n# (\"51\" < \"6\" and \"50\" <= \"5\" and \"6\" <= \"6\" and \"90\" == 90) or (\"True\" >= \"False\")\n\n \n# __.\nQ1 = create_multipleChoice_widget('Choose your answer:',[s1,s2],s1)\ndisplay(Q1)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": "#### MCQ \n### **08)**\nWhat code generates the following output:\n\n```python \n+++++HelloWorld+++++\n```\na)\n```python\nprint(f\"{'HelloWorld':+>20}\")\n```\nb)\n```python\nprint(f\"{'HelloWorld':+^20}\")\n```\nc) \n```python\nprint(f\"{'HelloWorld':+<20}\")\n```\nd)\n```python\nprint(f\"{'HelloWorld'}\".center(20,\"-\"))\n```"
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"code_folding": [
0
],
"hideCode": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Choose your answer:\n"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ad57716a45204622bebd6744affc9578",
"version_major": 2,
"version_minor": 0
},
"text/plain": "VBox(children=(Output(), RadioButtons(layout=Layout(height='100%', width='100%'), options=(('a', 0), ('b', 1),\u2026"
},
"metadata": {},
"output_type": "display_data"
}
],
"source": "# Please Run this cell to see the MCQs\n%reload_ext autoreload\n%autoreload 2\nimport ipywidgets as widgets\nimport sys\nfrom IPython.display import display\nfrom IPython.display import clear_output\ndef create_multipleChoice_widget(description, options, correct_answer):\n if correct_answer not in options:\n options.append(correct_answer)\n \n correct_answer_index = options.index(correct_answer)\n \n radio_options = [(words, i) for i, words in enumerate(options)]\n alternativ = widgets.RadioButtons(\n options = radio_options,\n description = '',\n disabled = False,\n layout=widgets.Layout(width='100%', height='100%'))\n \n description_out = widgets.Output()\n with description_out:\n print(description)\n \n feedback_out = widgets.Output()\n\n def check_selection(b):\n a = int(alternativ.value)\n if a==correct_answer_index:\n s = '\\x1b[1;32m' + \"Correct.\\n\" #green color\n else:\n s = '\\x1b[1;31m' + \"Wrong.\\n\" #red color\n with feedback_out:\n clear_output()\n print(s)\n return\n \n check = widgets.Button(\n description=\"Submit\",\n button_style=\"danger\"\n )\n\n# check = widgets.Button(description='(50% width, 80px height) submit',\n# layout=widgets.Layout(width='50%', height='80px'))\n check.on_click(check_selection)\n \n \n return widgets.VBox([description_out, alternativ, check, feedback_out])\n\ns1 = \"a\"\ns2 = \"b\"\ns3 = \"c\"\ns4 = \"d\"\n\n\n# (\"51\" < \"6\" and \"50\" <= \"5\" and \"6\" <= \"6\" and \"90\" == 90) or (\"True\" >= \"False\")\n\n \n# __.\nQ1 = create_multipleChoice_widget('Choose your answer:',[s1,s2,s3,s4],s2)\ndisplay(Q1)"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.7",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment