{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "given-replication",
   "metadata": {},
   "source": [
    "# Estrutura de dados (2) e strings\n",
    "\n",
    "Na aula passada aprendemos a mexer com listas, uma das estruturas de dados mais importantes e flexíveis que existe.\n",
    "\n",
    "Nesta aula veremos outras estruturas de dados importantes como os dicionários, os conjuntos e as tuplas.\n",
    "\n",
    "Antes disso vamos rever o que aprendemos com as listas.\n",
    "\n",
    "Também vamos ver mais funcionalidades de strings."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "qualified-paragraph",
   "metadata": {},
   "source": [
    "## Revisão de listas\n",
    "<!-- TEASER_END -->\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "mechanical-mouse",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L = [1,2,3,4] # Como criar uma lista\n",
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "growing-constitutional",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(L) # Comprimento de uma lista"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "surrounded-college",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L[0] # Acessar os elementos da lista"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "laden-wheat",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L[1:3] # Fatiamento das listas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "developing-ancient",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 5]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L.append(5) # Adicionar um elemento ao final da lista\n",
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "potential-disclosure",
   "metadata": {},
   "outputs": [],
   "source": [
    "M = [1,2,3,] + [4,5,6,7,8] # Concatenar listas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "homeless-fever",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 5, 6, 7, 8]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L.extend([6,7,8]) # Extender lista\n",
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "lesser-transport",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 5]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del L[5:] # Remover elementos da lista\n",
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "proprietary-suspension",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L.pop(-1)  # Retirar o último elemento da lista e retornar seu valor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "under-gathering",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "retained-treasury",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L.pop(0) # Retirar o primeiro elemento da lista e retornar seu valor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "yellow-cambridge",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "knowing-haiti",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4, 2, 3, 4, 2, 3, 4]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Algo que não vimos!\n",
    "L*3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "retained-avenue",
   "metadata": {},
   "source": [
    "### Vimos que existem vários métodos\n",
    "\n",
    "Estes métodos podem ser bastante úteis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "regional-lithuania",
   "metadata": {},
   "outputs": [],
   "source": [
    "L = [32,3456,124,687,523,456,23,634,576]\n",
    "M = L[:]  # Cuidado ao copiar a lista!!!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "concrete-syntax",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L.index(124) # Buscar índice de elemento da lista"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "bound-advertiser",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[2,34,3,2,3,6,6,6,6,32,4,4,3,2].count(6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "indian-aberdeen",
   "metadata": {},
   "outputs": [],
   "source": [
    "L.sort() # Reordenar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "english-exposure",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[23, 32, 124, 456, 523, 576, 634, 687, 3456]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "registered-kitty",
   "metadata": {},
   "source": [
    "### Vimos o algorítimo de Bubble Sort para reordenar listas"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "diagnostic-nature",
   "metadata": {},
   "source": [
    "## Dicionários\n",
    "\n",
    "Estrutura de dados semelhante à lista mas com acesso diferente.\n",
    "\n",
    "Os dicionários em Python são compostos por\n",
    " \n",
    " * Chaves\n",
    " * Valores\n",
    " \n",
    "O dicionário relaciona uma chava a um valor. A cada chave, existe um valor associado.\n",
    "\n",
    "De certo modo a lista pode ser vista como um dicionário: as chaves são números inteiros ordenados. \n",
    "\n",
    "\n",
    "Para se criar um dicionário, utilizam-se chaves ({})\n",
    "\n",
    "Imagine como exemplo, uma lista de preços de um supermercado:\n",
    "\n",
    "| Produto | Preço   |\n",
    "| ------- | ------- |\n",
    "| Alface  | R\\$ 0,45 |\n",
    "| Batata  | R\\$ 1,20 |\n",
    "| Tomate  | R\\$ 2,30 |\n",
    "| Feijão  | R\\$ 1,50 |\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "binding-cross",
   "metadata": {},
   "outputs": [],
   "source": [
    "tabela = {\"Alface\": 0.45, \n",
    "         \"Batata\": 1.20, \n",
    "         \"Tomate\": 2.30, \n",
    "         \"Feijão\": 1.50}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "northern-secretariat",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Alface': 0.45, 'Batata': 1.2, 'Tomate': 2.3, 'Feijão': 1.5}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "republican-clone",
   "metadata": {},
   "source": [
    "Em um dicionário, para se acessar um valor, usa-se a chave:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "naval-enclosure",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.45"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela[\"Alface\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "functional-chick",
   "metadata": {},
   "source": [
    "Também podemos atribuir um valor à chave:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "polish-crowd",
   "metadata": {},
   "outputs": [],
   "source": [
    "tabela[\"Alface\"] = 0.55  # Aumentamos o preço"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "sized-conservation",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Alface': 0.55, 'Batata': 1.2, 'Tomate': 2.3, 'Feijão': 1.5}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "retained-storm",
   "metadata": {},
   "source": [
    "Se atribuirmos um valor a uma chave que **não** existe, essa nova chave com este valor será adicionada ao dicionário:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "bigger-program",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Alface': 0.55, 'Batata': 1.2, 'Tomate': 2.3, 'Feijão': 1.5, 'Cebola': 1.35}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela[\"Cebola\"] = 1.35\n",
    "tabela"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "physical-camping",
   "metadata": {},
   "source": [
    "Se a chave não existir, ocorrerá um erro:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "regulated-kingston",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'Picanha'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[0;32m/tmp/ipykernel_19331/2276766913.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtabela\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"Picanha\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m: 'Picanha'"
     ]
    }
   ],
   "source": [
    "tabela[\"Picanha\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "convinced-toilet",
   "metadata": {},
   "source": [
    "Para se verificar se um chave faz parte do dicionário, use o operador `in`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "aquatic-orbit",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Feijão\" in tabela"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "empty-memphis",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Manga\" in tabela"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "severe-disclaimer",
   "metadata": {},
   "source": [
    "O método `.keys()` retorna uma lista (algo parecido) com as chaves:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "exceptional-memphis",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['Alface', 'Batata', 'Tomate', 'Feijão', 'Cebola'])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "certified-foster",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entre com o nome do produto, fim para terminar: Alface\n",
      "Preço  0.45\n",
      "Entre com o nome do produto, fim para terminar: Feijão\n",
      "Preço  1.50\n",
      "Entre com o nome do produto, fim para terminar: fim\n"
     ]
    }
   ],
   "source": [
    "# Programa para obter o preço da tabela:\n",
    "tabela = {\"Alface\": 0.45, \n",
    "         \"Batata\": 1.20, \n",
    "         \"Tomate\": 2.30, \n",
    "         \"Feijão\": 1.50}\n",
    "\n",
    "while True:\n",
    "    produto = input(\"Entre com o nome do produto, fim para terminar: \")\n",
    "    if produto == 'fim':\n",
    "        break\n",
    "    if produto in tabela:\n",
    "        print(f\"Preço {tabela[produto]:5.2f}\")\n",
    "    else:\n",
    "        print(\"Produto não encontrado!\")\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "historical-necklace",
   "metadata": {},
   "source": [
    "Assim como nas listas, podemos apagar uma chave com a instrução `del`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "technical-lancaster",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Alface': 0.45, 'Batata': 1.2, 'Feijão': 1.5}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tabela = {\"Alface\": 0.45, \n",
    "         \"Batata\": 1.20, \n",
    "         \"Tomate\": 2.30, \n",
    "         \"Feijão\": 1.50}\n",
    "\n",
    "del tabela[\"Tomate\"]\n",
    "tabela"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "informational-provision",
   "metadata": {},
   "source": [
    "### Quando usar listas ou dicionários?\n",
    "\n",
    "Quando você quer acessar os dados pela chave. Observe que nas versões mais antigas de Python (antes da versão 3.7) **a ordem de inserção não\n",
    "era preservada**!\n",
    "\n",
    "O acesso de elementos de listas pode ser mais rápido. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "annual-feelings",
   "metadata": {},
   "source": [
    "**Cuidado** ao usar os f-strings com dicionários:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "illegal-folks",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Banana: R$ 2.00 Maçã: R$ 5.00'"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {\"banana\": 2.00, \"maçã\": 5.00}\n",
    "f\"Banana: R${d['banana']:5.2f} Maçã: R${d['maçã']:5.2f}\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "controlling-dressing",
   "metadata": {},
   "source": [
    "### O que pode ser usado como chave em um dicionário?\n",
    "\n",
    " * Strings\n",
    " * Números\n",
    " * Tuplas (veremos mais tarde)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "settled-magnet",
   "metadata": {},
   "source": [
    "### Os elementos de um dicionário podem ser qualquer coisa..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "familiar-donor",
   "metadata": {},
   "outputs": [],
   "source": [
    "estoque = {\"tomate\": [1000, 2.30],\n",
    "           \"alface\": [500, 0.45],\n",
    "           \"batata\": [2001, 1.20], \n",
    "           \"feijão\": [100, 1.5]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "finished-disability",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vendas:\n",
      "\n",
      "tomate      :   5 x   2.30 =  11.50\n",
      "batata      :  10 x   1.20 =  12.00\n",
      "alface      :   5 x   0.45 =   2.25\n",
      " Custo total:                 25.75\n",
      "\n",
      "Estoque:\n",
      "\n",
      "Descrição:  tomate\n",
      "Quantidade:  995\n",
      "Preço:   2.30\n",
      "\n",
      "Descrição:  alface\n",
      "Quantidade:  495\n",
      "Preço:   0.45\n",
      "\n",
      "Descrição:  batata\n",
      "Quantidade:  1991\n",
      "Preço:   1.20\n",
      "\n",
      "Descrição:  feijão\n",
      "Quantidade:  100\n",
      "Preço:   1.50\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Programa para atualizar estoque após venda\n",
    "venda = [[\"tomate\", 5], [\"batata\",10], [\"alface\",5]]\n",
    "total = 0\n",
    "print(\"Vendas:\\n\")\n",
    "for operação in venda:\n",
    "    produto, quantidade = operação\n",
    "    preço = estoque[produto][1]\n",
    "    custo = preço * quantidade\n",
    "    print(f\"{produto:12s}: {quantidade:3d} x {preço:6.2f} = {custo:6.2f}\")\n",
    "    estoque[produto][0] -= quantidade\n",
    "    total += custo\n",
    "print(f\" Custo total: {total:21.2f}\\n\")\n",
    "print(\"Estoque:\\n\")\n",
    "for chave, dados in estoque.items():\n",
    "    print(\"Descrição: \", chave)\n",
    "    print(\"Quantidade: \", dados[0])\n",
    "    print(f\"Preço: {dados[1]:6.2f}\\n\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hungry-corps",
   "metadata": {},
   "source": [
    "### Exercício 1\n",
    "Altere o programa anterior de modo que o produto e a quantidade vendida seja solicitada ao usuário. Verifique se o produto digitado existe e só então efetue a baixa no estoque. Também verifique se o estoque é o suficiente para atender ao pedido.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "permanent-testing",
   "metadata": {},
   "source": [
    "### Exercício 2\n",
    "Escreva um programa que que gere um dicionário a partir de uma string onde a chave seja um caracter e o valor o número de vezes que este caracter aparece no dicionário\n",
    "\n",
    "o rolo -> {'o': 3, ' ': 1, 'l': 1}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "guided-thanks",
   "metadata": {},
   "source": [
    "### Dicionário com valores padrão\n",
    "\n",
    "Algo comum é que ao se recuperar o valor de uma chave, se essa chave não existir, utilizar um valor padrão"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "united-alert",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': 1, 'B': 2}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {}\n",
    "d[\"A\"] = 1\n",
    "d[\"B\"] = 2\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "virtual-spell",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'C'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[0;32m/tmp/ipykernel_19331/852664300.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"C\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m: 'C'"
     ]
    }
   ],
   "source": [
    "d[\"C\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "adjustable-wrong",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "x = d.get(\"C\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "numerical-negative",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x is None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "cathedral-dress",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "999"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = d.get(\"C\", 999)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "metropolitan-offer",
   "metadata": {},
   "source": [
    "### Iterando um dicionário com `for`\n",
    "\n",
    "Também dá usar for em um dicionário."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "exact-soviet",
   "metadata": {},
   "outputs": [],
   "source": [
    "estoque = {\"tomate\": [1000, 2.30],\n",
    "           \"alface\": [500, 0.45],\n",
    "           \"batata\": [2001, 1.20], \n",
    "           \"feijão\": [100, 1.5]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "stretch-detroit",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tomate\n",
      "alface\n",
      "batata\n",
      "feijão\n"
     ]
    }
   ],
   "source": [
    "for x in estoque:\n",
    "    print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "parental-annex",
   "metadata": {},
   "source": [
    "E se você precisa da chave e do valor? Use o método `.items()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "opened-participant",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------\n",
      "Chave: tomate\n",
      "Valor: [1000, 2.3]\n",
      "------------\n",
      "Chave: alface\n",
      "Valor: [500, 0.45]\n",
      "------------\n",
      "Chave: batata\n",
      "Valor: [2001, 1.2]\n",
      "------------\n",
      "Chave: feijão\n",
      "Valor: [100, 1.5]\n"
     ]
    }
   ],
   "source": [
    "for c,v in estoque.items():\n",
    "    print(\"------------\")\n",
    "    print(f\"Chave: {c}\")\n",
    "    print(f\"Valor: {v}\")\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "advanced-sheep",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('tomate', [1000, 2.3]), ('alface', [500, 0.45]), ('batata', [2001, 1.2]), ('feijão', [100, 1.5])])"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "estoque.items()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "surgical-drinking",
   "metadata": {},
   "source": [
    "## Tuplas\n",
    "\n",
    "Muito parecida com a lista mas com uma diferença: são imutáveis!\n",
    "\n",
    "Tem alguma semelhança com as strings. Strings se *parecem* com listas que não podem ser modificadas. Mas as strings são otimizadas para caracteres. \n",
    "\n",
    "Apesar de imutáveis, os elementos da tupla podem ter tipos distintos.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "frozen-canvas",
   "metadata": {},
   "source": [
    "### Tuplas são parecidas com listas!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "fresh-titanium",
   "metadata": {},
   "outputs": [],
   "source": [
    "tupla = (\"a\", \"b\", \"c\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "certified-leisure",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('a', 'b', 'c')"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tupla"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "individual-whale",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a'"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tupla[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "becoming-removal",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'b'"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tupla[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "varied-cancer",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 1, 2, 3]"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[1,2,3]*2 # repetição"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "touched-proportion",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('b', 'c')"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tupla[1:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "handed-junior",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(tupla)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "polished-empire",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "b\n",
      "c\n"
     ]
    }
   ],
   "source": [
    "for e in tupla:\n",
    "    print(e)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "informational-humanity",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m/tmp/ipykernel_19331/2537307119.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# Lembre-se as tuplas são imutáveis!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtupla\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'd'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "# Lembre-se as tuplas são imutáveis!\n",
    "tupla[1] = 'd'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brief-philippines",
   "metadata": {},
   "source": [
    "### Tuplas como múltiplos valores, empacotamento e desempacotamento\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "distinct-anderson",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100, 200, 300)"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tupla = 100,200,300\n",
    "tupla"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "broken-tender",
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b, c = tupla"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "hispanic-lodge",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a = 100, b = 200, c = 300\n"
     ]
    }
   ],
   "source": [
    "print(f\"a = {a}, b = {b}, c = {c}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "editorial-calculator",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(10, 20)"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a, b = 10, 20\n",
    "a,b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "guided-vietnamese",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(20, 10)"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Operação realizada de maneira 'paralela'\n",
    "a, b = b, a\n",
    "a,b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "mexican-freight",
   "metadata": {},
   "source": [
    "Se lembram do bubble sort?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "american-ferry",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4, 6, 8, 9]"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L = [9, 2, 4, 3, 8, 6]\n",
    "N = len(L)\n",
    "for i in range(N):\n",
    "    trocou = False\n",
    "    for k in range(N-i-1):\n",
    "        if L[k] > L[k+1]: # Inverter a posição\n",
    "            trocou = True\n",
    "            # Como era antes\n",
    "            # tmp = L[k]\n",
    "            # L[k] = L[k+1]\n",
    "            #L[k+1] = tmp\n",
    "            L[k], L[k+1] = L[k+1], L[k] # Olha só que simples!\n",
    "    if not trocou:\n",
    "        break\n",
    "\n",
    "L\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "presidential-positive",
   "metadata": {},
   "source": [
    "### Tuplas com um elemento"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "grateful-joint",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t1 = (1)\n",
    "t1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "figured-capture",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1,)"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t2 = (1,)\n",
    "t2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "passing-harvest",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Tupla vazia\n",
    "t3 = ()\n",
    "t3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ranging-yellow",
   "metadata": {},
   "source": [
    "### Tuplas a partir de listas (e vice e versa):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "cooperative-chance",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 2, 3)"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L = [1,2,3]\n",
    "T = tuple(L)\n",
    "T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "numeric-istanbul",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "T = (1,2,3)\n",
    "L = list(T)\n",
    "L"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "optional-omaha",
   "metadata": {},
   "source": [
    "\n",
    "### Concatenação\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "scientific-template",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 2, 3, 4, 5, 6)"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(1,2,3) + (4,5,6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "generous-individual",
   "metadata": {},
   "source": [
    "### A tupla é imutável, não seus elementos (pode ou não ser!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "choice-sheffield",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, [2, 3, 4])"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "T = (1,[2,3,4])\n",
    "T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "peripheral-marathon",
   "metadata": {},
   "outputs": [],
   "source": [
    "T[1].append(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "still-theta",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, [2, 3, 4, 5])"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "severe-willow",
   "metadata": {},
   "source": [
    "### Exercício 3\n",
    "Explore os métodos disponíveis aos dicionários. Brinque com eles"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "focal-radar",
   "metadata": {},
   "source": [
    "### Mais empacotamento e desempacotamento (listas também podem)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "lovely-overview",
   "metadata": {},
   "outputs": [],
   "source": [
    "tupla = 1,2\n",
    "a,b = tupla"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "satisfactory-jerusalem",
   "metadata": {},
   "outputs": [],
   "source": [
    "a,b = 1,2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "ultimate-settlement",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c = 3, d = 4\n"
     ]
    }
   ],
   "source": [
    "c,d = [3,4]\n",
    "print(f\"c = {c}, d = {d}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "ideal-final",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "*a, b = [1,2,3,4,5]\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "systematic-thousand",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4]"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "realistic-gasoline",
   "metadata": {},
   "outputs": [],
   "source": [
    "*a,b = (1,2,3,4,5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "fifteen-string",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4]"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "medieval-sharp",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "assisted-memorial",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a,*b = [1,2,3,4,5]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "broad-schema",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4, 5]"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "blocked-karma",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a,*b,c = [1,2,3,4,5]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "driven-serve",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4]"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "plastic-dispute",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "contrary-median",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "*a,b,c = [1,2,3,4,5]\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "micro-jewel",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "major-ecuador",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "major-magnet",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a,b,*c = [1,2,3,4,5]\n",
    "a\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "balanced-packing",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "alike-danish",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 4, 5]"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ahead-shuttle",
   "metadata": {},
   "source": [
    "## Conjuntos (`set`)\n",
    "\n",
    "Os conjuntos em Python são uma estrutura de dados que funcionam como conjuntos que aprendemos na escola. \n",
    "\n",
    "Um conjunto é uma coleção de elementos que não são repetidos. \n",
    "\n",
    "Ah, podemos fazer as operações união e intersecção!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "binary-linux",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3}"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {1,2,3} # Notação para conjuntos\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "thirty-stretch",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5, 6}"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.add(4)\n",
    "a.add(5)\n",
    "a.add(6)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "tropical-round",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5, 6}"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.add(1)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "informed-portable",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 1, 2, 3, 4, 5, 6}"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.add(-1)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "sexual-pollution",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bigger-means",
   "metadata": {},
   "source": [
    "### Ver se um elemento pertence a um conjunto:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "embedded-olympus",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " 2 in a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "progressive-studio",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "123 in a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "constitutional-parameter",
   "metadata": {},
   "source": [
    "### Criando conjuntos a partir de listas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "august-profit",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5}"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = set([1,2,3,4,5])\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "sublime-witness",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 4, 5}"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = set([1,2,3,4,5,1,2,3,4,5])\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "collaborative-general",
   "metadata": {},
   "source": [
    "### Operações com conjuntos\n",
    "\n",
    "Diferença entre conjuntos:\n",
    "```python\n",
    "a - b\n",
    "```\n",
    "O resultado é um conjunto com os elementos de `a` que não estão em `b`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "overhead-algorithm",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 0, 1}"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {0, 1, 2, 3, -1}\n",
    "b = {2, 3}\n",
    "a-b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "southern-services",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 0, 1, 4, 5}"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {0, 1, 2, 3, -1, 4, 5}\n",
    "b = {2, 3}\n",
    "a-b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "amino-mapping",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 0, 1}"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {0, 1, 2, 3, -1}\n",
    "b = {2, 3, 4}\n",
    "a-b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "conservative-yukon",
   "metadata": {},
   "source": [
    "União entre conjuntos:\n",
    "```python\n",
    "a | b\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "advised-harrison",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 0, 1, 2, 3}"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {0,1,2,3,-1}\n",
    "b = {2,3}\n",
    "a | b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "prerequisite-bradford",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{-1, 0, 1, 2, 3, 4, 5, 6}"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c = {4,5,6}\n",
    "a | c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "south-mission",
   "metadata": {},
   "source": [
    "Interseção de conjuntos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "id": "analyzed-evans",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2, 3}"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a & b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "talented-second",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "set()"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a & c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "numerical-museum",
   "metadata": {},
   "source": [
    "### Exercício 4\n",
    "Veja os métodos disponíveis aos conjuntos. Brinque com eles"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acoustic-contractor",
   "metadata": {},
   "source": [
    "### Exercício 5\n",
    "Escreva um programa que compare duas listas. Utilizando operações com conjuntos, imprima:\n",
    "\n",
    " * Os valores comuns às duas listas\n",
    " * Os valores que só existem na primeira\n",
    " * Os valores que existem apenas na segunda\n",
    " * Uma lista com os elementos não repetidos das duas listas\n",
    " * A primeira lista sem os elementos repetidos na segunda"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "chemical-professional",
   "metadata": {},
   "source": [
    "## Qual estrutura de dados utilizar?\n",
    "\n",
    "|             |  Listas    |  Tuplas   | Dicionários   | Conjuntos   |\n",
    "| ----------- | ---------- | --------- | ------------- | ----------- |\n",
    "| Ordem dos elementos | Fixa | Fixa | Fixa a partir da versão 3.7 | Indeterminada |\n",
    "| Tamanho | Variável | Fixo | Variável | Variável |\n",
    "| Elementos repetidos | Sim | Sim | Valores mas não chaves| Não |\n",
    "| Pesquisa | Sequencial | Sequencial | Direto pela chave | Direta pelo valor |\n",
    "| Alterações | Sim | Não | Sim | Sim |\n",
    "| Uso primário | Sequências | Sequências constantes | Dados indexados por chave | Verificação de unicidade |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "historical-cheese",
   "metadata": {},
   "source": [
    "# Trabalhando com strings\n",
    "\n",
    "Temos usado strings desde a primeira aula. Strings são úteis e extremamente importantes. Vimos que existem algumas semelhanças entre strings e listas e entre strings e tuplas: strings são sequências *imutáveis* de caracteres."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "id": "phantom-speech",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A'"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"Alô mundo\"\n",
    "s[0]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "likely-letter",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m/tmp/ipykernel_19331/2311957138.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ms\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'X'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "s[0] = 'X'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "absent-fight",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['A', 'l', 'ô', ' ', 'm', 'u', 'n', 'd', 'o']"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L = list(s)\n",
    "L"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "severe-washer",
   "metadata": {},
   "source": [
    "### Strings também têm métodos! "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "exclusive-wilderness",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Alô mundo'"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1 = \"\".join(L)\n",
    "s1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "id": "located-theta",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abc\n",
      "a b c\n",
      "a.b.c\n",
      "a_|_b_|_c\n"
     ]
    }
   ],
   "source": [
    "L = ['a','b','c']\n",
    "print(\"\".join(L))\n",
    "print(\" \".join(L))\n",
    "print(\".\".join(L))\n",
    "print(\"_|_\".join(L))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fantastic-index",
   "metadata": {},
   "outputs": [],
   "source": [
    "s."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unsigned-firmware",
   "metadata": {},
   "source": [
    "### Verificação parcial de strings\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "id": "hairy-bread",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome = \"Instituto de Pesquisas Tecnológicas\"\n",
    "nome.startswith(\"Inst\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "id": "delayed-truth",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome.startswith(\"inst\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brown-aspect",
   "metadata": {},
   "source": [
    "### Maíusculas e minúsculas\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "id": "jewish-bahrain",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'INSTITUTO DE PESQUISAS TECNOLÓGICAS'"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome.upper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "handmade-topic",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'instituto de pesquisas tecnológicas'"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome.lower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "id": "honest-refund",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome.lower().startswith(\"inst\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "id": "fabulous-symphony",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nome.upper().startswith(\"INST\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "id": "chinese-omega",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Uma frase simples com letras minúsculas'"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"uma frase simples com letras minúsculas\".capitalize()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "practical-category",
   "metadata": {},
   "source": [
    "### Pesquisando em strings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "id": "mysterious-carbon",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"o rato roeu a roupa do rei de roma\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "id": "worldwide-effect",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 116,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"rato\" in s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "earlier-marble",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Rato\" in s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "id": "cloudy-discussion",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"u a r\" in s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "id": "equivalent-whale",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"santos\" not in s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "id": "internal-stress",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 120,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'roupa' not in s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deadly-sheriff",
   "metadata": {},
   "source": [
    "Cuidado com acentos!!!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "id": "herbal-halifax",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"além da cúpula do trovão\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "id": "fitted-cheat",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"além\" in s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "vanilla-masters",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 123,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"alem\" in s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "compound-referral",
   "metadata": {},
   "source": [
    "Algumas vezes queremos saber onde se encontra uma substring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "id": "foreign-republic",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"o rato roeu a roupa do rei de roma\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "annoying-walnut",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "i = s.find(\"roeu\")\n",
    "i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "id": "pleasant-leadership",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'roeu'"
      ]
     },
     "execution_count": 126,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[i:i+4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "golden-voice",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.find(\"gato\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "indonesian-interaction",
   "metadata": {},
   "source": [
    "Buscando pelo fim\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "id": "brilliant-being",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"o rato roeu a roupa do rato de roma\"\n",
    "i = s.find(\"rato\")\n",
    "i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "living-marriage",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'rato'"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[i:i+4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "id": "therapeutic-promise",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "23"
      ]
     },
     "execution_count": 130,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "i = s.rfind(\"rato\")\n",
    "i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "close-housing",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'rato'"
      ]
     },
     "execution_count": 131,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[i:i+4]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "heard-mileage",
   "metadata": {},
   "source": [
    "Dá para falar de onde queremos começar a procurar!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "id": "introductory-diary",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "23"
      ]
     },
     "execution_count": 132,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.find(\"rato\", 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "greenhouse-bachelor",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Posição: 3\n",
      "Posição: 15\n",
      "Posição: 28\n"
     ]
    }
   ],
   "source": [
    "# Programa que pesquisa *todas* as ocorrênicas\n",
    "s = \"um tigre, dois tigres, três tigres\"\n",
    "ss = \"tigre\"\n",
    "p = 0\n",
    "while p > -1:\n",
    "    p = s.find(ss, p)\n",
    "    if p >= 0:\n",
    "        print(f\"Posição: {p}\")\n",
    "        p += 1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apart-classroom",
   "metadata": {},
   "source": [
    "### Exercício 6\n",
    "Teste a diferença entre os métodos `.find` e `.rfind` com `.index` e `.rindex`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "norwegian-translation",
   "metadata": {},
   "source": [
    "### Exercício 7\n",
    "Escreva um programa que leia duas strings. Verifique se a segunda ocorre dentro da primeira e imprima sua posição de início"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "wrapped-russia",
   "metadata": {},
   "source": [
    "### Exercício 8\n",
    "Escreva um programa que leia duas strings e gere uma  terceira string com todos os caracteres que aparecem nas duas strings. A ordem não interessa."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "military-resort",
   "metadata": {},
   "source": [
    "### Exercício 9\n",
    "Escreva um programa que leia uma string e imprima quantas vezes cada caracter aparece nessa string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "modular-namibia",
   "metadata": {},
   "source": [
    "### Justificação de strings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "id": "outstanding-branch",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'        bola        '"
      ]
     },
     "execution_count": 134,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = 'bola'\n",
    "s.center(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "nutritional-minority",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'X   bola   X'"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'X' + s.center(10) + 'X'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "id": "general-luxembourg",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'X...bola...X'"
      ]
     },
     "execution_count": 136,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'X' + s.center(10, '.') + 'X'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "composed-logan",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'bola      '"
      ]
     },
     "execution_count": 137,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.ljust(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "id": "voluntary-arrangement",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'bola......'"
      ]
     },
     "execution_count": 138,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.ljust(10,'.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "unknown-palestinian",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'      bola'"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.rjust(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "id": "expanded-navigator",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'......bola'"
      ]
     },
     "execution_count": 140,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.rjust(10,'.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "floating-stick",
   "metadata": {},
   "source": [
    "### Remoção de espaços em branco"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "id": "annual-employer",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'IPT'"
      ]
     },
     "execution_count": 141,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"   IPT    \"\n",
    "s.strip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "id": "biological-tutorial",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'   IPT'"
      ]
     },
     "execution_count": 142,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.rstrip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "id": "endangered-generator",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'IPT    '"
      ]
     },
     "execution_count": 143,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.lstrip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "id": "stylish-judge",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'   IPT    '"
      ]
     },
     "execution_count": 144,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.lstrip('.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "id": "wireless-cabin",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'  IPT   ...  '"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = '....  IPT   ...  .'\n",
    "s.strip('.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "id": "honest-classroom",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'IPT'"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.strip('. ')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "brown-lover",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'....  IPT'"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.rstrip(' .')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "id": "relative-terrorist",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'IPT   ...  .'"
      ]
     },
     "execution_count": 148,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.lstrip(' .')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "remarkable-malaysia",
   "metadata": {},
   "source": [
    "### Quebrando strings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "id": "criminal-kansas",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1', '2', '3', '4', '5', '6']"
      ]
     },
     "execution_count": 149,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"1,2,3,4,5,6\"\n",
    "s.split(\",\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "id": "smooth-movement",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1', '2', '3', '4', '5', '6']"
      ]
     },
     "execution_count": 150,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"1 2 3 4 5 6\".split(\" \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "id": "circular-pattern",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1', '2', '3', '4', '5', '6']"
      ]
     },
     "execution_count": 151,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"1 e 2 e 3 e 4 e 5 e 6\".split(\" e \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "therapeutic-rates",
   "metadata": {},
   "source": [
    "### Substituindo strings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "id": "based-satellite",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'um gato, dois gatos, três gatos'"
      ]
     },
     "execution_count": 152,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"um tigre, dois tigres, três tigres\"\n",
    "s.replace(\"tigre\", \"gato\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "id": "fantastic-career",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'um gato, dois tigres, três tigres'"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.replace(\"tigre\", \"gato\", 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "id": "recent-venezuela",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'um gato, dois gatos, três tigres'"
      ]
     },
     "execution_count": 154,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.replace(\"tigre\", \"gato\", 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "id": "senior-claim",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'um , dois s, três s'"
      ]
     },
     "execution_count": 155,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.replace(\"tigre\", \"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "id": "illegal-lottery",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'-u-m- -t-i-g-r-e-,- -d-o-i-s- -t-i-g-r-e-s-,- -t-r-ê-s- -t-i-g-r-e-s-'"
      ]
     },
     "execution_count": 156,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.replace(\"\", \"-\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "future-float",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "unsigned-survivor",
   "metadata": {},
   "source": [
    "### Validação por tipo de conteúdo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "auburn-butter",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"125\"\n",
    "p = \"uma pequena frase\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "id": "interested-appearance",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isalnum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "automotive-competition",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "p.isalnum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "id": "identical-carroll",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 160,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc123\".isalnum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "id": "familiar-tulsa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 161,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"125\".isalpha()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 162,
   "id": "advance-option",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 162,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"uma frase pequena\".isalpha()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "id": "detected-department",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 163,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"palavra\".isalpha()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 164,
   "id": "graphic-public",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 164,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"123\".isdigit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "isolated-construction",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 165,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "\"3.14\".isdigit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 166,
   "id": "alert-yacht",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 166,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"-123\".isdigit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 167,
   "id": "parallel-cooper",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 167,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"123\".isnumeric()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 168,
   "id": "embedded-binding",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 168,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"3.14\".isnumeric()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 169,
   "id": "together-transparency",
   "metadata": {},
   "outputs": [],
   "source": [
    "# .isdigit() -> caracteres numéricos em Unicode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 170,
   "id": "geographic-finland",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'⅓'"
      ]
     },
     "execution_count": 170,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"\\u2153\"\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 171,
   "id": "provincial-domestic",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 171,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isnumeric()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 172,
   "id": "neural-ordinary",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 172,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isdigit()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "professional-lying",
   "metadata": {},
   "source": [
    "Como reconhecer se o número é ponto flutuante? Isso é mais chato do que parece. Mas temos aqui uma solução. Aqui introduzimos uma nova funcionalidade: exceções:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 173,
   "id": "terminal-snapshot",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 173,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"123e23\"\n",
    "\n",
    "try:\n",
    "    float(s)\n",
    "    isfloat = True\n",
    "except:\n",
    "    isfloat = False\n",
    "    \n",
    "isfloat\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 174,
   "id": "metropolitan-companion",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 174,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"  \".isspace()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "id": "adequate-apache",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 175,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\\n\\r\\t \".isspace()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 176,
   "id": "unnecessary-marker",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 176,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\\n\\t\\r\".isprintable()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 177,
   "id": "ethical-convertible",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 177,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"um testo simples\".isprintable()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 178,
   "id": "divine-prize",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 178,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"ABC\".isupper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "id": "future-trinidad",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 179,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"ABC\".islower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 180,
   "id": "funded-canberra",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 180,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc\".isupper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 181,
   "id": "worth-catalyst",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 181,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc\".islower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 182,
   "id": "theoretical-curtis",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 182,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Abc\".istitle()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "female-decline",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 183,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"ABC\".istitle()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 184,
   "id": "endangered-miracle",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 184,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc\".istitle()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "crude-jersey",
   "metadata": {},
   "source": [
    "### Formatação de strings\n",
    "Já temos usado bastante isso.  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "id": "scenic-commitment",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Oi mundo'"
      ]
     },
     "execution_count": 185,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{0} {1}\".format(\"Oi\", \"mundo\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 186,
   "id": "opening-moldova",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1 2 3'"
      ]
     },
     "execution_count": 186,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{} {} {}\".format(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "id": "convertible-arbitration",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3 2 1'"
      ]
     },
     "execution_count": 187,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{2} {1} {0}\".format(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 188,
   "id": "announced-fitting",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'XIPT       X'"
      ]
     },
     "execution_count": 188,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"X{0:<10}X\".format(\"IPT\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 189,
   "id": "ecological-drill",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'X       IPTX'"
      ]
     },
     "execution_count": 189,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"X{0:>10}X\".format(\"IPT\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 190,
   "id": "nearby-campbell",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'X   IPT    X'"
      ]
     },
     "execution_count": 190,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"X{0:^10}X\".format(\"IPT\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "id": "trained-montreal",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'XIPT.......X'"
      ]
     },
     "execution_count": 191,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"X{0:.<10}X\".format(\"IPT\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "id": "accessible-fetish",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'X...IPT....X'"
      ]
     },
     "execution_count": 192,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"X{0:.^10}X\".format(\"IPT\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sensitive-andrews",
   "metadata": {},
   "source": [
    "Os parâmetros de `format` podem ser uma lista:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "id": "widespread-closer",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1 2 3 4'"
      ]
     },
     "execution_count": 193,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "\"{0[0]} {0[1]} {1[0]} {1[1]}\".format([1,2], [3,4])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fabulous-optics",
   "metadata": {},
   "source": [
    "Até mesmo um dicionário:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 194,
   "id": "printable-latin",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'João 3767-0000 1 2'"
      ]
     },
     "execution_count": 194,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{0[nome]} {0[telefone]} {1[0]} {1[1]}\".format({\"telefone\": \"3767-0000\", \"nome\": \"João\"}, [1,2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "compound-maximum",
   "metadata": {},
   "source": [
    "Tem como formatar números. Na verdade esta formatação é quase uma minilinguagem. Para maiores informações, veja a documentação oficial do Python:\n",
    "\n",
    " * <https://docs.python.org/pt-br/3/tutorial/inputoutput.html#formatted-string-literals>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "devoted-chuck",
   "metadata": {},
   "source": [
    "### Jogo da forca"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "id": "motivated-liabilities",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Digite a plavra secreta: rato\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "....\n",
      "\n",
      "Digite uma letra: t\n",
      "||==:==\n",
      "||  :  \n",
      "||\n",
      "||\n",
      "||\n",
      "||\n",
      "==========\n",
      "..t.\n",
      "\n",
      "Digite uma letra: a\n",
      "||==:==\n",
      "||  :  \n",
      "||\n",
      "||\n",
      "||\n",
      "||\n",
      "==========\n",
      ".at.\n",
      "\n",
      "Digite uma letra: o\n",
      "||==:==\n",
      "||  :  \n",
      "||\n",
      "||\n",
      "||\n",
      "||\n",
      "==========\n",
      ".ato\n",
      "\n",
      "Digite uma letra: r\n",
      "||==:==\n",
      "||  :  \n",
      "||\n",
      "||\n",
      "||\n",
      "||\n",
      "==========\n",
      "rato\n",
      "Você acertou!\n"
     ]
    }
   ],
   "source": [
    "palavra = input(\"Digite a plavra secreta: \").strip().lower()\n",
    "for x in range(100): \n",
    "    print()\n",
    "\n",
    "digitadas = []\n",
    "acertos = []\n",
    "erros = 0\n",
    "\n",
    "while True:\n",
    "    senha = \"\"\n",
    "    for letra in palavra:\n",
    "        senha += letra if letra in acertos else \".\"\n",
    "    print(senha)\n",
    "    if senha == palavra:\n",
    "        print(\"Você acertou!\")\n",
    "        break\n",
    "    tentativa = input(\"\\nDigite uma letra: \").strip().lower()\n",
    "    if tentativa in digitadas:\n",
    "        print(\"Você já tentou esta letra!\")\n",
    "        continue\n",
    "    else:\n",
    "        digitadas += tentativa\n",
    "        if tentativa in palavra:\n",
    "            acertos += tentativa\n",
    "        else:\n",
    "            erros += 1\n",
    "            print(\"Você errou!\")\n",
    "    print(\"||==:==\\n||  :  \")\n",
    "    print(\"||  O  \" if erros >= 1 else \"||\")\n",
    "    linha2 = \"\"\n",
    "    if erros == 2:\n",
    "        linha2 = \"  |  \"\n",
    "    elif erros == 3:\n",
    "        linha2 = \" \\|  \" \n",
    "    elif erros >= 4:\n",
    "        linha2 = \" \\|/ \"\n",
    "    print(f\"||{linha2}\")\n",
    "    linha3 = \"\"\n",
    "    if erros == 5:\n",
    "        linha3 += \" /  \"\n",
    "    elif erros >= 6:\n",
    "        linha3 += \" / \\ \"\n",
    "    print(f\"||{linha3}\")\n",
    "    print(\"||\\n==========\")\n",
    "    if erros == 6:\n",
    "        print(\"Enforcado!\")\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sunrise-success",
   "metadata": {},
   "source": [
    "## Escrevendo scripts\n",
    "\n",
    "Scripts são pequenos programas que fazem alguma tarefa específica. Python surgiu como uma linguagem de script e é muito usada para isso.\n",
    "\n",
    "Um exemplo comum é executar um programa repetidas vezes mudando algum dado de entrada.\n",
    "\n",
    "Aqui, vamos fazer um script com o jogo de forca acima. Convenhamos, usar isso no notebook jupyter não é a melhor coisa do mundo...\n",
    "\n",
    "Para se fazer o script, você vai precisar usar um editor de texto. Pode ser o spyder, notepad++, geany, visual studio code, emacs ou qualquer editor de texto. Não processador de texto. Não vai funcionar com o Word!!!\n",
    "\n",
    "Crie um arquivo novo e copie e cole o programa acima. Chame o arquivo de `forca.py`\n",
    "\n",
    "Agora basta você executar \n",
    "```\n",
    "python forca.py\n",
    "```\n",
    "\n",
    "Tem como tornar isso um pouco melhor.\n",
    "\n",
    "### No Linux ou Unix\n",
    "\n",
    "Em linux (e mac OS?) é interessante adicionar a seguinte linha no topo:\n",
    "```\n",
    "#!/usr/bin/env python3\n",
    "```\n",
    "aí você torna o arquivo executável com a seguinte linha de comando\n",
    "```\n",
    "chmod +x forca.py\n",
    "```\n",
    "\n",
    "Agora o arquivo funciona como se fosse um executável!\n",
    "\n",
    "### No windows\n",
    "Se você instalou o python, clique duplo no arquivo forca.py já deveria funcionar. Se a associação da extensão do arquivo estiver correta. \n",
    "\n",
    "Na linha de comando você pode fazer algo parecido com o Linux. Na primeira linha, coloque o caminho para o executável do Python. No meu computador, esta primeira linha é:\n",
    "\n",
    "```\n",
    "#!\"C:\\ProgramData\\Anaconda3\\python.exe\"\n",
    "```\n",
    "\n",
    "Aí você pode usar o programa como se fosse um executável.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "consecutive-antenna",
   "metadata": {},
   "source": [
    "### Exercício 10\n",
    "Modifique o jogo da forca de forma que a palavra secreta seja escrita caso o jpgador perca"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fifty-amsterdam",
   "metadata": {},
   "source": [
    "### Exercício 11\n",
    "Modifique o jogo da forca de forma a utilizar uma lista de palavras. No início pergunte um número e calcule o índice da palavra a utilizar pela fórmula:\n",
    "```python\n",
    "índice = (número * 776) % len(lista_de_palavras)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "actual-gather",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
