{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Основы программирования в Python\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "## Семинар 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 1\n", "\n", "Напишите программу, которая запрашивает у пользователя его фамилию, имя, отчество, введенные в одну строчку через пробел, и выводит на экран сообщения:\n", "\n", " Ваша фамилия: фамилия\n", " Ваше имя: имя\n", " Ваше отчество: отчество\n", "\n", "**Пример:**\n", "\n", "*Входные данные:*\n", "\n", " Введите Ваши ФИО: Тамбовцева Алла Андреевна\n", "\n", "*Выходные данные:*\n", "\n", " Ваша фамилия: Тамбовцева\n", " Ваше имя: Алла\n", " Ваше отчество: Андреевна" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Введите Ваши ФИО: Тамбовцева Алла Андреевна\n", "Ваша фамилия: Тамбовцева\n", "Ваше имя: Алла\n", "Ваше отчество: Андреевна\n" ] } ], "source": [ "fio = input(\"Введите Ваши ФИО: \")\n", "fio_list = fio.split()\n", "f = fio_list[0]\n", "i = fio_list[1]\n", "o = fio_list[2]\n", "print(\"Ваша фамилия:\", f)\n", "print(\"Ваше имя:\", i)\n", "print(\"Ваше отчество:\", o)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 2\n", "\n", "Напишите программу, которая берет строку \"1; 2; 3; 100\" и возвращает:\n", "\n", "* список из целых чисел\n", "* список из чисел с плавающей точкой" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 100]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = \"1; 2; 3; 100\"\n", "s_list = s.split(\";\")\n", "int_nums = []\n", "for i in s_list:\n", " num = int(i)\n", " int_nums.append(num)\n", "int_nums" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Или более компактно и эффективно, используя списковые включения." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 100]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = \"1; 2; 3; 100\"\n", "s_list = s.split(\";\")\n", "int_nums = [int(i) for i in s_list]\n", "int_nums" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "То же самое, но для чисел с плавающей точкой:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.0, 2.0, 3.0, 100.0]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = \"1; 2; 3; 100\"\n", "s_list = s.split(\";\")\n", "f_nums = []\n", "for i in s_list:\n", " num = float(i)\n", " f_nums.append(num)\n", "f_nums" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Через списковые включения:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.0, 2.0, 3.0, 100.0]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = \"1; 2; 3; 100\"\n", "s_list = s.split(\";\")\n", "f_nums = [float(i) for i in s_list]\n", "f_nums" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 3\n", "\n", "Напишите программу, которая запрашивает у пользователя номер мобильного телефона, введенный через дефис, а возвращает номер, записанный без дефисов и пробелов.\n", "\n", "*Входные данные:*\n", "\n", " 8-900-123-45-67\n", "\n", "*Выходные данные:*\n", "\n", " 89001234567" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8-900-123-45-67\n", "89001234567\n" ] } ], "source": [ "tel = input()\n", "tel_list = tel.split(\"-\")\n", "newtel = \"\".join(tel_list)\n", "print(newtel)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 4\n", "\n", "Напишите программу, которая принимает на вход список L, в котором хранятся значения доходов домохозяйств за месяц, а возвращает новый список L2 ‒ список логарифмированных значений доходов." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9.210340371976184, 10.126631103850338, 12.429216196844383, 11.918390573078392]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [10000, 25000, 250000, 150000]\n", "import math\n", "L2 = []\n", "for l in L:\n", " res = math.log(l)\n", " L2.append(res)\n", "L2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Можно добавлять элемент в список без создания `res`, выполняя все преобразования в скобках в `append`:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9.210340371976184, 10.126631103850338, 12.429216196844383, 11.918390573078392]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [10000, 25000, 250000, 150000]\n", "import math\n", "L2 = []\n", "for l in L:\n", " L2.append(math.log(l))\n", "L2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "И через списковые включения:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9.210340371976184, 10.126631103850338, 12.429216196844383, 11.918390573078392]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L2 = [math.log(l) for l in L]\n", "L2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 5\n", "\n", "Напишите программу, которая принимает на вход список слов такого вида:\n", "\n", " words = [\"Speak \",\"to\", \"me \", \"of\", \"Florence\" ,\"And \", \"of\", \"the\", \"Renaissance\"]\n", "\n", "а возвращает список\n", "\n", " words_clean = [\"speak\", \"to\", \"me\", \"of\", \"florence\", \"and\", \"of\", \"the\", \"renaissance\"]\n", "\n", "Другими словами, программа убирает пробелы в словах и приводит все слова к нижнему регистру.\n", "\n", "**Подсказка:** запросите `help()` по методам `strip()` и `lower()`." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "words = [\"Speak \",\"to\", \"me \", \"of\", \"Florence\" ,\"And \", \"of\", \"the\", \"Renaissance\"]" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['speak', 'to', 'me', 'of', 'florence', 'and', 'of', 'the', 'renaissance']" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "words_clean = []\n", "for w in words:\n", " low = w.lower()\n", " stripped = low.strip()\n", " words_clean.append(stripped)\n", "words_clean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Или совсем компактный вариант, используя списковые включения (да-да, методы можно применять, \"наслаивая\" друг на друга, то есть ставя точку и добавляя новый метод)." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['speak', 'to', 'me', 'of', 'florence', 'and', 'of', 'the', 'renaissance']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "words_clean = [w.lower().strip() for w in words_clean]\n", "words_clean" ] } ], "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.5.2" } }, "nbformat": 4, "nbformat_minor": 2 }