├── Data Collection and Processing with Python ├── Readme.md ├── Week 1 Assessment-Nested Data and Iteration.ipynb └── Week 2 Assessment-Advanced Accumulation.ipynb ├── Python Basics ├── Assignment Week Three.ipynb ├── Assignment Week Two.ipynb ├── Readme ├── Week 4 Assessment Methods-Lists and Strings.ipynb ├── Week 4 Assessment-Accumulating Lists and Strings.ipynb └── Week 4-Final Course Assignment.ipynb ├── Python Classes and Inheritance └── Readme.md ├── Python Functions, Files, and Dictionaries ├── Project - Part 1 Sentiment Classifier.ipynb ├── Project - Part 2 Sentiment Analysis.xlsx ├── Readme ├── Scatterplot of Number of Retweets vs Net Score.PNG ├── Week 1 Assessment-Files and CSV.ipynb ├── Week 2 Assessment-Dictionary Accumulation.ipynb ├── Week 2 Assessment-Dictionary Mechanics.ipynb ├── Week 3 Assessment-Functions.ipynb ├── Week 3 Assessment-Tuples.ipynb ├── Week 3-Returning a Value from a Function.ipynb ├── Week 4 Assessment- More about Iteration.ipynb ├── Week 4 Assessment-Advanced Functions.ipynb └── Week 5 Assessment-Sorting.ipynb └── README.md /Data Collection and Processing with Python/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Data Collection and Processing with Python/Week 1 Assessment-Nested Data and Iteration.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question 1\n", 8 | "The variable _nested_ contains a nested list. Assign ‘snake’ to the variable _output_ using indexing." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']]" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 2, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "output=nested[1][2]" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "### Question 2\n", 34 | "Below, a list of lists is provided. Use in and not in tests to create variables with Boolean values. See comments for further instructions." 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 5, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']]\n", 44 | "\n", 45 | "#Test to see if 'yellow' is in the third list of lst. Save to variable ``yellow``\n", 46 | "yellow='yellow' in lst[2]\n", 47 | "\n", 48 | "#Test to see if 4 is in the second list of lst. Save to variable ``four``\n", 49 | "four=4 in lst[1]\n", 50 | "\n", 51 | "#Test to see if 'orange' is in the first element of lst. Save to variable ``orange``\n", 52 | "orange='orange' in lst[0]" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "### Question 3\n", 60 | "Below, we’ve provided a list of lists. Use in statements to create variables with Boolean values - see the ActiveCode window for further directions." 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 6, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "L = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']]\n", 70 | "\n", 71 | "# Test if 'hola' is in the list L. Save to variable name test1\n", 72 | "test1='hola' in L\n", 73 | "\n", 74 | "# Test if [5, 8, 7] is in the list L. Save to variable name test2\n", 75 | "test2=[5,8,7] in L\n", 76 | "\n", 77 | "# Test if 6.6 is in the third element of list L. Save to variable name test3\n", 78 | "test3=6.6 in L[2]" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "### Question 4\n", 86 | "Provided is a nested data structure. Follow the instructions in the comments below. Do not hard code." 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 16, 92 | "metadata": {}, 93 | "outputs": [ 94 | { 95 | "name": "stdout", 96 | "output_type": "stream", 97 | "text": [ 98 | "True\n", 99 | "False\n", 100 | "False\n", 101 | "False\n" 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], 'window': ['part', 'whole', [], 'sum', ['math', 'calculus', 'algebra', 'geometry', 'statistics',['physics', 'chemistry', 'biology']]]}\n", 107 | "\n", 108 | "# Check to see if the string data is a key in nested, if it is, assign True to the variable data, otherwise assign False.\n", 109 | "if 'data' in nested.keys():\n", 110 | " data=True\n", 111 | "else:\n", 112 | " data=False\n", 113 | "print(data)\n", 114 | "\n", 115 | "# Check to see if the integer 24 is in the value of the key data, if it is then assign to the variable twentyfour the value of True, otherwise False.\n", 116 | "if 24 in nested['data']:\n", 117 | " twentyfour=True\n", 118 | "else:\n", 119 | " twentyfour=False\n", 120 | "print(twentyfour)\n", 121 | "\n", 122 | "# Check to see that the string 'whole' is not in the value of the key window. If it's not, then assign to the variable whole the value of True, otherwise False.\n", 123 | "if 'whole' not in nested['window']:\n", 124 | " whole=True\n", 125 | "else:\n", 126 | " whole=False\n", 127 | "print(whole)\n", 128 | "\n", 129 | "# Check to see if the string 'physics' is a key in the dictionary nested. If it is, assign to the variable physics, the value of True, otherwise False.\n", 130 | "if 'physics' in nested.keys():\n", 131 | " physics=True\n", 132 | "else:\n", 133 | " physics=False\n", 134 | "print(physics)" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "### Question 5\n", 142 | "The variable nested_d contains a nested dictionary with the gold medal counts for the top four countries in the past three Olympics. Assign the value of Great Britain’s gold medal count from the London Olympics to the variable london_gold. Use indexing. Do not hardcode." 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 17, 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 18, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "#Answer:\n", 161 | "\n", 162 | "london_gold=nested_d['London']['Great Britain']" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "### Question 6\n", 170 | "Below, we have provided a nested dictionary. Index into the dictionary to create variables that we have listed in the ActiveCode window." 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "sports = {'swimming': ['butterfly', 'breaststroke', 'backstroke', 'freestyle'], 'diving': ['springboard', 'platform', 'synchronized'], 'track': ['sprint', 'distance', 'jumps', 'throws'], 'gymnastics': {'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']}}\n", 180 | "\n", 181 | "# Assign the string 'backstroke' to the name v1\n", 182 | "v1=sports['swimming'][2]\n", 183 | "\n", 184 | "# Assign the string 'platform' to the name v2\n", 185 | "v2=sports['diving'][1]\n", 186 | "\n", 187 | "# Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3\n", 188 | "v3=sports['gymnastics']['women']\n", 189 | "\n", 190 | "# Assign the string 'rings' to the name v4\n", 191 | "v4=sports['gymnastics']['men'][3]" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "### Question 7\n", 199 | "Given the dictionary, nested_d, save the medal count for the USA from all three Olympics in the dictionary to the list US_count." 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": 20, 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}\n", 209 | "\n", 210 | "US_count = []" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": 21, 216 | "metadata": {}, 217 | "outputs": [ 218 | { 219 | "name": "stdout", 220 | "output_type": "stream", 221 | "text": [ 222 | "[36, 46, 35]\n" 223 | ] 224 | } 225 | ], 226 | "source": [ 227 | "#Answer:\n", 228 | "\n", 229 | "for olympics in nested_d.keys():\n", 230 | " US_count.append(nested_d[olympics]['USA'])\n", 231 | "\n", 232 | "print(US_count)" 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": {}, 238 | "source": [ 239 | "### Question 8\n", 240 | "Iterate through the contents of l_of_l and assign the third element of sublist to a new list called third." 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": 22, 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']]" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 23, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "['blue', 'blood orange', 'lavender', 'mac n cheese']\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "#Answer:\n", 267 | "\n", 268 | "third=[]\n", 269 | "\n", 270 | "for sublists in l_of_l:\n", 271 | " third.append(sublists[2])\n", 272 | " \n", 273 | "print(third)" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "metadata": {}, 279 | "source": [ 280 | "### Question 9\n", 281 | "Given below is a list of lists of athletes. Create a list, t, that saves only the athlete’s name if it contains the letter “t”. If it does not contain the letter “t”, save the athlete name into list other." 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 24, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']]" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 25, 296 | "metadata": {}, 297 | "outputs": [ 298 | { 299 | "name": "stdout", 300 | "output_type": "stream", 301 | "text": [ 302 | "['Lochte', 'Bolt', 'Eaton', 'Dalton']\n", 303 | "['Phelps', 'Schooling', 'Ledecky', 'Franklin', 'Felix', 'Gardner', 'Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak']\n" 304 | ] 305 | } 306 | ], 307 | "source": [ 308 | "#Answer:\n", 309 | "\n", 310 | "t=[]\n", 311 | "other=[]\n", 312 | "\n", 313 | "for sublists in athletes:\n", 314 | " for name in sublists:\n", 315 | " if 't' in name:\n", 316 | " t.append(name)\n", 317 | " else:\n", 318 | " other.append(name)\n", 319 | " \n", 320 | "print(t)\n", 321 | "print(other)" 322 | ] 323 | } 324 | ], 325 | "metadata": { 326 | "kernelspec": { 327 | "display_name": "Python 3", 328 | "language": "python", 329 | "name": "python3" 330 | }, 331 | "language_info": { 332 | "codemirror_mode": { 333 | "name": "ipython", 334 | "version": 3 335 | }, 336 | "file_extension": ".py", 337 | "mimetype": "text/x-python", 338 | "name": "python", 339 | "nbconvert_exporter": "python", 340 | "pygments_lexer": "ipython3", 341 | "version": "3.7.3" 342 | } 343 | }, 344 | "nbformat": 4, 345 | "nbformat_minor": 2 346 | } 347 | -------------------------------------------------------------------------------- /Data Collection and Processing with Python/Week 2 Assessment-Advanced Accumulation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Questions from Reading 23.2 Map" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Question 1\n", 15 | "Using map, create a list assigned to the variable greeting_doubled that doubles each element in the list lst." 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "lst = [[\"hi\", \"bye\"], \"hello\", \"goodbye\", [9, 2], 4]" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 3, 30 | "metadata": {}, 31 | "outputs": [ 32 | { 33 | "name": "stdout", 34 | "output_type": "stream", 35 | "text": [ 36 | "[['hi', 'bye', 'hi', 'bye'], 'hellohello', 'goodbyegoodbye', [9, 2, 9, 2], 8]\n" 37 | ] 38 | } 39 | ], 40 | "source": [ 41 | "#Answer:\n", 42 | "\n", 43 | "greeting_doubled=map(lambda x:x*2,lst)\n", 44 | "\n", 45 | "print(list(greeting_doubled))" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "### Question 2\n", 53 | "Below, we have provided a list of strings called abbrevs. Use map to produce a new list called abbrevs_upper that contains all the same strings in upper case." 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 4, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "abbrevs = [\"usa\", \"esp\", \"chn\", \"jpn\", \"mex\", \"can\", \"rus\", \"rsa\", \"jam\"]" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 6, 68 | "metadata": {}, 69 | "outputs": [ 70 | { 71 | "name": "stdout", 72 | "output_type": "stream", 73 | "text": [ 74 | "['USA', 'ESP', 'CHN', 'JPN', 'MEX', 'CAN', 'RUS', 'RSA', 'JAM']\n" 75 | ] 76 | } 77 | ], 78 | "source": [ 79 | "#Answer:\n", 80 | "\n", 81 | "abbrevs_upper=list(map(lambda x:x.upper(),abbrevs))\n", 82 | "\n", 83 | "print(abbrevs_upper)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "### Questions from Reading 23.3 Filter" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": {}, 96 | "source": [ 97 | "### Question 1\n", 98 | "Write code to assign to the variable filter_testing all the elements in lst_check that have a w in them using filter." 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 7, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 2, 113 | "metadata": {}, 114 | "outputs": [ 115 | { 116 | "name": "stdout", 117 | "output_type": "stream", 118 | "text": [ 119 | "['watermelon', 'kiwi', 'strawberries']\n" 120 | ] 121 | } 122 | ], 123 | "source": [ 124 | "filter_testing=[]\n", 125 | "\n", 126 | "for word in lst_check:\n", 127 | " if 'w' in word:\n", 128 | " filter_testing.append(word)\n", 129 | "print(filter_testing)" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 8, 135 | "metadata": {}, 136 | "outputs": [ 137 | { 138 | "name": "stdout", 139 | "output_type": "stream", 140 | "text": [ 141 | "['watermelon', 'kiwi', 'strawberries']\n" 142 | ] 143 | } 144 | ], 145 | "source": [ 146 | "filter_testing=filter(lambda word:'w' in word,lst_check)\n", 147 | "'''\n", 148 | "the function in filter function returns a True/False indicator\n", 149 | "'''\n", 150 | "print(list(filter_testing))" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "### Questions from Reading 23.4 List Comprehensions" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "[ for in if ]" 167 | ] 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "metadata": {}, 172 | "source": [ 173 | "### Question 2\n", 174 | "The for loop below produces a list of numbers greater than 10. Below the given code, use list comprehension to accomplish the same thing. Assign it the the variable lst2. Only one line of code is needed." 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": 2, 180 | "metadata": {}, 181 | "outputs": [ 182 | { 183 | "name": "stdout", 184 | "output_type": "stream", 185 | "text": [ 186 | "[12, 34, 21, 42]\n" 187 | ] 188 | } 189 | ], 190 | "source": [ 191 | "L = [12, 34, 21, 4, 6, 9, 42]\n", 192 | "lst = []\n", 193 | "for x in L:\n", 194 | " if x > 10:\n", 195 | " lst.append(x)\n", 196 | "print(lst)" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 5, 202 | "metadata": {}, 203 | "outputs": [ 204 | { 205 | "name": "stdout", 206 | "output_type": "stream", 207 | "text": [ 208 | "[12, 34, 21, 42]\n" 209 | ] 210 | } 211 | ], 212 | "source": [ 213 | "#Answer:\n", 214 | "lst2=[num for num in L if num>10]\n", 215 | "print(lst2)" 216 | ] 217 | }, 218 | { 219 | "cell_type": "markdown", 220 | "metadata": {}, 221 | "source": [ 222 | "### Question 3\n", 223 | "Write code to assign to the variable compri all the values of the key name in any of the sub-dictionaries in the dictionary tester. Do this using a list comprehension." 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 6, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "tester = {'info': [{\"name\": \"Lauren\", 'class standing': 'Junior', 'major': \"Information Science\"},{'name': 'Ayo', 'class standing': \"Bachelor's\", 'major': 'Information Science'}, {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]}" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 8, 238 | "metadata": {}, 239 | "outputs": [ 240 | { 241 | "name": "stdout", 242 | "output_type": "stream", 243 | "text": [ 244 | "['Lauren', 'Ayo', 'Kathryn', 'Nick', 'Gladys', 'Adam']\n" 245 | ] 246 | } 247 | ], 248 | "source": [ 249 | "#Answer:\n", 250 | "compri=[dictionary['name'] for dictionary in tester['info']]\n", 251 | "print(compri)" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "metadata": {}, 257 | "source": [ 258 | "### Questions from the Reading 23.5" 259 | ] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "metadata": {}, 264 | "source": [ 265 | "### Question 1\n", 266 | "Below we have provided two lists of numbers, L1 and L2. Using zip and list comprehension, create a new list, L3, that sums the two numbers if the number from L1 is greater than 10 and the number from L2 is less than 5. This can be accomplished in one line of code." 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 1, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "L1 = [1, 5, 2, 16, 32, 3, 54, 8, 100]\n", 276 | "L2 = [1, 3, 10, 2, 42, 2, 3, 4, 3]" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 4, 282 | "metadata": {}, 283 | "outputs": [ 284 | { 285 | "name": "stdout", 286 | "output_type": "stream", 287 | "text": [ 288 | "[18, 57, 103]\n" 289 | ] 290 | } 291 | ], 292 | "source": [ 293 | "# Answer:\n", 294 | "L3=[x1+x2 for (x1,x2) in list(zip(L1,L2)) if x1>10 and x2<5]\n", 295 | "print(L3)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "metadata": {}, 301 | "source": [ 302 | "### Week 2 Assessment: Advanced Accumulation" 303 | ] 304 | }, 305 | { 306 | "cell_type": "markdown", 307 | "metadata": {}, 308 | "source": [ 309 | "### Question 1\n", 310 | "Write code to assign to the variable map_testing all the elements in lst_check while adding the string “Fruit: ” to the beginning of each element using mapping." 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": 1, 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [ 319 | "lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": 3, 325 | "metadata": {}, 326 | "outputs": [ 327 | { 328 | "name": "stdout", 329 | "output_type": "stream", 330 | "text": [ 331 | "['Fruit: plums', 'Fruit: watermelon', 'Fruit: kiwi', 'Fruit: strawberries', 'Fruit: blueberries', 'Fruit: peaches', 'Fruit: apples', 'Fruit: mangos', 'Fruit: papaya']\n" 332 | ] 333 | } 334 | ], 335 | "source": [ 336 | "# Answer:\n", 337 | "\n", 338 | "def addition(word):\n", 339 | " return \"Fruit: \"+word\n", 340 | "\n", 341 | "map_testing=map(addition,lst_check)\n", 342 | "\n", 343 | "print(list(map_testing))" 344 | ] 345 | }, 346 | { 347 | "cell_type": "markdown", 348 | "metadata": {}, 349 | "source": [ 350 | "### Question 2\n", 351 | "Below, we have provided a list of strings called countries. Use filter to produce a list called b_countries that only contains the strings from countries that begin with B." 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": 9, 357 | "metadata": {}, 358 | "outputs": [], 359 | "source": [ 360 | "countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium']" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": 12, 366 | "metadata": {}, 367 | "outputs": [ 368 | { 369 | "name": "stdout", 370 | "output_type": "stream", 371 | "text": [ 372 | "['Brazil', 'Botswana', 'Britain', 'Bangladesh', 'Belarus', 'Belgium']\n" 373 | ] 374 | } 375 | ], 376 | "source": [ 377 | "# Answer:\n", 378 | "\n", 379 | "b_countries=filter(lambda word:'B' in word[0], countries)\n", 380 | "\n", 381 | "print(list(b_countries))" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "### Question 3\n", 389 | "Below, we have provided a list of tuples that contain the names of Game of Thrones characters. Using list comprehension, create a list of strings called first_names that contains only the first names of everyone in the original list." 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": 13, 395 | "metadata": {}, 396 | "outputs": [], 397 | "source": [ 398 | "people = [('Snow', 'Jon'), ('Lannister', 'Cersei'), ('Stark', 'Arya'), ('Stark', 'Robb'), ('Lannister', 'Jamie'), ('Targaryen', 'Daenerys'), ('Stark', 'Sansa'), ('Tyrell', 'Margaery'), ('Stark', 'Eddard'), ('Lannister', 'Tyrion'), ('Baratheon', 'Joffrey'), ('Bolton', 'Ramsey'), ('Baelish', 'Peter')]" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": 16, 404 | "metadata": {}, 405 | "outputs": [ 406 | { 407 | "name": "stdout", 408 | "output_type": "stream", 409 | "text": [ 410 | "['Jon', 'Cersei', 'Arya', 'Robb', 'Jamie', 'Daenerys', 'Sansa', 'Margaery', 'Eddard', 'Tyrion', 'Joffrey', 'Ramsey', 'Peter']\n" 411 | ] 412 | } 413 | ], 414 | "source": [ 415 | "# Answer:\n", 416 | "first_names=[name[1] for name in people]\n", 417 | "\n", 418 | "print(first_names)" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "metadata": {}, 424 | "source": [ 425 | "### Question 4\n", 426 | "Use list comprehension to create a list called lst2 that doubles each element in the list, lst." 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": 17, 432 | "metadata": {}, 433 | "outputs": [], 434 | "source": [ 435 | "lst = [[\"hi\", \"bye\"], \"hello\", \"goodbye\", [9, 2], 4]" 436 | ] 437 | }, 438 | { 439 | "cell_type": "code", 440 | "execution_count": 18, 441 | "metadata": {}, 442 | "outputs": [ 443 | { 444 | "name": "stdout", 445 | "output_type": "stream", 446 | "text": [ 447 | "[['hi', 'bye', 'hi', 'bye'], 'hellohello', 'goodbyegoodbye', [9, 2, 9, 2], 8]\n" 448 | ] 449 | } 450 | ], 451 | "source": [ 452 | "# Answer:\n", 453 | "\n", 454 | "lst2=[element*2 for element in lst]\n", 455 | "\n", 456 | "print(lst2)" 457 | ] 458 | }, 459 | { 460 | "cell_type": "markdown", 461 | "metadata": {}, 462 | "source": [ 463 | "### Question 5\n", 464 | "Below, we have provided a list of tuples that contain students’ names and their final grades in PYTHON 101. Using list comprehension, create a new list passed that contains the names of students who passed the class (had a final grade of 70 or greater)." 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": 19, 470 | "metadata": {}, 471 | "outputs": [], 472 | "source": [ 473 | "students = [('Tommy', 95), ('Linda', 63), ('Carl', 70), ('Bob', 100), ('Raymond', 50), ('Sue', 75)]" 474 | ] 475 | }, 476 | { 477 | "cell_type": "code", 478 | "execution_count": 20, 479 | "metadata": {}, 480 | "outputs": [ 481 | { 482 | "name": "stdout", 483 | "output_type": "stream", 484 | "text": [ 485 | "['Tommy', 'Carl', 'Bob', 'Sue']\n" 486 | ] 487 | } 488 | ], 489 | "source": [ 490 | "# Answer:\n", 491 | "\n", 492 | "passed=[name[0] for name in students if name[1]>=70]\n", 493 | "\n", 494 | "print(passed)" 495 | ] 496 | }, 497 | { 498 | "cell_type": "markdown", 499 | "metadata": {}, 500 | "source": [ 501 | "### Question 6\n", 502 | "Write code using zip and filter so that these lists (l1 and l2) are combined into one big list and assigned to the variable opposites if they are both longer than 3 characters each." 503 | ] 504 | }, 505 | { 506 | "cell_type": "code", 507 | "execution_count": 21, 508 | "metadata": {}, 509 | "outputs": [], 510 | "source": [ 511 | "l1 = ['left', 'up', 'front']\n", 512 | "l2 = ['right', 'down', 'back']" 513 | ] 514 | }, 515 | { 516 | "cell_type": "code", 517 | "execution_count": 37, 518 | "metadata": {}, 519 | "outputs": [ 520 | { 521 | "name": "stdout", 522 | "output_type": "stream", 523 | "text": [ 524 | "[('left', 'right'), ('front', 'back')]\n", 525 | "[('left', 'right'), ('front', 'back')]\n" 526 | ] 527 | } 528 | ], 529 | "source": [ 530 | "# Answer:\n", 531 | "\n", 532 | "l3=list(zip(l1,l2))\n", 533 | "\n", 534 | "def filtering(atuple):\n", 535 | " if len(atuple[0])>3 and len(atuple[1])>3:\n", 536 | " return True\n", 537 | " else:\n", 538 | " return False\n", 539 | "\n", 540 | "opposites=list(filter(filtering,l3))\n", 541 | "\n", 542 | "print(opposites)\n", 543 | "\n", 544 | "'''\n", 545 | "Alternative: lambda function\n", 546 | "'''\n", 547 | "\n", 548 | "opposites=list(filter(lambda atuple:len(atuple[0])>3 and len(atuple[1])>3, l3))\n", 549 | "\n", 550 | "print(opposites)" 551 | ] 552 | }, 553 | { 554 | "cell_type": "markdown", 555 | "metadata": {}, 556 | "source": [ 557 | "### Question 7\n", 558 | "Below, we have provided a species list and a population list. Use zip to combine these lists into one list of tuples called pop_info. From this list, create a new list called endangered that contains the names of species whose populations are below 2500." 559 | ] 560 | }, 561 | { 562 | "cell_type": "code", 563 | "execution_count": 30, 564 | "metadata": {}, 565 | "outputs": [], 566 | "source": [ 567 | "species = ['golden retriever', 'white tailed deer', 'black rhino', 'brown squirrel', 'field mouse', 'orangutan', 'sumatran elephant', 'rainbow trout', 'black bear', 'blue whale', 'water moccasin', 'giant panda', 'green turtle', 'blue jay', 'japanese beetle']\n", 568 | "\n", 569 | "population = [10000, 90000, 1000, 2000000, 500000, 500, 1200, 8000, 12000, 2300, 7500, 100, 1800, 9500, 125000]" 570 | ] 571 | }, 572 | { 573 | "cell_type": "code", 574 | "execution_count": 32, 575 | "metadata": {}, 576 | "outputs": [ 577 | { 578 | "name": "stdout", 579 | "output_type": "stream", 580 | "text": [ 581 | "[('golden retriever', 10000), ('white tailed deer', 90000), ('black rhino', 1000), ('brown squirrel', 2000000), ('field mouse', 500000), ('orangutan', 500), ('sumatran elephant', 1200), ('rainbow trout', 8000), ('black bear', 12000), ('blue whale', 2300), ('water moccasin', 7500), ('giant panda', 100), ('green turtle', 1800), ('blue jay', 9500), ('japanese beetle', 125000)]\n", 582 | "['black rhino', 'orangutan', 'sumatran elephant', 'blue whale', 'giant panda', 'green turtle']\n" 583 | ] 584 | } 585 | ], 586 | "source": [ 587 | "# Answer:\n", 588 | "\n", 589 | "pop_info=list(zip(species,population))\n", 590 | "\n", 591 | "print(pop_info)\n", 592 | "\n", 593 | "endangered=[animal[0] for animal in pop_info if animal[1]<2500]\n", 594 | "\n", 595 | "print(endangered)" 596 | ] 597 | } 598 | ], 599 | "metadata": { 600 | "kernelspec": { 601 | "display_name": "Python 3", 602 | "language": "python", 603 | "name": "python3" 604 | }, 605 | "language_info": { 606 | "codemirror_mode": { 607 | "name": "ipython", 608 | "version": 3 609 | }, 610 | "file_extension": ".py", 611 | "mimetype": "text/x-python", 612 | "name": "python", 613 | "nbconvert_exporter": "python", 614 | "pygments_lexer": "ipython3", 615 | "version": "3.7.3" 616 | } 617 | }, 618 | "nbformat": 4, 619 | "nbformat_minor": 2 620 | } 621 | -------------------------------------------------------------------------------- /Python Basics/Assignment Week Three.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### A question from *8.10 The Accumulator Pattern with Conditions*\n", 8 | "For each word in words, add ‘d’ to the end of the word if the word ends in “e” to make it past tense. Otherwise, add ‘ed’ to make it past tense. Save these past tense words to a list called past_tense." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "words = [\"adopt\", \"bake\", \"beam\", \"confide\", \"grill\", \"plant\", \"time\", \"wave\", \"wish\"]" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 2, 23 | "metadata": {}, 24 | "outputs": [ 25 | { 26 | "name": "stdout", 27 | "output_type": "stream", 28 | "text": [ 29 | "['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']\n" 30 | ] 31 | } 32 | ], 33 | "source": [ 34 | "# Answer:\n", 35 | "past_tense=[]\n", 36 | "\n", 37 | "for word in words:\n", 38 | " if word[-1]!=\"e\":\n", 39 | " past_tense.append(word+\"ed\")\n", 40 | " else:\n", 41 | " past_tense.append(word+\"d\")\n", 42 | "print(past_tense)" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "### Question 1\n", 50 | "*rainfall_mi* is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of rainfall. Store the result in the variable *num_rainy_months*. In other words, count the number of items with values *> 3.0*.\n", 51 | "\n", 52 | "Hard-coded answers will receive no credit." 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 12, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "rainfall_mi = \"1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85\"" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 13, 67 | "metadata": {}, 68 | "outputs": [ 69 | { 70 | "name": "stdout", 71 | "output_type": "stream", 72 | "text": [ 73 | "5\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "# Answer:\n", 79 | "rainfall_mi=rainfall_mi.split(\",\")\n", 80 | "\n", 81 | "num_rainy_months=0\n", 82 | "\n", 83 | "for rain in rainfall_mi:\n", 84 | " if float(rain)>3.00:\n", 85 | " num_rainy_months+=1\n", 86 | "\n", 87 | "print(num_rainy_months)" 88 | ] 89 | }, 90 | { 91 | "cell_type": "markdown", 92 | "metadata": {}, 93 | "source": [ 94 | "### Question 2\n", 95 | "The variable *sentence* stores a string. Write code to determine how many words in *sentence* start and end with the same letter, including one-letter words. Store the result in the variable *same_letter_count*.\n", 96 | "\n", 97 | "Hard-coded answers will receive no credit." 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 15, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "sentence = \"students flock to the arb for a variety of outdoor activities such as jogging and picnicking\"" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 16, 112 | "metadata": {}, 113 | "outputs": [ 114 | { 115 | "name": "stdout", 116 | "output_type": "stream", 117 | "text": [ 118 | "2\n" 119 | ] 120 | } 121 | ], 122 | "source": [ 123 | "# Answer:\n", 124 | "sentence=sentence.split()\n", 125 | "\n", 126 | "same_letter_count=0\n", 127 | "\n", 128 | "for word in sentence:\n", 129 | " if word[0]==word[-1]:\n", 130 | " same_letter_count+=1\n", 131 | "\n", 132 | "print(same_letter_count)" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "### Question 3\n", 140 | "Write code to count the number of strings in list *items* that have the character w in it. Assign that number to the variable acc_num.\n", 141 | "\n", 142 | "HINT 1: Use the accumulation pattern!\n", 143 | "\n", 144 | "HINT 2: the _in_ operator checks whether a substring is present in a string.\n", 145 | "\n", 146 | "Hard-coded answers will receive no credit." 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 17, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [ 155 | "items = [\"whirring\", \"wow!\", \"calendar\", \"wry\", \"glass\", \"\", \"llama\",\"tumultuous\",\"owing\"]" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 18, 161 | "metadata": {}, 162 | "outputs": [ 163 | { 164 | "name": "stdout", 165 | "output_type": "stream", 166 | "text": [ 167 | "4\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "# Answer:\n", 173 | "acc_num=0\n", 174 | "\n", 175 | "for item in items:\n", 176 | " if \"w\" in item:\n", 177 | " acc_num+=1\n", 178 | "\n", 179 | "print(acc_num)" 180 | ] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "### Question 4\n", 187 | "Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable num_a_or_e.\n", 188 | "\n", 189 | "Note 1: be sure to not double-count words that contain both an a and an e.\n", 190 | "\n", 191 | "HINT 1: Use the in operator.\n", 192 | "\n", 193 | "HINT 2: You can either use or or elif.\n", 194 | "\n", 195 | "Hard-coded answers will receive no credit." 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": 19, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "sentence = \"python is a high level general purpose programming language that can be applied to many different classes of problems.\"" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": 23, 210 | "metadata": {}, 211 | "outputs": [ 212 | { 213 | "name": "stdout", 214 | "output_type": "stream", 215 | "text": [ 216 | "14\n" 217 | ] 218 | } 219 | ], 220 | "source": [ 221 | "# Answer:\n", 222 | "sentence=sentence.split()\n", 223 | "\n", 224 | "num_a_or_e=0\n", 225 | "\n", 226 | "for word in sentence:\n", 227 | " if \"a\" in word or \"e\" in word:\n", 228 | " num_a_or_e+=1\n", 229 | " \n", 230 | "print(num_a_or_e)" 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "metadata": {}, 236 | "source": [ 237 | "### Question 5\n", 238 | "Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem, vowels are only a, e, i, o, and u. Hint: use the in operator with vowels." 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 21, 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "s = \"singing in the rain and playing in the rain are two entirely different situations but both can be fun\"\n", 248 | "vowels = ['a','e','i','o','u']" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 25, 254 | "metadata": {}, 255 | "outputs": [ 256 | { 257 | "name": "stdout", 258 | "output_type": "stream", 259 | "text": [ 260 | "32\n" 261 | ] 262 | } 263 | ], 264 | "source": [ 265 | "# Answer:\n", 266 | "num_vowels=0\n", 267 | "\n", 268 | "for char in s:\n", 269 | " if char in vowels:\n", 270 | " num_vowels+=1\n", 271 | " \n", 272 | "print(num_vowels)" 273 | ] 274 | } 275 | ], 276 | "metadata": { 277 | "kernelspec": { 278 | "display_name": "Python 3", 279 | "language": "python", 280 | "name": "python3" 281 | }, 282 | "language_info": { 283 | "codemirror_mode": { 284 | "name": "ipython", 285 | "version": 3 286 | }, 287 | "file_extension": ".py", 288 | "mimetype": "text/x-python", 289 | "name": "python", 290 | "nbconvert_exporter": "python", 291 | "pygments_lexer": "ipython3", 292 | "version": "3.7.3" 293 | } 294 | }, 295 | "nbformat": 4, 296 | "nbformat_minor": 2 297 | } 298 | -------------------------------------------------------------------------------- /Python Basics/Assignment Week Two.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question 1:\n", 8 | "Write one for loop to print out each character of the string my_str on a separate line." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 3, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "my_str = \"MICHIGAN\"" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 4, 23 | "metadata": {}, 24 | "outputs": [ 25 | { 26 | "name": "stdout", 27 | "output_type": "stream", 28 | "text": [ 29 | "M\n", 30 | "I\n", 31 | "C\n", 32 | "H\n", 33 | "I\n", 34 | "G\n", 35 | "A\n", 36 | "N\n" 37 | ] 38 | } 39 | ], 40 | "source": [ 41 | "# Answer:\n", 42 | "for char in my_str:\n", 43 | " print(char)" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "### Question 2:\n", 51 | "Write one for loop to print out each element of the list several_things. Then, write another for loop to print out the TYPE of each element of the list several_things. To complete this problem you should have written two different for loops, each of which iterates over the list several_things, but each of those 2 for loops should have a different result." 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 2, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "several_things = [\"hello\", 2, 4, 6.0, 7.5, 234352354, \"the end\", \"\", 99]" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 7, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "hello\n", 73 | "2\n", 74 | "4\n", 75 | "6.0\n", 76 | "7.5\n", 77 | "234352354\n", 78 | "the end\n", 79 | "\n", 80 | "99\n", 81 | "\n", 82 | "\n", 83 | "\n", 84 | "\n", 85 | "\n", 86 | "\n", 87 | "\n", 88 | "\n", 89 | "\n" 90 | ] 91 | } 92 | ], 93 | "source": [ 94 | "# Answer:\n", 95 | "for element in several_things:\n", 96 | " print(element)\n", 97 | " \n", 98 | "for element in several_things:\n", 99 | " print(type(element))" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "### Question 3:\n", 107 | "Write code that uses iteration to print out the length of each element of the list stored in str_list." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 10, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "str_list = [\"hello\", \"\", \"goodbye\", \"wonderful\", \"I love Python\"]" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 11, 122 | "metadata": {}, 123 | "outputs": [ 124 | { 125 | "name": "stdout", 126 | "output_type": "stream", 127 | "text": [ 128 | "5\n", 129 | "0\n", 130 | "7\n", 131 | "9\n", 132 | "13\n" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "# Answer:\n", 138 | "for element in str_list:\n", 139 | " print(len(element))" 140 | ] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "metadata": {}, 145 | "source": [ 146 | "### Question 4:\n", 147 | "Write code to count the number of characters in original_str using the accumulation pattern and assign the answer to a variable num_chars. Do NOT use the len function to solve the problem (if you use it while you are working on this problem, comment it out afterward!)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 12, 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "original_str = \"The quick brown rhino jumped over the extremely lazy fox.\"" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 14, 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "57\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "# Answer:\n", 174 | "num_chars=0\n", 175 | "\n", 176 | "for char in original_str:\n", 177 | " num_chars=num_chars+1\n", 178 | "print(num_chars) " 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "metadata": {}, 184 | "source": [ 185 | "### Question 5:\n", 186 | "addition_str is a string with a list of numbers separated by the + sign. Write code that uses the accumulation pattern to take the sum of all of the numbers and assigns it to sum_val (an integer). (You should use the .split(\"+\") function to split by \"+\" and int() to cast to an integer)." 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": 15, 192 | "metadata": {}, 193 | "outputs": [], 194 | "source": [ 195 | "addition_str = \"2+5+10+20\"" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": 22, 201 | "metadata": {}, 202 | "outputs": [ 203 | { 204 | "name": "stdout", 205 | "output_type": "stream", 206 | "text": [ 207 | "37\n" 208 | ] 209 | } 210 | ], 211 | "source": [ 212 | "# Answer\n", 213 | "numbers=addition_str.split(\"+\")\n", 214 | "\n", 215 | "sum_val=0\n", 216 | "\n", 217 | "for num in numbers:\n", 218 | " sum_val=sum_val+int(num)\n", 219 | "print(sum_val)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "metadata": {}, 225 | "source": [ 226 | "### Question 6:\n", 227 | "week_temps_f is a string with a list of fahrenheit temperatures separated by the , sign. Write code that uses the accumulation pattern to compute the average (sum divided by number of items) and assigns it to avg_temp. Do not hard code your answer (i.e., make your code compute both the sum or the number of items in week_temps_f) (You should use the .split(\",\") function to split by \",\" and float() to cast to a float)." 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 23, 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "week_temps_f = \"75.1,77.7,83.2,82.5,81.0,79.5,85.7\"" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": 27, 242 | "metadata": {}, 243 | "outputs": [ 244 | { 245 | "name": "stdout", 246 | "output_type": "stream", 247 | "text": [ 248 | "80.67142857142858\n" 249 | ] 250 | } 251 | ], 252 | "source": [ 253 | "# Answer\n", 254 | "temperature=week_temps_f.split(\",\")\n", 255 | "\n", 256 | "avg_temp=0\n", 257 | "\n", 258 | "for temp in temperature:\n", 259 | " avg_temp=avg_temp+float(temp)\n", 260 | "\n", 261 | "avg_temp=avg_temp/len(temperature)\n", 262 | "\n", 263 | "print(avg_temp)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "metadata": {}, 269 | "source": [ 270 | "### Question 7:\n", 271 | "Write code to create a list of numbers from 0 to 67 and assign that list to the variable nums. Do not hard code the list." 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": 31, 277 | "metadata": {}, 278 | "outputs": [], 279 | "source": [ 280 | "# Answer\n", 281 | "nums=list(range(68))" 282 | ] 283 | }, 284 | { 285 | "cell_type": "markdown", 286 | "metadata": {}, 287 | "source": [ 288 | "### Question 8:\n", 289 | "Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list. (You should use the len function)." 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": 32, 295 | "metadata": {}, 296 | "outputs": [], 297 | "source": [ 298 | "original_str = \"The quick brown rhino jumped over the extremely lazy fox\"" 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 37, 304 | "metadata": {}, 305 | "outputs": [ 306 | { 307 | "name": "stdout", 308 | "output_type": "stream", 309 | "text": [ 310 | "[3, 5, 5, 5, 6, 4, 3, 9, 4, 3]\n" 311 | ] 312 | } 313 | ], 314 | "source": [ 315 | "# Answer\n", 316 | "words=original_str.split()\n", 317 | "\n", 318 | "num_words_list=[]\n", 319 | "\n", 320 | "for word in words:\n", 321 | " num_words_list.append(len(word))\n", 322 | "\n", 323 | "print(num_words_list)" 324 | ] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "metadata": {}, 329 | "source": [ 330 | "### Question 9:\n", 331 | "Create an empty string and assign it to the variable lett. Then using range, write code such that when your code is run, lett has 7 b’s (\"bbbbbbb\")." 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": 41, 337 | "metadata": {}, 338 | "outputs": [ 339 | { 340 | "name": "stdout", 341 | "output_type": "stream", 342 | "text": [ 343 | "bbbbbbb\n" 344 | ] 345 | } 346 | ], 347 | "source": [ 348 | "lett=\"\"\n", 349 | "\n", 350 | "for i in range(7):\n", 351 | " lett=lett+'b'\n", 352 | "\n", 353 | "print(lett)" 354 | ] 355 | } 356 | ], 357 | "metadata": { 358 | "kernelspec": { 359 | "display_name": "Python 3", 360 | "language": "python", 361 | "name": "python3" 362 | }, 363 | "language_info": { 364 | "codemirror_mode": { 365 | "name": "ipython", 366 | "version": 3 367 | }, 368 | "file_extension": ".py", 369 | "mimetype": "text/x-python", 370 | "name": "python", 371 | "nbconvert_exporter": "python", 372 | "pygments_lexer": "ipython3", 373 | "version": "3.7.3" 374 | } 375 | }, 376 | "nbformat": 4, 377 | "nbformat_minor": 2 378 | } 379 | -------------------------------------------------------------------------------- /Python Basics/Readme: -------------------------------------------------------------------------------- 1 | 2 | Answer keys to weekly assessments. 3 | -------------------------------------------------------------------------------- /Python Basics/Week 4 Assessment Methods-Lists and Strings.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Week 4 Assessment: Methods: Lists and Strings" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Question 3\n", 15 | "Write code to add ‘horseback riding’ to the third position (i.e., right before volleyball) in the list sports." 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 2, 30 | "metadata": {}, 31 | "outputs": [ 32 | { 33 | "data": { 34 | "text/plain": [ 35 | "['cricket',\n", 36 | " 'football',\n", 37 | " 'horseback riding',\n", 38 | " 'volleyball',\n", 39 | " 'baseball',\n", 40 | " 'softball',\n", 41 | " 'track and field',\n", 42 | " 'curling',\n", 43 | " 'ping pong',\n", 44 | " 'hockey']" 45 | ] 46 | }, 47 | "execution_count": 2, 48 | "metadata": {}, 49 | "output_type": "execute_result" 50 | } 51 | ], 52 | "source": [ 53 | "sports.insert(2,'horseback riding')\n", 54 | "sports" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "### Question 4\n", 62 | "Write code to take ‘London’ out of the list trav_dest." 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 5, 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'London', 'Melbourne']" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 6, 77 | "metadata": {}, 78 | "outputs": [ 79 | { 80 | "data": { 81 | "text/plain": [ 82 | "['Beirut',\n", 83 | " 'Milan',\n", 84 | " 'Pittsburgh',\n", 85 | " 'Buenos Aires',\n", 86 | " 'Nairobi',\n", 87 | " 'Kathmandu',\n", 88 | " 'Osaka',\n", 89 | " 'Melbourne']" 90 | ] 91 | }, 92 | "execution_count": 6, 93 | "metadata": {}, 94 | "output_type": "execute_result" 95 | } 96 | ], 97 | "source": [ 98 | "trav_dest.remove('London')\n", 99 | "trav_dest" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "### Question 5\n", 107 | "Write code to add ‘Guadalajara’ to the end of the list trav_dest using a list method." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 9, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne']" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 10, 122 | "metadata": {}, 123 | "outputs": [ 124 | { 125 | "data": { 126 | "text/plain": [ 127 | "['Beirut',\n", 128 | " 'Milan',\n", 129 | " 'Pittsburgh',\n", 130 | " 'Buenos Aires',\n", 131 | " 'Nairobi',\n", 132 | " 'Kathmandu',\n", 133 | " 'Osaka',\n", 134 | " 'Melbourne',\n", 135 | " 'Guadalajara']" 136 | ] 137 | }, 138 | "execution_count": 10, 139 | "metadata": {}, 140 | "output_type": "execute_result" 141 | } 142 | ], 143 | "source": [ 144 | "trav_dest.append('Guadalajara')\n", 145 | "trav_dest" 146 | ] 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "metadata": {}, 151 | "source": [ 152 | "### Question 6\n", 153 | "Write code to rearrange the strings in the list winners so that they are in alphabetical order from A to Z." 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 11, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "winners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth']" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 12, 168 | "metadata": {}, 169 | "outputs": [ 170 | { 171 | "data": { 172 | "text/plain": [ 173 | "['Alice Munro',\n", 174 | " 'Alvin E. Roth',\n", 175 | " 'Kazuo Ishiguro',\n", 176 | " 'Malala Yousafzai',\n", 177 | " 'Rainer Weiss',\n", 178 | " 'Youyou Tu']" 179 | ] 180 | }, 181 | "execution_count": 12, 182 | "metadata": {}, 183 | "output_type": "execute_result" 184 | } 185 | ], 186 | "source": [ 187 | "winners.sort()\n", 188 | "winners" 189 | ] 190 | }, 191 | { 192 | "cell_type": "markdown", 193 | "metadata": {}, 194 | "source": [ 195 | "### Question 7\n", 196 | "Write code to switch the order of the winners list so that it is now Z to A. Assign this list to the variable z_winners." 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 23, 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [ 205 | "winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu']" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": 24, 211 | "metadata": {}, 212 | "outputs": [ 213 | { 214 | "data": { 215 | "text/plain": [ 216 | "['Youyou Tu',\n", 217 | " 'Rainer Weiss',\n", 218 | " 'Malala Yousafzai',\n", 219 | " 'Kazuo Ishiguro',\n", 220 | " 'Alvin E. Roth',\n", 221 | " 'Alice Munro']" 222 | ] 223 | }, 224 | "execution_count": 24, 225 | "metadata": {}, 226 | "output_type": "execute_result" 227 | } 228 | ], 229 | "source": [ 230 | "z_winners=winners\n", 231 | "z_winners.reverse()\n", 232 | "z_winners" 233 | ] 234 | } 235 | ], 236 | "metadata": { 237 | "kernelspec": { 238 | "display_name": "Python 3", 239 | "language": "python", 240 | "name": "python3" 241 | }, 242 | "language_info": { 243 | "codemirror_mode": { 244 | "name": "ipython", 245 | "version": 3 246 | }, 247 | "file_extension": ".py", 248 | "mimetype": "text/x-python", 249 | "name": "python", 250 | "nbconvert_exporter": "python", 251 | "pygments_lexer": "ipython3", 252 | "version": "3.7.3" 253 | } 254 | }, 255 | "nbformat": 4, 256 | "nbformat_minor": 2 257 | } 258 | -------------------------------------------------------------------------------- /Python Basics/Week 4 Assessment-Accumulating Lists and Strings.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Week 4 Assessment: Accumulating Lists and Strings" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Question from Reading 9.11 The Accumulator Pattern with Strings\n", 15 | "Assign an empty string to the variable output. Using the range function, write code to make it so that the variable output has 35 a s inside it (like \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"). Hint: use the accumulation pattern!" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [ 23 | { 24 | "name": "stdout", 25 | "output_type": "stream", 26 | "text": [ 27 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 28 | ] 29 | } 30 | ], 31 | "source": [ 32 | "output=\"\"\n", 33 | "\n", 34 | "for i in range(35):\n", 35 | " output=output+'a'\n", 36 | "print(output)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "### Question 1\n", 44 | "Currently there is a string called str1. Write code to create a list called chars which should contain the characters from str1. Each character in str1 should be its own element in the list chars." 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 10, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "str1 = \"I love python\"\n", 54 | "# HINT: what's the accumulator? That should go here." 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 15, 60 | "metadata": {}, 61 | "outputs": [ 62 | { 63 | "name": "stdout", 64 | "output_type": "stream", 65 | "text": [ 66 | "['I', 'love', 'python']\n" 67 | ] 68 | } 69 | ], 70 | "source": [ 71 | "chars=[]\n", 72 | "\n", 73 | "for char in str1:\n", 74 | " chars.append(char)\n", 75 | " \n", 76 | "print(chars)\n" 77 | ] 78 | } 79 | ], 80 | "metadata": { 81 | "kernelspec": { 82 | "display_name": "Python 3", 83 | "language": "python", 84 | "name": "python3" 85 | }, 86 | "language_info": { 87 | "codemirror_mode": { 88 | "name": "ipython", 89 | "version": 3 90 | }, 91 | "file_extension": ".py", 92 | "mimetype": "text/x-python", 93 | "name": "python", 94 | "nbconvert_exporter": "python", 95 | "pygments_lexer": "ipython3", 96 | "version": "3.7.3" 97 | } 98 | }, 99 | "nbformat": 4, 100 | "nbformat_minor": 2 101 | } 102 | -------------------------------------------------------------------------------- /Python Basics/Week 4-Final Course Assignment.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question 1\n", 8 | "Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 or above and assign that result to the value a_scores." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 6, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "scores = \"67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100\"" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 12, 23 | "metadata": {}, 24 | "outputs": [ 25 | { 26 | "name": "stdout", 27 | "output_type": "stream", 28 | "text": [ 29 | "10\n" 30 | ] 31 | } 32 | ], 33 | "source": [ 34 | "# Answer:\n", 35 | "scores2=scores.split()\n", 36 | "\n", 37 | "a_scores=0\n", 38 | "\n", 39 | "for score in scores2:\n", 40 | " if int(score)==90 or int(score)>90:\n", 41 | " a_scores+=1\n", 42 | " \n", 43 | "print(a_scores)" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "### Question 2\n", 51 | "Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro. Only the first letter of each word should be used, each letter in the acronym should be a capital letter, and there should be nothing to separate the letters of the acronym. Words that should not be included in the acronym are stored in the list stopwords. For example, if org was assigned the string “hello to world” then the resulting acronym should be “HW”." 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 24, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', \"The\"]\n", 61 | "org = \"The organization for health, safety, and education\"" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 27, 67 | "metadata": {}, 68 | "outputs": [ 69 | { 70 | "name": "stdout", 71 | "output_type": "stream", 72 | "text": [ 73 | "OHSE\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "org2=org.split()\n", 79 | "\n", 80 | "acro=''\n", 81 | "\n", 82 | "for word in org2:\n", 83 | " if word not in stopwords:\n", 84 | " acro=acro+word[0].upper()\n", 85 | "\n", 86 | "print(acro)" 87 | ] 88 | }, 89 | { 90 | "cell_type": "markdown", 91 | "metadata": {}, 92 | "source": [ 93 | "### Question 3\n", 94 | "Write code that uses the string stored in sent and creates an acronym which is assigned to the variable acro. The first two letters of each word should be used, each letter in the acronym should be a capital letter, and each element of the acronym should be separated by a “. ” (dot and space). Words that should not be included in the acronym are stored in the list stopwords. For example, if sent was assigned the string “height and ewok wonder” then the resulting acronym should be “HE. EW. WO”." 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 54, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']\n", 104 | "sent = \"The water earth and air are vital\"" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 56, 110 | "metadata": {}, 111 | "outputs": [ 112 | { 113 | "name": "stdout", 114 | "output_type": "stream", 115 | "text": [ 116 | "WA. EA. AI. AR. VI\n" 117 | ] 118 | } 119 | ], 120 | "source": [ 121 | "sent2=sent.split()\n", 122 | "\n", 123 | "acro=''\n", 124 | "\n", 125 | "for word in sent2:\n", 126 | " if word not in stopwords:\n", 127 | " acro=acro+word[0].upper()+word[1].upper()+'. '\n", 128 | " \n", 129 | "\n", 130 | "acro=acro[:-2]\n", 131 | "\n", 132 | "print(acro)" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "### Question 4\n", 140 | "A palindrome is a phrase that, if reversed, would read the exact same. Write code that checks if p_phrase is a palindrome by reversing it and then checking if the reversed version is equal to the original. Assign the reversed version of p_phrase to the variable r_phrase so that we can check your work." 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 30, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "p_phrase = \"was it a car or a cat I saw\"" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 33, 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "name": "stdout", 159 | "output_type": "stream", 160 | "text": [ 161 | "was I tac a ro rac a ti saw\n", 162 | "False\n" 163 | ] 164 | } 165 | ], 166 | "source": [ 167 | "r_phrase=''\n", 168 | "\n", 169 | "for char in p_phrase:\n", 170 | " r_phrase=char+r_phrase\n", 171 | " \n", 172 | "print(r_phrase)\n", 173 | "print(r_phrase==p_phrase)" 174 | ] 175 | }, 176 | { 177 | "cell_type": "markdown", 178 | "metadata": {}, 179 | "source": [ 180 | "### Question 5\n", 181 | "Provided is a list of data about a store’s inventory where each item in the list represents the name of an item, how much is in stock, and how much it costs. Print out each item in the list with the same formatting, using the .format method (not string concatenation). For example, the first print statment should read The store has 12 shoes, each for 29.99 USD." 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": 34, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "inventory = [\"shoes, 12, 29.99\", \"shirts, 20, 9.99\", \"sweatpants, 25, 15.00\", \"scarves, 13, 7.75\"]" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 38, 196 | "metadata": {}, 197 | "outputs": [ 198 | { 199 | "name": "stdout", 200 | "output_type": "stream", 201 | "text": [ 202 | "The store has 12 shoes, each for 29.99 USD.\n", 203 | "The store has 20 shirts, each for 9.99 USD.\n", 204 | "The store has 25 sweatpants, each for 15.00 USD.\n", 205 | "The store has 13 scarves, each for 7.75 USD.\n" 206 | ] 207 | } 208 | ], 209 | "source": [ 210 | "for item in inventory:\n", 211 | " print(\"The store has {} {}, each for {} USD.\".format(item.split(', ')[1],item.split(', ')[0],item.split(', ')[2]))" 212 | ] 213 | } 214 | ], 215 | "metadata": { 216 | "kernelspec": { 217 | "display_name": "Python 3", 218 | "language": "python", 219 | "name": "python3" 220 | }, 221 | "language_info": { 222 | "codemirror_mode": { 223 | "name": "ipython", 224 | "version": 3 225 | }, 226 | "file_extension": ".py", 227 | "mimetype": "text/x-python", 228 | "name": "python", 229 | "nbconvert_exporter": "python", 230 | "pygments_lexer": "ipython3", 231 | "version": "3.7.3" 232 | } 233 | }, 234 | "nbformat": 4, 235 | "nbformat_minor": 2 236 | } 237 | -------------------------------------------------------------------------------- /Python Classes and Inheritance/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Project - Part 1 Sentiment Classifier.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "To start, define a function called strip_punctuation which takes one parameter, a string which represents a word, and removes characters considered punctuation from everywhere in the word. (Hint: remember the .replace() method for strings.)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "punctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", '#', '@']" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 27, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "# Answer:\n", 26 | "\n", 27 | "def strip_punctuation(string):\n", 28 | " \n", 29 | " for char in string:\n", 30 | " if char in punctuation_chars:\n", 31 | " string=string.replace(char,\"\")\n", 32 | "\n", 33 | " return string " 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "Next, copy in your strip_punctuation function and define a function called get_pos which takes one parameter, a string which represents a one or more sentences, and calculates how many words in the string are considered positive words. Use the list, positive_words to determine what words will count as positive. The function should return a positive integer - how many occurances there are of positive words in the text." 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# Answer: \n", 50 | "\n", 51 | "punctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", '#', '@']\n", 52 | "# list of positive words to use\n", 53 | "positive_words = []\n", 54 | "with open(\"positive_words.txt\") as pos_f:\n", 55 | " for lin in pos_f:\n", 56 | " if lin[0] != ';' and lin[0] != '\\n':\n", 57 | " positive_words.append(lin.strip())\n", 58 | "#------------------------Provided------------------------------------\n", 59 | " \n", 60 | "def strip_punctuation(string):\n", 61 | " \n", 62 | " for char in string:\n", 63 | " if char in punctuation_chars:\n", 64 | " string=string.replace(char,\"\")\n", 65 | "\n", 66 | " return string \n", 67 | "#----------------------Answer from Above----------------------------\n", 68 | "\n", 69 | "def get_pos(sentence):\n", 70 | " \n", 71 | " count=0\n", 72 | " \n", 73 | " for string in sentence.split(\" \"):\n", 74 | " if strip_punctuation(string) in positive_words:\n", 75 | " count+=1\n", 76 | " \n", 77 | " return count\n", 78 | "#--------------------Real Answer to this Question --------------------" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter, a string which represents a one or more sentences, and calculates how many words in the string are considered negative words. Use the list, negative_words to determine what words will count as negative. The function should return a positive integer - how many occurances there are of negative words in the text." 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "punctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", '#', '@']\n", 95 | "\n", 96 | "negative_words = []\n", 97 | "with open(\"negative_words.txt\") as pos_f:\n", 98 | " for lin in pos_f:\n", 99 | " if lin[0] != ';' and lin[0] != '\\n':\n", 100 | " negative_words.append(lin.strip())\n", 101 | "#------------------------Provided------------------------------------\n", 102 | " \n", 103 | "def strip_punctuation(string):\n", 104 | " \n", 105 | " for char in string:\n", 106 | " if char in punctuation_chars:\n", 107 | " string=string.replace(char,\"\")\n", 108 | "\n", 109 | " return string \n", 110 | "#----------------------Answer from Part 1----------------------------\n", 111 | "\n", 112 | "def get_neg(sentence):\n", 113 | " \n", 114 | " count=0\n", 115 | " \n", 116 | " for string in sentence.split(\" \"):\n", 117 | " if strip_punctuation(string) in negative_words:\n", 118 | " count+=1\n", 119 | " \n", 120 | " return count\n", 121 | "#--------------------Similar to Answer in Part 2--------------------" 122 | ] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "metadata": {}, 127 | "source": [ 128 | "Finally, copy in your previous functions and write code that opens the file project_twitter_data.csv which has the fake generated twitter data (the text of a tweet, the number of retweets of that tweet, and the number of replies to that tweet). Your task is to build a sentiment classifier, which will detect how positive or negative each tweet is. Copy the code from the code windows above, and put that in the top of this code window. Now, you will write code to create a csv file called resulting_data.csv, which contains the Number of Retweets, Number of Replies, Positive Score (which is how many happy words are in the tweet), Negative Score (which is how many angry words are in the tweet), and the Net Score (how positive or negative the text is overall) for each tweet. The file should have those headers in that order. Remember that there is another component to this project. You will upload the csv file to Excel or Google Sheets and produce a graph of the Net Score vs Number of Retweets. Check Coursera for that portion of the assignment, if you’re accessing this textbook from Coursera." 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "metadata": {}, 134 | "source": [ 135 | "See https://github.com/RichardDanielOliva/Python_FunctionsFilesDictionaries_FinalCourseProject/blob/master/pyProjectFunctionFilesDictionary.py" 136 | ] 137 | } 138 | ], 139 | "metadata": { 140 | "kernelspec": { 141 | "display_name": "Python 3", 142 | "language": "python", 143 | "name": "python3" 144 | }, 145 | "language_info": { 146 | "codemirror_mode": { 147 | "name": "ipython", 148 | "version": 3 149 | }, 150 | "file_extension": ".py", 151 | "mimetype": "text/x-python", 152 | "name": "python", 153 | "nbconvert_exporter": "python", 154 | "pygments_lexer": "ipython3", 155 | "version": "3.7.3" 156 | } 157 | }, 158 | "nbformat": 4, 159 | "nbformat_minor": 2 160 | } 161 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Project - Part 2 Sentiment Analysis.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctzhou86/Coursera-Python-3-Programming-Specialization/c6d251b510ee47bd7d60a32b005e587cda5ac150/Python Functions, Files, and Dictionaries/Project - Part 2 Sentiment Analysis.xlsx -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Readme: -------------------------------------------------------------------------------- 1 | 2 | Answer keys to weekly assignments. 3 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Scatterplot of Number of Retweets vs Net Score.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctzhou86/Coursera-Python-3-Programming-Specialization/c6d251b510ee47bd7d60a32b005e587cda5ac150/Python Functions, Files, and Dictionaries/Scatterplot of Number of Retweets vs Net Score.PNG -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 1 Assessment-Files and CSV.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question 1\n", 8 | "The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. Find the total number of characters in the file and save to the variable num." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "# Answer:\n", 18 | "fileref=open('travel_plans.txt','r')\n", 19 | "\n", 20 | "contents=fileref.read()\n", 21 | "\n", 22 | "num=len(contents)\n", 23 | "\n", 24 | "print(num)\n", 25 | "\n", 26 | "fileref.close()" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "### Question 2\n", 34 | "We have provided a file called emotion_words.txt that contains lines of words that describe emotions. Find the total number of words in the file and assign this value to the variable num_words." 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "fileref=open('emotion_words.txt','r')\n", 44 | "\n", 45 | "num_words=0\n", 46 | "\n", 47 | "for line in fileref.readlines():\n", 48 | " values=line.split() # notice that the question asks for words. have to split a sentence into a sequence of strings first\n", 49 | " # values is a list of strings\n", 50 | " num_words+=len(values) # for each row, count the number of strings in the list and add that number to num_words\n", 51 | " \n", 52 | "print(num_words)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "### Question 3\n", 60 | "Assign to the variable num_lines the number of lines in the file school_prompt.txt." 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "# Answer:\n", 70 | "fileref=open('school_prompt.txt','r')\n", 71 | "\n", 72 | "num_lines=0\n", 73 | "\n", 74 | "for line in fileref.readlines():\n", 75 | " num_lines+=1\n", 76 | " \n", 77 | "print(num_lines)" 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "### Question 4\n", 85 | "Assign the first 30 characters of school_prompt.txt as a string to the variable beginning_chars." 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "# Answer:\n", 95 | "fileref=open('school_prompt.txt','r')\n", 96 | "\n", 97 | "beginning_chars=fileref.read(30)\n", 98 | "\n", 99 | "print(beginning_chars)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "### Question 5\n", 107 | "Challenge: Using the file school_prompt.txt, assign the third word of every line to a list called three." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "# Answer:\n", 117 | "fileref=open('school_prompt.txt','r')\n", 118 | "\n", 119 | "three=[]\n", 120 | "\n", 121 | "for line in fileref.readlines():\n", 122 | " line2=line.split() # notice that the question asks for words. have to split a sentence into a sequence of strings first\n", 123 | " three.append(line2[2])\n", 124 | " \n", 125 | "print(three)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "### Question 6\n", 133 | "Challenge: Create a list called emotions that contains the first word of every line in emotion_words.txt." 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "# Answer:\n", 143 | "fileref=open('emotion_words.txt','r')\n", 144 | "\n", 145 | "emotions=[]\n", 146 | "\n", 147 | "for line in fileref.readlines():\n", 148 | " line2=line.split()\n", 149 | " emotions.append(line2[0])\n", 150 | " \n", 151 | "print(emotions)" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "### Question 7\n", 159 | "Assign the first 33 characters from the textfile, travel_plans.txt to the variable first_chars." 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "fileref=open('travel_plans.txt','r')\n", 169 | "\n", 170 | "first_chars=fileref.read(33)\n", 171 | "\n", 172 | "print(first_chars)" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "### Question 8\n", 180 | "Challenge: Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called p_words." 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [ 189 | "fileref=open('school_prompt.txt','r')\n", 190 | "\n", 191 | "p_words=[]\n", 192 | "\n", 193 | "for line in fileref.readlines():\n", 194 | " values=line.split() # for each line, split it into a list of strings first\n", 195 | " for word in values: # loop through all words in the list (for all rows)\n", 196 | " if 'p' in word: # if statement\n", 197 | " p_words.append(word)\n", 198 | " \n", 199 | " \n", 200 | "print(p_words)" 201 | ] 202 | } 203 | ], 204 | "metadata": { 205 | "kernelspec": { 206 | "display_name": "Python 3", 207 | "language": "python", 208 | "name": "python3" 209 | }, 210 | "language_info": { 211 | "codemirror_mode": { 212 | "name": "ipython", 213 | "version": 3 214 | }, 215 | "file_extension": ".py", 216 | "mimetype": "text/x-python", 217 | "name": "python", 218 | "nbconvert_exporter": "python", 219 | "pygments_lexer": "ipython3", 220 | "version": "3.7.3" 221 | } 222 | }, 223 | "nbformat": 4, 224 | "nbformat_minor": 2 225 | } 226 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 2 Assessment-Dictionary Accumulation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question from *Introduction: Accumulating Multiple Results in a Dictionary*" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "2. Provided is a string saved to the variable name sentence. Split the string into a list of words, then create a dictionary that contains each word and the number of times it occurs. Save this dictionary to the variable name word_counts." 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "sentence = \"The dog chased the rabbit into the forest but the rabbit was too quick.\"" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 5, 29 | "metadata": {}, 30 | "outputs": [ 31 | { 32 | "name": "stdout", 33 | "output_type": "stream", 34 | "text": [ 35 | "{'The': 1, 'dog': 1, 'chased': 1, 'the': 3, 'rabbit': 2, 'into': 1, 'forest': 1, 'but': 1, 'was': 1, 'too': 1, 'quick.': 1}\n" 36 | ] 37 | } 38 | ], 39 | "source": [ 40 | "# Answer:\n", 41 | "sentence2=sentence.split()\n", 42 | "\n", 43 | "word_counts={}\n", 44 | "\n", 45 | "for word in sentence2:\n", 46 | " if word not in word_counts.keys():\n", 47 | " word_counts[word]=0\n", 48 | " \n", 49 | " word_counts[word]+=1\n", 50 | " \n", 51 | "print(word_counts)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "3. Create a dictionary called char_d from the string stri, so that the key is a character and the value is how many times it occurs." 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 6, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "stri = \"what can I do\"" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": 7, 73 | "metadata": {}, 74 | "outputs": [ 75 | { 76 | "name": "stdout", 77 | "output_type": "stream", 78 | "text": [ 79 | "{'w': 1, 'h': 1, 'a': 2, 't': 1, ' ': 3, 'c': 1, 'n': 1, 'I': 1, 'd': 1, 'o': 1}\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "# Answer:\n", 85 | "char_d={}\n", 86 | "\n", 87 | "for char in stri:\n", 88 | " if char not in char_d.keys():\n", 89 | " char_d[char]=0\n", 90 | " \n", 91 | " char_d[char]+=1\n", 92 | " \n", 93 | "print(char_d)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "### Question 1\n", 101 | "The dictionary Junior shows a schedule for a junior year semester. The key is the course name and the value is the number of credits. Find the total number of credits taken this semester and assign it to the variable credits. Do not hardcode this – use dictionary accumulation!" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 8, 107 | "metadata": {}, 108 | "outputs": [], 109 | "source": [ 110 | "Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3}" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 9, 116 | "metadata": {}, 117 | "outputs": [ 118 | { 119 | "name": "stdout", 120 | "output_type": "stream", 121 | "text": [ 122 | "18\n" 123 | ] 124 | } 125 | ], 126 | "source": [ 127 | "# Answer:\n", 128 | "credits=0\n", 129 | "\n", 130 | "for key in Junior.keys():\n", 131 | " credits+=Junior[key]\n", 132 | " \n", 133 | "print(credits)" 134 | ] 135 | }, 136 | { 137 | "cell_type": "markdown", 138 | "metadata": {}, 139 | "source": [ 140 | "### Question 2\n", 141 | "Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value." 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": 10, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "str1 = \"peter piper picked a peck of pickled peppers\"" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 13, 156 | "metadata": {}, 157 | "outputs": [ 158 | { 159 | "name": "stdout", 160 | "output_type": "stream", 161 | "text": [ 162 | "{'p': 9, 'e': 8, 't': 1, 'r': 3, ' ': 7, 'i': 3, 'c': 3, 'k': 3, 'd': 2, 'a': 1, 'o': 1, 'f': 1, 'l': 1, 's': 1}\n" 163 | ] 164 | } 165 | ], 166 | "source": [ 167 | "# Answer:\n", 168 | "freq={}\n", 169 | "\n", 170 | "for char in str1:\n", 171 | " if char not in freq.keys():\n", 172 | " freq[char]=0\n", 173 | " \n", 174 | " freq[char]+=1\n", 175 | " \n", 176 | "print(freq) " 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "### Question 3\n", 184 | "Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1 and the number of times it occurs." 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 14, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "s1 = \"hello\"" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": 15, 199 | "metadata": {}, 200 | "outputs": [ 201 | { 202 | "name": "stdout", 203 | "output_type": "stream", 204 | "text": [ 205 | "{'h': 1, 'e': 1, 'l': 2, 'o': 1}\n" 206 | ] 207 | } 208 | ], 209 | "source": [ 210 | "# Answer:\n", 211 | "counts={}\n", 212 | "\n", 213 | "for char in s1:\n", 214 | " if char not in counts.keys():\n", 215 | " counts[char]=0\n", 216 | " \n", 217 | " counts[char]+=1\n", 218 | " \n", 219 | "print(counts) " 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "metadata": {}, 225 | "source": [ 226 | "### Question 4\n", 227 | "Create a dictionary, freq_words, that displays each word in string str1 as the key and its frequency as the value." 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 16, 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "str1 = \"I wish I wish with all my heart to fly with dragons in a land apart\"" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": 18, 242 | "metadata": {}, 243 | "outputs": [ 244 | { 245 | "name": "stdout", 246 | "output_type": "stream", 247 | "text": [ 248 | "{'I': 2, 'wish': 2, 'with': 2, 'all': 1, 'my': 1, 'heart': 1, 'to': 1, 'fly': 1, 'dragons': 1, 'in': 1, 'a': 1, 'land': 1, 'apart': 1}\n" 249 | ] 250 | } 251 | ], 252 | "source": [ 253 | "# Answer:\n", 254 | "freq_words={}\n", 255 | "\n", 256 | "for word in str1.split():\n", 257 | " if word not in freq_words.keys(): # a sginle string to a list of words\n", 258 | " freq_words[word]=0\n", 259 | " \n", 260 | " freq_words[word]+=1\n", 261 | " \n", 262 | "print(freq_words)" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "### Question 5\n", 270 | "Create a dictionary called wrd_d from the string sent, so that the key is a word and the value is how many times you have seen that word." 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 19, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "sent = \"Singing in the rain and playing in the rain are two entirely different situations but both can be good\"" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 20, 285 | "metadata": {}, 286 | "outputs": [ 287 | { 288 | "name": "stdout", 289 | "output_type": "stream", 290 | "text": [ 291 | "{'Singing': 1, 'in': 2, 'the': 2, 'rain': 2, 'and': 1, 'playing': 1, 'are': 1, 'two': 1, 'entirely': 1, 'different': 1, 'situations': 1, 'but': 1, 'both': 1, 'can': 1, 'be': 1, 'good': 1}\n" 292 | ] 293 | } 294 | ], 295 | "source": [ 296 | "# Answer:\n", 297 | "wrd_d={}\n", 298 | "\n", 299 | "for word in sent.split():\n", 300 | " if word not in wrd_d.keys(): # a sginle string to a list of words\n", 301 | " wrd_d[word]=0\n", 302 | " \n", 303 | " wrd_d[word]+=1\n", 304 | " \n", 305 | "print(wrd_d)" 306 | ] 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "metadata": {}, 311 | "source": [ 312 | "### Question 6\n", 313 | "Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the most frequent letter based on the dictionary. Assign this letter to the variable best_char." 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": 21, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "sally = \"sally sells sea shells by the sea shore\"" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 23, 328 | "metadata": {}, 329 | "outputs": [ 330 | { 331 | "name": "stdout", 332 | "output_type": "stream", 333 | "text": [ 334 | "{'s': 8, 'a': 3, 'l': 6, 'y': 2, ' ': 7, 'e': 6, 'h': 3, 'b': 1, 't': 1, 'o': 1, 'r': 1}\n", 335 | "s\n" 336 | ] 337 | } 338 | ], 339 | "source": [ 340 | "characters={}\n", 341 | "\n", 342 | "for char in sally:\n", 343 | " if char not in characters.keys():\n", 344 | " characters[char]=0\n", 345 | " \n", 346 | " characters[char]+=1\n", 347 | " \n", 348 | "print(characters)\n", 349 | "\n", 350 | "# get all keys from characters and put them in a list\n", 351 | "letters=list(characters.keys())\n", 352 | "\n", 353 | "# assume the biggest value appears after the first key\n", 354 | "best_char=letters[0] # best_char is also a letter\n", 355 | "\n", 356 | "# loop\n", 357 | "for letter in letters: # remember: letters list contains letters (keys of characters) only\n", 358 | " if characters[letter]>characters[best_char]:\n", 359 | " best_char=letter # if our assumption (the first letter has the largest value) doesn't hold, replace best_char with the new letter \n", 360 | "\n", 361 | "print(best_char)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "markdown", 366 | "metadata": {}, 367 | "source": [ 368 | "### Question 7\n", 369 | "Do the same as above but now find the least frequent letter. Create the dictionary characters that shows each character from string sally and its frequency. Then, find the least frequent letter in the string and assign the letter to the variable worst_char." 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 24, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "sally = \"sally sells sea shells by the sea shore and by the road\"" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": 25, 384 | "metadata": {}, 385 | "outputs": [ 386 | { 387 | "name": "stdout", 388 | "output_type": "stream", 389 | "text": [ 390 | "{'s': 8, 'a': 5, 'l': 6, 'y': 3, ' ': 11, 'e': 7, 'h': 4, 'b': 2, 't': 2, 'o': 2, 'r': 2, 'n': 1, 'd': 2}\n", 391 | "n\n" 392 | ] 393 | } 394 | ], 395 | "source": [ 396 | "characters={}\n", 397 | "\n", 398 | "for char in sally:\n", 399 | " if char not in characters.keys():\n", 400 | " characters[char]=0\n", 401 | " \n", 402 | " characters[char]+=1\n", 403 | " \n", 404 | "print(characters)\n", 405 | "\n", 406 | "letters=list(characters.keys())\n", 407 | "\n", 408 | "worst_char=letters[0]\n", 409 | "\n", 410 | "for letter in letters: \n", 411 | " if characters[letter]=5:\n", 187 | " return \"Longer than 5\"\n", 188 | " else:\n", 189 | " return \"Less than 5\"" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "### Question 6\n", 197 | "You will need to write two functions for this problem. The first function, divide that takes in any number and returns that same number divided by 2. The second function called sum should take any number, divide it by 2, and add 6. It should return this new number. You should call the divide function within the sum function. Do not worry about decimals." 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "metadata": {}, 204 | "outputs": [], 205 | "source": [ 206 | "def divide(num):\n", 207 | " return num/2\n", 208 | "\n", 209 | "def sum(num2):\n", 210 | " return divide(num2)+6" 211 | ] 212 | } 213 | ], 214 | "metadata": { 215 | "kernelspec": { 216 | "display_name": "Python 3", 217 | "language": "python", 218 | "name": "python3" 219 | }, 220 | "language_info": { 221 | "codemirror_mode": { 222 | "name": "ipython", 223 | "version": 3 224 | }, 225 | "file_extension": ".py", 226 | "mimetype": "text/x-python", 227 | "name": "python", 228 | "nbconvert_exporter": "python", 229 | "pygments_lexer": "ipython3", 230 | "version": "3.7.3" 231 | } 232 | }, 233 | "nbformat": 4, 234 | "nbformat_minor": 2 235 | } 236 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 3 Assessment-Tuples.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Question 1\n", 8 | "Create a tuple called olympics with four elements: “Beijing”, “London”, “Rio”, “Tokyo”." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 2, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "# Answer:\n", 18 | "olympics=('Beijing', 'London', 'Rio', 'Tokyo')" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "### Question 2\n", 26 | "The list below, tuples_lst, is a list of tuples. Create a list of the second elements of each tuple and assign this list to the variable country." 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 3, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "tuples_lst = [('Beijing', 'China', 2008), ('London', 'England', 2012), ('Rio', 'Brazil', 2016, 'Current'), ('Tokyo', 'Japan', 2020, 'Future')]" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 4, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "name": "stdout", 45 | "output_type": "stream", 46 | "text": [ 47 | "['China', 'England', 'Brazil', 'Japan']\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "# Answer:\n", 53 | "country=[]\n", 54 | "\n", 55 | "for tuple in tuples_lst:\n", 56 | " country.append(tuple[1])\n", 57 | " \n", 58 | "print(country)" 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "### Question 3\n", 66 | "With only one line of code, assign the variables city, country, and year to the values of the tuple olymp." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 5, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "olymp = ('Rio', 'Brazil', 2016)" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 6, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "# Answer:\n", 85 | "city,country,year=olymp[0],olymp[1],olymp[2]" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "### Question 4\n", 93 | "Define a function called info with five parameters: name, gender, age, bday_month, and hometown. The function should then return a tuple with all five parameters in that order." 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 7, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "# Answer:\n", 103 | "def info(name, gender, age, bday_month, hometown):\n", 104 | " return name, gender, age, bday_month, hometown" 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "### Question 5\n", 112 | "Given is the dictionary, gold, which shows the country and the number of gold medals they have earned so far in the 2016 Olympics. Create a list, num_medals, that contains only the number of medals for each country. You must use the .items() method. Note: The .items() method provides a list of tuples. Do not use .keys() method." 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 8, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "gold = {'USA':31, 'Great Britain':19, 'China':19, 'Germany':13, 'Russia':12, 'Japan':10, 'France':8, 'Italy':8}" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": 12, 127 | "metadata": {}, 128 | "outputs": [ 129 | { 130 | "name": "stdout", 131 | "output_type": "stream", 132 | "text": [ 133 | "[31, 19, 19, 13, 12, 10, 8, 8]\n" 134 | ] 135 | } 136 | ], 137 | "source": [ 138 | "# Answer:\n", 139 | "num_medals=[]\n", 140 | "\n", 141 | "for i in gold.items():\n", 142 | " num_medals.append(i[1])\n", 143 | " \n", 144 | "print(num_medals)" 145 | ] 146 | } 147 | ], 148 | "metadata": { 149 | "kernelspec": { 150 | "display_name": "Python 3", 151 | "language": "python", 152 | "name": "python3" 153 | }, 154 | "language_info": { 155 | "codemirror_mode": { 156 | "name": "ipython", 157 | "version": 3 158 | }, 159 | "file_extension": ".py", 160 | "mimetype": "text/x-python", 161 | "name": "python", 162 | "nbconvert_exporter": "python", 163 | "pygments_lexer": "ipython3", 164 | "version": "3.7.3" 165 | } 166 | }, 167 | "nbformat": 4, 168 | "nbformat_minor": 2 169 | } 170 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 3-Returning a Value from a Function.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Questions from _Returning a Value from a Function_" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Question 8\n", 15 | "Write a function named same that takes a string as input, and simply returns that string." 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "def same(string):\n", 25 | " return string" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "### Question 9\n", 33 | "Write a function called same_thing that returns the parameter, unchanged." 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "def same_thing(parameter):\n", 43 | " return parameter" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "### Question 10\n", 51 | "Write a function called subtract_three that takes an integer or any number as input, and returns that number minus three." 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 7, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "def subtract_three(num):\n", 61 | " return num-3" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "### Question 11\n", 69 | "Write a function called change that takes one number as its input and returns that number, plus 7." 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 11, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "def change(num):\n", 79 | " return num+7" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "### Question 12\n", 87 | "Write a function named intro that takes a string as input. Given the string “Becky” as input, the function should return: “Hello, my name is Becky and I love SI 106.”" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 22, 93 | "metadata": {}, 94 | "outputs": [ 95 | { 96 | "name": "stdout", 97 | "output_type": "stream", 98 | "text": [ 99 | "Hello, my name is Mike and I love SI 106.\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "def intro(string):\n", 105 | " print(\"Hello, my name is {} and I love SI 106.\".format(string))" 106 | ] 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "metadata": {}, 111 | "source": [ 112 | "### Question 13\n", 113 | "Write a function called s_change that takes one string as input and returns that string, concatenated with the string ” for fun.”." 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 24, 119 | "metadata": {}, 120 | "outputs": [], 121 | "source": [ 122 | "def s_change(string):\n", 123 | " return string+\" for fun.\"" 124 | ] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "metadata": {}, 129 | "source": [ 130 | "### Question 14\n", 131 | "Write a function called decision that takes a string as input, and then checks the number of characters. If it has over 17 characters, return “This is a long string”, if it is shorter or has 17 characters, return “This is a short string”." 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 38, 137 | "metadata": {}, 138 | "outputs": [ 139 | { 140 | "name": "stdout", 141 | "output_type": "stream", 142 | "text": [ 143 | "This is a short string\n", 144 | "\n" 145 | ] 146 | } 147 | ], 148 | "source": [ 149 | "def decision(string):\n", 150 | " if len(string)>17:\n", 151 | " return 'This is a long string'\n", 152 | " else:\n", 153 | " return 'This is a short string'\n", 154 | "\n", 155 | "print(decision('asd')) \n", 156 | "print(type(decision('asd')))" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 39, 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "This is a short string\n", 169 | "None\n", 170 | "This is a short string\n", 171 | "\n" 172 | ] 173 | } 174 | ], 175 | "source": [ 176 | "def decision(string):\n", 177 | " if len(string)>17:\n", 178 | " print('This is a long string')\n", 179 | " else:\n", 180 | " print('This is a short string')\n", 181 | "\n", 182 | "print(decision('asd')) \n", 183 | "print(type(decision('asd')))" 184 | ] 185 | } 186 | ], 187 | "metadata": { 188 | "kernelspec": { 189 | "display_name": "Python 3", 190 | "language": "python", 191 | "name": "python3" 192 | }, 193 | "language_info": { 194 | "codemirror_mode": { 195 | "name": "ipython", 196 | "version": 3 197 | }, 198 | "file_extension": ".py", 199 | "mimetype": "text/x-python", 200 | "name": "python", 201 | "nbconvert_exporter": "python", 202 | "pygments_lexer": "ipython3", 203 | "version": "3.7.3" 204 | } 205 | }, 206 | "nbformat": 4, 207 | "nbformat_minor": 2 208 | } 209 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 4 Assessment- More about Iteration.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Questions from the reading _The While Statement_" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Write a while loop that is initialized at 0 and stops at 15. If the counter is an even number, append the counter to a list called eve_nums." 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 6, 20 | "metadata": {}, 21 | "outputs": [ 22 | { 23 | "data": { 24 | "text/plain": [ 25 | "[1, 3, 5, 7, 9, 11, 13, 15]" 26 | ] 27 | }, 28 | "execution_count": 6, 29 | "metadata": {}, 30 | "output_type": "execute_result" 31 | } 32 | ], 33 | "source": [ 34 | "eve_nums=[]\n", 35 | "num=0\n", 36 | "\n", 37 | "while num<=15:\n", 38 | " num+=1\n", 39 | " if num%2==1:\n", 40 | " eve_nums.append(num)\n", 41 | "\n", 42 | "eve_nums" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "Below, we’ve provided a for loop that sums all the elements of list1. Write code that accomplishes the same task, but instead uses a while loop. Assign the accumulator variable to the name accum." 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 7, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "list1 = [8, 3, 4, 5, 6, 7, 9]\n", 59 | "\n", 60 | "tot = 0\n", 61 | "for elem in list1:\n", 62 | " tot = tot + elem" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 3, 68 | "metadata": {}, 69 | "outputs": [ 70 | { 71 | "data": { 72 | "text/plain": [ 73 | "42" 74 | ] 75 | }, 76 | "execution_count": 3, 77 | "metadata": {}, 78 | "output_type": "execute_result" 79 | } 80 | ], 81 | "source": [ 82 | "# Answer:\n", 83 | "list1 = [8, 3, 4, 5, 6, 7, 9]\n", 84 | "\n", 85 | "idx=0\n", 86 | "accum=0\n", 87 | "\n", 88 | "while idx11. will keep the first 10 elements\n", 342 | " #if len(list)<10, say 5, it will try to loop through elements number 6~10, which don't exist at all\n", 343 | " \n", 344 | " if lst[idx]!='bye':\n", 345 | " alist.append(lst[idx]) \n", 346 | " if lst[idx]=='bye':\n", 347 | " return alist\n", 348 | " \n", 349 | " idx+=1\n", 350 | " \n", 351 | " return alist" 352 | ] 353 | } 354 | ], 355 | "metadata": { 356 | "kernelspec": { 357 | "display_name": "Python 3", 358 | "language": "python", 359 | "name": "python3" 360 | }, 361 | "language_info": { 362 | "codemirror_mode": { 363 | "name": "ipython", 364 | "version": 3 365 | }, 366 | "file_extension": ".py", 367 | "mimetype": "text/x-python", 368 | "name": "python", 369 | "nbconvert_exporter": "python", 370 | "pygments_lexer": "ipython3", 371 | "version": "3.7.3" 372 | } 373 | }, 374 | "nbformat": 4, 375 | "nbformat_minor": 2 376 | } 377 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 4 Assessment-Advanced Functions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Questions from the reading _Keyword Parameters_" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Define a function called multiply. It should have one required parameter, a string. It should also have one optional parameter, an integer, named mult_int, with a default value of 10. The function should return the string multiplied by the integer. (i.e.: Given inputs “Hello”, mult_int=3, the function should return “HelloHelloHello”)" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "def multiply(string,mult_int=10):\n", 24 | " return string*mult_int" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": {}, 30 | "source": [ 31 | "Currently the function is supposed to take 1 required parameter, and 2 optional parameters, however the code doesn’t work. Fix the code so that it passes the test. This should only require changing one line of code." 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 6, 37 | "metadata": {}, 38 | "outputs": [ 39 | { 40 | "ename": "SyntaxError", 41 | "evalue": "non-default argument follows default argument (, line 1)", 42 | "output_type": "error", 43 | "traceback": [ 44 | "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m def waste(var = \"Water\", mar, marble = \"type\"):\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n" 45 | ] 46 | } 47 | ], 48 | "source": [ 49 | "def waste(var = \"Water\", mar, marble = \"type\"):\n", 50 | " final_string = var + \" \" + marble + \" \" + mar\n", 51 | " return final_string" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "# Answer:\n", 61 | "def waste( mar,var = \"Water\",marble = \"type\"):\n", 62 | " final_string = var + \" \" + marble + \" \" + mar\n", 63 | " return final_string" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | "### Question 1\n", 71 | "Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second." 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 7, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "def mult(integer,x=6):\n", 81 | " return integer*x" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "### Question 2\n", 89 | "The following function, greeting, does not work. Please fix the code so that it runs without error. This only requires one change in the definition of the function." 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "def greeting(greeting=\"Hello \", name, excl=\"!\"):\n", 99 | " return greeting + name + excl\n", 100 | "\n", 101 | "print(greeting(\"Bob\"))\n", 102 | "print(greeting(\"\"))\n", 103 | "print(greeting(\"Bob\", excl=\"!!!\"))" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 10, 109 | "metadata": {}, 110 | "outputs": [ 111 | { 112 | "name": "stdout", 113 | "output_type": "stream", 114 | "text": [ 115 | "Hello Bob!\n", 116 | "Hello !\n", 117 | "Hello Bob!!!\n" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "# Answer:\n", 123 | "def greeting(name, greeting=\"Hello \", excl=\"!\"):\n", 124 | " return greeting + name + excl\n", 125 | "\n", 126 | "print(greeting(\"Bob\"))\n", 127 | "print(greeting(\"\"))\n", 128 | "print(greeting(\"Bob\", excl=\"!!!\"))" 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "metadata": {}, 134 | "source": [ 135 | "### Question 3\n", 136 | "Below is a function, sum, that does not work. Change the function definition so the code works. The function should still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5." 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "def sum(intz=5, intx):\n", 146 | " return intz + intx" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 11, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [ 155 | "# Answer:\n", 156 | "def sum(intx,intz=5):\n", 157 | " return intz + intx" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": {}, 163 | "source": [ 164 | "### Question 4\n", 165 | "Write a function, test, that takes in three parameters: a required integer, an optional boolean whose default value is True, and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, the function should test to see if the integer is a key in the dictionary. The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”." 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 29, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "def test(integer,dummy=True,dict1={2:3, 4:5, 6:8}):\n", 175 | " if dummy==True:\n", 176 | " if integer in dict1.keys():\n", 177 | " return dict1[integer]\n", 178 | " \n", 179 | " if dummy==False:\n", 180 | " return dummy" 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "metadata": {}, 186 | "source": [ 187 | "### Question 5\n", 188 | "Write a function called checkingIfIn that takes three parameters. The first is a required parameter, which should be a string. The second is an optional parameter called direction with a default value of True. The third is an optional parameter called d that has a default value of {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}. Write the function checkingIfIn so that when the second parameter is True, it checks to see if the first parameter is a key in the third parameter; if it is, return True, otherwise return False.\n", 189 | "\n", 190 | "But if the second paramter is False, then the function should check to see if the first parameter is not a key of the third. If it’s not, the function should return True in this case, and if it is, it should return False." 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 32, 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "def checkingIfIn(string,direction=True,d={'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}):\n", 200 | " \n", 201 | " if direction==True:\n", 202 | " if string in d.keys():\n", 203 | " return True\n", 204 | " else:\n", 205 | " return False\n", 206 | " \n", 207 | " if direction==False:\n", 208 | " if string not in d.keys():\n", 209 | " return True\n", 210 | " else:\n", 211 | " return False" 212 | ] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "metadata": {}, 217 | "source": [ 218 | "### Question 6\n", 219 | "We have provided the function checkingIfIn such that if the first input parameter is in the third, dictionary, input parameter, then the function returns that value, and otherwise, it returns False. Follow the instructions in the active code window for specific variable assignmemts." 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 33, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}):\n", 229 | " if direction == True:\n", 230 | " if a in d:\n", 231 | " return d[a]\n", 232 | " else:\n", 233 | " return False\n", 234 | " else:\n", 235 | " if a not in d:\n", 236 | " return True\n", 237 | " else:\n", 238 | " return d[a]\n", 239 | "\n", 240 | "# Call the function so that it returns False and assign that function call to the variable c_false\n", 241 | "\n", 242 | "# Call the fucntion so that it returns True and assign it to the variable c_true\n", 243 | "\n", 244 | "# Call the function so that the value of fruit is assigned to the variable fruit_ans\n", 245 | "\n", 246 | "# Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check\n", 247 | "\n" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 34, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "# Call the function so that it returns False and assign that function call to the variable c_false\n", 257 | "c_false=checkingIfIn('d')" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 37, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "# Call the fucntion so that it returns True and assign it to the variable c_true\n", 267 | "c_true=checkingIfIn('d',direction=False)" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "# Call the function so that the value of fruit is assigned to the variable fruit_ans\n", 277 | "fruit_ans= checkingIfIn('fruit')" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": 39, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "# Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check\n", 287 | "param_check = checkingIfIn('a',True, {'a': 8})" 288 | ] 289 | } 290 | ], 291 | "metadata": { 292 | "kernelspec": { 293 | "display_name": "Python 3", 294 | "language": "python", 295 | "name": "python3" 296 | }, 297 | "language_info": { 298 | "codemirror_mode": { 299 | "name": "ipython", 300 | "version": 3 301 | }, 302 | "file_extension": ".py", 303 | "mimetype": "text/x-python", 304 | "name": "python", 305 | "nbconvert_exporter": "python", 306 | "pygments_lexer": "ipython3", 307 | "version": "3.7.3" 308 | } 309 | }, 310 | "nbformat": 4, 311 | "nbformat_minor": 2 312 | } 313 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/Week 5 Assessment-Sorting.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Questions in the Reading _Optional key parameter_\n", 8 | "\n", 9 | "You will be sorting the following list by each element’s second letter a to z. Create a function to use when sorting that takes a string as input and return the second letter of that string and name it second_let. Create a variable called func_sort and assign the sorted list to it. Do not use lambda." 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 1, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 4, 24 | "metadata": {}, 25 | "outputs": [ 26 | { 27 | "name": "stdout", 28 | "output_type": "stream", 29 | "text": [ 30 | "['dance', 'zebra', 'hi', 'how are you', 'apple', 'bye']\n" 31 | ] 32 | } 33 | ], 34 | "source": [ 35 | "# Answer:\n", 36 | "\n", 37 | "def second_let(string):\n", 38 | " return string[1]\n", 39 | "\n", 40 | "func_sort=sorted(ex_lst,key=second_let)\n", 41 | "\n", 42 | "print(func_sort)" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "Below, we have provided a list of strings called nums. Write a function called last_char that takes a string as input, and returns only its last character. Use this function to sort the list nums by the last digit of each number, from highest to lowest, and save this as a new list called nums_sorted." 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 5, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16']" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 6, 64 | "metadata": {}, 65 | "outputs": [ 66 | { 67 | "name": "stdout", 68 | "output_type": "stream", 69 | "text": [ 70 | "['19', '14378', '8907', '16', '1005', '44', '33', '32', '871', '1450']\n" 71 | ] 72 | } 73 | ], 74 | "source": [ 75 | "# Answer:\n", 76 | "\n", 77 | "def last_char(string):\n", 78 | " return string[-1]\n", 79 | "\n", 80 | "nums_sorted=sorted(nums,reverse=True,key=last_char)\n", 81 | "\n", 82 | "print(nums_sorted)" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": {}, 88 | "source": [ 89 | "Once again, sort the list nums based on the last digit of each number from highest to lowest. However, now you should do so by writing a lambda function. Save the new list as nums_sorted_lambda." 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 8, 95 | "metadata": {}, 96 | "outputs": [ 97 | { 98 | "name": "stdout", 99 | "output_type": "stream", 100 | "text": [ 101 | "['19', '14378', '8907', '16', '1005', '44', '33', '32', '871', '1450']\n" 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "# Answer:\n", 107 | "\n", 108 | "nums_sorted_lambda=sorted(nums,reverse=True,key=lambda x:x[-1])\n", 109 | "\n", 110 | "print(nums_sorted_lambda)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### Questions in the reading _Sorting a Dictionary_\n", 118 | "Sort the following dictionary based on the keys so that they are sorted a to z. Assign the resulting value to the variable sorted_keys." 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": 9, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "dictionary = {\"Flowers\": 10, 'Trees': 20, 'Chairs': 6, \"Firepit\": 1, 'Grill': 2, 'Lights': 14}" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 13, 133 | "metadata": {}, 134 | "outputs": [ 135 | { 136 | "name": "stdout", 137 | "output_type": "stream", 138 | "text": [ 139 | "['Chairs', 'Firepit', 'Flowers', 'Grill', 'Lights', 'Trees']\n" 140 | ] 141 | } 142 | ], 143 | "source": [ 144 | "# Answer:\n", 145 | "\n", 146 | "sorted_keys=sorted(dictionary)\n", 147 | "\n", 148 | "print(sorted_keys)" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": {}, 154 | "source": [ 155 | "Below, we have provided the dictionary groceries, whose keys are grocery items, and values are the number of each item that you need to buy at the store. Sort the dictionary’s keys into alphabetical order, and save them as a list called grocery_keys_sorted." 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 14, 161 | "metadata": {}, 162 | "outputs": [], 163 | "source": [ 164 | "groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9}" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": 15, 170 | "metadata": {}, 171 | "outputs": [ 172 | { 173 | "name": "stdout", 174 | "output_type": "stream", 175 | "text": [ 176 | "['apples', 'bananas', 'carrots', 'cereal', 'coffee', 'granola bars', 'onions', 'orange juice', 'pasta', 'peanut butter', 'popcorn', 'rice', 'salsa', 'spinach']\n" 177 | ] 178 | } 179 | ], 180 | "source": [ 181 | "# Answer:\n", 182 | "\n", 183 | "grocery_keys_sorted=sorted(groceries)\n", 184 | "\n", 185 | "print(grocery_keys_sorted)" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "Sort the following dictionary’s keys based on the value from highest to lowest. Assign the resulting value to the variable sorted_values" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": 16, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "dictionary = {\"Flowers\": 10, 'Trees': 20, 'Chairs': 6, \"Firepit\": 1, 'Grill': 2, 'Lights': 14}" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 17, 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "name": "stdout", 211 | "output_type": "stream", 212 | "text": [ 213 | "['Trees', 'Lights', 'Flowers', 'Chairs', 'Grill', 'Firepit']\n" 214 | ] 215 | } 216 | ], 217 | "source": [ 218 | "# Answer:\n", 219 | "\n", 220 | "sorted_values=sorted(dictionary,reverse=True,key=lambda k:dictionary[k])\n", 221 | "\n", 222 | "print(sorted_values)" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": 34, 228 | "metadata": {}, 229 | "outputs": [ 230 | { 231 | "name": "stdout", 232 | "output_type": "stream", 233 | "text": [ 234 | "['Trees', 'Lights', 'Flowers', 'Chairs', 'Grill', 'Firepit']\n" 235 | ] 236 | } 237 | ], 238 | "source": [ 239 | "# Answer2:\n", 240 | "\n", 241 | "def sort_key(key):\n", 242 | " return dictionary[key]\n", 243 | " \n", 244 | "sorted_values=sorted(dictionary,reverse=True,key=sort_key)\n", 245 | "\n", 246 | "print(sorted_values)" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "metadata": {}, 252 | "source": [ 253 | "### Questions in _Assessment: Sorting_" 254 | ] 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "metadata": {}, 259 | "source": [ 260 | "### Question 1\n", 261 | "Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters." 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": 1, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "letters = \"alwnfiwaksuezlaeiajsdl\"" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 3, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "# Answer:\n", 280 | "\n", 281 | "sorted_letters=sorted(letters,reverse=True)" 282 | ] 283 | }, 284 | { 285 | "cell_type": "markdown", 286 | "metadata": {}, 287 | "source": [ 288 | "### Question 2\n", 289 | "Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted." 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": 4, 295 | "metadata": {}, 296 | "outputs": [], 297 | "source": [ 298 | "animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear']" 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 6, 304 | "metadata": {}, 305 | "outputs": [], 306 | "source": [ 307 | "# Answer:\n", 308 | "\n", 309 | "animals_sorted=sorted(animals)" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "### Question 3\n", 317 | "The dictionary, medals, shows the medal count for six countries during the Rio Olympics. Sort the country names so they appear alphabetically. Save this list to the variable alphabetical." 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": 7, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": 9, 332 | "metadata": {}, 333 | "outputs": [ 334 | { 335 | "data": { 336 | "text/plain": [ 337 | "['China', 'Germany', 'Japan', 'Russia', 'South Korea', 'United States']" 338 | ] 339 | }, 340 | "execution_count": 9, 341 | "metadata": {}, 342 | "output_type": "execute_result" 343 | } 344 | ], 345 | "source": [ 346 | "# Answer:\n", 347 | "\n", 348 | "alphabetical=sorted(medals)\n", 349 | "alphabetical" 350 | ] 351 | }, 352 | { 353 | "cell_type": "markdown", 354 | "metadata": {}, 355 | "source": [ 356 | "### Question 4\n", 357 | "Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count to the list, top_three." 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": 10, 363 | "metadata": {}, 364 | "outputs": [], 365 | "source": [ 366 | "medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": 14, 372 | "metadata": {}, 373 | "outputs": [ 374 | { 375 | "data": { 376 | "text/plain": [ 377 | "['United States', 'China', 'Russia']" 378 | ] 379 | }, 380 | "execution_count": 14, 381 | "metadata": {}, 382 | "output_type": "execute_result" 383 | } 384 | ], 385 | "source": [ 386 | "# Answer:\n", 387 | "\n", 388 | "top_three=sorted(medals,key=lambda country:medals[country],reverse=True)[:3]\n", 389 | "top_three" 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "metadata": {}, 395 | "source": [ 396 | "### Question 5\n", 397 | "We have provided the dictionary groceries. You should return a list of its keys, but they should be sorted by their values, from highest to lowest. Save the new list as most_needed." 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": 15, 403 | "metadata": {}, 404 | "outputs": [], 405 | "source": [ 406 | "groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9}" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": 17, 412 | "metadata": {}, 413 | "outputs": [ 414 | { 415 | "data": { 416 | "text/plain": [ 417 | "['granola bars',\n", 418 | " 'carrots',\n", 419 | " 'spinach',\n", 420 | " 'bananas',\n", 421 | " 'onions',\n", 422 | " 'apples',\n", 423 | " 'coffee',\n", 424 | " 'cereal',\n", 425 | " 'pasta',\n", 426 | " 'salsa',\n", 427 | " 'orange juice',\n", 428 | " 'peanut butter',\n", 429 | " 'popcorn',\n", 430 | " 'rice']" 431 | ] 432 | }, 433 | "execution_count": 17, 434 | "metadata": {}, 435 | "output_type": "execute_result" 436 | } 437 | ], 438 | "source": [ 439 | "# Answer:\n", 440 | "\n", 441 | "most_needed=sorted(groceries,key=lambda fruit:groceries[fruit],reverse=True)\n", 442 | "most_needed" 443 | ] 444 | }, 445 | { 446 | "cell_type": "markdown", 447 | "metadata": {}, 448 | "source": [ 449 | "### Question 6\n", 450 | "Create a function called last_four that takes in an ID number and returns the last four digits. For example, the number 17573005 should return 3005. Then, use this function to sort the list of ids stored in the variable, ids, from lowest to highest. Save this sorted list in the variable, sorted_ids. Hint: Remember that only strings can be indexed, so conversions may be needed." 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": 31, 456 | "metadata": {}, 457 | "outputs": [], 458 | "source": [ 459 | "ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": 59, 465 | "metadata": {}, 466 | "outputs": [ 467 | { 468 | "data": { 469 | "text/plain": [ 470 | "[17570002, 17572342, 17572345, 17573005, 17579000, 17579329]" 471 | ] 472 | }, 473 | "execution_count": 59, 474 | "metadata": {}, 475 | "output_type": "execute_result" 476 | } 477 | ], 478 | "source": [ 479 | "# Wrong (i wrote this):\n", 480 | "\n", 481 | "def last_four(x):\n", 482 | " for i in x:\n", 483 | " str(i)[-4:]\n", 484 | " \n", 485 | "sorted_ids=sorted(ids,key=last_four(ids))\n", 486 | "sorted_ids" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": 62, 492 | "metadata": {}, 493 | "outputs": [ 494 | { 495 | "data": { 496 | "text/plain": [ 497 | "[17570002, 17572342, 17572345, 17573005, 17579000, 17579329]" 498 | ] 499 | }, 500 | "execution_count": 62, 501 | "metadata": {}, 502 | "output_type": "execute_result" 503 | } 504 | ], 505 | "source": [ 506 | "# Correct:\n", 507 | "\n", 508 | "def last_four(x):\n", 509 | " return str(x)[-4:] #have trouble understanding this\n", 510 | "\n", 511 | "sorted_ids=sorted(ids,key=last_four)\n", 512 | "sorted_ids" 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "### Question 7\n", 520 | "Sort the list ids by the last four digits of each id. Do this using lambda and not using a defined function. Save this sorted list in the variable sorted_id." 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": 63, 526 | "metadata": {}, 527 | "outputs": [], 528 | "source": [ 529 | "ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329]" 530 | ] 531 | }, 532 | { 533 | "cell_type": "code", 534 | "execution_count": 64, 535 | "metadata": {}, 536 | "outputs": [ 537 | { 538 | "data": { 539 | "text/plain": [ 540 | "[17570002, 17572342, 17572345, 17573005, 17579000, 17579329]" 541 | ] 542 | }, 543 | "execution_count": 64, 544 | "metadata": {}, 545 | "output_type": "execute_result" 546 | } 547 | ], 548 | "source": [ 549 | "# Answer:\n", 550 | "\n", 551 | "sorted_id=sorted(ids,key=lambda x:str(x)[-4:])\n", 552 | "sorted_id" 553 | ] 554 | }, 555 | { 556 | "cell_type": "markdown", 557 | "metadata": {}, 558 | "source": [ 559 | "### Question 8\n", 560 | "Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to the variable lambda_sort." 561 | ] 562 | }, 563 | { 564 | "cell_type": "code", 565 | "execution_count": 65, 566 | "metadata": {}, 567 | "outputs": [], 568 | "source": [ 569 | "ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']" 570 | ] 571 | }, 572 | { 573 | "cell_type": "code", 574 | "execution_count": 68, 575 | "metadata": {}, 576 | "outputs": [ 577 | { 578 | "data": { 579 | "text/plain": [ 580 | "['dance', 'zebra', 'hi', 'how are you', 'apple', 'bye']" 581 | ] 582 | }, 583 | "execution_count": 68, 584 | "metadata": {}, 585 | "output_type": "execute_result" 586 | } 587 | ], 588 | "source": [ 589 | "# Answer 1:\n", 590 | "\n", 591 | "def sort_second(x):\n", 592 | " return x[1]\n", 593 | " \n", 594 | "lambda_sort=sorted(ex_lst,key=sort_second)\n", 595 | "lambda_sort" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": 69, 601 | "metadata": {}, 602 | "outputs": [ 603 | { 604 | "data": { 605 | "text/plain": [ 606 | "['dance', 'zebra', 'hi', 'how are you', 'apple', 'bye']" 607 | ] 608 | }, 609 | "execution_count": 69, 610 | "metadata": {}, 611 | "output_type": "execute_result" 612 | } 613 | ], 614 | "source": [ 615 | "# Answer 2:\n", 616 | "\n", 617 | "lambda_sort=sorted(ex_lst,key=lambda x:x[1])\n", 618 | "lambda_sort" 619 | ] 620 | } 621 | ], 622 | "metadata": { 623 | "kernelspec": { 624 | "display_name": "Python 3", 625 | "language": "python", 626 | "name": "python3" 627 | }, 628 | "language_info": { 629 | "codemirror_mode": { 630 | "name": "ipython", 631 | "version": 3 632 | }, 633 | "file_extension": ".py", 634 | "mimetype": "text/x-python", 635 | "name": "python", 636 | "nbconvert_exporter": "python", 637 | "pygments_lexer": "ipython3", 638 | "version": "3.7.3" 639 | } 640 | }, 641 | "nbformat": 4, 642 | "nbformat_minor": 2 643 | } 644 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python 3 Programming 2 | Coursera Python 3 Programming Specialization. 3 | --------------------------------------------------------------------------------