python_for_analytics

Форк
0
/
1.4_LEC_functions.ipynb 
939 строк · 23.6 Кб
1
{
2
 "cells": [
3
  {
4
   "cell_type": "markdown",
5
   "metadata": {
6
    "id": "U72FhsNpDhxX"
7
   },
8
   "source": [
9
    "\n",
10
    "\n",
11
    "1.   Вспомним args\n",
12
    "2.   Вспомним lambda-функции и посмотрим на итераторы\n",
13
    "3.   Напишем программу в процедурном стиле на основе функций\n",
14
    "\n",
15
    "\n"
16
   ]
17
  },
18
  {
19
   "cell_type": "markdown",
20
   "metadata": {
21
    "id": "XOY7VKI357LA"
22
   },
23
   "source": [
24
    "### Практика. Напишем функцию, которая определяет является ли слово палиндромом\n",
25
    "\n",
26
    "Пример работы программы:\n",
27
    "```\n",
28
    "print(is_palindrom('Радар'))\n",
29
    "True\n",
30
    "```\n",
31
    "\n",
32
    "```\n",
33
    "print(is_palindrom('строка'))\n",
34
    "False\n",
35
    "```"
36
   ]
37
  },
38
  {
39
   "cell_type": "code",
40
   "execution_count": null,
41
   "metadata": {
42
    "colab": {
43
     "base_uri": "https://localhost:8080/"
44
    },
45
    "id": "TL8qWkEI6mLE",
46
    "outputId": "915746e6-355a-4b92-cc51-630db0c405f5"
47
   },
48
   "outputs": [
49
    {
50
     "data": {
51
      "text/plain": [
52
       "True"
53
      ]
54
     },
55
     "execution_count": 8,
56
     "metadata": {},
57
     "output_type": "execute_result"
58
    }
59
   ],
60
   "source": [
61
    "def palindrom(string):\n",
62
    "    string = string.lower().replace(' ', '')\n",
63
    "    return string[::-1] == string\n",
64
    "\n",
65
    "palindrom('А роза упала на лапу Азора')"
66
   ]
67
  },
68
  {
69
   "cell_type": "markdown",
70
   "metadata": {
71
    "id": "BF7EhPbcSVBV"
72
   },
73
   "source": [
74
    "## args and kwargs\n",
75
    "Иногда возникает ситуация, когда вы заранее не знаете, какое количество аргументов будет необходимо принять функции. В этом случае следует использовать аргументы произвольной длины ([args и kwargs](https://teletype.in/@pythontalk/python_asteriks)). Они задаются произвольным именем переменной, перед которой ставится звездочка (args) или две здездочки (kwargs)."
76
   ]
77
  },
78
  {
79
   "cell_type": "code",
80
   "execution_count": null,
81
   "metadata": {
82
    "colab": {
83
     "base_uri": "https://localhost:8080/"
84
    },
85
    "id": "ilXaysWUawBT",
86
    "outputId": "7c46a6ac-869e-4a1d-e6f3-21360f5b66a7"
87
   },
88
   "outputs": [
89
    {
90
     "name": "stdout",
91
     "output_type": "stream",
92
     "text": [
93
      "(1, 2, 3, 4, 5, 6, 7, 10)\n",
94
      "{'divisor': 7, 'accuracy': 2, 'some': 1}\n",
95
      "5.43\n"
96
     ]
97
    }
98
   ],
99
   "source": [
100
    "# Сумму всех позиционных аргументов вычисляем с помощью sum\n",
101
    "# *args упаковывает все позиционные аргументы в кортеж\n",
102
    "# **kwargs упаковывает все именованные аргументы в словарь, из которого получаем значение по ключу\n",
103
    "\n",
104
    "def sum_division(*args, **kwargs):\n",
105
    "    print(args)\n",
106
    "    print(kwargs)\n",
107
    "    return round(sum(args) / kwargs['divisor'], kwargs['accuracy'])\n",
108
    "\n",
109
    "print(sum_division(1, 2, 3, 4, 5, 6, 7, 10, divisor=7, accuracy=2, some=1))"
110
   ]
111
  },
112
  {
113
   "cell_type": "code",
114
   "execution_count": null,
115
   "metadata": {
116
    "id": "9XSfxweRawBT"
117
   },
118
   "outputs": [],
119
   "source": [
120
    "# распаковка позволяет отделить создание списка аргументов от их передачи в функцию\n",
121
    "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
122
    "params = {'divisor':7,'accuracy':2}\n",
123
    "\n",
124
    "print(sum_division(*numbers, **params))"
125
   ]
126
  },
127
  {
128
   "cell_type": "markdown",
129
   "metadata": {
130
    "id": "6GGM5SzuRYl3"
131
   },
132
   "source": [
133
    "### Практика. Напишем функцию, которая будет находить среднюю цену квартиры по всем переданным в нее районам города"
134
   ]
135
  },
136
  {
137
   "cell_type": "code",
138
   "execution_count": null,
139
   "metadata": {
140
    "id": "CRljX_0tRexA"
141
   },
142
   "outputs": [],
143
   "source": [
144
    "district_1 = {'flat_1': 10500, 'flat_2': 11000}\n",
145
    "district_2 = {'flat_3': 15000}\n",
146
    "district_3 = {'flat_4': 6500, 'flat_5': 7000, 'flat_6': 6000}   "
147
   ]
148
  },
149
  {
150
   "cell_type": "code",
151
   "execution_count": null,
152
   "metadata": {
153
    "colab": {
154
     "base_uri": "https://localhost:8080/"
155
    },
156
    "id": "d9DWnJhOqVVL",
157
    "outputId": "8b1402ce-a690-4101-b1aa-ed8e75f31f86"
158
   },
159
   "outputs": [
160
    {
161
     "data": {
162
      "text/plain": [
163
       "9333.333333333334"
164
      ]
165
     },
166
     "execution_count": 18,
167
     "metadata": {},
168
     "output_type": "execute_result"
169
    }
170
   ],
171
   "source": [
172
    "def average_price(distrcits):\n",
173
    "    return sum(distrcits.values()) / len(distrcits.values())\n",
174
    "\n",
175
    "average_price({**district_2, **district_1, **district_3})"
176
   ]
177
  },
178
  {
179
   "cell_type": "code",
180
   "execution_count": null,
181
   "metadata": {
182
    "colab": {
183
     "base_uri": "https://localhost:8080/"
184
    },
185
    "id": "hjoxWHPmx3aW",
186
    "outputId": "e48fbbe7-25f2-44c2-e6dd-e2afb72062e7"
187
   },
188
   "outputs": [
189
    {
190
     "name": "stdout",
191
     "output_type": "stream",
192
     "text": [
193
      "Введите названия районов через ,d1, d3\n"
194
     ]
195
    },
196
    {
197
     "data": {
198
      "text/plain": [
199
       "['d1', 'd3']"
200
      ]
201
     },
202
     "execution_count": 20,
203
     "metadata": {},
204
     "output_type": "execute_result"
205
    }
206
   ],
207
   "source": [
208
    "districts = {'d1': {'flat_1': 10500, 'flat_2': 11000},\n",
209
    "             'd2': {'flat_3': 15000},\n",
210
    "             'd3': {'flat_4': 6500, 'flat_5': 7000, 'flat_6': 6000}\n",
211
    "}\n",
212
    "\n",
213
    "user_d = input('Введите названия районов через ,').split(', ')\n",
214
    "\n",
215
    "user_d"
216
   ]
217
  },
218
  {
219
   "cell_type": "code",
220
   "execution_count": null,
221
   "metadata": {
222
    "colab": {
223
     "base_uri": "https://localhost:8080/"
224
    },
225
    "id": "-oqSgaJDy4BU",
226
    "outputId": "deed827d-ec16-4d65-c06a-5f50c34b815b"
227
   },
228
   "outputs": [
229
    {
230
     "data": {
231
      "text/plain": [
232
       "8200.0"
233
      ]
234
     },
235
     "execution_count": 23,
236
     "metadata": {},
237
     "output_type": "execute_result"
238
    }
239
   ],
240
   "source": [
241
    "def get_avg_price(d_list):\n",
242
    "    res = {}\n",
243
    "    for d in d_list:\n",
244
    "        res.update(districts[d])\n",
245
    "    return sum(res.values()) / len(res)\n",
246
    "\n",
247
    "get_avg_price(user_d)"
248
   ]
249
  },
250
  {
251
   "cell_type": "code",
252
   "execution_count": null,
253
   "metadata": {
254
    "colab": {
255
     "base_uri": "https://localhost:8080/"
256
    },
257
    "id": "YlkV5DCpzp5A",
258
    "outputId": "adeb3273-73d4-49b7-8fa8-853cad7355fe"
259
   },
260
   "outputs": [
261
    {
262
     "data": {
263
      "text/plain": [
264
       "[('flat_1', 10500), ('flat_2', 11000), ('flat_3', 15000)]"
265
      ]
266
     },
267
     "execution_count": 25,
268
     "metadata": {},
269
     "output_type": "execute_result"
270
    }
271
   ],
272
   "source": [
273
    "list(district_1.items()) + list(district_2.items())"
274
   ]
275
  },
276
  {
277
   "cell_type": "markdown",
278
   "metadata": {
279
    "id": "_mY3dvurRsd4"
280
   },
281
   "source": [
282
    "## Комплексный пример"
283
   ]
284
  },
285
  {
286
   "cell_type": "code",
287
   "execution_count": null,
288
   "metadata": {
289
    "id": "OPd5-8lVRuL5"
290
   },
291
   "outputs": [],
292
   "source": [
293
    "students_list = [\n",
294
    "    {\"name\": \"Василий\", \"surname\": \"Теркин\", \"gender\": \"\", \"program_exp\": True, \"grade\": [8, 8, 9, 10], \"exam\": 8},\n",
295
    "    {\"name\": \"Мария\", \"surname\": \"Павлова\", \"gender\": \"ж\", \"program_exp\": True, \"grade\": [7, 8, 9, 7, 9], \"exam\": 9},\n",
296
    "    {\"name\": \"Ирина\", \"surname\": \"Андреева\", \"gender\": \"ж\", \"program_exp\": False, \"grade\": [10, 9, 8, 10], \"exam\": 7},\n",
297
    "    {\"name\": \"Татьяна\", \"surname\": \"Сидорова\", \"gender\": \"ж\", \"program_exp\": False, \"grade\": [7, 8, 8, 9, 8],\"exam\": 10},\n",
298
    "    {\"name\": \"Иван\", \"surname\": \"Васильев\", \"gender\": \"м\", \"program_exp\": True, \"grade\": [9, 8, 9, 6, 9, 4], \"exam\": 5},\n",
299
    "    {\"name\": \"Роман\", \"surname\": \"Золотарев\", \"gender\": \"м\", \"program_exp\": False, \"grade\": [8, 9, 9, 6, 9], \"exam\": 6}\n",
300
    "]"
301
   ]
302
  },
303
  {
304
   "cell_type": "code",
305
   "execution_count": null,
306
   "metadata": {
307
    "id": "8SXGrYZLqXjx"
308
   },
309
   "outputs": [],
310
   "source": [
311
    "def change_type(students, key):\n",
312
    "    for student in students:\n",
313
    "        student[key] = str(student[key])\n",
314
    "change_type(students_list, 'exam')\n",
315
    "# students_list"
316
   ]
317
  },
318
  {
319
   "cell_type": "code",
320
   "execution_count": null,
321
   "metadata": {
322
    "colab": {
323
     "base_uri": "https://localhost:8080/"
324
    },
325
    "id": "pp3BuTSe6d8w",
326
    "outputId": "673238c2-c860-449a-b610-ad335af28761"
327
   },
328
   "outputs": [
329
    {
330
     "data": {
331
      "text/plain": [
332
       "[{'name': 'Мария',\n",
333
       "  'surname': 'Павлова',\n",
334
       "  'gender': 'ж',\n",
335
       "  'program_exp': True,\n",
336
       "  'grade': [7, 8, 9, 7, 9],\n",
337
       "  'exam': '9'},\n",
338
       " {'name': 'Ирина',\n",
339
       "  'surname': 'Андреева',\n",
340
       "  'gender': 'ж',\n",
341
       "  'program_exp': False,\n",
342
       "  'grade': [10, 9, 8, 10],\n",
343
       "  'exam': '7'},\n",
344
       " {'name': 'Татьяна',\n",
345
       "  'surname': 'Сидорова',\n",
346
       "  'gender': 'ж',\n",
347
       "  'program_exp': False,\n",
348
       "  'grade': [7, 8, 8, 9, 8],\n",
349
       "  'exam': '10'}]"
350
      ]
351
     },
352
     "execution_count": 56,
353
     "metadata": {},
354
     "output_type": "execute_result"
355
    }
356
   ],
357
   "source": [
358
    "def filter_students(students, exp=None, gender=None):\n",
359
    "    res = filter(lambda student: \n",
360
    "                 (student['program_exp'] is exp or exp is None) and\n",
361
    "                 (student['gender'] == gender or gender is None), \n",
362
    "                 students)\n",
363
    "    return list(res)\n",
364
    "\n",
365
    "filter_students(students_list, None, 'ж')\n",
366
    "filter_students(students_list, gender='ж')"
367
   ]
368
  },
369
  {
370
   "cell_type": "code",
371
   "execution_count": null,
372
   "metadata": {
373
    "id": "JzUSwoP-9gTB"
374
   },
375
   "outputs": [],
376
   "source": [
377
    "# datetime"
378
   ]
379
  },
380
  {
381
   "cell_type": "code",
382
   "execution_count": null,
383
   "metadata": {
384
    "colab": {
385
     "base_uri": "https://localhost:8080/"
386
    },
387
    "id": "A7yHex1Z17Im",
388
    "outputId": "2d4f66cf-d1c8-408a-9fec-76b8b02444e6"
389
   },
390
   "outputs": [
391
    {
392
     "name": "stdout",
393
     "output_type": "stream",
394
     "text": [
395
      "8.28\n",
396
      "8.48\n",
397
      "8.08\n"
398
     ]
399
    }
400
   ],
401
   "source": [
402
    "# def get_avg_hw_grade(students, exp=None):\n",
403
    "#     hw_grade = 0\n",
404
    "#     counter = 0\n",
405
    "#     for student in students:\n",
406
    "#         if student['program_exp'] is exp or exp is None:\n",
407
    "#             hw_grade += sum(student['grade']) / len(student['grade'])\n",
408
    "#             counter += 1\n",
409
    "\n",
410
    "#     return round(hw_grade / counter, 2)\n",
411
    "\n",
412
    "# print(get_avg_hw_grade(students_list))\n",
413
    "# print(get_avg_hw_grade(students_list, False))\n",
414
    "# print(get_avg_hw_grade(students_list, True))\n",
415
    "# print(get_avg_hw_grade(students_list))"
416
   ]
417
  },
418
  {
419
   "cell_type": "code",
420
   "execution_count": null,
421
   "metadata": {
422
    "colab": {
423
     "base_uri": "https://localhost:8080/"
424
    },
425
    "id": "r7JFrpyA3bzS",
426
    "outputId": "f0e6b65b-d0a5-4308-f34c-dc5c975e690e"
427
   },
428
   "outputs": [
429
    {
430
     "data": {
431
      "text/plain": [
432
       "8.08"
433
      ]
434
     },
435
     "execution_count": 44,
436
     "metadata": {},
437
     "output_type": "execute_result"
438
    }
439
   ],
440
   "source": [
441
    "def get_avg_hw_grade(students):\n",
442
    "    res = [sum(student['grade']) / len(student['grade']) for student in students]\n",
443
    "    return round(sum(res) / len(res), 2)\n",
444
    "\n",
445
    "get_avg_hw_grade(filter_students(students_list, True))    "
446
   ]
447
  },
448
  {
449
   "cell_type": "code",
450
   "execution_count": null,
451
   "metadata": {
452
    "colab": {
453
     "base_uri": "https://localhost:8080/"
454
    },
455
    "id": "uqt04xE9AZjy",
456
    "outputId": "a5e058e9-7760-4d71-f562-57a6f45670fb"
457
   },
458
   "outputs": [
459
    {
460
     "name": "stdout",
461
     "output_type": "stream",
462
     "text": [
463
      "Введите команду1\n",
464
      "8.28\n",
465
      "Введите команду2\n",
466
      "8.42\n",
467
      "Введите команду3\n",
468
      "8.08\n",
469
      "Введите команду1\n",
470
      "8.28\n",
471
      "Введите команду2\n",
472
      "8.42\n",
473
      "Введите команду3\n",
474
      "8.08\n",
475
      "Введите командуq\n",
476
      "Выход\n"
477
     ]
478
    }
479
   ],
480
   "source": [
481
    "def main(students):\n",
482
    "    while True:\n",
483
    "        comand = input('Введите команду')\n",
484
    "        if comand == '1':\n",
485
    "            print(get_avg_hw_grade(filter_students(students)))\n",
486
    "        elif comand == '2':\n",
487
    "            print(get_avg_hw_grade(filter_students(students, None, 'ж')))\n",
488
    "        elif comand == '3':\n",
489
    "            print(get_avg_hw_grade(filter_students(students, True)))\n",
490
    "        elif comand == 'q':\n",
491
    "            print('Выход')\n",
492
    "            break\n",
493
    "\n",
494
    "\n",
495
    "main(students_list)      "
496
   ]
497
  },
498
  {
499
   "cell_type": "code",
500
   "execution_count": null,
501
   "metadata": {
502
    "colab": {
503
     "base_uri": "https://localhost:8080/"
504
    },
505
    "id": "zVV3Zghw_pVl",
506
    "outputId": "8ea08183-5763-4f36-bb4c-70706560cef8"
507
   },
508
   "outputs": [
509
    {
510
     "name": "stdout",
511
     "output_type": "stream",
512
     "text": [
513
      "2207 876234 : Василий Гупкин passport\n",
514
      "11-2 : Геннадий Покемонов invoice\n",
515
      "10006 : Аристарх Павлов insurance\n"
516
     ]
517
    }
518
   ],
519
   "source": [
520
    "documents = [\n",
521
    "    {'type': 'passport', 'number': '2207 876234', 'name': 'Василий Гупкин'},\n",
522
    "    {'type': 'invoice', 'number': '11-2', 'name': 'Геннадий Покемонов'},\n",
523
    "    {'type': 'insurance', 'number': '10006', 'name': 'Аристарх Павлов'}\n",
524
    "]\n",
525
    "\n",
526
    "for doc in documents:\n",
527
    "    print(f\"{doc['number']} : {doc['name']} {doc['type']}\")"
528
   ]
529
  },
530
  {
531
   "cell_type": "markdown",
532
   "metadata": {
533
    "id": "mgMjftejd7Ph"
534
   },
535
   "source": [
536
    "## Анонимные функции, функции map и filter\n",
537
    "\n",
538
    "[Анонимные функции](https://habr.com/ru/post/507642/) создаются при помощи инструкции lambda и используются для более краткой записи функций с одним выражением. Выполняются быстрее обычных и не требуют инструкции return."
539
   ]
540
  },
541
  {
542
   "cell_type": "markdown",
543
   "metadata": {
544
    "id": "1whxQleKMlLv"
545
   },
546
   "source": [
547
    "Получим список из средних цен в каждой категории товаров"
548
   ]
549
  },
550
  {
551
   "cell_type": "code",
552
   "execution_count": null,
553
   "metadata": {
554
    "id": "uacfNii3HqFO"
555
   },
556
   "outputs": [],
557
   "source": []
558
  },
559
  {
560
   "cell_type": "code",
561
   "execution_count": null,
562
   "metadata": {
563
    "id": "xZTL8aTPMNEE"
564
   },
565
   "outputs": [],
566
   "source": [
567
    "prices_by_categories = [[100, 200, 400, 600], [200, 500], [100, 200, 100, 100], [800, 900]]"
568
   ]
569
  },
570
  {
571
   "cell_type": "code",
572
   "execution_count": null,
573
   "metadata": {
574
    "colab": {
575
     "base_uri": "https://localhost:8080/"
576
    },
577
    "id": "m1DA5YEIMxw3",
578
    "outputId": "3282862c-aa15-4e28-9643-3b7e784d4bb1"
579
   },
580
   "outputs": [
581
    {
582
     "name": "stdout",
583
     "output_type": "stream",
584
     "text": [
585
      "[325.0, 350.0, 125.0, 850.0]\n"
586
     ]
587
    }
588
   ],
589
   "source": [
590
    "def get_avg_prices(prices):\n",
591
    "    mean_prices = []\n",
592
    "    for category in prices:\n",
593
    "        mean_prices.append(sum(category) / len(category))\n",
594
    "    return mean_prices\n",
595
    "\n",
596
    "print(get_avg_prices(prices_by_categories))"
597
   ]
598
  },
599
  {
600
   "cell_type": "code",
601
   "execution_count": null,
602
   "metadata": {
603
    "colab": {
604
     "base_uri": "https://localhost:8080/"
605
    },
606
    "id": "3dbFgNmqqbwS",
607
    "outputId": "dd132725-88d8-428e-9638-7b8cfe7714d0"
608
   },
609
   "outputs": [
610
    {
611
     "data": {
612
      "text/plain": [
613
       "[325.0, 350.0, 125.0, 850.0]"
614
      ]
615
     },
616
     "execution_count": 65,
617
     "metadata": {},
618
     "output_type": "execute_result"
619
    }
620
   ],
621
   "source": [
622
    "list(map(lambda el: sum(el)/len(el), prices_by_categories))"
623
   ]
624
  },
625
  {
626
   "cell_type": "markdown",
627
   "metadata": {
628
    "id": "yH-gS2ATQesE"
629
   },
630
   "source": [
631
    "Решим задачу с фильтрацией структуры по гордам без цикла"
632
   ]
633
  },
634
  {
635
   "cell_type": "code",
636
   "execution_count": null,
637
   "metadata": {
638
    "id": "EBLHeZpvQnFZ"
639
   },
640
   "outputs": [],
641
   "source": [
642
    "geo_logs = [\n",
643
    "    {'visit1': ['Москва', 'Россия']},\n",
644
    "    {'visit2': ['Дели', 'Индия']},\n",
645
    "    {'visit3': ['Владимир', 'Россия']},\n",
646
    "    {'visit4': ['Лиссабон', 'Португалия']},\n",
647
    "    {'visit5': ['Париж', 'Франция']},\n",
648
    "    {'visit7': ['Тула', 'Россия']},\n",
649
    "    {'visit9': ['Курск', 'Россия']},\n",
650
    "    {'visit10': ['Архангельск', 'Россия']}\n",
651
    "]"
652
   ]
653
  },
654
  {
655
   "cell_type": "code",
656
   "execution_count": null,
657
   "metadata": {
658
    "colab": {
659
     "base_uri": "https://localhost:8080/"
660
    },
661
    "id": "DaRAQ3R1QsP1",
662
    "outputId": "d102c49f-c787-49ee-a078-9077f223ebc4"
663
   },
664
   "outputs": [
665
    {
666
     "name": "stdout",
667
     "output_type": "stream",
668
     "text": [
669
      "[{'visit1': ['Москва', 'Россия']}, {'visit3': ['Владимир', 'Россия']}, {'visit7': ['Тула', 'Россия']}, {'visit9': ['Курск', 'Россия']}, {'visit10': ['Архангельск', 'Россия']}]\n"
670
     ]
671
    }
672
   ],
673
   "source": [
674
    "result = []\n",
675
    "for log in geo_logs:\n",
676
    "    if 'Россия' in list(log.values())[0]:\n",
677
    "        result.append(log)\n",
678
    "        \n",
679
    "print(result)"
680
   ]
681
  },
682
  {
683
   "cell_type": "code",
684
   "execution_count": null,
685
   "metadata": {
686
    "colab": {
687
     "base_uri": "https://localhost:8080/"
688
    },
689
    "id": "69ru-aTZQu8j",
690
    "outputId": "99dd320e-861c-49dd-8375-8bd9da7d6da8"
691
   },
692
   "outputs": [
693
    {
694
     "data": {
695
      "text/plain": [
696
       "[{'visit1': ['Москва', 'Россия']},\n",
697
       " {'visit3': ['Владимир', 'Россия']},\n",
698
       " {'visit7': ['Тула', 'Россия']},\n",
699
       " {'visit9': ['Курск', 'Россия']},\n",
700
       " {'visit10': ['Архангельск', 'Россия']}]"
701
      ]
702
     },
703
     "execution_count": 68,
704
     "metadata": {},
705
     "output_type": "execute_result"
706
    }
707
   ],
708
   "source": [
709
    "list(filter(lambda log: 'Россия' in list(log.values())[0], geo_logs))"
710
   ]
711
  },
712
  {
713
   "cell_type": "code",
714
   "execution_count": null,
715
   "metadata": {
716
    "id": "J5pIt-BVE625"
717
   },
718
   "outputs": [],
719
   "source": [
720
    "def move(directories):\n",
721
    "    if doc_number not in directories:\n",
722
    "        return...\n",
723
    "    for n, d in directories.items():\n",
724
    "        if doc_number in d:\n",
725
    "            directories[new_shelf] += doc_number\n",
726
    "            d.remove(doc_number)\n",
727
    "\n",
728
    "            return\n",
729
    "    print('Не найден')"
730
   ]
731
  },
732
  {
733
   "cell_type": "code",
734
   "execution_count": null,
735
   "metadata": {
736
    "colab": {
737
     "base_uri": "https://localhost:8080/"
738
    },
739
    "id": "tnVaf4Q6Fo0H",
740
    "outputId": "87f076a2-fead-4a50-f92c-1196aa6f5727"
741
   },
742
   "outputs": [
743
    {
744
     "data": {
745
      "text/plain": [
746
       "11"
747
      ]
748
     },
749
     "execution_count": 82,
750
     "metadata": {},
751
     "output_type": "execute_result"
752
    }
753
   ],
754
   "source": [
755
    "my_func = lambda x, y: x+y\n",
756
    "\n",
757
    "my_func(5, 6)\n",
758
    "\n"
759
   ]
760
  },
761
  {
762
   "cell_type": "code",
763
   "execution_count": null,
764
   "metadata": {
765
    "colab": {
766
     "base_uri": "https://localhost:8080/"
767
    },
768
    "id": "Tz_84J1sFzFL",
769
    "outputId": "0f53f1ce-5029-4ed1-8ed4-aa35367eb397"
770
   },
771
   "outputs": [
772
    {
773
     "data": {
774
      "text/plain": [
775
       "9"
776
      ]
777
     },
778
     "execution_count": 84,
779
     "metadata": {},
780
     "output_type": "execute_result"
781
    }
782
   ],
783
   "source": [
784
    "(lambda x, y: x+y)(4,5)"
785
   ]
786
  },
787
  {
788
   "cell_type": "markdown",
789
   "metadata": {
790
    "id": "ONpdieq_fpaF"
791
   },
792
   "source": [
793
    "## Цикл / рекурсия / reduce ?\n",
794
    "\n",
795
    "Напишем функцию, преобразующую произвольный список вида `['2018-01-01', 'yandex', 'cpc', 100]` (он может быть любой длины) в словарь `{'2018-01-01': {'yandex': {'cpc': 100}}}`"
796
   ]
797
  },
798
  {
799
   "cell_type": "code",
800
   "execution_count": null,
801
   "metadata": {
802
    "id": "GEn97dBdfxx_"
803
   },
804
   "outputs": [],
805
   "source": [
806
    "some_list = ['2018-01-01', 'yandex', 'cpc', 100]"
807
   ]
808
  },
809
  {
810
   "cell_type": "code",
811
   "execution_count": null,
812
   "metadata": {
813
    "colab": {
814
     "base_uri": "https://localhost:8080/"
815
    },
816
    "id": "DeIngK7nC8AO",
817
    "outputId": "e9328770-afd4-42e2-9650-5ed45056fd56"
818
   },
819
   "outputs": [
820
    {
821
     "data": {
822
      "text/plain": [
823
       "-1"
824
      ]
825
     },
826
     "execution_count": 80,
827
     "metadata": {},
828
     "output_type": "execute_result"
829
    }
830
   ],
831
   "source": [
832
    "def get_dict(some_list):\n",
833
    "    res = some_list[-1]\n",
834
    "    for el in reversed(some_list[:-1]):\n",
835
    "        res = {el: res}\n",
836
    "    return res\n",
837
    "\n",
838
    "get_dict(some_list)"
839
   ]
840
  },
841
  {
842
   "cell_type": "code",
843
   "execution_count": null,
844
   "metadata": {
845
    "colab": {
846
     "base_uri": "https://localhost:8080/"
847
    },
848
    "id": "VrartfKXDUuW",
849
    "outputId": "c0383581-0908-4b0a-dfe7-e45715d00721"
850
   },
851
   "outputs": [
852
    {
853
     "data": {
854
      "text/plain": [
855
       "2520"
856
      ]
857
     },
858
     "execution_count": 74,
859
     "metadata": {},
860
     "output_type": "execute_result"
861
    }
862
   ],
863
   "source": [
864
    "from functools import reduce\n",
865
    "\n",
866
    "reduce(lambda a,b: a*b, [1, 5, 7, 8, 9])"
867
   ]
868
  },
869
  {
870
   "cell_type": "code",
871
   "execution_count": null,
872
   "metadata": {
873
    "colab": {
874
     "base_uri": "https://localhost:8080/"
875
    },
876
    "id": "Md52UNw3D49e",
877
    "outputId": "97e027f2-f513-457c-a857-081152a8631d"
878
   },
879
   "outputs": [
880
    {
881
     "name": "stdout",
882
     "output_type": "stream",
883
     "text": [
884
      "{'2018-01-01': {'yandex': {'cpc': 100}}}\n"
885
     ]
886
    }
887
   ],
888
   "source": [
889
    "print(reduce(lambda last, prev: {prev: last}, reversed(some_list)))"
890
   ]
891
  },
892
  {
893
   "cell_type": "code",
894
   "execution_count": null,
895
   "metadata": {
896
    "id": "yKfYs2AeEO0_"
897
   },
898
   "outputs": [],
899
   "source": []
900
  },
901
  {
902
   "cell_type": "code",
903
   "execution_count": null,
904
   "metadata": {
905
    "id": "Ck9UZINMG2Jh"
906
   },
907
   "outputs": [],
908
   "source": [
909
    "res = {'sdg': (lambda x,y: x+y)}\n",
910
    "\n",
911
    "res[....]()"
912
   ]
913
  }
914
 ],
915
 "metadata": {
916
  "colab": {
917
   "provenance": []
918
  },
919
  "kernelspec": {
920
   "display_name": "Python 3 (ipykernel)",
921
   "language": "python",
922
   "name": "python3"
923
  },
924
  "language_info": {
925
   "codemirror_mode": {
926
    "name": "ipython",
927
    "version": 3
928
   },
929
   "file_extension": ".py",
930
   "mimetype": "text/x-python",
931
   "name": "python",
932
   "nbconvert_exporter": "python",
933
   "pygments_lexer": "ipython3",
934
   "version": "3.9.13"
935
  }
936
 },
937
 "nbformat": 4,
938
 "nbformat_minor": 1
939
}
940

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.