{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Программирование на Python\n", "\n", "## Практикум 2: списки vs массивы, условия и циклы\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 1\n", "\n", "Дан массив `Height` содержащий рост 10 человек в сантиметрах. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "Height = np.array([158, 160, 175, 172, 190, 188, \n", " 173, 177, 165, 148, 156, 180]) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "a. Создайте новый массив `Height_m`, содержащий рост в метрах.\n", "\n", "b. Сохраните в массив `A1` только те элементы `Height`, которые меньше 170 см. \n", "\n", "c. Сохраните в массив `A2` только те элементы `Height`, которые не менее 160 и не более 180.\n", "\n", "d. Сохраните в массив `A3` только чётные элементы `Height`." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1.58 1.6 1.75 1.72 1.9 1.88 1.73 1.77 1.65 1.48 1.56 1.8 ]\n", "[158 160 165 148 156]\n", "[160 175 172 173 177 165 180]\n", "[158 160 172 190 188 148 156 180]\n" ] } ], "source": [ "height_m = Height / 100\n", "print(height_m)\n", "\n", "A1 = Height[Height < 170]\n", "print(A1)\n", "\n", "A2 = Height[(Height >= 160) & (Height <= 180)]\n", "print(A2)\n", "\n", "A3 = Height[Height % 2 == 0]\n", "print(A3)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[158 190 188 148 156]\n" ] } ], "source": [ "# дополнение – с ИЛИ\n", "\n", "A4 = Height[(Height < 160) | (Height > 180)] # or\n", "A4 = Height[(Height < 160) ^ (Height > 180)] # xor\n", "print(A4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 2\n", "\n", "Дан список `height`, содержащий рост 10 человек в сантиметрах. " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "height = [158, 160, 175, 172, 190, 188, 173, 177, 165, 148, 156, 180]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "a. Создайте новый список `height_m`, содержащий рост в метрах.\n", "\n", "b. Сохраните в список `L1` только те элементы `height`, которые меньше 170 см. \n", "\n", "c. Сохраните в список `L2` только те элементы `height`, которые не менее 160 и не более 180.\n", "\n", "d. Сохраните в список `L3` только чётные элементы `height`." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1.58, 1.6, 1.75, 1.72, 1.9, 1.88, 1.73, 1.77, 1.65, 1.48, 1.56, 1.8]\n" ] } ], "source": [ "height_m = []\n", "for h in height:\n", " height_m.append(h/100)\n", "print(height_m)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# списковое включение (генератор списков)\n", "\n", "height_m = [h/100 for h in height]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[158, 160, 165, 148, 156]\n" ] } ], "source": [ "L1 = []\n", "for h in height:\n", " if h < 170:\n", " L1.append(h)\n", "print(L1)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[160, 175, 172, 173, 177, 165, 180]\n" ] } ], "source": [ "L2 = []\n", "for h in height:\n", " if h >= 160 and h <= 180:\n", " L2.append(h)\n", "print(L2)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[158, 160, 172, 190, 188, 148, 156, 180]\n" ] } ], "source": [ "L3 = []\n", "for h in height:\n", " if h % 2 == 0:\n", " L3.append(h)\n", "print(L3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 3\n", "\n", "Дана последовательность `s` из целых чисел:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "s = range(0, 2000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Используя таймер из модуля `time`, сравните исполнение следующих программ:\n", "\n", "1. Программа создаёт список `squares` из квадратов чисел из `s`, используя цикл `for`.\n", "2. Программа создаёт список `squares` из квадратов чисел из `s`, используя списковые включения.\n", "3. Программа создаёт массив `squares` из квадратов чисел из `s`." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.0010965760000090086 seconds\n", "0.0007895059999896148 seconds\n", "0.00041777400002729337 seconds\n" ] } ], "source": [ "import timeit\n", "\n", "# списки\n", "\n", "start = timeit.default_timer()\n", "squares = []\n", "for i in s:\n", " squares.append(i**2)\n", "stop = timeit.default_timer()\n", "execution_time = stop - start\n", "print(str(execution_time) + \" seconds\")\n", "\n", "# списковые включения\n", "\n", "start = timeit.default_timer()\n", "squares = [i**2 for i in s]\n", "stop = timeit.default_timer()\n", "execution_time = stop - start\n", "print(str(execution_time) + \" seconds\")\n", "\n", "\n", "# массивы\n", "\n", "start = timeit.default_timer()\n", "squares = np.array(s) ** 2\n", "stop = timeit.default_timer()\n", "execution_time = stop - start\n", "print(str(execution_time) + \" seconds\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 4\n", "\n", "У питона есть набор любимых чисел." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "favorites = [3, 7, 11, 23, 18, 48, 81]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Напишите программу, которая просит пользователя ввести целое число, и если оно нравится питону, на экран будет выводиться сообщение: \"Мое любимое число!\", если нет – \"Эх, ну почему?\"." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n", "Мое любимое число!\n" ] } ], "source": [ "# оператор in\n", "\n", "n = int(input())\n", "\n", "if n in favorites:\n", " print(\"Мое любимое число!\")\n", "else:\n", " print(\"Эх, ну почему?\")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "Эх, ну почему?\n" ] } ], "source": [ "# без in, ручной вариант с for и break\n", "\n", "n = int(input())\n", "check = False\n", "\n", "for i in favorites:\n", " if i == n:\n", " print(\"Мое любимое число!\")\n", " check = True\n", " break\n", "if check == False:\n", " print(\"Эх, ну почему?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 5\n", "\n", "Напишите программу, которая запрашивает с клавиатуры любое количество целых чисел через пробел и выводит на экран медиану заданной выборки.\n", "\n", "Для определённости давайте считать, что медиана выборки из $n$ значений определяется следующим образом:\n", "\n", "* если $n$ нечётное, медиана – $k$-ый элемент в выборке, упорядоченной по возрастанию, где $k = \\frac{n+1}{2}$;\n", "* если $n$ чётное, медиана – среднее арифметическое $k$-ого и $(k+1)$-ого элемента в выборке, упорядоченной по возрастанию, где $k = \\frac{n}{2}$." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6 8 9 5\n", "7.0\n" ] } ], "source": [ "inp = input()\n", "sample = [int(i) for i in inp.split()]\n", "sample.sort()\n", "n = len(sample)\n", "\n", "if n % 2 != 0:\n", " med = sample[(n+1)//2-1]\n", "else:\n", " med = (sample[n//2-1] + sample[n//2]) / 2\n", "print(med)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 6\n", "\n", "Напишите программу, которая просит пользователя ввести положительное число, и если пользователь вводит положительное число, выводит на экран сообщение \"Молодец!\", если нет – \"Это не положительное число!\" в предположении:\n", "\n", "a. что пользователь всегда вводит какие-то числа, целые или дробные, а не текст;\n", "\n", "b. что пользователь может ввести с клавиатуры что угодно.\n", "\n", "При решении этой задачи нельзя использовать исключения, то есть запрещена конструкция `try-except` (если вы с ней уже знакомы)." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "Молодец!\n" ] } ], "source": [ "# a - easy\n", "\n", "x = float(input())\n", "if x > 0:\n", " print(\"Молодец!\")\n", "else:\n", " print(\"Не молодец\")" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-4.7\n", "Не молодец!\n" ] } ], "source": [ "# b - hard\n", "\n", "x = input()\n", "\n", "if x == \"0\":\n", " print(\"Не молодец!\")\n", "else:\n", " if x.startswith(\"-\") == False:\n", " if x.coun-t(\".\") == 1:\n", " if x.replace(\".\", \"\").isdigit():\n", " print(\"Молодец!\")\n", " else:\n", " print(\"Это не число!\")\n", " elif x.isdigit():\n", " print(\"Молодец!\")\n", " else:\n", " print(\"Это не число!\")\n", " else:\n", " if x.count(\".\") == 1:\n", " if x[1:].replace(\".\", \"\").isdigit():\n", " print(\"Не молодец!\")\n", " else:\n", " print(\"Это не число!\")\n", " elif x[1:].isdigit():\n", " print(\"Не молодец!\")\n", " else:\n", " print(\"Это не число!\")" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "Молодец!\n" ] } ], "source": [ "# для желающих – конструкция try-except\n", "# будем обсуждать потом\n", "\n", "x = input()\n", "try:\n", " n = float(x)\n", " if n > 0:\n", " print(\"Молодец!\")\n", " else:\n", " print(\"Не молодец!\")\n", "except:\n", " print(\"Не число\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 7\n", "\n", "Напишите программу, которая запрашивает у пользователя пароль, и далее:\n", "\n", "* если пароль верный, выводит на экран сообщение \"Login success\".\n", "* если пароль неверный, выводит на экран сообщение \"Incorrect password, try again!\" до тех пор, пока пользователь не введёт верный пароль." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }