Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xiaoouwang/b9845c3bce33eb5c9ec1df2939bd05a7 to your computer and use it in GitHub Desktop.
Save xiaoouwang/b9845c3bce33eb5c9ec1df2939bd05a7 to your computer and use it in GitHub Desktop.
100 Best Python Exercises for Beginners 1-10
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[FIRST PUBLISHED HERE WITH SOME DETAILED EXPLANATIONS](https://xiaoouwang.github.io/post/python100exercices/)\n",
"\n",
"[link to all the questions](https://hackmd.io/dcoNudOsS4eWwdEU0_Otqg?view#Question-9)\n",
"\n",
"[link to the markdown file](https://gist.github.com/xiaoouwang/be7133cb9705bb9cb23caa4515d48daf)"
]
},
{
"cell_type": "markdown",
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:30:37.409996Z",
"start_time": "2020-02-25T20:30:37.322707Z"
}
},
"source": [
"## 1. Find all numbers divisible by 7 but not a multiple of 5, between 2000 and 3200 (both sides included).\n",
"\n",
"The numbers obtained should be printed in a comma-separated sequence on a single line."
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:30:57.052942Z",
"start_time": "2020-02-25T20:30:57.020202Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2002,2009,2016,2023,2037,2044,2051,2058,2072,2079,2086,2093,2107,2114,2121,2128,2142,2149,2156,2163,2177,2184,2191,2198,2212,2219,2226,2233,2247,2254,2261,2268,2282,2289,2296,2303,2317,2324,2331,2338,2352,2359,2366,2373,2387,2394,2401,2408,2422,2429,2436,2443,2457,2464,2471,2478,2492,2499,2506,2513,2527,2534,2541,2548,2562,2569,2576,2583,2597,2604,2611,2618,2632,2639,2646,2653,2667,2674,2681,2688,2702,2709,2716,2723,2737,2744,2751,2758,2772,2779,2786,2793,2807,2814,2821,2828,2842,2849,2856,2863,2877,2884,2891,2898,2912,2919,2926,2933,2947,2954,2961,2968,2982,2989,2996,3003,3017,3024,3031,3038,3052,3059,3066,3073,3087,3094,3101,3108,3122,3129,3136,3143,3157,3164,3171,3178,3192,3199,"
]
}
],
"source": [
"# 1. most intuitive way\n",
"for number in range(2000,3201):\n",
" if (number%7 == 0) and (number%5 != 0):\n",
" print(number,end = \",\")"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:31:25.282912Z",
"start_time": "2020-02-25T20:31:25.251920Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"'2002,2009,2016,2023,2037,2044,2051,2058,2072,2079,2086,2093,2107,2114,2121,2128,2142,2149,2156,2163,2177,2184,2191,2198,2212,2219,2226,2233,2247,2254,2261,2268,2282,2289,2296,2303,2317,2324,2331,2338,2352,2359,2366,2373,2387,2394,2401,2408,2422,2429,2436,2443,2457,2464,2471,2478,2492,2499,2506,2513,2527,2534,2541,2548,2562,2569,2576,2583,2597,2604,2611,2618,2632,2639,2646,2653,2667,2674,2681,2688,2702,2709,2716,2723,2737,2744,2751,2758,2772,2779,2786,2793,2807,2814,2821,2828,2842,2849,2856,2863,2877,2884,2891,2898,2912,2919,2926,2933,2947,2954,2961,2968,2982,2989,2996,3003,3017,3024,3031,3038,3052,3059,3066,3073,3087,3094,3101,3108,3122,3129,3136,3143,3157,3164,3171,3178,3192,3199'"
]
},
"execution_count": 97,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 2. use list and join\n",
"l=[]\n",
"for i in range(2000, 3201):\n",
" if (i%7==0) and (i%5!=0):\n",
" # str() very important coz join only work on strings\n",
" l.append(str(i))\n",
"','.join(l)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 3. one liner \n",
"# see here for a very common caveat\n",
"# https://stackoverflow.com/questions/60379194/why-join-doesnt-work-on-a-list-comprehension\n",
"','.join([str(number) for number in range(2000,3201) if number%7 == 0 and number%5 != 0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 4. use filter see https://www.geeksforgeeks.org/filter-in-python/\n",
"numbers = range(2000,3201)\n",
"result = filter(lambda x: x%7 == 0 and x%5 !=0, numbers)\n",
"print(list(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Compute the factorial of a given numbers.\n",
"\n",
"Suppose the following input is supplied to the program:\n",
"\n",
"8\n",
"\n",
"Then, the output should be:\n",
"\n",
"40320"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:32:47.994808Z",
"start_time": "2020-02-25T20:32:47.984652Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 99,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def factorial(number):\n",
" # prevent some user input bug\n",
" if number < 0:\n",
" raise ValueError(\"No negative numbers please\")\n",
" # this is called the base case in recursion\n",
" elif number == 0:\n",
" return 1\n",
" return number*factorial(number-1)\n",
"factorial(0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"for some nice introduction to recursion, see https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursive-factorial\n",
"\n",
"When we're computing n! in this way, we call the first case, where we immediately know the answer, the base case, and we call the second case, where we have to compute the same function but on a different value, the recursive case."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Compute power and use dictionary\n",
"\n",
"With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.\n",
"\n",
"Suppose the following input is supplied to the program:\n",
"\n",
"8\n",
"\n",
"Then, the output should be:\n",
"\n",
"{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:34:12.284059Z",
"start_time": "2020-02-25T20:34:12.276621Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{1: 1, 2: 4}\n"
]
}
],
"source": [
"def powerNumber(number):\n",
" output = {} # or dict() if takes user input use int(input(\"please enter a number\"))\n",
" for i in range(1,number):\n",
" output[i] = i*i\n",
" return output\n",
"print(powerNumber(3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Convert comma separated string\n",
"\n",
"Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number\n",
"\n",
"input: 34,67,55,33,12,98\n",
"\n",
"output:\n",
"\n",
"[‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’]\n",
"\n",
"(‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’)"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:35:20.025740Z",
"start_time": "2020-02-25T20:35:20.018025Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['34', '67', '55', '33', '12', '98']\n",
"('34', '67', '55', '33', '12', '98')\n"
]
}
],
"source": [
"L = \"34,67,55,33,12,98\".split(\",\") # the join syntax is with \".\",join(L)\n",
"print(L)\n",
"print(tuple(L))"
]
},
{
"cell_type": "markdown",
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:36:06.122417Z",
"start_time": "2020-02-25T20:36:06.115053Z"
}
},
"source": [
"## 5. Class and methods\n",
"\n",
"getString: to get a string from console input. \n",
"printString: to print the string in upper case. \n",
"Also please include simple test function to test the class methods."
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:38:34.098240Z",
"start_time": "2020-02-25T20:38:31.645479Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"please type a string herehehe\n",
"HEHE\n"
]
}
],
"source": [
"## the self parameter is a must, but not the others, see the setString method for a comparaison\n",
"class upper:\n",
" def __init__(self):\n",
" self.text = \"\"\n",
" def getString(self):\n",
"# self.text = \"test\"\n",
" self.text = input(\"please type a string here\")\n",
" def upper(self):\n",
" print(self.text.upper())\n",
" def setString(self,newText):\n",
" self.text = newText\n",
"# No new keyword, class is kind of like a function in Python\n",
"test = upper()\n",
"test.getString()\n",
"test.upper()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For more about class see https://www.geeksforgeeks.org/python-classes-and-objects/ \n",
" \n",
"raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Formula\n",
"\n",
"Q = Square root of [(2 * C * D)/H]\n",
"\n",
"C is 50. H is 30.\n",
"\n",
"D is the variable whose values should be input to your program in a comma-separated sequence.\n",
"\n",
"Input: 100,150,180\n",
"\n",
"Output: 18,22,24"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:38:18.910525Z",
"start_time": "2020-02-25T20:38:18.886132Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"18,22,24\n"
]
}
],
"source": [
"import math\n",
"c=50\n",
"h=30\n",
"value = []\n",
"# items = input(\"please enter comma separated numbers\").split(',')\n",
"items = \"100,150,180\".split(',')\n",
"for d in items:\n",
" # note the use of float() and str()\n",
" value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))\n",
"print(','.join(value))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. 2-dimensional array"
]
},
{
"cell_type": "raw",
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T17:25:24.953864Z",
"start_time": "2020-02-25T17:25:24.930680Z"
}
},
"source": [
"Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.\n",
"Note: i=0,1.., X-1; j=0,1..., Y-1.\n",
"Example\n",
"Suppose the following inputs are given to the program:\n",
"i = 3, j = 5\n",
"Then, the output of the program should be:\n",
"[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]\n",
"first row = 0*(0|1|2|3|4)\n",
"second row = 1*(0|1|2|3|4)"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T19:33:19.826980Z",
"start_time": "2020-02-25T19:33:19.806180Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]\n"
]
}
],
"source": [
"def toArray(row, col):\n",
" multilist = [[0 for i in range(col)] for j in range(row)]\n",
" for i in range(row):\n",
" for j in range(col):\n",
" multilist[i][j] = i * j\n",
" print(multilist)\n",
"\n",
"toArray(3, 5)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"Explanation and some extra thinking https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T19:44:20.603178Z",
"start_time": "2020-02-25T19:44:20.582155Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# In fact [[0 for i in range(col)] for j in range(row)] = the following code\n",
"# first draw the column\n",
"hehehe = []\n",
"hehe = []\n",
"for col in range(x):\n",
" hehe.append(0)\n",
"# then repeat the column to draw the whole array\n",
"for row in range(y):\n",
" hehehe.append(hehe)\n",
"hehehe"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T19:45:40.830228Z",
"start_time": "2020-02-25T19:45:40.820044Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8]\n",
"[1, 2, 3, 4, 5, 6]\n"
]
}
],
"source": [
"# However the list comprehension normally takes the following form\n",
"non_flat = [ [1,2,3], [4,5,6], [7,8] ]\n",
"# the first for is the outer for, the next is the inner\n",
"print([y for x in non_flat for y in x])\n",
"for x in non_flat:\n",
" for y in x:\n",
" y\n",
"# see another example here : exclude all the lists of length < 2\n",
"print([ y for x in non_flat if len(x) > 2 for y in x ])\n",
"# equals to\n",
"for x in non_flat:\n",
" if len(x) > 2:\n",
" for y in x:\n",
" y\n",
"# it's really important to see the last for as the innermost for"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T19:44:44.359083Z",
"start_time": "2020-02-25T19:44:44.349574Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[('f', 0),\n",
" ('o', 0),\n",
" ('o', 0),\n",
" ('b', 0),\n",
" ('a', 0),\n",
" ('r', 0),\n",
" ('b', 1),\n",
" ('a', 1),\n",
" ('z', 1),\n",
" ('t', 1),\n",
" ('a', 1),\n",
" ('z', 1),\n",
" ('k', 2),\n",
" ('o', 2),\n",
" ('k', 2),\n",
" ('o', 2)]"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# another somewhat complicate example, read from rightmost for = print all the letters and corresponding index for words of length > 2 \n",
"strings = [ ['foo', 'bar'], ['baz', 'taz'], ['w', 'koko'] ]\n",
"[ (letter, idx) for idx, lst in enumerate(strings) for word in lst if len(word)>2 for letter in word]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. Sort a list\n",
"\n",
"Take a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.\n",
"\n",
"Input:\n",
"without,hello,bag,world\n",
"\n",
"Output:\n",
"bag,hello,without,world"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T19:58:35.412959Z",
"start_time": "2020-02-25T19:58:35.396275Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['bag', 'hello', 'without', 'world']\n",
"['without', 'hello', 'bag', 'world']\n",
"['bag', 'hello', 'without', 'world']\n"
]
}
],
"source": [
"words = \"without,hello,bag,world\".split(',')\n",
"# sorted(words) doesn't change words but return a new list, so it's better\n",
"print(sorted(words))\n",
"print(words)\n",
"# sort() returns None and changes the list in place\n",
"words.sort()\n",
"print(words)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"sorted(words) doesn't change words but return a new list, so it's better"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9. Capitalization\n",
"\n",
"Take a sequence of lines as input and prints the lines capitalized.\n",
"\n",
"Input:\n",
"\n",
"Hello world\n",
"\n",
"Practice makes perfect\n",
"\n",
"Output:\n",
"\n",
"HELLO WORLD\n",
"\n",
"PRACTICE MAKES PERFECT"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:08:29.747526Z",
"start_time": "2020-02-25T20:08:26.956447Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"put some lines heress\n",
"put some lines heresss\n",
"put some lines here\n",
"SS\n",
"SSS\n"
]
}
],
"source": [
"lines = []\n",
"while True:\n",
" s = input(\"put some lines here\")\n",
" if s:\n",
" lines.append(s.upper())\n",
" else:\n",
" break;\n",
"\n",
"for sentence in lines:\n",
" print(sentence)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"Nothing complicated. \n",
"The interesting thing here is how to use `while` to keep asking inputs."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 10. Move duplicates\n",
"\n",
"Take a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.\n",
"\n",
"Input:\n",
"hello world and practice makes perfect and hello world again\n",
"\n",
"output:\n",
"again and hello makes perfect practice world"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {
"ExecuteTime": {
"end_time": "2020-02-25T20:09:43.033198Z",
"start_time": "2020-02-25T20:09:43.019858Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"['again', 'and', 'hello', 'makes', 'perfect', 'practice', 'world']"
]
},
"execution_count": 94,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"words = \"hello world and practice makes perfect and hello world again\"\n",
"wordsList = words.split(\" \")\n",
"sorted(set(wordsList))"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"The key thing is to understant the difference between list and set (no duplicates in set)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"file_extension": ".py",
"hide_input": false,
"kernelspec": {
"display_name": "Python 3.7.4 64-bit ('base': conda)",
"language": "python",
"name": "python37464bitbasecondae7af3db540e340afa4382ca07c1bd9d3"
},
"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.4"
},
"mimetype": "text/x-python",
"name": "python",
"npconvert_exporter": "python",
"pygments_lexer": "ipython3",
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": true
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
},
"version": 3
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment