├── README.md ├── automation_access_esaude_reports.py ├── chat-gpt └── audiochatgpt.py ├── codewars ├── files-01-to-99 │ ├── challenge01.py │ ├── challenge02.py │ ├── challenge03.py │ ├── challenge04.py │ ├── challenge05.py │ ├── challenge06.py │ ├── challenge07.py │ ├── challenge08.py │ ├── challenge09.py │ ├── challenge10.py │ ├── challenge11.py │ ├── challenge12.py │ ├── challenge13.py │ ├── challenge14.py │ ├── challenge15.py │ ├── challenge16.py │ ├── challenge17.py │ ├── challenge18.py │ ├── challenge19.py │ ├── challenge20.py │ ├── challenge21.py │ ├── challenge22.py │ ├── challenge23.py │ ├── challenge24.py │ ├── challenge25.py │ ├── challenge26.py │ ├── challenge27.py │ ├── challenge28.py │ ├── challenge29.py │ ├── challenge30.py │ ├── challenge31.py │ ├── challenge32.py │ ├── challenge33.py │ ├── challenge34.py │ ├── challenge35.py │ ├── challenge36.py │ ├── challenge37.py │ ├── challenge38.py │ ├── challenge39.py │ ├── challenge40.py │ ├── challenge41.py │ ├── challenge42.py │ ├── challenge43.py │ ├── challenge44.py │ ├── challenge45.py │ ├── challenge46.py │ ├── challenge47.py │ ├── challenge48.py │ ├── challenge49.py │ ├── challenge50.py │ ├── challenge51.py │ ├── challenge52.py │ ├── challenge53.py │ ├── challenge54.py │ ├── challenge55.py │ ├── challenge56.py │ ├── challenge57.py │ ├── challenge58.py │ ├── challenge59.py │ ├── challenge60.py │ ├── challenge61.py │ ├── challenge62.py │ ├── challenge63.py │ ├── challenge64.py │ ├── challenge65.py │ ├── challenge66.py │ ├── challenge67.py │ ├── challenge68.py │ ├── challenge69.py │ ├── challenge70.py │ ├── challenge71.py │ ├── challenge72.py │ ├── challenge73.py │ ├── challenge74.py │ ├── challenge75.py │ ├── challenge76.py │ ├── challenge77.py │ ├── challenge78.py │ ├── challenge79.py │ ├── challenge80.py │ ├── challenge81.py │ ├── challenge82.py │ ├── challenge83.py │ ├── challenge84.py │ ├── challenge85.py │ ├── challenge86.py │ ├── challenge87.py │ ├── challenge88.py │ ├── challenge89.py │ ├── challenge90.py │ ├── challenge91.py │ ├── challenge92.py │ ├── challenge93.py │ ├── challenge94.py │ ├── challenge95.py │ ├── challenge96.py │ ├── challenge97.py │ ├── challenge98.py │ └── challenge99.py ├── files-100-to-199 │ ├── challenge100.py │ ├── challenge101.py │ ├── challenge102.py │ ├── challenge103.py │ ├── challenge104.py │ ├── challenge105.py │ ├── challenge106.py │ ├── challenge107.py │ ├── challenge108.py │ ├── challenge109.py │ ├── challenge110.py │ ├── challenge111.py │ ├── challenge112.py │ ├── challenge113.py │ ├── challenge114.py │ ├── challenge115.py │ ├── challenge116.py │ ├── challenge117.py │ ├── challenge118.py │ ├── challenge119.py │ ├── challenge120.py │ ├── challenge121.py │ ├── challenge122.py │ ├── challenge123.py │ ├── challenge124.py │ ├── challenge125.py │ ├── challenge126.py │ ├── challenge127.py │ ├── challenge128.py │ ├── challenge129.py │ ├── challenge130.py │ ├── challenge131.py │ ├── challenge132.py │ ├── challenge133.py │ ├── challenge134.py │ ├── challenge135.py │ ├── challenge136.py │ ├── challenge137.py │ ├── challenge138.py │ ├── challenge139.py │ ├── challenge140.py │ ├── challenge141.py │ ├── challenge142.py │ ├── challenge143.py │ ├── challenge144.py │ ├── challenge145.py │ ├── challenge146.py │ ├── challenge147.py │ ├── challenge148.py │ ├── challenge149.py │ ├── challenge150.py │ ├── challenge151.py │ ├── challenge152.py │ ├── challenge153.py │ ├── challenge154.py │ ├── challenge155.py │ ├── challenge156.py │ ├── challenge157.py │ ├── challenge158.py │ ├── challenge159.py │ ├── challenge160.py │ ├── challenge161.py │ ├── challenge162.py │ ├── challenge163.py │ ├── challenge164.py │ ├── challenge165.py │ ├── challenge166.py │ ├── challenge167.py │ ├── challenge168.py │ ├── challenge169.py │ ├── challenge170.py │ ├── challenge171.py │ ├── challenge172.py │ ├── challenge173.py │ ├── challenge174.py │ ├── challenge175.py │ ├── challenge176.py │ ├── challenge177.py │ ├── challenge178.py │ ├── challenge179.py │ ├── challenge180.py │ ├── challenge181.py │ ├── challenge182.py │ ├── challenge183.py │ ├── challenge184.py │ ├── challenge185.py │ ├── challenge186.py │ ├── challenge187.py │ ├── challenge188.py │ ├── challenge189.py │ ├── challenge190.py │ ├── challenge191.py │ ├── challenge192.py │ ├── challenge193.py │ ├── challenge194.py │ ├── challenge195.py │ ├── challenge196.py │ ├── challenge197.py │ ├── challenge198.py │ └── challenge199.py ├── files-200-to-299 │ ├── challenge200.py │ ├── challenge201.py │ ├── challenge202.py │ ├── challenge203.py │ ├── challenge204.py │ ├── challenge205.py │ ├── challenge206.py │ ├── challenge207.py │ ├── challenge208.py │ ├── challenge209.py │ ├── challenge210.py │ ├── challenge211.py │ ├── challenge212.py │ ├── challenge213.py │ ├── challenge214.py │ ├── challenge215.py │ ├── challenge216.py │ ├── challenge217.py │ ├── challenge218.py │ ├── challenge219.py │ ├── challenge220.py │ ├── challenge221.py │ ├── challenge222.py │ ├── challenge223.py │ ├── challenge224.py │ ├── challenge225.py │ ├── challenge226.py │ ├── challenge227.py │ ├── challenge2278.py │ ├── challenge228.py │ ├── challenge229.py │ ├── challenge230.py │ ├── challenge231.py │ ├── challenge232.py │ ├── challenge233.py │ ├── challenge234.py │ ├── challenge235.py │ ├── challenge236.py │ ├── challenge237.py │ ├── challenge238.py │ ├── challenge239.py │ ├── challenge240.py │ ├── challenge241.py │ ├── challenge242.py │ ├── challenge243.py │ ├── challenge244.py │ ├── challenge245.py │ ├── challenge246.py │ ├── challenge247.py │ ├── challenge248.py │ ├── challenge249.py │ ├── challenge250.py │ ├── challenge251.py │ ├── challenge252.py │ ├── challenge253.py │ ├── challenge254.py │ ├── challenge255.py │ ├── challenge256.py │ ├── challenge257.py │ ├── challenge258.py │ ├── challenge259.py │ ├── challenge260.py │ ├── challenge261.py │ ├── challenge262.py │ ├── challenge263.py │ ├── challenge264.py │ ├── challenge265.py │ ├── challenge266.py │ ├── challenge267.py │ ├── challenge268.py │ ├── challenge269.py │ ├── challenge270.py │ ├── challenge271.py │ ├── challenge272.py │ ├── challenge273.py │ ├── challenge274.py │ ├── challenge275.py │ ├── challenge276.py │ ├── challenge277.py │ ├── challenge278.py │ ├── challenge279.py │ ├── challenge280.py │ ├── challenge281.py │ ├── challenge282.py │ ├── challenge283.py │ ├── challenge284.py │ ├── challenge285.py │ ├── challenge286.py │ ├── challenge287.py │ ├── challenge288.py │ ├── challenge289.py │ ├── challenge290.py │ ├── challenge291.py │ ├── challenge292.py │ ├── challenge293.py │ ├── challenge294.py │ ├── challenge295.py │ ├── challenge296.py │ ├── challenge297.py │ ├── challenge298.py │ └── challenge299.py └── files-300-to-399 │ ├── challenge300.py │ ├── challenge301.py │ ├── challenge302.py │ ├── challenge303.py │ ├── challenge304.py │ ├── challenge305.py │ ├── challenge306.py │ ├── challenge307.py │ ├── challenge308.py │ ├── challenge309.py │ ├── challenge310.py │ ├── challenge311.py │ ├── challenge321.py │ ├── challenge322.py │ ├── challenge323.py │ ├── challenge324.py │ ├── challenge325.py │ ├── challenge326.py │ ├── challenge327.py │ ├── challenge328.py │ ├── challenge329.py │ ├── challenge330.py │ ├── challenge331.py │ ├── challenge332.py │ └── challenge333.py ├── curso-em-video ├── aula04 │ ├── aula04desa01.py │ ├── aula04desa02.py │ └── aula04desa03.py ├── aula06 │ ├── aula06desa01.py │ └── aula06desa02.py ├── aula07 │ ├── aula07desa01.py │ ├── aula07desa02.py │ ├── aula07desa03.py │ ├── aula07desa04.py │ ├── aula07desa05.py │ ├── aula07desa06.py │ ├── aula07desa07.py │ ├── aula07desa08.py │ ├── aula07desa09.py │ ├── aula07exemplo01.py │ └── aula07exemplo02.py ├── aula08 │ ├── aula08desa01.py │ ├── aula08desa02.py │ ├── aula08desa03.py │ ├── aula08desa04.py │ ├── aula08desa05.py │ ├── aula08desa06.py │ └── olhos.mp3 ├── aula09 │ ├── aula09desa01.py │ ├── aula09desa02.py │ ├── aula09desa03.py │ ├── aula09desa04.py │ ├── aula09desa05.py │ ├── aula09desa06.py │ ├── aula09exemplo01.py │ └── aula09exemplo02.py ├── aula10 │ ├── aula10desa01.py │ ├── aula10desa02.py │ ├── aula10desa03.py │ ├── aula10desa04.py │ ├── aula10desa05.py │ ├── aula10desa06.py │ ├── aula10desa07.py │ └── aula10desa08.py ├── aula12 │ ├── aula12desa01.py │ ├── aula12desa02.py │ ├── aula12desa03.py │ ├── aula12desa04.py │ ├── aula12desa05.py │ ├── aula12desa06.py │ ├── aula12desa07.py │ ├── aula12desa08.py │ ├── aula12desa09.py │ └── aula12desa10.py ├── aula13 │ ├── aula13desa01.py │ ├── aula13desa02.py │ ├── aula13desa03.py │ ├── aula13desa04.py │ ├── aula13desa05.py │ ├── aula13desa06.py │ ├── aula13desa07.py │ ├── aula13desa08.py │ ├── aula13desa09.py │ ├── aula13desa10.py │ ├── aula13desa11.py │ └── aula13exemplos.py ├── aula14 │ ├── aula14desa01(forma01).py │ ├── aula14desa01(forma02).py │ ├── aula14desa02(forma01).py │ ├── aula14desa02(forma02).py │ ├── aula14desa03.py │ ├── aula14desa04(forma01).py │ ├── aula14desa04(forma02).py │ ├── aula14desa05.py │ ├── aula14desa06.py │ ├── aula14desa07.py │ ├── aula14desa08(forma01).py │ ├── aula14desa08(forma02).py │ ├── aula14desa09.py │ └── aula14exemplos.py ├── aula15 │ ├── aula15desa01.py │ ├── aula15desa02.py │ ├── aula15desa03.py │ ├── aula15desa04.py │ ├── aula15desa05.py │ ├── aula15desa06.py │ └── aula15exemplos.py ├── aula16 │ ├── aula16desa01.py │ ├── aula16desa02.py │ ├── aula16desa03.py │ ├── aula16desa04.py │ ├── aula16desa05(forma01).py │ ├── aula16desa05(forma02).py │ ├── aula16desa06.py │ └── aula16exemplos.py ├── aula17 │ ├── aula17desa01.py │ ├── aula17desa02.py │ ├── aula17desa03.py │ ├── aula17desa04.py │ ├── aula17desa05.py │ ├── aula17desa06.py │ ├── aula17exemplos01.py │ └── aula17exemplos02.py ├── aula18 │ ├── aula18desa01.py │ ├── aula18desa02.py │ ├── aula18desa03.py │ ├── aula18desa04.py │ ├── aula18desa05.py │ ├── aula18desa06.py │ ├── aula18exemplos01.py │ └── aula18exemplos02.py ├── aula19 │ ├── aula19desa01.py │ ├── aula19desa02.py │ ├── aula19desa03.py │ ├── aula19desa04.py │ ├── aula19desa05.py │ ├── aula19exemplos01.py │ ├── aula19exemplos02.py │ └── aula19exemplos03.py ├── aula20 │ ├── aula20desa01.py │ ├── aula20desa02.py │ ├── aula20desa03.py │ ├── aula20desa04.py │ ├── aula20desa05.py │ ├── aula20exemplos01.py │ ├── aula20exemplos02.py │ ├── aula20exemplos03.py │ ├── aula20exemplos04.py │ ├── aula20exemplos05.py │ └── aula20exemplos06.py ├── aula21 │ ├── aula21desa01.py │ ├── aula21desa03.py │ ├── aula21exemplos01.py │ ├── aula21exemplos02.py │ ├── aula21exemplos03.py │ ├── aula21exemplos04.py │ ├── aula21exemplos05.py │ └── aula21exemplos06.py ├── aula23 │ ├── aula23desa01.py │ ├── aula23desa02.py │ └── aula23exemplos01.py └── diversos │ └── coresconsolepython.py ├── monitorying_os_tasy.py ├── pucpr └── ads │ └── 2022 │ └── raciocinio-computacional │ ├── semana01 │ ├── exapli02.py │ ├── exapli03.py │ ├── exapli04.py │ └── exfixa02.py │ ├── semana02 │ ├── exapli03.py │ ├── exapli06.py │ ├── exapli08.py │ ├── exapli09.py │ ├── exfixa01.py │ ├── exfixa02.py │ ├── exfixa03.py │ ├── exfixa04.py │ ├── exfixa05.py │ ├── exfixa06.py │ ├── exfixa07.py │ ├── exfixa08.py │ └── exfixa09.py │ ├── semana03 │ ├── exapli03.py │ ├── exapli04.py │ ├── exapli05.py │ ├── exapli06.py │ ├── exapli07.py │ ├── exapli09.py │ ├── exapli10.py │ ├── exapli12.py │ ├── exevideo.py │ ├── exfixa01.py │ ├── exfixa02.py │ ├── exfixa03.py │ ├── exfixa04.py │ ├── exfixa05.py │ ├── exfixa06.py │ ├── exfixa07.py │ └── exfixa09.py │ ├── semana04 │ ├── exapli01.py │ ├── exapli02.py │ ├── exapli03.py │ ├── exapli04.py │ ├── exapli05.py │ ├── exapli06.py │ ├── exapli07.py │ ├── exapli08.py │ ├── exapli09.py │ ├── exevideo.py │ ├── exfixa01.py │ ├── exfixa02.py │ ├── exfixa03.py │ ├── exfixa04.py │ ├── exfixa05.py │ ├── exfixa06.py │ ├── exfixa07.py │ ├── exfixa08.py │ ├── exlistas01.py │ └── exlistas02.py │ ├── semana05 │ ├── exapli01.py │ ├── exapli02.py │ ├── exapli03.py │ ├── exapli04.py │ ├── exapli05.py │ ├── exapli06.py │ ├── exapli07.py │ ├── exdesavideo.py │ ├── exdiciometodos.py │ ├── exfixa01.py │ ├── exfixa02.py │ ├── exfixa03.py │ ├── exfixa04.py │ ├── exfixa05.py │ └── exvideo.py │ └── semana06 │ ├── exapli01.py │ ├── exapli02.py │ ├── exapli03.py │ ├── exapli04.py │ ├── exapli05.py │ ├── exapli06.py │ ├── exdesavideo.py │ ├── exemplos.py │ ├── exfixa01.py │ ├── exfixa02.py │ ├── exfixa03.py │ ├── exfixa04.py │ ├── exfixa06.py │ ├── exfixa50.py │ └── exvideo.py ├── python-3-completo-udemy ├── 1.arquivos-01-a-99 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06-exercicio.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09-exercicio.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14-exercicio.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19-exercicio.py │ ├── 19.py │ ├── 20.py │ ├── 21.py │ ├── 22.py │ ├── 23.py │ ├── 24.py │ ├── 25.py │ ├── 26.py │ ├── 27.py │ ├── 28.py │ ├── 29.py │ ├── 30.py │ ├── 31.py │ ├── 32.py │ ├── 33.py │ ├── 34.py │ ├── 35.py │ ├── 36.py │ ├── 37.py │ ├── 38.py │ ├── 39.py │ ├── 40-exercicio.py │ ├── 40.py │ ├── 41.py │ ├── 42.py │ ├── 43.py │ ├── 44-exercicio.py │ ├── 44.py │ ├── 45.py │ ├── 46.py │ ├── 47.py │ ├── 48.py │ ├── 49.py │ ├── 50.py │ ├── 51.py │ ├── 52.py │ ├── 53.py │ ├── 54.py │ ├── 55.py │ ├── 56.py │ ├── 57.py │ ├── 58-exercicio.py │ ├── 58.py │ ├── 59.py │ ├── 60.py │ ├── 61.py │ ├── 62.py │ ├── 63.py │ ├── 64-exercicio.py │ ├── 64.py │ ├── 65.py │ ├── 66.py │ ├── 67.py │ ├── 68.py │ ├── 69.py │ ├── 70.py │ ├── 71.py │ ├── 72.py │ ├── 73.py │ ├── 74.py │ ├── 75.py │ ├── 76.py │ ├── 77.py │ ├── 78.py │ ├── 79.py │ ├── 80.py │ ├── 81.py │ ├── 82.py │ ├── 83.py │ ├── 84.py │ ├── 85.py │ ├── 86.py │ ├── 87.py │ ├── 88-modulo.py │ ├── 88.py │ ├── 89-modulo.py │ ├── 89.py │ ├── 90.py │ ├── 91.py │ ├── 92.py │ ├── 93.py │ ├── 94.py │ ├── 95.py │ ├── 96.py │ ├── 97.py │ ├── 98.py │ └── 99.py ├── 2.arquivos-100-a-163 │ ├── 100.py │ ├── 101.py │ ├── 102.py │ ├── 103.py │ ├── 104.py │ ├── 105.py │ ├── 106.py │ ├── 107.py │ ├── 108.py │ ├── 109.py │ ├── 115.py │ ├── 117.py │ ├── 118.py │ ├── 119.py │ ├── 120.py │ ├── 122.py │ ├── 123.py │ ├── 124.py │ ├── 125.py │ ├── 126.py │ ├── 127.py │ ├── 128.py │ ├── 129.py │ ├── 130.py │ ├── 131.py │ ├── 132.py │ ├── 133.py │ ├── 134.py │ ├── 135.py │ ├── 136.py │ ├── 137.py │ ├── 138.py │ ├── 139.py │ ├── 140.py │ ├── 141.py │ ├── 142.py │ ├── 143.py │ ├── 144.py │ ├── 145.py │ ├── 146.py │ ├── 147.py │ ├── 148.py │ ├── 149.py │ ├── 150.py │ ├── 151.py │ ├── 152.py │ ├── 153.py │ ├── 154.py │ ├── 155.py │ ├── 156.py │ ├── 157.py │ ├── 158.py │ ├── 159.py │ ├── 160.py │ ├── 161.py │ ├── 162.py │ └── 163.py ├── 3.arquivo-110 │ ├── arquivo.txt │ ├── criacao_arquivo.py │ └── leitura_arquivo.py ├── 4.arquivo-111 │ ├── arquivo.txt │ └── aula111.py ├── 5.arquivo-112 │ ├── arquivo.txt │ └── aula112.py ├── 6.arquivo-113 │ ├── aula113.json │ └── aula113.py ├── 7.arquivo-114 │ ├── aula114.json │ └── aula114.py ├── 8.arquivo-116 │ ├── aula116.py │ └── lista_tarefas.json └── 9.arquivo-121 │ ├── aula121a.py │ ├── aula121b.py │ └── classe.json ├── python-brasil ├── estrutura-decisão │ ├── exestrudecisao01.py │ ├── exestrudecisao02.py │ ├── exestrudecisao03.py │ ├── exestrudecisao04.py │ ├── exestrudecisao05.py │ ├── exestrudecisao06.py │ ├── exestrudecisao07.py │ ├── exestrudecisao08.py │ ├── exestrudecisao09.py │ ├── exestrudecisao10.py │ ├── exestrudecisao11.py │ ├── exestrudecisao12.py │ ├── exestrudecisao13.py │ ├── exestrudecisao14.py │ ├── exestrudecisao15.py │ ├── exestrudecisao16.py │ ├── exestrudecisao17.py │ ├── exestrudecisao23.py │ ├── exestrudecisao25.py │ ├── exestrudecisao26.py │ └── exestrudecisao27.py ├── estrutura-repetição │ ├── exestrurepeticao01.py │ ├── exestrurepeticao02.py │ ├── exestrurepeticao03.py │ ├── exestrurepeticao04.py │ ├── exestrurepeticao05.py │ ├── exestrurepeticao06.py │ ├── exestrurepeticao07.py │ ├── exestrurepeticao08.py │ ├── exestrurepeticao09.py │ ├── exestrurepeticao10.py │ ├── exestrurepeticao11.py │ ├── exestrurepeticao12.py │ ├── exestrurepeticao13.py │ ├── exestrurepeticao14.py │ ├── exestrurepeticao15.py │ ├── exestrurepeticao18.py │ ├── exestrurepeticao19.py │ ├── exestrurepeticao24.py │ ├── exestrurepeticao25.py │ ├── exestrurepeticao26.py │ ├── exestrurepeticao27.py │ ├── exestrurepeticao28.py │ ├── exestrurepeticao29.py │ ├── exestrurepeticao30.py │ ├── exestrurepeticao31.py │ └── exestrurepeticao33.py ├── estrutura-sequencial │ ├── exestruseq01.py │ ├── exestruseq02.py │ ├── exestruseq03.py │ ├── exestruseq04.py │ ├── exestruseq05.py │ ├── exestruseq06.py │ ├── exestruseq07.py │ ├── exestruseq08.py │ ├── exestruseq09.py │ ├── exestruseq10.py │ ├── exestruseq11.py │ ├── exestruseq12.py │ ├── exestruseq13.py │ ├── exestruseq14.py │ ├── exestruseq15.py │ ├── exestruseq16.py │ ├── exestruseq17.py │ └── exestruseq18.py ├── funções │ ├── exfuncoes03.py │ ├── exfuncoes04.py │ └── exfuncoes05.py └── listas │ ├── exlistas01.py │ ├── exlistas02.py │ ├── exlistas03.py │ ├── exlistas04.py │ ├── exlistas05.py │ ├── exlistas06.py │ ├── exlistas07.py │ ├── exlistas08.py │ ├── exlistas09.py │ ├── exlistas10.py │ ├── exlistas15.py │ └── exlistas17.py ├── sms-project ├── monitoring_contingency.py ├── monitoring_tasy.py ├── send_login.py └── tasy_production_password_reset.py └── truth_table.py /codewars/files-01-to-99/challenge02.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this kata you will create a function that takes in a list and returns a list with the reverse order. 3 | 4 | Examples (Input -> Output): 5 | 1) [1, 2, 3, 4] -> [4, 3, 2, 1] 6 | 2) [9, 2, 0, 7] -> [7, 0, 2, 9] 7 | """ 8 | 9 | 10 | def reverse_list(lst): 11 | return lst[::-1] 12 | 13 | # Usage examples. 14 | example1 = [1, 2, 3, 4] 15 | result1 = reverse_list(example1) 16 | print(result1) # Expected output: [4, 3, 2, 1]. 17 | example2 = [9, 2, 0, 7] 18 | result2 = reverse_list(example2) 19 | print(result2) # Expected output: [7, 0, 2, 9]. 20 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge04.py: -------------------------------------------------------------------------------- 1 | """ 2 | Terminal game move function. 3 | 4 | In this game, the hero moves from left to right. The player rolls the dice and moves the number of spaces indicated by the dice two 5 | times. Create a function for the terminal game that takes the current position of the hero and the roll (1-6) and return the new position. 6 | 7 | Example: 8 | 1) move(3, 6) should equal 15. 9 | """ 10 | 11 | 12 | def move(position, roll): 13 | return position + roll * 2 14 | 15 | current_position = 3 16 | dice_roll = 6 17 | new_position = move(current_position, dice_roll) 18 | print(new_position) 19 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge10.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a single non-empty string of only lowercase and uppercase ascii letters (word) as its argument, and returns 3 | an ordered list containing the indices of all capital (uppercase) letters in the string. 4 | 5 | Example (Input --> Output): 6 | 1) "CodEWaRs" --> [0,3,4,6]. 7 | """ 8 | 9 | 10 | def find_capital_indices(word): 11 | return [index for index, char in enumerate(word) if char.isupper()] 12 | 13 | # Usage example. 14 | word = "CodEWaRs" 15 | print(find_capital_indices(word)) # Output: [0, 3, 4, 6]. 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge13.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write function RemoveExclamationMarks which removes all exclamation marks from a given string. 3 | """ 4 | 5 | 6 | def RemoveExclamationMarks(s): 7 | # Remove all exclamation marks from the input string and return the result. 8 | return s.replace('!', '') 9 | 10 | # Usage example. 11 | example_string = "Hello! World!! This is an example!!!" 12 | result = RemoveExclamationMarks(example_string) 13 | print(result) # Output: Hello World This is an example. 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge15.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given two interior angles (in degrees) of a triangle. 3 | 4 | Write a function to return the 3rd. 5 | 6 | Note: only positive integers will be tested. 7 | """ 8 | 9 | 10 | def find_third_angle(angle1, angle2): 11 | return 180 - angle1 - angle2 12 | 13 | # Usage examples. 14 | example_angle1 = 45 15 | example_angle2 = 90 16 | find_third_angle(example_angle1, example_angle2) 17 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge17.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that multiplying a given number by eight if it is an even number and by nine otherwise. 3 | """ 4 | 5 | 6 | def multiply_by_eight_or_nine(n): 7 | if n % 2 == 0: # Check if n is even. 8 | return n * 8 9 | else: 10 | return n * 9 11 | 12 | # Usage example. 13 | test_numbers = [2, 3, 4, 5, 10] 14 | results = [multiply_by_eight_or_nine(n) for n in test_numbers] 15 | print(results) 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge18.py: -------------------------------------------------------------------------------- 1 | """ 2 | When provided with a letter, return its position in the alphabet. 3 | 4 | Example Input -> Output: 5 | 1) a -> Position 1 of alphabet. 6 | """ 7 | 8 | 9 | def letter_position(letter): 10 | position = ord(letter.lower()) - 96 11 | return f"Position {position} of alphabet." 12 | 13 | # Usage example. 14 | input_letter = "a" 15 | print(letter_position(input_letter)) 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge19.py: -------------------------------------------------------------------------------- 1 | """ 2 | Make a function that returns the value multiplied by 50 and increased by 6. 3 | If the value entered is a string it should return "Error". 4 | """ 5 | 6 | 7 | def multiply_and_increase(value): 8 | if isinstance(value, (int, float)): 9 | return value * 50 + 6 10 | else: 11 | return "Error" 12 | 13 | # Usage Examples. 14 | print(multiply_and_increase(10)) # Should return 506. 15 | print(multiply_and_increase("test")) # Should return "Error". 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge20.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple, given a string of words, return the length of the shortest word(s). 3 | 4 | String will never be empty and you do not need to account for different data types. 5 | """ 6 | 7 | 8 | def shortest_word_length(s): 9 | # Split the string into words. 10 | words = s.split() 11 | # Find the lengths of all words. 12 | lengths = [len(word) for word in words] 13 | # Return the length of the shortest word. 14 | return min(lengths) 15 | 16 | # Usage example. 17 | test_string = "The quick brown fox jumps over the lazy dog." 18 | print(shortest_word_length(test_string)) 19 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge21.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. 3 | Return your answer as a number. 4 | """ 5 | 6 | 7 | def sum_array_values(arr): 8 | return sum(int(i) for i in arr) 9 | 10 | example_array = ["3", 6, "7", 4, "2", 8] 11 | 12 | sum_example_array = sum_array_values(example_array) 13 | 14 | print(sum_example_array) 15 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge22.py: -------------------------------------------------------------------------------- 1 | """ 2 | You will be given an array and a limit value. You must check that all values in the array 3 | are below or equal to the limit value. If they are, return true. Else, return false. 4 | 5 | You can assume all values in the array are numbers. 6 | """ 7 | 8 | 9 | def check_array_against_limit(array, limit): 10 | # Check each value in the array. 11 | for value in array: 12 | if value > limit: 13 | return False 14 | return True 15 | 16 | # Usage example. 17 | array = [10, 20, 30, 40] 18 | limit = 50 19 | result = check_array_against_limit(array, limit) 20 | print("All values are within the limit:", result) 21 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge23.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. 3 | """ 4 | 5 | 6 | def even_or_odd(number): 7 | if number % 2 == 0: 8 | return "Even" 9 | else: 10 | return "Odd" 11 | 12 | # Usage example. 13 | test_numbers = [0, 1, 2, 3, 4, 5] 14 | for number in test_numbers: 15 | print(f"{number}: {even_or_odd(number)}") 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge25.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the solution so that the function will break up camel casing, using a space between words. 3 | """ 4 | 5 | 6 | def break_camel_case(s): 7 | return ''.join(' ' + c if c.isupper() and i != 0 else c for i, c in enumerate(s)) 8 | 9 | # Usage example. 10 | test_string = "exampleCamelCase." 11 | print(break_camel_case(test_string)) 12 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge26.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes an integer as input, and returns the number of bitsthat are 3 | equal to one in the binary representation of that number. You can guarantee that input is 4 | non-negative. 5 | """ 6 | 7 | 8 | function countBits(n): 9 | count = 0 10 | while n > 0: 11 | if n % 2 == 1: 12 | count += 1 13 | n = n // 2 14 | return count 15 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge27.py: -------------------------------------------------------------------------------- 1 | """ 2 | You will be given an array a and a value x. 3 | All you need to do is check whether the provided array contains the value. 4 | Array can contain numbers or strings. X can be either. 5 | Return true if the array contains the value, false if not. 6 | """ 7 | 8 | 9 | def check(seq, elem): 10 | return elem in seq 11 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge28.py: -------------------------------------------------------------------------------- 1 | """ 2 | Jenny has written a function that returns a greeting for a user. 3 | However, she's in love with Johnny, and would like to greet him slightly 4 | different. She added a special case to her function, but she made a mistake. 5 | """ 6 | 7 | 8 | def greet_user(name): 9 | if name == "Johnny": 10 | return "Hello, my love!" 11 | else: 12 | return "Hello, " + name + "!" 13 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge30.py: -------------------------------------------------------------------------------- 1 | """ 2 | Make a simple function called greet that returns the most-famous "hello world!". 3 | 4 | Style Points: Sure, this is about as easy as it gets. But how clever can you be 5 | to create the most creative "hello world" you can think of? What is a "hello world" 6 | solution you would want to show your friends? 7 | """ 8 | 9 | 10 | def greet(): 11 | return ''.join([chr(x) for x in [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]]) 12 | 13 | print(greet()) 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge33.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that takes a list of non-negative integers and strings and 3 | returns a new list with the strings filtered out. 4 | """ 5 | 6 | 7 | def filter_list(l): 8 | return [item for item in l if isinstance(item, int)] 9 | 10 | # Usage examples. 11 | print(filter_list([1, 2, 'a', 'b'])) 12 | print(filter_list([1, 'a', 'b', 0, 15])) 13 | print(filter_list([1, 2, 'aasf', '1', '123', 123])) 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge37.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that removes the spaces from the string, then return the resultant string. 3 | """ 4 | 5 | 6 | def no_space(x): 7 | result_string = x.replace(" ", "") 8 | return result_string 9 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge38.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. 3 | """ 4 | 5 | 6 | def move_zeros(array): 7 | for i in array: 8 | if i == 0: 9 | array.remove(i) 10 | array.append(i) 11 | return array 12 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge41.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, you have to return a string in which each character (case-sensitive) is repeated once. 3 | """ 4 | 5 | 6 | def repeat_characters(input_string): 7 | repeated_string = "" 8 | for char in input_string: 9 | repeated_string += char * 2 10 | return repeated_string 11 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge42.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your classmates asked you to copy some paperwork for them. 3 | 4 | You know that there are "n" classmates and the paperwork has "m" pages. 5 | 6 | Your task is to calculate how many blank pages do you need. If n < 0 or m < 0 return 0. 7 | """ 8 | 9 | 10 | def blank_pages_needed(n, m): 11 | if n < 0 or m < 0: 12 | return 0 13 | else: 14 | return n * m 15 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge43.py: -------------------------------------------------------------------------------- 1 | """ 2 | You were camping with your friends far away from home, but when it's time to go back, 3 | you realize that your fuel is running out and the nearest pump is 50 miles away! 4 | You know that on average, your car runs on about 25 miles per gallon. There are 2 gallons left. 5 | 6 | Considering these factors, write a function that tells you if it is possible to get to the pump or not. 7 | 8 | Function should return true if it is possible and false if not. 9 | """ 10 | 11 | 12 | def zero_fuel(distance_to_pump, mpg, fuel_left): 13 | max_distance = mpg * fuel_left 14 | return max_distance >= distance_to_pump 15 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge44.py: -------------------------------------------------------------------------------- 1 | """ 2 | An isogram is a word that has no repeating letters, 3 | consecutive or non-consecutive. Implement a function 4 | that determines whether a string that contains only 5 | letters is an isogram. Assume the empty string is an isogram. 6 | Ignore letter case. 7 | """ 8 | 9 | 10 | def is_isogram(word): 11 | # Normalize the word to lower case to ignore case differences. 12 | normalized_word = word.lower() 13 | # Convert the word into a set of characters to remove duplicates. 14 | letters = set(normalized_word) 15 | return len(letters) == len(normalized_word) 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge45.py: -------------------------------------------------------------------------------- 1 | """ 2 | The cockroach is one of the fastest insects. 3 | Write a function which takes its speed in km per 4 | hour and returns it in cm per second, rounded down 5 | to the integer (= floored). 6 | """ 7 | 8 | 9 | def cockroach_speed(speed_km_hr): 10 | speed_cm_s = speed_km_hr * 100000 / 3600 11 | return int(speed_cm_s) 12 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge47.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task is to make a function that can take any non-negative 3 | integer as an argument and return it with its digits in descending order. 4 | Essentially, rearrange the digits to create the highest possible number. 5 | """ 6 | 7 | 8 | def descending_order(num): 9 | digits = [int(x) for x in str(num)] 10 | sorted_digits = sorted(digits, reverse=True) 11 | result = int(''.join(map(str, sorted_digits))) 12 | return result 13 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge49.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string indicating a range of letters, return a string 3 | which includes all the letters in that range, including the last letter. 4 | Note that if the range is given in capital letters, return the string in capitals also! 5 | """ 6 | 7 | 8 | def expand_range(letters_range): 9 | start, end = letters_range.split('-') 10 | if start.isupper(): 11 | return ''.join(chr(i) for i in range(ord(start), ord(end)+1)).upper() 12 | else: 13 | return ''.join(chr(i) for i in range(ord(start), ord(end)+1)).lower() 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge50.py: -------------------------------------------------------------------------------- 1 | """ 2 | Check to see if a string has the same amount of "x"s and "o"s. 3 | The method must return a boolean and be case insensitive. 4 | The string can contain any char. 5 | """ 6 | 7 | 8 | def equal_x_and_o(string): 9 | string_lower = string.lower() 10 | count_x = string_lower.count('x') 11 | count_o = string_lower.count('o') 12 | return count_x == count_o 13 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge53.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a month as an integer from 1 to 12, return to which quarter 3 | of the year it belongs as an integer number. 4 | 5 | For example: month 2 (February), is part of the first quarter; month 6 (June), 6 | is part of the second quarter; and month 11 (November), is part of the fourth quarter. 7 | """ 8 | 9 | 10 | def month_to_quarter(month): 11 | if 1 <= month <= 12: 12 | quarter = (month - 1) // 3 + 1 13 | return quarter 14 | else: 15 | return "Invalid month" 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge55.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this kata you get the start number and the end number of a region 3 | and should return the count of all numbers except numbers with a 5 in it. 4 | The start and the end number are both inclusive! 5 | """ 6 | 7 | 8 | def dont_give_me_five(start, end): 9 | count = 0 10 | for number in range(start, end + 1): 11 | if '5' not in str(number): 12 | count += 1 13 | return count 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge56.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this Kata, you will be given an array of arrays and your task will be to 3 | return the number of unique arrays that can be formed by picking exactly one 4 | element from each subarray. 5 | """ 6 | 7 | from itertools import product 8 | 9 | 10 | def unique_combinations(arrays): 11 | # Generate all combinations by picking one element from each subarray. 12 | all_combinations = product(*arrays) 13 | # Convert combinations to set to get unique combinations. 14 | unique_combinations = set(all_combinations) 15 | # Return the number of unique combinations. 16 | return len(unique_combinations) 17 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge57.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that accepts an array of 10 integers (between 0 and 9), 3 | that returns a string of those numbers in the form of a phone number. 4 | """ 5 | 6 | 7 | def create_phone_number(numbers): 8 | if len(numbers) != 10 or not all(0 <= num <= 9 for num in numbers): 9 | raise ValueError("Input must be an array of 10 integers between 0 and 9.") 10 | 11 | phone_number = "({}{}{}) {}{}{}-{}{}{}{}".format(*numbers) 12 | return phone_number 13 | 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge65.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function to convert a name into initials. 3 | This kata strictly takes two words with one space in between them. 4 | The output should be two capital letters with a dot separating them. 5 | """ 6 | 7 | 8 | def abbrev_name(full_name: str) -> str: 9 | name, surname = full_name.split() 10 | return f"{name[0].capitalize()}.{surname[0].capitalize()}" 11 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge66.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an odd-length array of integers, in which all of them are the same, except for one single number. 3 | Complete the method which accepts such an array, and returns that single different number. 4 | The input array will always be valid! (odd-length >= 3). 5 | """ 6 | 7 | 8 | def stray(arr): 9 | counts = {} 10 | 11 | for num in arr: 12 | if num in counts: 13 | counts[num] += 1 14 | else: 15 | counts[num] = 1 16 | 17 | for num, count in counts.items(): 18 | if count == 1: 19 | return num 20 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge67.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. 3 | You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2. 4 | The array will always contain letters in only one case. 5 | """ 6 | 7 | 8 | def find_missing_letter(chars): 9 | start = ord(chars[0]) 10 | 11 | for i in range(len(chars)): 12 | if ord(chars[i]) != start + i: 13 | return chr(start + i) 14 | 15 | return None 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge68.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function named get_planet_name that takes an integer id as its parameter. 3 | The function should return the name of the planet corresponding to the given id. 4 | """ 5 | 6 | 7 | def get_planet_name(id): 8 | planet_names = { 9 | 1: "Mercury", 10 | 2: "Venus", 11 | 3: "Earth", 12 | 4: "Mars", 13 | 5: "Jupiter", 14 | 6: "Saturn", 15 | 7: "Uranus", 16 | 8: "Neptune" 17 | } 18 | return planet_names.get(id, "") 19 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge71.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that returns the sum of the two lowest positive 3 | numbers given an array of minimum 4 positive integers. 4 | No floats or non-positive integers will be passed. 5 | """ 6 | 7 | 8 | def sum_two_smallest_numbers(numbers): 9 | # Sort the list to find the two smallest numbers. 10 | sorted_numbers = sorted(numbers) 11 | # Return the sum of the first two elements in the sorted list. 12 | return sorted_numbers[0] + sorted_numbers[1] 13 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge72.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are going to be given a word. Your job is to return the middle character of the word. 3 | If the word's length is odd, return the middle character. If the word's length is even, 4 | return the middle 2 characters. 5 | """ 6 | 7 | 8 | def get_middle(s): 9 | length = len(s) 10 | middle = length // 2 11 | 12 | if length % 2 == 0: 13 | return s[middle - 1: middle + 1] 14 | else: 15 | return s[middle] 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge74.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given n, take the sum of the digits of n. 3 | If that value has more than one digit, 4 | continue reducing in this way until a 5 | single-digit number is produced. 6 | The input will be a non-negative integer. 7 | """ 8 | 9 | 10 | def digital_root(n): 11 | while n >= 10: 12 | n = sum(int(digit) for digit in str(n)) 13 | return n 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge75.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this kata you are required to, given a string, replace every letter with its position in the alphabet. 3 | If anything in the text isn't a letter, ignore it and don't return it. 4 | """ 5 | 6 | 7 | def alphabet_position(text): 8 | positions = [] 9 | for char in text: 10 | if char.isalpha(): # Check if the character is a letter. 11 | position = ord(char.lower()) - ord('a') + 1 # Convert letter to its alphabet position. 12 | positions.append(str(position)) 13 | return ' '.join(positions) 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge76.py: -------------------------------------------------------------------------------- 1 | """ 2 | If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of 3 | these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below 4 | the number passed in. Additionally, if the number is negative, return 0. 5 | 6 | Note: If the number is a multiple of both 3 and 5, only count it once. 7 | """ 8 | 9 | 10 | def solution(number): 11 | if number < 0: 12 | return 0 13 | return sum(i for i in range(number) if i % 3 == 0 or i % 5 == 0) 14 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge77.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that converts US dollars (USD) to Chinese Yuan (CNY). 3 | The input is the amount of USD as an integer, and the output should be a 4 | string that states the amount of Yuan followed by "Chinese Yuan" 5 | """ 6 | 7 | 8 | def usdcny(usd): 9 | conversion_rate = 6.75 10 | cny = usd * conversion_rate 11 | return f"{cny:.2f} Chinese Yuan" 12 | 13 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge78.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find the total sum of internal angles (in degrees) 3 | in an n-sided simple polygon. N will be greater than 2. 4 | """ 5 | 6 | 7 | def angle(n): 8 | return (n - 2) * 180 9 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge80.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this kata, your task is to implement an 3 | extended version of the famous rock-paper-scissors game. 4 | """ 5 | 6 | 7 | def rpsls(pl1, pl2): 8 | # Dictionary to store the winning cases. 9 | rules = { 10 | "scissors": ["paper", "lizard"], 11 | "paper": ["rock", "spock"], 12 | "rock": ["lizard", "scissors"], 13 | "lizard": ["spock", "paper"], 14 | "spock": ["scissors", "rock"] 15 | } 16 | 17 | if pl1 == pl2: 18 | return "Draw!" 19 | elif pl2 in rules[pl1]: 20 | return "Player 1 Won!" 21 | else: 22 | return "Player 2 Won!" 23 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge81.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function filterLucky/filter_lucky() that accepts a 3 | list of integers and filters the list to only include the 4 | elements that contain the digit 7. 5 | """ 6 | 7 | 8 | def filter_lucky(lst): 9 | # Filter elements in lst that contain the digit 7. 10 | return [num for num in lst if '7' in str(num)] 11 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge83.py: -------------------------------------------------------------------------------- 1 | """ 2 | Now you have to write a function that takes an argument and returns the square of it. 3 | """ 4 | 5 | 6 | def square(n): 7 | return n * n 8 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge90.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this example you have to validate if a user input string is alphanumeric. 3 | The given string is not nil/null/NULL/None, so you don't have to check that. 4 | 5 | The string has the following conditions to be alphanumeric: 6 | - At least one character ("" is not valid); 7 | - Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9; 8 | - No whitespaces / underscore. 9 | """ 10 | 11 | 12 | def alphanumeric(password): 13 | if len(password) == 0: 14 | return False 15 | for char in password: 16 | if not char.isalnum(): 17 | return False 18 | return True 19 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge92.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your goal in this kata is to implement a difference function, 3 | which subtracts one list from another and returns the result. 4 | It should remove all values from list a, which are present in 5 | list b keeping their order. 6 | 7 | array_diff([1,2],[1]) == [2] 8 | 9 | If a value is present in b, all of its occurrences must be 10 | removed from the other: array_diff([1,2,2,2,3],[2]) == [1,3] 11 | """ 12 | 13 | 14 | def array_diff(a, b): 15 | return [item for item in a if item not in b] 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge93.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unfinished Loop - Bug Fixing #1 3 | 4 | Oh no, Timmy's created an infinite loop! 5 | Help Timmy find and fix the bug in his unfinished for loop! 6 | """ 7 | 8 | 9 | def create_array(n): 10 | res = [] 11 | i = 1 12 | while i <= n: 13 | res.append(i) 14 | i += 1 # Increment i by 1 in each iteration. 15 | return res 16 | -------------------------------------------------------------------------------- /codewars/files-01-to-99/challenge95.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function/method so that it takes a PascalCase string and returns 3 | the string in snake_case notation. Lowercase characters can be numbers. 4 | If the method gets a number as input, it should return a string. 5 | """ 6 | 7 | import re 8 | 9 | 10 | def to_underscore(string): 11 | if isinstance(string, int): 12 | return str(string) 13 | 14 | # Insert underscores before uppercase letters and convert to lowercase. 15 | snake_case_string = re.sub(r'(?= 5: 16 | result.append(word[::-1]) 17 | else: 18 | result.append(word) 19 | 20 | return ' '.join(result) 21 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge101.py: -------------------------------------------------------------------------------- 1 | """ 2 | Usually when you buy something, you're asked whether your credit card number, 3 | phone number or answer to your most secret question is still correct. 4 | However, since someone could look over your shoulder, you don't want that shown 5 | on your screen. Instead, we mask it. 6 | Your task is to write a function maskify, which changes all but the last four characters into '#'. 7 | """ 8 | 9 | 10 | def maskify(cc): 11 | # Check if the length of the string is less than or equal to 4. 12 | if len(cc) <= 4: 13 | return cc 14 | # Mask all but the last four characters. 15 | return '#' * (len(cc) - 4) + cc[-4:] 16 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge102.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this little assignment you are given a string of 3 | space separated numbers, and have to return the highest 4 | and lowest number. 5 | """ 6 | 7 | 8 | def high_and_low(numbers): 9 | num_list = [int(num) for num in numbers.split()] 10 | return f"{max(num_list)} {min(num_list)}" 11 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge103.py: -------------------------------------------------------------------------------- 1 | """ 2 | This time no story, no theory. 3 | 4 | The examples below show you how to write function accum: 5 | accum("abcd") -> "A-Bb-Ccc-Dddd" 6 | accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" 7 | accum("cwAt") -> "C-Ww-Aaa-Tttt" 8 | 9 | The parameter of accum is a string which includes only letters from a..z and A..Z. 10 | """ 11 | 12 | 13 | def accum(s): 14 | return '-'.join((char * (i + 1)).capitalize() for i, char in enumerate(s)) 15 | 16 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge105.py: -------------------------------------------------------------------------------- 1 | """ 2 | Can you find the needle in the haystack? 3 | Write a function findNeedle() that takes 4 | an array full of junk but containing one "needle" 5 | """ 6 | 7 | 8 | def find_needle(haystack): 9 | # Iterate through the array to find the needle. 10 | for index, item in enumerate(haystack): 11 | if item == "needle": 12 | return f"found the needle at position {index}" 13 | # If needle is not found, return a message. 14 | return "needle not found" 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge106.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ). 3 | The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value. 4 | Mind the input validation. 5 | """ 6 | 7 | 8 | def sum_array(arr): 9 | if arr is None or len(arr) < 3: 10 | return 0 11 | 12 | # Remove the highest and lowest values. 13 | arr = sorted(arr) 14 | return sum(arr[1:-1]) 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge107.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a string and outputs a 3 | strings of 1's and 0's where vowels become 1's and 4 | non-vowels become 0's. 5 | 6 | All non-vowels including non alpha characters (spaces,commas etc.) 7 | should be included. 8 | """ 9 | 10 | 11 | def vowel_one(s): 12 | # Define a set of vowels for easy lookup. 13 | vowels = set('aeiouAEIOU') 14 | 15 | # Use a list comprehension to convert each character. 16 | result = ''.join('1' if char in vowels else '0' for char in s) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge110.py: -------------------------------------------------------------------------------- 1 | """ 2 | While making a game, your partner, Greg, decided to create a function to check if the user 3 | is still alive called checkAlive/CheckAlive/check_alive. Unfortunately, Greg made some errors 4 | while creating the function. checkAlive/CheckAlive/check_alive should return true if the player's 5 | health is greater than 0 or false if it is 0 or below. 6 | The function receives one parameter health which will always be a whole number between -10 and 10. 7 | """ 8 | 9 | 10 | def check_alive(health): 11 | if health > 0: 12 | return True 13 | else: 14 | return False 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge112.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that checks if a number n is divisible by 3 | two numbers x AND y. All inputs are positive, non-zero numbers. 4 | """ 5 | 6 | 7 | def is_divisible(n, x, y): 8 | return (n % x == 0) and (n % y == 0) 9 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge113.py: -------------------------------------------------------------------------------- 1 | """ 2 | ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. 3 | If the function is passed a valid PIN string, return true, else return false. 4 | """ 5 | 6 | 7 | def validate_pin(pin): 8 | # Check if the length of the PIN is either 4 or 6. 9 | if len(pin) == 4 or len(pin) == 6: 10 | # Check if all characters in the PIN are digits 11 | return pin.isdigit() 12 | # Return False if the length is not 4 or 6. 13 | return False 14 | 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge114.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of integers, determine whether the sum of its elements is odd or even. 3 | Give your answer as a string matching "odd" or "even". 4 | If the input array is empty consider it as: [0] (array with a zero). 5 | """ 6 | 7 | 8 | def odd_or_even(arr): 9 | # Handle the case where the list is empty. 10 | if not arr: 11 | arr = [0] 12 | 13 | # Calculate the sum of the elements in the list. 14 | total_sum = sum(arr) 15 | 16 | # Determine if the sum is odd or even and return the appropriate string. 17 | if total_sum % 2 == 0: 18 | return "even" 19 | else: 20 | return "odd" 21 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge115.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function which takes two arguments and returns 3 | all numbers which are divisible by the given divisor. 4 | First argument is an array of numbers and the second is the divisor. 5 | """ 6 | 7 | 8 | def divisible_by(numbers, divisor): 9 | return [number for number in numbers if number % divisor == 0] 10 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge118.py: -------------------------------------------------------------------------------- 1 | """ 2 | As a part of this Kata, you need to create a function that when provided with a triplet, 3 | returns the index of the numerical element that lies between the other two elements. 4 | The input to the function will be an array of three distinct numbers (Haskell: a tuple). 5 | """ 6 | 7 | 8 | def gimme(input_array): 9 | # Find the middle value. 10 | middle_value = sorted(input_array)[1] 11 | 12 | # Return the index of the middle value. 13 | return input_array.index(middle_value) 14 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge121.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string str, reverse it and omit all non-alphabetic characters. 3 | """ 4 | 5 | 6 | def reverse_letter(st): 7 | # Filter only alphabetic characters from the string. 8 | filtered = ''.join(char for char in st if char.isalpha()) 9 | # Reverse the filtered string. 10 | reversed_str = filtered[::-1] 11 | return reversed_str 12 | 13 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge126.py: -------------------------------------------------------------------------------- 1 | """ 2 | This code should store "codewa.rs" as a variable called name but it's not working. Can you figure out why? 3 | """ 4 | 5 | 6 | a = "code" 7 | b = "wa.rs" 8 | name = a + b 9 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge127.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that accepts a list/array and a number n, and returns a list/array of the first n elements from the list/array. 3 | """ 4 | 5 | 6 | def take(arr, n): 7 | return arr[:n] 8 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge128.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function to split a string and convert it into an array of words. 3 | """ 4 | 5 | 6 | def string_to_array(input_string): 7 | # Check if the input string is empty. 8 | if input_string == "": 9 | return [''] 10 | # Otherwise, split the string into words. 11 | words = input_string.split() 12 | return words 13 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge129.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a simple function that takes as a parameter a date object and returns 3 | a boolean value representing whether the date is today or not. 4 | Make sure that your function does not return a false positive by only checking the day. 5 | """ 6 | 7 | from datetime import datetime 8 | 9 | 10 | def is_today(date: datetime) -> bool: 11 | today = datetime.now().date() # Get today's date. 12 | return date.date() == today # Compare the date part only. 13 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge135.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer as input, can you round it to the next (meaning, "greater than or equal") multiple of 5? 3 | Input may be any positive or negative integer (including 0). 4 | You can assume that all inputs are valid integers. 5 | """ 6 | 7 | 8 | def round_to_next5(n): 9 | return ((n + 4) // 5) * 5 10 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge138.py: -------------------------------------------------------------------------------- 1 | """ 2 | Debugging sayHello function 3 | 4 | The starship Enterprise has run into some problem when creating 5 | a program to greet everyone as they come aboard. It is your job 6 | to fix the code and get the program working again! 7 | """ 8 | 9 | 10 | def say_hello(name): 11 | # Create the greeting message. 12 | return f"Hello, {name}" 13 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge142.py: -------------------------------------------------------------------------------- 1 | """ 2 | Kids drink toddy. 3 | Teens drink coke. 4 | Young adults drink beer. 5 | Adults drink whisky. 6 | 7 | Make a function that receive age, and return what they drink. 8 | 9 | Rules: 10 | 11 | Children under 14 old. 12 | Teens under 18 old. 13 | Young under 21 old. 14 | Adults have 21 or more. 15 | """ 16 | 17 | 18 | def people_with_age_drink(age): 19 | if age < 14: 20 | return "Drink toddy!" 21 | elif age < 18: 22 | return "Drink coke!" 23 | elif age < 21: 24 | return "Drink beer!" 25 | else: 26 | return "Drink whisky!" 27 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge143.py: -------------------------------------------------------------------------------- 1 | """ 2 | You take your son to the forest to see the monkeys. 3 | You know that there are a certain number there (n), 4 | but your son is too young to just appreciate the full number, 5 | he has to start counting them from 1. 6 | 7 | As a good parent, you will sit and count with him. 8 | Given the number (n), populate an array with all numbers up to and 9 | including that number, but excluding zero. 10 | """ 11 | 12 | 13 | def monkey_count(n): 14 | return list(range(1, n + 1)) 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge144.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write function bmi that calculates body mass index (bmi = weight / height2). 3 | 4 | if bmi <= 18.5 return "Underweight" 5 | if bmi <= 25.0 return "Normal" 6 | if bmi <= 30.0 return "Overweight" 7 | if bmi > 30 return "Obese" 8 | """ 9 | 10 | 11 | def bmi(weight, height): 12 | # Calculate BMI. 13 | bmi_value = weight / (height ** 2) 14 | 15 | # Determine the BMI category. 16 | if bmi_value <= 18.5: 17 | return "Underweight" 18 | elif bmi_value <= 25.0: 19 | return "Normal" 20 | elif bmi_value <= 30.0: 21 | return "Overweight" 22 | else: 23 | return "Obese" 24 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge145.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove an exclamation mark from the end of a string. For a beginner kata, you can assume that the input data is always a string, no need to verify it. 3 | """ 4 | 5 | 6 | def remove(s): 7 | if s.endswith('!'): 8 | return s[:-1] 9 | return s 10 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge148.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that gives a personalized greeting. This function takes two parameters: name and owner. 3 | 4 | Use conditionals to return the proper message: 5 | 6 | case return 7 | name equals owner "Hello boss" 8 | otherwise "Hello guest" 9 | """ 10 | 11 | 12 | def greet(name, owner): 13 | if name == owner: 14 | return "Hello boss" 15 | else: 16 | return "Hello guest" 17 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge149.py: -------------------------------------------------------------------------------- 1 | """ 2 | You need to write a function that reverses the words in a given string. 3 | Words are always separated by a single space. 4 | As the input may have trailing spaces, you will also need to ignore unneccesary whitespace. 5 | """ 6 | 7 | 8 | def reverse(st): 9 | # Split the string into words by spaces. 10 | words = st.split() 11 | # Reverse the list of words. 12 | reversed_words = words[::-1] 13 | # Join the reversed words into a single string with spaces in between. 14 | reversed_string = ' '.join(reversed_words) 15 | return reversed_string 16 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge151.py: -------------------------------------------------------------------------------- 1 | """ 2 | This series of katas will introduce you to basics of doing geometry with computers. 3 | Write the function circleArea/CircleArea which takes in a Circle object and calculates the area of that circle. 4 | """ 5 | 6 | import math 7 | 8 | 9 | def circle_area(circle): 10 | return math.pi * (circle.radius ** 2) 11 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge153.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a combat function that takes the player's current 3 | health and the amount of damage received, and returns the 4 | player's new health. Health can't be less than 0. 5 | """ 6 | 7 | 8 | def combat(health, damage): 9 | # Calculate the new health after damage. 10 | new_health = health - damage 11 | # Ensure health doesn't drop below 0. 12 | if new_health < 0: 13 | new_health = 0 14 | return new_health 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge155.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function to find the count of the most frequent item of an array. 3 | You can assume that input is an array of integers. For an empty array return 0 4 | """ 5 | 6 | from collections import Counter 7 | 8 | 9 | def most_frequent_item_count(collection): 10 | if not collection: 11 | return 0 12 | 13 | count = Counter(collection) 14 | most_frequent = count.most_common(1)[0][1] 15 | 16 | return most_frequent 17 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge160.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this Kata we are passing a number (n) into a function. 3 | Your code will determine if the number passed is even (or not). 4 | The function needs to return either a true or false. 5 | Numbers may be positive or negative, integers or floats. 6 | Floats with decimal part non equal to zero are considered UNeven for this kata. 7 | """ 8 | 9 | 10 | def is_even(n): 11 | # Check if n is a float with a non-zero decimal part. 12 | if isinstance(n, float) and n % 1 != 0: 13 | return False 14 | 15 | # Check if n is an integer and divisible by 2. 16 | return n % 2 == 0 17 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge162.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that will calculate the number of trailing zeros in a factorial of a given number. 3 | 4 | N! = 1 * 2 * 3 * ... * N 5 | 6 | Be careful 1000! has 2568 digits... 7 | """ 8 | 9 | 10 | def zeros(n): 11 | count = 0 12 | power_of_5 = 5 13 | while n >= power_of_5: 14 | count += n // power_of_5 15 | power_of_5 *= 5 16 | return count 17 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge166.py: -------------------------------------------------------------------------------- 1 | """ 2 | Note: This kata is inspired by Convert a Number to a String! Try that one too. 3 | 4 | Description: We need a function that can transform a string into a number. What ways of achieving this do you know? 5 | 6 | Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number. 7 | """ 8 | 9 | 10 | def string_to_number(s): 11 | return int(s) 12 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge168.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function named setAlarm/set_alarm/set-alarm/setalarm (depending on language) 3 | which receives two parameters. The first parameter, employed, is true whenever you are 4 | employed and the second parameter, vacation is true whenever you are on vacation. 5 | 6 | The function should return true if you are employed and not on vacation 7 | (because these are the circumstances under which you need to set an alarm). 8 | It should return false otherwise. 9 | """ 10 | 11 | 12 | def set_alarm(employed, vacation): 13 | return employed and not vacation 14 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge172.py: -------------------------------------------------------------------------------- 1 | """ 2 | Return the Nth Even Number. 3 | 4 | The input will not be 0. 5 | """ 6 | 7 | 8 | def nth_even(n): 9 | return (n - 1) * 2 10 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge175.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function named sumDigits which takes a number as 3 | input and returns the sum of the absolute value of each 4 | of the number's decimal digits. 5 | """ 6 | 7 | 8 | def sum_digits(number): 9 | # Convert the number to its absolute value and then to a string. 10 | str_number = str(abs(number)) 11 | # Use a generator expression to sum the integer value of each digit. 12 | return sum(int(digit) for digit in str_number) 13 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge176.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define a function that removes duplicates from an array of non 3 | negative numbers and returns it as a result. 4 | The order of the sequence has to stay the same. 5 | """ 6 | 7 | 8 | def distinct(seq): 9 | seen = set() # To store unique elements. 10 | result = [] # To store the result in order. 11 | 12 | for num in seq: 13 | if num not in seen: # Check if the number is already seen. 14 | seen.add(num) # Add to seen set. 15 | result.append(num) # Append to result list. 16 | 17 | return result 18 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge177.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function which converts a binary number (given as a string) to a decimal number. 3 | """ 4 | 5 | 6 | def bin_to_decimal(inp): 7 | return int(inp, 2) 8 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge178.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define a method hello that returns "Hello, Name!" to a given name, 3 | or says Hello, World! if name is not given (or passed as an empty String). 4 | 5 | Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx). 6 | """ 7 | 8 | 9 | def hello(name=""): 10 | # Check if the name is not provided or is an empty string. 11 | if not name: 12 | return "Hello, World!" 13 | else: 14 | # Capitalize the first letter and make the rest lowercase. 15 | return f"Hello, {name.capitalize()}!" 16 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge180.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement the function generateRange which takes three arguments (start, stop, step) 3 | and returns the range of integers from start to stop (inclusive) in increments of step. 4 | """ 5 | 6 | 7 | def generate_range(start, stop, step): 8 | return list(range(start, stop + 1, step)) 9 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge182.py: -------------------------------------------------------------------------------- 1 | """ 2 | You're at the zoo... all the meerkats look weird. 3 | Something has gone terribly wrong - someone has gone 4 | and switched their heads and tails around! 5 | 6 | Save the animals by switching them back. 7 | You will be given an array which will have 8 | three values (tail, body, head). It is your job to 9 | re-arrange the array so that the animal is the right 10 | way round (head, body, tail). 11 | 12 | Same goes for all the other arrays/lists that you will 13 | get in the tests: you have to change the element positions 14 | with the same exact logics 15 | """ 16 | 17 | 18 | def fix_the_meerkat(arr): 19 | return arr[::-1] 20 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge184.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fix the function 3 | 4 | I created this function to add five to any number that was passed 5 | in to it and return the new value. It doesn't throw any errors but 6 | it returns the wrong number. 7 | 8 | Can you help me fix the function? 9 | """ 10 | 11 | 12 | def add_five(num): 13 | total = num + 5 14 | return total 15 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge188.py: -------------------------------------------------------------------------------- 1 | """ 2 | This series of katas will introduce you to basics of doing geometry with computers. 3 | Point objects have attributes x and y. 4 | Write a function calculating distance between Point a and Point b. 5 | """ 6 | 7 | import math 8 | 9 | 10 | def distance_between_points(a, b): 11 | return math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2) 12 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge191.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a method (or function, depending on the language) that converts a string to camelCase, 3 | that is, all words must have their first letter capitalized and spaces must be removed. 4 | """ 5 | 6 | 7 | def camel_case(s): 8 | # Split the string into words, capitalize each word, and join them without spaces. 9 | return ''.join(word.capitalize() for word in s.split()) 10 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge193.py: -------------------------------------------------------------------------------- 1 | """ 2 | We need a simple function that determines if a plural is needed or not. 3 | It should take a number, and return true if a plural should be used with 4 | that number or false if not. This would be useful when printing out a string 5 | such as 5 minutes, 14 apples, or 1 sun. 6 | You only need to worry about english grammar rules for this kata, where anything 7 | that isn't singular (one of something), it is plural (not one of something). 8 | All values will be positive integers or floats, or zero. 9 | """ 10 | 11 | 12 | def plural(n): 13 | return n != 1 14 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge194.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task, is to create N×N multiplication table, of size provided in parameter. 3 | """ 4 | 5 | 6 | def multiplication_table(size): 7 | return [[(i + 1) * (j + 1) for j in range(size)] for i in range(size)] 8 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge196.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, find the one that appears an odd number of times. 3 | There will always be only one integer that appears an odd number of times. 4 | """ 5 | 6 | from collections import Counter 7 | 8 | 9 | def find_it(seq): 10 | # Count occurrences of each number. 11 | counts = Counter(seq) 12 | 13 | # Find and return the number that appears an odd number of times. 14 | for num, count in counts.items(): 15 | if count % 2 != 0: 16 | return num 17 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge197.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function which converts hex number (given as a string) to a decimal number. 3 | """" 4 | 5 | 6 | def hex_to_dec(s): 7 | return int(s, 16) 8 | -------------------------------------------------------------------------------- /codewars/files-100-to-199/challenge199.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a Divisor and a Bound, Find the largest integer N, Such That. 3 | 4 | Conditions: 5 | 6 | - N is divisible by divisor; 7 | - N is less than or equal to bound; 8 | - N is greater than 0. 9 | 10 | Notes: 11 | 12 | - The parameters (divisor, bound) passed to the function are only positive values; 13 | - It's guaranteed that a divisor is Found. 14 | """ 15 | 16 | 17 | def max_multiple(divisor, bound): 18 | # Calculate the largest multiple of "divisor" that is less than or equal to "bound". 19 | return bound - (bound % divisor) 20 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge200.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a 2D (nested) list (array, vector, ...) of size m * n, your task is to find the sum of the minimum values in each row. 3 | """ 4 | 5 | 6 | def sum_of_minimums(numbers): 7 | # Use a list comprehension to find the minimum of each row and sum them. 8 | return sum(min(row) for row in numbers) 9 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge201.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grasshopper - Function syntax debugging 3 | 4 | A student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them. 5 | """ 6 | 7 | 8 | def main(verb, noun): 9 | return verb + noun 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge202.py: -------------------------------------------------------------------------------- 1 | """ 2 | You will be given an array of numbers. 3 | You have to sort the odd numbers in ascending 4 | order while leaving the even numbers at their 5 | original positions. 6 | """ 7 | 8 | 9 | def sort_array(source_array): 10 | # Extract odd numbers and sort them. 11 | sorted_odds = sorted([num for num in source_array if num % 2 != 0]) 12 | 13 | # Use an iterator for sorted_odds to place each odd number in sorted order. 14 | odd_iterator = iter(sorted_odds) 15 | result = [ 16 | next(odd_iterator) if num % 2 != 0 else num for num in source_array 17 | ] 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge204.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, capitalize the letters that occupy even indexes and odd indexes separately, 3 | and return as shown below. Index 0 will be considered even. 4 | """ 5 | 6 | 7 | def capitalize(s): 8 | even_caps = ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(s)]) 9 | odd_caps = ''.join([c.upper() if i % 2 != 0 else c for i, c in enumerate(s)]) 10 | return [even_caps, odd_caps] 11 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge205.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to determine if a string contains only unique characters. 3 | Return true if it does and false otherwise. 4 | 5 | The string may contain any of the 128 ASCII characters. 6 | Characters are case-sensitive, e.g. "a" and "A" are considered different characters. 7 | """ 8 | 9 | 10 | def has_unique_chars(string): 11 | seen_chars = set() 12 | for char in string: 13 | if char in seen_chars: 14 | return False 15 | seen_chars.add(char) 16 | return True 17 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge207.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order. 3 | """ 4 | 5 | 6 | def flatten_and_sort(array): 7 | # Flatten the array using a list comprehension. 8 | flattened = [num for sublist in array for num in sublist] 9 | # Sort the flattened list. 10 | return sorted(flattened) 11 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge208.py: -------------------------------------------------------------------------------- 1 | """ 2 | Replace all vowel to exclamation mark in the sentence. 3 | """ 4 | 5 | 6 | def replace_exclamation(st): 7 | vowels = "aeiouAEIOU" 8 | return ''.join('!' if char in vowels else char for char in st) 9 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge209.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your coworker was supposed to write a simple helper function to capitalize 3 | a string (that contains a single word) before they went on vacation. 4 | Unfortunately, they have now left and the code they gave you doesn't work. 5 | Fix the helper function they wrote so that it works as intended (i.e. it must make the first character in the string upper case). 6 | 7 | The string will always start with a letter and will never be empty. 8 | """ 9 | 10 | 11 | def capitalize_word(word: str) -> str: 12 | return word[0].upper() + word[1:] 13 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge212.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that accepts a string and a single character, 3 | and returns an integer of the count of occurrences the 2nd argument 4 | is found in the first one. 5 | 6 | If no occurrences can be found, a count of 0 should be returned. 7 | 8 | ("Hello", 'o') => 1 9 | ("Hello", 'l') => 2 10 | ("", 'z') => 0 11 | 12 | Notes: 13 | - The first argument can be an empty string; 14 | - In languages with no distinct character data type, the second argument will be a string of length 1. 15 | """ 16 | 17 | 18 | def str_count(strng, letter): 19 | return strng.count(letter) 20 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge215.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two integer arrays a, b, both of length >= 1, 3 | create a program that returns true if the sum of the 4 | squares of each element in a is strictly greater than 5 | the sum of the cubes of each element in b. 6 | """ 7 | 8 | 9 | def array_madness(a, b): 10 | # Calculate the sum of squares for array a. 11 | sum_squares = sum(x ** 2 for x in a) 12 | # Calculate the sum of cubes for array b. 13 | sum_cubes = sum(x ** 3 for x in b) 14 | # Return True if sum_squares is greater than sum_cubes. 15 | return sum_squares > sum_cubes 16 | 17 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge217.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function which takes a number and returns the corresponding ASCII char for that value. 3 | """ 4 | 5 | 6 | def get_char(c): 7 | """ 8 | Takes a number and returns the corresponding ASCII character. 9 | 10 | :param c: Integer representing the ASCII value. 11 | :return: Character corresponding to the ASCII value. 12 | """ 13 | return chr(c) 14 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge219.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a small function that returns the values of an array that are not odd. 3 | All values in the array will be integers. Return the good values in the order they are given. 4 | """ 5 | 6 | 7 | def no_odds(values): 8 | # Return list of only even values. 9 | return [value for value in values if value % 2 == 0] 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge220.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a method that takes as input a name, city, 3 | and state to welcome a person. Note that name will 4 | be an array consisting of one or more values that 5 | should be joined together with one space between each, 6 | and the length of the name array in test cases will vary. 7 | """ 8 | 9 | 10 | def say_hello(name, city, state): 11 | # Join the name array into a single string with a space between each value. 12 | full_name = ' '.join(name) 13 | # Construct the welcome message. 14 | return f"Hello, {full_name}! Welcome to {city}, {state}!" 15 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge225.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative integer b, write a function which returns an integer d 3 | such that the binary representation of b is the same as the decimal representation of d. 4 | """ 5 | 6 | 7 | def to_binary(n): 8 | # Convert the number to binary (removing the "0b" prefix) and return as an integer. 9 | return int(bin(n)[2:]) 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge226.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of positive integers (the weights of the people), 3 | return a new array / tuple of two integers (depending on your language), 4 | whereby the first one is the total weight of team 1, and the second one 5 | is the total weight of team 2. Note that the array will never be empty. 6 | """ 7 | 8 | 9 | def row_weights(array): 10 | team1 = sum(array[i] for i in range(0, len(array), 2)) # Sum of weights for team 1 (even indices). 11 | team2 = sum(array[i] for i in range(1, len(array), 2)) # Sum of weights for team 2 (odd indices). 12 | return (team1, team2) 13 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge227.py: -------------------------------------------------------------------------------- 1 | """ 2 | You will be given an array a and a value x. 3 | All you need to do is check whether the provided 4 | array contains the value, without using a loop. 5 | 6 | Array can contain numbers or strings. x can be either. 7 | Return true if the array contains the value, false if not. 8 | With strings you will need to account for case. 9 | """ 10 | 11 | 12 | def check(a, x): 13 | return x in a 14 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge2278.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove all exclamation marks from sentence but ensure a exclamation mark at the end of string. 3 | For a beginner kata, you can assume that the input data is always a non empty string, no need to verify it. 4 | """ 5 | 6 | 7 | def remove(st): 8 | return st.replace("!", "") + "!" 9 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge229.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that returns the total surface area and volume of a box as an array: [area, volume]. 3 | """ 4 | 5 | 6 | def get_size(w, h, d): 7 | # Calculate surface area. 8 | surface_area = 2 * (w * h + h * d + w * d) 9 | 10 | # Calculate volume. 11 | volume = w * h * d 12 | 13 | # Return the result as an array. 14 | return [surface_area, volume] 15 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge230.py: -------------------------------------------------------------------------------- 1 | """ 2 | In Python, there is a built-in filter function that operates similarly to JS's filter. 3 | 4 | For more information on how to use this function, visit https://docs.python.org/3/library/functions.html#filter 5 | """ 6 | 7 | 8 | def get_even_numbers(arr): 9 | return list(filter(lambda x: x % 2 == 0, arr)) 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge232.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that accepts a list/array and a number n, and returns a list/array of the first n elements from the list/array. 3 | """ 4 | 5 | 6 | def take(arr, n): 7 | return arr[:n] 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge233.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a number n, return the number of positive odd numbers below n, EASY! 3 | """ 4 | 5 | 6 | def odd_count(n): 7 | return n // 2 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge234.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this kata, your task is to create all permutations of a non-empty input string and remove duplicates, if present. 3 | 4 | Create as many "shufflings" as you can! 5 | """ 6 | 7 | from itertools import permutations as perm 8 | 9 | 10 | def permutations(s): 11 | # Use itertools.permutations to generate all permutations of the input string. 12 | all_permutations = set(perm(s)) # Use a set to automatically remove duplicates. 13 | 14 | # Convert the tuples back to strings and return as a list. 15 | return [''.join(p) for p in all_permutations] 16 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge235.py: -------------------------------------------------------------------------------- 1 | """ 2 | What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array? 3 | 4 | Your task is to write a function that takes a String and returns an Array/list with the length of each word added to each element. 5 | 6 | Note: String will have at least one element; words will always be separated by a space. 7 | """ 8 | 9 | 10 | def add_length(str_): 11 | # Split the string into words. 12 | words = str_.split() 13 | # Add the length of each word to the word and return as a list. 14 | return [f"{word} {len(word)}" for word in words] 15 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge236.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function that takes 2 integers in form of a string as an input, and outputs the sum (also as a string). 3 | 4 | Notes: 5 | - If either input is an empty string, consider it as zero; 6 | - Inputs and the expected output will never exceed the signed 32-bit integer limit (2^31 - 1). 7 | """ 8 | 9 | 10 | def sum_str(a, b): 11 | # Convert inputs to integers, treating empty strings as zero. 12 | num1 = int(a) if a else 0 13 | num2 = int(b) if b else 0 14 | # Calculate the sum and return it as a string. 15 | return str(num1 + num2) 16 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge237.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define String.prototype.toAlternatingCase (or a similar function/method such as to_alternating_case/toAlternatingCase/ToAlternatingCase in your selected language. 3 | See the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. 4 | 5 | As usual, your function/method should be pure, i.e. it should not mutate the original string. 6 | """ 7 | 8 | 9 | def to_alternating_case(string): 10 | # List comprehension to swap case for each character. 11 | return ''.join([char.lower() if char.isupper() else char.upper() for char in string]) 12 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge241.py: -------------------------------------------------------------------------------- 1 | """ 2 | There's a "3 for 2" (or "2+1" if you like) offer on mangoes. 3 | For a given quantity and price (per mango), calculate the total cost of the mangoes. 4 | """ 5 | 6 | 7 | def mango(quantity, price): 8 | # Calculate the number of mangoes you pay for. 9 | chargeable_mangoes = (quantity // 3) * 2 + (quantity % 3) 10 | # Calculate the total cost. 11 | total_cost = chargeable_mangoes * price 12 | return total_cost 13 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge242.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a class Ball. Ball objects should accept one argument for "ball type" when instantiated. 3 | 4 | If no arguments are given, ball objects should instantiate with a "ball type" of "regular." 5 | 6 | ball1 = Ball() 7 | ball2 = Ball("super") 8 | ball1.ball_type #=> "regular" 9 | ball2.ball_type #=> "super" 10 | """ 11 | 12 | 13 | class Ball: 14 | def __init__(self, ball_type="regular"): 15 | self.ball_type = ball_type 16 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge243.py: -------------------------------------------------------------------------------- 1 | """ 2 | Oh no! Timmy hasn't followed instructions very carefully and forgot how to 3 | use the new String Template feature, Help Timmy with his string template so 4 | it works as he expects! 5 | """ 6 | 7 | 8 | def build_string(*args): 9 | return "I like {}!".format(", ".join(args)) 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge246.py: -------------------------------------------------------------------------------- 1 | """ 2 | Classy Extensions 3 | 4 | Classy Extensions, this kata is mainly aimed at the new JS ES6 Update introducing extends keyword. 5 | You will be preloaded with the Animal class, so you should only edit the Cat class. 6 | 7 | Task 8 | 9 | Your task is to complete the Cat class which Extends Animal and replace the speak method to 10 | return the cats name + meows. e.g. 'Mr Whiskers meows.' 11 | """ 12 | 13 | from preloaded import Animal 14 | 15 | 16 | class Cat(Animal): 17 | def speak(self): 18 | return f"{self.name} meows." 19 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge249.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a method that accepts a list and an item, and returns true if the item belongs to the list, otherwise false. 3 | """ 4 | 5 | 6 | def include(arr, item): 7 | return item in arr 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge251.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function named combineNames/combine_names/CombineNames that accepts two parameters (first and last name). The function should return the full name. 3 | 4 | Example: With "James" as the first name and "Stevens" as the last name should return "James Stevens" 5 | """ 6 | 7 | 8 | def combine_names(first_name, last_name): 9 | return f"{first_name} {last_name}" 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge252.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task is to remove all duplicate words from a string, leaving only single (first) words entries. 3 | """ 4 | 5 | 6 | def remove_duplicate_words(s): 7 | # Split the string into words. 8 | words = s.split() 9 | # Use an ordered set to keep track of seen words. 10 | seen = set() 11 | result = [] 12 | for word in words: 13 | if word not in seen: 14 | seen.add(word) 15 | result.append(word) 16 | # Join the result back into a string. 17 | return ' '.join(result) 18 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge254.py: -------------------------------------------------------------------------------- 1 | """ 2 | The code provided is supposed replace all the dots in the specified String str with dashes, but it's not working properly. 3 | Fix the bug so we can all go home early. 4 | String str will never be null. 5 | """ 6 | 7 | import re 8 | 9 | 10 | def replace_dots(s): 11 | return re.sub(r"\.", "-", s) 12 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge256.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a function called _if which takes 3 arguments: a value bool and 2 functions (which do not take any parameters): func1 and func2. 3 | 4 | When bool is truthy, func1 should be called, otherwise call the func2. 5 | """ 6 | 7 | 8 | def _if(condition, func1, func2): 9 | if condition: 10 | func1() 11 | else: 12 | func2() 13 | 14 | 15 | # Usage example. 16 | def truthy(): 17 | print("True") 18 | 19 | 20 | def falsey(): 21 | print("False") 22 | 23 | _if(True, truthy, falsey) # prints 'True'. 24 | _if(False, truthy, falsey) # prints 'False'. 25 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge260.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove all exclamation marks from the end of sentence. 3 | """ 4 | 5 | 6 | def remove(st): 7 | return st.rstrip("!") 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge262.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a method all which takes two params: 3 | 4 | - a sequence; 5 | - a function (function pointer in C) 6 | 7 | and returns true if the function in the params returns true for every element in the sequence. 8 | Otherwise, it should return false. If the sequence is empty, it should return true, 9 | since technically nothing failed the test. 10 | """ 11 | 12 | 13 | def _all(seq, fun): 14 | return all(fun(x) for x in seq) 15 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge263.py: -------------------------------------------------------------------------------- 1 | """ 2 | Kevin is noticing his space run out! Write a function that removes the spaces from the values and returns an array showing the space decreasing. 3 | """ 4 | 5 | 6 | def spacey(array): 7 | result = [] 8 | current = "" 9 | for word in array: 10 | current += word # Concatenate the word to the current string. 11 | result.append(current) # Add the updated string to the result list. 12 | return result 13 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge267.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). 3 | All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one. 4 | """ 5 | 6 | from ipaddress import ip_address 7 | 8 | 9 | def ips_between(start: str, end: str) -> int: 10 | return int(ip_address(end)) - int(ip_address(start)) 11 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge269.py: -------------------------------------------------------------------------------- 1 | """ 2 | We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). 3 | 4 | So given a string "super", we should return a list of [2, 4]. 5 | 6 | Some examples: 7 | Mmmm => [] 8 | Super => [2,4] 9 | Apple => [1,5] 10 | YoMama => [1,2,4,6] 11 | 12 | NOTES 13 | - Vowels in this context refers to: a e i o u y (including upper case). 14 | - This is indexed from [1..n] (not zero indexed!). 15 | """ 16 | 17 | 18 | def vowel_indices(word): 19 | vowels = "aeiouyAEIOUY" 20 | return [i + 1 for i, letter in enumerate(word) if letter in vowels] 21 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge271.py: -------------------------------------------------------------------------------- 1 | """ 2 | Jack really likes his number five: the trick here is that you have to multiply each number by 5 raised to the number of digits of each numbers, so, for example: 3 | 4 | 3 --> 15 ( 3 * 5¹) 5 | 10 --> 250 ( 10 * 5²) 6 | 200 --> 25000 (200 * 5³) 7 | 0 --> 0 ( 0 * 5¹) 8 | -3 --> -15 ( -3 * 5¹) 9 | """ 10 | 11 | 12 | def multiply(n): 13 | return n * (5 ** len(str(abs(n)))) 14 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge274.py: -------------------------------------------------------------------------------- 1 | """ 2 | You can print your name on a billboard ad. Find out how much it will cost you. 3 | Each character has a default price of £30, but that can be different if you are 4 | given 2 parameters instead of 1 (always 2 for Java). 5 | You can not use multiplier "*" operator. 6 | If your name would be Jeong-Ho Aristotelis, ad would cost £600. 20 letters * 30 = 600 (Space counts as a character). 7 | """ 8 | 9 | 10 | def billboard(name, price=30): 11 | total = 0 12 | for _ in name: 13 | total += price 14 | return total 15 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge275.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string of arbitrary length with any ascii characters. Write a function to determine whether the string contains the whole word "English". 3 | The order of characters is important -- a string "abcEnglishdef" is correct but "abcnEglishsef" is not correct. 4 | Upper or lower case letter does not matter -- "eNglisH" is also correct. 5 | Return value as boolean values, true for the string to contains "English", false for it does not. 6 | """ 7 | 8 | 9 | def sp_eng(sentence): 10 | return "english" in sentence.lower() 11 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge278.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your goal is to return multiplication table for number that is always an integer from 1 to 10. 3 | """ 4 | 5 | 6 | def multi_table(number): 7 | return '\n'.join(f"{i} * {number} = {i * number}" for i in range(1, 11)) 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge279.py: -------------------------------------------------------------------------------- 1 | """ 2 | Extend the String object (JS) or create a function (Python, C#) that converts 3 | the value of the String to and from Base64 using the ASCII (UTF-8 for C#) character set. 4 | """ 5 | 6 | import base64 7 | 8 | 9 | def to_base_64(string): 10 | # Codifica para bytes, aplica Base64 e remove os '=' do final. 11 | return base64.b64encode(string.encode('ascii')).decode('ascii').rstrip('=') 12 | 13 | def from_base_64(string): 14 | # Calcula quantos '=' precisamos adicionar para o Base64 ser válido. 15 | padding = '=' * ((4 - len(string) % 4) % 4) 16 | return base64.b64decode(string + padding).decode('ascii') 17 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge280.py: -------------------------------------------------------------------------------- 1 | """ 2 | I would like to be able to pass an array with two elements to my swapValues function to swap the values. 3 | However it appears that the values aren't changing. 4 | Can you figure out what's wrong here? 5 | """ 6 | 7 | 8 | def swap_values(args): 9 | temp = args[0] 10 | args[0] = args[1] 11 | args[1] = temp 12 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge281.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a positive integer n, sums all the cubed values from 1 to n (inclusive), and returns that sum. 3 | Assume that the input n will always be a positive integer. 4 | """ 5 | 6 | 7 | def sum_cubes(n): 8 | return sum(i**3 for i in range(1, n + 1)) 9 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge282.py: -------------------------------------------------------------------------------- 1 | """ 2 | Add the value "codewars" to the websites array. 3 | After your code executes the websites array should == ["codewars"] 4 | The websites array has already been defined for you using the following code: websites = [] 5 | """ 6 | 7 | websites.append("codewars") 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge283.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Arara is an isolated tribe found in the Amazon who count in pairs. For example one to eight is as follows: 3 | 4 | 1 = anane 5 | 2 = adak 6 | 3 = adak anane 7 | 4 = adak adak 8 | 5 = adak adak anane 9 | 6 = adak adak adak 10 | 7 = adak adak adak anane 11 | 8 = adak adak adak adak 12 | 13 | Take a given number and return the Arara's equivalent. 14 | """ 15 | 16 | 17 | def count_arara(n): 18 | pairs = n // 2 19 | result = ['adak'] * pairs 20 | if n % 2 == 1: 21 | result.append('anane') 22 | return ' '.join(result) 23 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge286.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the function power_of_two/powerOfTwo (or equivalent, depending on your language) 3 | that determines if a given non-negative integer is a power of two. 4 | 5 | From the corresponding Wikipedia entry: a power of two is a number of the form 2n where n is an 6 | integer, i.e. the result of exponentiation with number two as the base and integer n as the exponent. 7 | 8 | You may assume the input is always valid. 9 | """ 10 | 11 | 12 | def power_of_two(x): 13 | return x > 0 and (x & (x - 1)) == 0 14 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge287.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove n exclamation marks in the sentence from left to right. n is positive integer. 3 | """ 4 | 5 | 6 | def remove(st, n): 7 | result = "" 8 | for char in st: 9 | if char == "!" and n > 0: 10 | n -= 1 # pula esse ponto de exclamação. 11 | else: 12 | result += char # mantém o caractere. 13 | return result 14 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge289.py: -------------------------------------------------------------------------------- 1 | """ 2 | Inspired by the development team at Vooza, write the function that accepts the name of a programmer, and 3 | returns the number of lightsabers owned by that person. 4 | 5 | The only person who owns lightsabers is Zach, by the way. He owns 18, which is an awesome number of lightsabers. Anyone else owns 0. 6 | 7 | Note: your function should have a default parameter. 8 | """ 9 | 10 | 11 | def how_many_light_sabers_do_you_own(name=""): 12 | return 18 if name == "Zach" else 0 13 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge291.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this Kata, you will implement a function count that takes an integer and returns the number of digits in factorial(n). 3 | 4 | For example, count(5) = 3, because 5! = 120, and 120 has 3 digits. 5 | 6 | Brute force is not possible. A little research will go a long way, as this is a well known series. 7 | """ 8 | 9 | import math 10 | 11 | 12 | def count(n): 13 | if n == 0 or n == 1: 14 | return 1 15 | log_sum = 0 16 | for i in range(2, n + 1): 17 | log_sum += math.log10(i) 18 | return math.floor(log_sum) + 1 19 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge292.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hey awesome programmer! 3 | 4 | You've got much data to manage and of course you use zero-based and non-negative ID's to make each data item unique! 5 | 6 | Therefore you need a method, which returns the smallest unused ID for your next new data item... 7 | 8 | Note: The given array of used IDs may be unsorted. For test reasons there may be duplicate IDs, but you don't have to find or remove them! 9 | 10 | Go on and code some pure awesomeness! 11 | """ 12 | 13 | 14 | def next_id(arr): 15 | i = 0 16 | while i in arr: 17 | i += 1 18 | return i 19 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge293.py: -------------------------------------------------------------------------------- 1 | """ 2 | The first century spans from the year 1 up to and including the year 100, the second century - from the year 101 up to and including the year 200, etc. 3 | Given a year, return the century it is in. 4 | """ 5 | 6 | 7 | def century(year): 8 | return (year + 99) // 100 9 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge294.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement String#digit? (in Java StringUtils.isDigit(String)), which should return true if given object is a single digit (0-9), false otherwise. 3 | """ 4 | 5 | 6 | def is_digit(n): 7 | return isinstance(n, str) and len(n) == 1 and n.isdigit() 8 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge296.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your task is to write function factorial. 3 | """ 4 | 5 | 6 | def factorial(n): 7 | if n == 0 or n == 1: 8 | return 1 9 | return n * factorial(n - 1) 10 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge298.py: -------------------------------------------------------------------------------- 1 | """ 2 | Extend the Math object (JS) or module (Ruby and Python) to convert degrees to radians and viceversa. 3 | The result should be rounded to two decimal points. Note that all methods of Math object are static. 4 | """ 5 | 6 | 7 | def degrees(rad): 8 | return f"{(rad * (180 / math.pi)):.2f}".rstrip('0').rstrip('.') + "deg" 9 | 10 | 11 | def radians(deg): 12 | return f"{(deg * (math.pi / 180)):.2f}".rstrip('0').rstrip('.') + "rad" 13 | 14 | # Criar um objeto "math" fake com pi e as funções. 15 | math = type('math', (), {})() 16 | math.pi = 3.141592653589793 17 | math.degrees = degrees 18 | math.radians = radians 19 | -------------------------------------------------------------------------------- /codewars/files-200-to-299/challenge299.py: -------------------------------------------------------------------------------- 1 | """ 2 | Input: Array of elements 3 | 4 | ["h","o","l","a"] 5 | 6 | Output: String with comma delimited elements of the array in th same order. 7 | 8 | "h,o,l,a" 9 | 10 | Note: if this seems too simple for you try the next level. 11 | 12 | Note2: the input data can be: boolean array, array of objects, array of string arrays, array of number arrays...😕. 13 | """ 14 | 15 | 16 | def print_array(arr): 17 | return ','.join(map(str, arr)) 18 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge304.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a method that takes one argument as name and then greets that name, capitalized and ends with an exclamation point. 3 | """ 4 | 5 | 6 | def greet(name): 7 | return f"Hello {name.capitalize()}!" 8 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge305.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321) 3 | Numbers should preserve their sign; i.e. a negative number should still be negative when reversed. 4 | """ 5 | 6 | 7 | def reverse_number(n): 8 | sign = -1 if n < 0 else 1 9 | reversed_str = str(abs(n))[::-1] 10 | return sign * int(reversed_str) 11 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge308.py: -------------------------------------------------------------------------------- 1 | """ 2 | You need to write regex that will validate a password to make sure it meets the following criteria: 3 | 4 | - At least six characters long; 5 | - Contains a lowercase letter; 6 | - Contains an uppercase letter; 7 | - Contains a digit; 8 | - Only contains alphanumeric characters (note that '_' is not alphanumeric). 9 | """ 10 | 11 | import re 12 | 13 | regex = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{6,}$' 14 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge310.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sequence of numbers, find the largest pair sum in the sequence. 3 | 4 | For example: 5 | 6 | [10, 14, 2, 23, 19] --> 42 (= 23 + 19) 7 | [99, 2, 2, 23, 19] --> 122 (= 99 + 23) 8 | 9 | Input sequence contains minimum two elements and every element is an integer. 10 | """ 11 | 12 | 13 | def largest_pair_sum(numbers): 14 | numbers.sort(reverse=True) 15 | return numbers[0] + numbers[1] 16 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge322.py: -------------------------------------------------------------------------------- 1 | """ 2 | Assume "#" is like a backspace in string. This means that string "a#bc#d" actually is "bd". 3 | Your task is to process a string with "#" symbols. 4 | """ 5 | 6 | 7 | def clean_string(s): 8 | stack = [] 9 | for char in s: 10 | if char == '#': 11 | if stack: 12 | stack.pop() 13 | else: 14 | stack.append(char) 15 | return ''.join(stack) 16 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge324.py: -------------------------------------------------------------------------------- 1 | """ 2 | Each number should be formatted that it is rounded to two decimal places. 3 | You don't need to check whether the input is a valid number because only valid numbers are used in the tests. 4 | """ 5 | 6 | 7 | def two_decimal_places(n): 8 | return round(n, 2) 9 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge328.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of numbers, check if any of the numbers are the character codes for lower case vowels (a, e, i, o, u). 3 | 4 | If they are, change the array value to a string of that vowel. 5 | """ 6 | 7 | 8 | def is_vow(inp): 9 | return [chr(i) if chr(i) in 'aeiou' else i for i in inp] 10 | -------------------------------------------------------------------------------- /codewars/files-300-to-399/challenge330.py: -------------------------------------------------------------------------------- 1 | """ 2 | Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads. 3 | Implement a function returning the number of red beads. If there are less than 2 blue beads return 0. 4 | """ 5 | 6 | 7 | def count_red_beads(n): 8 | if n < 2: 9 | return 0 10 | return (n - 1) * 2 11 | -------------------------------------------------------------------------------- /curso-em-video/aula04/aula04desa01.py: -------------------------------------------------------------------------------- 1 | # Crie um script Python que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas de acordo com o 2 | # valor digitado. 3 | 4 | nome = str(input('Qual é o seu nome? ')) 5 | print('É um prazer te conhecer, {}!'.format(nome)) 6 | -------------------------------------------------------------------------------- /curso-em-video/aula04/aula04desa02.py: -------------------------------------------------------------------------------- 1 | # Crie um script Python que leia o dia, mês e o ano de nascimento de uma pessoa e mostre uma mensagem com 2 | # a data formatada. 3 | 4 | dia = int(input('Digite o dia do seu aniversário: ')) 5 | mes = int(input('Digite o mês do seu aniversário: ')) 6 | ano = int(input('Digite o ano do seu aniversário: ')) 7 | print('Você nasceu no dia', dia, 'de', mes, 'de', ano) 8 | -------------------------------------------------------------------------------- /curso-em-video/aula04/aula04desa03.py: -------------------------------------------------------------------------------- 1 | # Crie um script Python que leia dois números e tente mostrar a soma entre eles. 2 | 3 | num1 = int(input('Digite o 1º número: ')) 4 | num2 = int(input('Digite o 2º número: ')) 5 | s = num1 + num2 6 | print('A soma é: {}'.format(s)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula06/aula06desa01.py: -------------------------------------------------------------------------------- 1 | # Crie um script Python que leia dois números e tente mostrar a soma entre eles. 2 | 3 | num1 = int(input('Digite o 1º número: ')) 4 | num2 = int(input('Digite o 2º número: ')) 5 | s = num1 + num2 6 | print('A soma entre {} e {} vale {}'.format(num1, num2, s)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula06/aula06desa02.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as possíveis informações 2 | # sobre ele. 3 | 4 | x = input('Digite algo: ') 5 | print('O tipo primitivo desse valor é: {}'.format(type(x))) 6 | print('Só tem espaços? {}'.format(x.isspace())) 7 | print('É um número? {}'.format(x.isnumeric())) 8 | print('É alfabético? {}'.format(x.isalpha())) 9 | print('É alfanumérico {}?'.format(x.isalnum())) 10 | print('Está em maiúsculo(a)? {}'.format(x.isupper())) 11 | print('Está em minúsculo(a)? {}'.format(x.islower())) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa01.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia um número e mostre na tela o seu antecessor e o seu sucessor. 2 | 3 | num = int(input('Digite um número inteiro qualquer: ')) 4 | print('O seu antecessor é: {}\nO seu sucessor é: {}'.format((num - 1), (num + 1))) 5 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa02.py: -------------------------------------------------------------------------------- 1 | # Faça um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. 2 | 3 | num = int(input('Digite um número inteiro qualquer: ')) 4 | print('O dobro de {} é: {} \nO triplo é: {} \nA raiz quadrada é: {:.2f}'.format(num, (num*2), (num*3), (num**(1/2)))) 5 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa03.py: -------------------------------------------------------------------------------- 1 | # Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. 2 | 3 | nota1 = float(input('Digite a nota 1: ')) 4 | nota2 = float(input('Digite a nota 2: ')) 5 | media = (nota1+nota2)/2 6 | print('A sua média é: {:.1f}'.format(media)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa04.py: -------------------------------------------------------------------------------- 1 | # Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros 2 | 3 | valor_metro = float(input('Digite um valor em metros: ')) 4 | print('{} metro(s) vale(m): {:.0f} centímetros e {:.0f} milímetros'.format(valor_metro, valor_metro*100, valor_metro*1000)) 5 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa06.py: -------------------------------------------------------------------------------- 1 | # Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode 2 | # comprar. Considere: US$1,00 = R$3,27. 3 | 4 | din_cart = float(input('Informe quanto de dinheiro você tem na carteira: R$')) 5 | cotacao_dolar = float(input('Informe a cotação do dólar hoje: US$')) 6 | conversao = din_cart / cotacao_dolar 7 | print('*' * 27) 8 | print('Você pode comprar US${:.2f}'.format(conversao)) 9 | print('*' * 27) 10 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa07.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta 2 | # necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. 3 | 4 | largura = float(input('Informe o valor da largura da parede (em m): ')) 5 | altura = float(input('Informe o valor da altura da parede (em m): ')) 6 | area = largura * altura 7 | gasto_tinta = area / 2 8 | print('A parede de {:.2f}x{:.2f} tem área igual a: {:.2f} m2'.format(largura, altura, area)) 9 | print('Você precisará de {:.1f} litros de tinta para pintar essa parede.'.format(gasto_tinta)) 10 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa08.py: -------------------------------------------------------------------------------- 1 | # Faça um algoritmo que leia o preço de um produto e mostre o seu novo preço, com 5% de desconto. 2 | 3 | valor_inic_prod = float(input('Informe o valor do produto: R$')) 4 | desconto = valor_inic_prod * 0.05 5 | valor_fin_prod = valor_inic_prod - desconto 6 | print('O valor do produto com 5% de desconto é: R${:.2f}'.format(valor_fin_prod)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07desa09.py: -------------------------------------------------------------------------------- 1 | # Faça um algoritmo que leia o salário de um funcionárioe mostre seu novo salário, com 15% de aumento. 2 | 3 | salario = float(input('Informe o valor do seu salário: R$')) 4 | aumento = salario * 0.15 5 | novo_salario = salario + aumento 6 | print('O seu novo salário, com um aumento de 15% é: R${:.2f}'.format(novo_salario)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula07/aula07exemplo01.py: -------------------------------------------------------------------------------- 1 | nome = input('Olá, qual é o seu nome? ') 2 | print('Muito prazer {}!'.format(nome)) 3 | print('Muito prazer {:20}!'.format(nome)) 4 | print('Muito prazer {:>20}!'.format(nome)) 5 | print('Muito prazer {:<20}!'.format(nome)) 6 | print('Muito prazer {:^20}!'.format(nome)) 7 | print('Muito prazer {:@^20}!'.format(nome)) 8 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa01.py: -------------------------------------------------------------------------------- 1 | # Crie um programa que leia um número real qualquer e mostre na tela a sua porção inteira. 2 | 3 | from math import trunc 4 | 5 | num = float(input('Digite um número real qualquer: ')) 6 | print('A porção inteira do número {} é: {}'.format(num, trunc(num))) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa02.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e 2 | # mostre o comprimento da hipotenusa. 3 | 4 | from math import hypot 5 | cat_oposto = float(input('Digite o valor do cateto oposto: ')) 6 | cat_adjacente = float(input('Digite o valor do cateto adjacente: ')) 7 | hipotenusa = hypot(cat_oposto, cat_adjacente) 8 | print('O valor da hipotenusa é: {:.2f}'.format(hipotenusa)) 9 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa03.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. 2 | 3 | from math import sin, cos, tan, radians 4 | angulo = float(input('Informe um ângulo qualquer: ')) 5 | seno = sin(radians(angulo)) 6 | cosseno = cos(radians(angulo)) 7 | tangente = tan(radians(angulo)) 8 | print('O ângulo {}º, possui:\nSeno igual a: {:.2f} radianos\nCosseno igual a: {:.2f} radianos\n' 9 | 'Tangente igual a: {:.2f} radianos'.format(angulo, seno, cosseno, tangente)) 10 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa04.py: -------------------------------------------------------------------------------- 1 | # Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o 2 | # nome deles e escrevendo o nome do escolhido. 3 | 4 | from random import choice 5 | 6 | aluno1 = str(input('Digite o nome do aluno 1: ')) 7 | aluno2 = str(input('Digite o nome do aluno 2: ')) 8 | aluno3 = str(input('Digite o nome do aluno 3: ')) 9 | aluno4 = str(input('Digite o nome do aluno 4: ')) 10 | sorteio = [aluno1, aluno2, aluno3, aluno4] 11 | print('O aluno escolhido foi: {}'.format(choice(sorteio))) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa05.py: -------------------------------------------------------------------------------- 1 | # Um professor quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro 2 | # alunos e mostre a ordem sorteada. 3 | 4 | from random import shuffle 5 | a1 = str(input('Informe o nome do aluno 1: ')) 6 | a2 = str(input('Informe o nome do aluno 2: ')) 7 | a3 = str(input('Informe o nome do aluno 3: ')) 8 | a4 = str(input('Informe o nome do aluno 4: ')) 9 | sorteio = [a1, a2, a3, a4] 10 | shuffle(sorteio) 11 | print('A ordem de apresentação dos trabalhos é a seguinte: {}'.format(sorteio)) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula08/aula08desa06.py: -------------------------------------------------------------------------------- 1 | # Faça um programa em Python que abra e reproduza o áudio de um arquivo mp3. 2 | 3 | import pygame 4 | pygame.mixer.init() 5 | pygame.init() 6 | pygame.mixer.music.load('olhos.mp3') 7 | pygame.mixer.music.play() 8 | pygame.event.wait() 9 | -------------------------------------------------------------------------------- /curso-em-video/aula08/olhos.mp3: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09desa02.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia o número de 0 a 9999 e mostre na tela cada um dos dígitos separados. 2 | # Exemplo: Digite o número: 1834 3 | # Unidade: 4 4 | # Dezena: 3 5 | # Centena: 8 6 | # Milhar: 1 7 | 8 | num = int(input('Informe um número inteiro entre 0 e 9999: ')) 9 | u = num // 1 % 10 10 | d = num // 10 % 10 11 | c = num // 100 % 10 12 | m = num // 1000 % 10 13 | print('Analisando o número {}, ele possui: '.format(num)) 14 | print('Milhar: {}'.format(m)) 15 | print('Centena: {}'.format(c)) 16 | print('Dezena: {}'.format(d)) 17 | print('Unidade: {}'.format(u)) 18 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09desa03.py: -------------------------------------------------------------------------------- 1 | # Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO". 2 | 3 | # A função strip serve para eliminar os espaços (antes ou depois da digitação). 4 | # A função upper serve troca tudo para maiúsculo. 5 | cidade = str(input('Digite o nome de uma cidade: ')).strip() 6 | print(cidade[0:5].upper() == 'SANTO') 7 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09desa04.py: -------------------------------------------------------------------------------- 1 | # Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome. 2 | 3 | # O operador "in" está procurando a palavra Silva dentro do nome digitado. 4 | nome = str(input('Digite o seu nome completo: ')).strip() 5 | print('O seu nome tem "SILVA"? {}'.format('SILVA' in nome.upper())) 6 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09desa05.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia uma frase pelo teclado e mostre: 2 | # Quantas vezes aparece a letra "A". 3 | # Em que posição ela apare a primeira vez. 4 | # Em que posição ela aparece a última vez. 5 | 6 | frase = str(input('Digite uma frase qualquer: ')).strip().upper() 7 | print('A letra A aparece {} vezes na frase digitada.'.format(frase.count('A'))) 8 | print('A letra A aparece pela primeira vez na posição {}'.format(frase.find('A')+1)) 9 | print('A letra A aparece pela última vez na posição {}'.format(frase.rfind('A')+1)) 10 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09desa06.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o 2 | # primeiro e o último nome separadamente. 3 | # Exemplo: 4 | # Nome: Ana Maria de Souza 5 | # Primeiro nome: Ana 6 | # Último nome: Souza 7 | 8 | nome_completo = str(input('Digite o seu nome completo: ')).strip() 9 | print('Muito prazer {}!!!'.format(nome_completo)) 10 | nome = nome_completo.split() 11 | print('O seu 1º nome é: {}'.format(nome[0])) 12 | print('O seu último nome é: {}'.format(nome[len(nome)-1])) 13 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09exemplo01.py: -------------------------------------------------------------------------------- 1 | frase = 'Curso em Vídeo Python' 2 | print(frase) 3 | print(frase[3]) 4 | print(frase[3:13]) 5 | print(frase[:13]) 6 | print(frase[13:]) 7 | print(frase[1:15]) 8 | print(frase[1:15:2]) 9 | print(frase[1::2]) 10 | print(frase[::2]) 11 | print(frase.count('o')) 12 | print(frase.upper()) 13 | print(frase.lower()) 14 | print(len(frase)) 15 | print(frase.replace('Python', 'Android')) 16 | print(frase.split()) 17 | -------------------------------------------------------------------------------- /curso-em-video/aula09/aula09exemplo02.py: -------------------------------------------------------------------------------- 1 | # Copiar, colar e imprimir textos longos. 2 | 3 | print("""Tropas russas se aproximam de Kiev neste domingo (6), em um avanço marcado por confrontos, bombardeios 4 | e mortes de civis. A cidade de Irpin, a apenas 25 quilômetros de distância da capital ucraniana e único ponto de 5 | evacuação de civis a oeste de Kiev, está sob intenso bombardeio. Ao menos oito civis morreram com os ataques.""") 6 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa01.py: -------------------------------------------------------------------------------- 1 | # Escreva um programa que faça o computador "pensar" num número inteiro entre 0 e 5 e peça para o usuário tentar 2 | # descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou 3 | # perdeu. 4 | 5 | from random import randint 6 | from time import sleep 7 | computador = randint(0, 5) 8 | num_digitado = int(input('Tente advinhar um número entre 0 e 5 que eu estou pensando, digite ele: ')) 9 | print('Processando...') 10 | sleep(2) 11 | if num_digitado == computador: 12 | print('Você venceu!!!') 13 | else: 14 | print('Você perdeu!!!') 15 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa02.py: -------------------------------------------------------------------------------- 1 | # Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80 km/h, mostre uma mensagem dizendo que ele 2 | # foi multado. A multa vai custar R$7,00 por cada km acima do limite. 3 | 4 | velocidade = int(input('Digite a velocidade do carro (em km/h): ')) 5 | multa = (velocidade - 80) * 7 6 | if velocidade > 80: 7 | print('Você foi multado!!! A sua multa vai custar R${:.2f}'.format(multa)) 8 | else: 9 | print('Parabéns, você está dentro do limite de velocidade!!!') 10 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa03.py: -------------------------------------------------------------------------------- 1 | # Crie um programa que leia um número inteiro e mostre na tela se ele é par ou ímpar. 2 | 3 | num = int(input('Digite um número inteiro qualquer: ')) 4 | if num % 2 == 0: 5 | print('O número digitado é par!!!') 6 | else: 7 | print('O número digitado é impar!!!') 8 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa04.py: -------------------------------------------------------------------------------- 1 | # Desenvolva um programa que pergunte a distância de uma viagem em km. Calcule o preço da passagem, cobrando R$0,50 por 2 | # km para viagens de até 200 km e R$0,45 para viagens mais longas. 3 | 4 | import time 5 | distancia = int(input('Qual é a distância da viagem? (em km): ')) 6 | print('Processando...') 7 | time.sleep(3) 8 | if distancia <= 200: 9 | print('O valor da sua passagem será de: R${:.2f}'.format(distancia * 0.5)) 10 | else: 11 | print('O valor da sua passagem será de: R${:.2f}'.format(distancia * 0.45)) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa05.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia um ano qualquer e mostre se ele é bissexto. 2 | 3 | from datetime import date 4 | ano = int(input('Digite um ano qualquer. Se quiser analisar o ano atual, digite 0: ')) 5 | if ano == 0: 6 | ano = date.today().year 7 | if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0: 8 | print('A ano {} é bissexto'.format(ano)) 9 | else: 10 | print('O ano {} não é bissexto'.format(ano)) 11 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa06.py: -------------------------------------------------------------------------------- 1 | # Faça um programa que leia três números e mostre qual é o maior e qual é o menor. 2 | 3 | a = float(input('Digite um 1º número qualquer: ')) 4 | b = float(input('Digite um 2º número qualquer: ')) 5 | c = float(input('Digite um 3º número qualquer: ')) 6 | menor = a 7 | if b < a and b < c: 8 | menor = b 9 | if c < a and c < b: 10 | menor = c 11 | maior = a 12 | if b > a and b > c: 13 | maior = b 14 | if c > a and c > b: 15 | maior = c 16 | print('O menor valor digitado foi {}'.format(menor)) 17 | print('O maior valor digitado foi {}'.format(maior)) 18 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa07.py: -------------------------------------------------------------------------------- 1 | # Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários 2 | # superiores a R$1.250,00, calcule um aumento de 10%. Para os iguais ou inferiores, o aumento é de 15%. 3 | 4 | salario = float(input('Informe o valor do seu salário R$')) 5 | if salario <= 1250: 6 | print('O valor do seu aumento será de R${:.2f}'.format(salario * 0.15)) 7 | else: 8 | print('O valor do seu aumento será de R${:.2f}'.format(salario * 0.10)) 9 | -------------------------------------------------------------------------------- /curso-em-video/aula10/aula10desa08.py: -------------------------------------------------------------------------------- 1 | # Desenvolva um programa que leia o comprimento de 3 retas e diga ao usuário se elas podem ou não formar um triângulo. 2 | 3 | print('=' * 24) 4 | print('Analisador de triângulos') 5 | print('=' * 24) 6 | reta1 = float(input('Informe o comprimento da reta 1: ')) 7 | reta2 = float(input('Informe o comprimento da reta 2: ')) 8 | reta3 = float(input('Informe o comprimento da reta 3: ')) 9 | if reta1 < reta2 + reta3 and reta2 < reta1 + reta3 and reta3 < reta1 + reta2: 10 | print('Esses 3 comprimentos de reta formam um triângulo') 11 | else: 12 | print('Esses 3 comprimentos de reta não formam um triângulo') 13 | -------------------------------------------------------------------------------- /curso-em-video/aula12/aula12desa03.py: -------------------------------------------------------------------------------- 1 | """Escreva um programa que leia 2 números inteiros e compare-os, mostrando uma mensagem na tela: 2 | — O primeiro valor é maior; 3 | — O segundo valor é maior; 4 | — Não existe valor maior, os dois são iguais.""" 5 | 6 | n1 = int(input('Informe um número inteiro qualquer: ')) 7 | n2 = int(input('Informe um outro número inteiro qualquer: ')) 8 | if n1 > n2: 9 | print('O primeiro número é maior') 10 | elif n1 < n2: 11 | print('O segundo número é maior') 12 | else: 13 | print('Não existe valor maior, os dois são iguais') 14 | -------------------------------------------------------------------------------- /curso-em-video/aula12/aula12desa05.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a 2 | média atingida: 3 | — Média abaixo de 5.0: Reprovado; 4 | — Média entre 5.0 e 6.9. Recuperação; 5 | — Média 7.0 ou superior. Aprovado.""" 6 | 7 | nota1 = float(input('Informe a nota 1: ')) 8 | nota2 = float(input('Informe a nota 2: ')) 9 | media = (nota1 + nota2) / 2 10 | print('A sua média é: {:.1f}'.format(media)) 11 | if media < 5: 12 | print('Você está reprovado.') 13 | elif 5 <= media <= 6.9: 14 | print('Você está em recuperação.') 15 | else: 16 | print('Você está aprovado.') 17 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa01.py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que mostre uma contagem regressiva na tela para estouro de fogos de artifício, indo de 10 até 0, 2 | com uma pausa de 1 segundo entre eles.""" 3 | 4 | import time 5 | for c in range(10, -1, -1): 6 | time.sleep(1) 7 | print(c) 8 | print('Feliz Ano Novo! 🎇🎇🎇') 9 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa02.py: -------------------------------------------------------------------------------- 1 | """"Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.""" 2 | 3 | for c in range(0, 51, 2): 4 | print(c, end=' ') 5 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa03.py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que calcule a soma entre todos os números ímpares que são múltiplos de 3 que se encontram no 2 | intervalo de 1 até 500.""" 3 | 4 | soma = 0 5 | valores = 0 6 | for c in range(1, 500, 2): 7 | if (c % 3) == 0: 8 | soma += c 9 | valores += 1 10 | print('A soma dos {} valores solicitados é igual a: {}.'.format(valores, soma)) 11 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa04.py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que mostre a tabuada de um número escolhido pelo usuário.""" 2 | 3 | n = int(input('Escolha um número inteiro qualquer: ')) 4 | print('Tabuada do {}.'.format(n)) 5 | for c in range(0,11): 6 | print('{} * {} = {}'.format(n, c, n*c)) 7 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa05.py: -------------------------------------------------------------------------------- 1 | """"Desenvolva um programa que leia 6 números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor 2 | digitado for ímpar, desconsidere-o.""" 3 | 4 | soma = 0 5 | for c in range(1, 7): 6 | n = int(input('Digite o {}º valor: '.format(c))) 7 | if n % 2 == 0: 8 | soma += n 9 | print('Obs.: Os números digitados que são ímpares foram desconsiderados.') 10 | print('A soma dos números pares digitados é: {}.'.format(soma)) 11 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa06.py: -------------------------------------------------------------------------------- 1 | """"Desenvolva um programa que leia o primeiro termo e a razão da uma PA. No final, mostre os 10 primeiros termos dessa 2 | progressão.""" 3 | 4 | primeiro_termo = int(input('Informe o 1º termo da PA: ')) 5 | razao = int(input('Informe a razão da PA: ')) 6 | decimo_termo = primeiro_termo + (10 - 1) * razao 7 | print('Os 10 primeiros termos da PA de razão {} é igual a: '.format(razao), end='') 8 | for c in range(primeiro_termo, decimo_termo + razao, razao): 9 | print('{}'.format(c), end= ' - ') 10 | print('Fim!') 11 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa07.py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.""" 2 | 3 | n = int(input('Digite um número inteiro qualquer: ')) 4 | total = 0 5 | for c in range(1, n + 1): 6 | if n % c == 0: 7 | print('\033[33m', end=' ') 8 | total += 1 9 | else: 10 | print('\033[31m', end=' ') 11 | print('{}'.format(c), end=' ') 12 | print('\n\33[mO número {} foi divisível {} vezes.'.format(n, total)) 13 | if total == 2: 14 | print('O número digitado é primo.') 15 | else: 16 | print('O número digitado não é primo.') 17 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa09.py: -------------------------------------------------------------------------------- 1 | """"Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram 2 | a maioridade e quantas já são maiores.""" 3 | 4 | from datetime import date 5 | maior21 = 0 6 | menor21 = 0 7 | for pessoa in range(1, 8): 8 | ano_nasc = int(input('Informe o ano de nascimento da pessoa {}: '.format(pessoa))) 9 | if (date.today().year - ano_nasc) > 21: 10 | maior21 += 1 11 | else: 12 | menor21 += 1 13 | print('{} pessoas já atingiram a maior idade e {} pessoas ainda não atingiram.'.format(maior21, menor21)) 14 | -------------------------------------------------------------------------------- /curso-em-video/aula13/aula13desa10.py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que leia o peso de 5 pessoas. No final, mostre qual foi o maior e o menor peso lidos.""" 2 | 3 | pesos = [] 4 | for pessoas in range(1,6): 5 | peso = float(input('Informe o peso da pessoa {} (em kg): '.format(pessoas))) 6 | pesos.append(peso) 7 | print('O maior peso é: {} kg e o menor peso é: {} kg.'.format(max(pesos), min(pesos))) 8 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa01(forma01).py: -------------------------------------------------------------------------------- 1 | """Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores "M" ou "F". Caso esteja errado, peça a 2 | digitação novamente até ter um valor correto.""" 3 | 4 | while True: 5 | sexo = str(input('Informe o sexo da pessoa: ')).strip().upper() 6 | if sexo == 'M' or sexo == 'F': 7 | print('Sexo {} informado com sucesso!'.format(sexo)) 8 | break 9 | else: 10 | print('Valor inválido! Digite novamente.') 11 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa01(forma02).py: -------------------------------------------------------------------------------- 1 | """Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores "M" ou "F". Caso esteja errado, peça a 2 | digitação novamente até ter um valor correto.""" 3 | 4 | sexo = str(input('Informe o sexo da pessoa: ')).strip().upper()[0] # Esse "[0]" serve para pegar a 1ª letra da string digitada, se houver (foi utilizado o fatiamento). 5 | while sexo not in 'MF': 6 | sexo = str(input('Dados inválidos! Informe o sexo da pessoa: ')).strip().upper()[0] 7 | print('Sexo {} informado com sucesso!'.format(sexo)) 8 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa04(forma01).py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que leia um número qualquer e mostre o seu fatorial. 2 | Exemplo: 5!=5*4*3*2*1 = 120.""" 3 | 4 | n = int(input('Informe um número inteiro qualquer para calcular o seu Fatorial: ')) 5 | contador = n 6 | # Quando eu for iniciar uma soma ou subtração, sempre inicio com "0". Na multiplicação, tenho que começar com 1, pois se multiplicar por "0", o resultado é igual a "0". 7 | f = 1 8 | print('{}! = '.format(n), end='') 9 | while contador > 0: 10 | print('{}'.format(contador), end='') 11 | print(' x ' if contador > 1 else ' = ', end='') 12 | f *= contador 13 | contador -= 1 14 | print(f) 15 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa04(forma02).py: -------------------------------------------------------------------------------- 1 | """"Faça um programa que leia um número qualquer e mostre o seu fatorial. 2 | Exemplo: 5!=5*4*3*2*1 = 120.""" 3 | 4 | from math import factorial 5 | n = int(input('Informe um número inteiro qualquer para calcular o seu Fatorial: ')) 6 | contador = n 7 | print('{}! = '.format(n), end='') 8 | while contador > 0: 9 | print('{}'.format(contador), end='') 10 | print(' x ' if contador > 1 else ' = ', end='') 11 | contador -= 1 12 | print(factorial(n)) 13 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa05.py: -------------------------------------------------------------------------------- 1 | """Faça um programa que leia o 1º termo e a razão de um PA, mostrando os 10 primeiros termos.""" 2 | 3 | primeiro_termo = int(input('Informe o 1º termo da PA: ')) 4 | razao = int(input('Informe a razão da PA: ')) 5 | termo = primeiro_termo 6 | contador = 1 7 | while contador <= 10: 8 | print('{} → '.format(termo), end='') 9 | termo += razao 10 | contador += 1 11 | print('Fim') 12 | -------------------------------------------------------------------------------- /curso-em-video/aula14/aula14desa08(forma01).py: -------------------------------------------------------------------------------- 1 | """Crie um programa que leia vários números inteiros pelo teclado. O programa vai parar quando o usuário digitar o 2 | valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles, 3 | desconsiderando a flag.""" 4 | 5 | n = 0 6 | contador = 0 7 | flag = 999 8 | soma = [] 9 | while n != flag: 10 | n = int(input('Digite um número inteiro qualquer (para finalizar, digite 999): ')) 11 | contador += 1 12 | soma.append(n) 13 | print('Foram digitados {} números.'.format(contador - 1)) 14 | print('A soma dos números digitados é igual a: {}.'.format(sum(soma)-flag)) 15 | -------------------------------------------------------------------------------- /curso-em-video/aula15/aula15desa01.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o 2 | valor "999", que é a condição de parada. No final, mostre quanto números foram digitados e qual foi a soma entre eles, 3 | desconsiderando a flag.""" 4 | 5 | soma = contador = 0 6 | while True: 7 | n = int(input('Digite um número inteiro qualquer. Digite [999] para sair: ')) 8 | if n == 999: 9 | break 10 | soma += n 11 | contador += 1 12 | print(f'Você digitou {contador} números. A soma entre eles é: {soma}.') 13 | -------------------------------------------------------------------------------- /curso-em-video/aula15/aula15exemplos.py: -------------------------------------------------------------------------------- 1 | # Aplicações do comando "break"" e das "fstrings" do Python. 2 | 3 | soma = [] 4 | while True: 5 | n = int(input('Digite um número inteiro qualquer: ')) 6 | soma.append(n) 7 | if n == 0: 8 | break 9 | print(f'A soma dos número digitados é igual a: {sum(soma)}.') # esse "f" substitui o comando ".format". 10 | 11 | nome = 'Valmir' 12 | sobrenome = 'Moro Conque Filho' 13 | idade = 42 14 | salario = 987.454 15 | print(f'{nome} {sobrenome} tem {idade} anos e ganha R${salario:.2f}.') 16 | -------------------------------------------------------------------------------- /curso-em-video/aula16/aula16desa01.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. 2 | O seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.""" 3 | 4 | numeros = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 5 | 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte') 6 | while True: 7 | n = int(input('Digite um número inteiro entre 0 e 20: ')) 8 | if 0 <= n <= 20: 9 | break 10 | print('Valor inválido!') 11 | print(f'Você digitou o número {numeros[n]}.') 12 | -------------------------------------------------------------------------------- /curso-em-video/aula16/aula16desa03.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de 2 | números gerados e também indique o menor e o maior valor que estão na tupla.""" 3 | 4 | from random import randint 5 | n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) 6 | print(f'Os número gerados foram: {n}.') 7 | print(f'O maior número da tupla é: {max(n)}.') 8 | print(f'O menor número da tupla é: {min(n)}.') 9 | -------------------------------------------------------------------------------- /curso-em-video/aula16/aula16desa05(forma02).py: -------------------------------------------------------------------------------- 1 | """Crie um programa que tenha uma tupla única com nomes de produtos e os seus respectivos preços na sequência. No final, 2 | mostre uma listagem de preços, organizando os dados em forma tabular.""" 3 | 4 | produtos = ('Calça', 123.52, 'Camisa', 114.32, 'Camiseta', 80.62, 'Tênis', 221.52, 'Blusa', 240.42) 5 | print('≈' * 39) 6 | print(f'{"LISTA DE PREÇOS":^40}') 7 | print('≈' * 39) 8 | for pos in range(0, len(produtos)): 9 | if pos % 2 == 0: 10 | print(f'{produtos[pos]:.<30}', end='') 11 | else: 12 | print(f'R${produtos[pos]:>7.2f}') 13 | print('≈' * 39) 14 | -------------------------------------------------------------------------------- /curso-em-video/aula16/aula16desa06.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para 2 | cada palavra, quais são as suas vogais.""" 3 | 4 | palavras = ('abacate', 'melancia', 'abacaxi', 'pera', 'melao', 'uva', 'pessego', 'kiwi', 'banana', 'morango', 'mamao') 5 | for palavra in palavras: 6 | print(f'\nNa palavra {palavra.upper()} temos as seguintes vogais: ', end='') 7 | for letra in palavra: 8 | if letra.lower() in 'aeiou': 9 | print(letra, end=' ') 10 | -------------------------------------------------------------------------------- /curso-em-video/aula17/aula17desa03.py: -------------------------------------------------------------------------------- 1 | """Crie um programa onde o usuário possa digitar 5 valores numéricos e cadastre-os em uma lista, já na posição correta 2 | (sem usar o comando "sort()"). No final, mostre a lista ordenada na tela.""" 3 | 4 | numeros = [] 5 | for n in range(0, 5): 6 | numero = int(input('Digite um número: ')) 7 | if n == 0 or numero > numeros[-1]: 8 | numeros.append(numero) 9 | else: 10 | pos = 0 11 | while pos < len(numeros): 12 | if numero <= numeros[pos]: 13 | numeros.insert(pos, numero) 14 | break 15 | pos += 1 16 | print(f'Os valores digitados foram: {numeros}') 17 | -------------------------------------------------------------------------------- /curso-em-video/aula18/aula18desa02.py: -------------------------------------------------------------------------------- 1 | """Crie um programa onde o usuário possa digitar 7 valores numéricos e cadastre-os em uma única lista que mantenha 2 | separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.""" 3 | 4 | valores = [[], []] 5 | for v in range(1, 8): 6 | valor = int(input(f'Digite o {v}º valor: ')) 7 | if valor % 2 == 0: 8 | valores[0].append(valor) 9 | else: 10 | valores[1].append(valor) 11 | print(f'Os valores pares são: {sorted(valores[0])}') 12 | print(f'OS valores ímpares são: {sorted(valores[1])}') 13 | -------------------------------------------------------------------------------- /curso-em-video/aula18/aula18desa03.py: -------------------------------------------------------------------------------- 1 | """Crie um programa que gere uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a 2 | matriz na tela com a formatação completa.""" 3 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] 5 | for l in range(0, 3): 6 | for c in range(0, 3): 7 | matriz[l][c] = int(input(f'Digite um valor para a posição [{l+1},{c+1}]: ')) 8 | for l in range(0, 3): 9 | for c in range(0, 3): 10 | print(f'[{matriz[l][c]:^5}]', end='') 11 | print() 12 | -------------------------------------------------------------------------------- /curso-em-video/aula18/aula18exemplos02.py: -------------------------------------------------------------------------------- 1 | # Aplicações de variáveis compostas em Python. 2 | # Listas em listas. 3 | 4 | galera = list() 5 | dado = list() 6 | for c in range(0, 3): 7 | dado.append(str(input('Nome: '))) 8 | dado.append(int(input('Idade: '))) 9 | galera.append(dado[:]) 10 | dado.clear() 11 | print(galera) 12 | for p in galera: 13 | if p[1] >= 21: # Está a verificar na posição 1 (idade) quem é maior de 21. 14 | print(p[0]) 15 | -------------------------------------------------------------------------------- /curso-em-video/aula19/aula19exemplos02.py: -------------------------------------------------------------------------------- 1 | # Aplicações de variáveis compostas em Python. 2 | # Dicionários 3 | 4 | estado1 = {'UF': 'Paraná', 'Sigla': 'PR'} 5 | estado2 = {'UF': 'Santa Catarina', 'Sigla': 'SC'} 6 | brasil = [estado1, estado2] # Incluí os 2 dicionários na lista. 7 | print(brasil) 8 | print(brasil[0]) # Imprime o dicionário da posição "0" da lista. 9 | print(brasil[0]['UF']) # Imprime o valor da chave "UF" da posição "0" da lista. 10 | -------------------------------------------------------------------------------- /curso-em-video/aula19/aula19exemplos03.py: -------------------------------------------------------------------------------- 1 | # Aplicações de variáveis compostas em Python. 2 | # Dicionários 3 | 4 | brasil = [] 5 | estado = {} 6 | for c in range(1, 4): 7 | estado['Estado'] = str(input('Digite o Estado: ')).strip().upper() 8 | estado['Sigla'] = str(input('Digite a Sigla: ')).strip().upper() 9 | brasil.append(estado.copy()) # O "copy" serve para copiar o dicionário para dentro da lista. 10 | for e in brasil: 11 | print(e) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20desa01.py: -------------------------------------------------------------------------------- 1 | """Faça um programa que tenha uma função chamada área, que receba as dimensões de um terreno retangular 2 | (largura e comprimento) e mostre a área do terreno.""" 3 | 4 | 5 | def area(l, c): 6 | a = l * c 7 | print(f'A área do terreno {l}x{c} é igual a: {a:.2f} m2.') 8 | 9 | 10 | area(l=float(input('Digite a largura (em metros) do terreno: ')), 11 | c=float(input('Digite o comprimento (em metros) do terreno: '))) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20desa02.py: -------------------------------------------------------------------------------- 1 | """Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma 2 | mensagem com tamanho adaptável.""" 3 | 4 | 5 | def escreva(texto): 6 | print('∞' * len(texto)) 7 | print(texto) 8 | print('∞' * len(texto)) 9 | 10 | 11 | escreva(str(input('Digite um texto qualquer: ')).strip().upper()) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20desa04.py: -------------------------------------------------------------------------------- 1 | """Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. O seu 2 | programa tem que analisar todos os valores e dizer qual deles é o maior.""" 3 | 4 | import time 5 | 6 | 7 | def maior(* n): 8 | print('§' * 60) 9 | print('Analisando os valores passados...') 10 | time.sleep(1) 11 | print(f'Foram informados os seguintes valores: {n}.') 12 | print(f'Total de valores: {len(n)}.') 13 | print(f'O maior valor informado foi: {max(n)}.') 14 | 15 | 16 | maior(2, 9, 4, 5, 7, 1) 17 | maior(4, 7, 0) 18 | maior(1, 2) 19 | print('§' * 60) 20 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos01.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def linha(): 4 | print('≈' * 30) 5 | 6 | 7 | linha() 8 | print('TESTE COM FUNÇÕES PYTHON') 9 | linha() 10 | 11 | 12 | def mensagem(msg): 13 | print('¥' * 30) 14 | print(msg) 15 | print('¥' * 30) 16 | 17 | 18 | mensagem('TESTE COM FUNÇÕES PYTHON') 19 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos02.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def operacoes(a, b): 4 | s = a + b 5 | m = a * b 6 | d = a / b 7 | p = a ** b 8 | print(s) 9 | print(m) 10 | print(f'{d:.2f}') 11 | print(p) 12 | 13 | 14 | operacoes(3, 8) 15 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos03.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def contador(*num): 4 | for valor in num: 5 | print(f'{valor}', end=' ') 6 | print(' Fim!') 7 | 8 | 9 | contador(2, 4, 5, 6, 7, 8) 10 | contador(2, 3, 7) 11 | contador(1) 12 | contador(1, 4) 13 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos04.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def contador(*num): 4 | tam = len(num) 5 | print(f'Números digitados: {num}. Total igual a: {tam}.') 6 | 7 | 8 | contador(2, 4, 5, 6, 7, 8) 9 | contador(2, 3, 7) 10 | contador(1) 11 | contador(1, 4) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos05.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def dobra(lista): 4 | pos = 0 5 | while pos < len(lista): 6 | lista[pos] *= 2 7 | pos += 1 8 | 9 | 10 | valores = [6, 3, 9, 1, 0, 2] 11 | dobra(valores) 12 | print(valores) 13 | -------------------------------------------------------------------------------- /curso-em-video/aula20/aula20exemplos06.py: -------------------------------------------------------------------------------- 1 | # Funções Python 2 | 3 | def soma(*valores): 4 | s = 0 5 | for num in valores: 6 | s += num 7 | print(f'Somando os valores {valores}, temos {s}.') 8 | 9 | 10 | soma(5, 2) 11 | soma(2, 9, 4) 12 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21desa03.py: -------------------------------------------------------------------------------- 1 | """Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e 2 | quantos gols ele marcou. O programa deverá conseguir mostrar a ficha do jogador, mesmo que algum dado não tenha sido 3 | informado corretamente.""" 4 | 5 | 6 | def ficha(jog='desconhecido', gol=0): 7 | print(f'O jogador {jog} fez {gol} gol(s) no campeonato.') 8 | 9 | 10 | n = str(input('Nome do jogador: ')) 11 | g = str(input('Número de gols: ')) 12 | if g.isnumeric(): 13 | g = int(g) 14 | else: 15 | g = 0 16 | if n.strip() == '': 17 | ficha(gol=g) 18 | else: 19 | ficha(n, g) 20 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos01.py: -------------------------------------------------------------------------------- 1 | # Interactive Help 2 | 3 | print(input.__doc__) # Apresenta no console informações sobre o comando input. 4 | help(input()) # Outra forma de apresentar no console informações sobre o comando input. 5 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos02.py: -------------------------------------------------------------------------------- 1 | # Docstrings 2 | 3 | def contador(i, f, p): 4 | """ 5 | A função contador faz uma contagem e mostra na tela. 6 | :param i: parâmetro de início da contagem. 7 | :param f: parâmetro de fim da contagem. 8 | :param p: passo da contagem. 9 | :return: não retorna nada. 10 | """ 11 | c = i 12 | while c <= f: 13 | print(f'{c} ', end='') 14 | c += p 15 | print('Fim!') 16 | 17 | 18 | contador(2, 10, 2) 19 | print() 20 | help(contador) 21 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos03.py: -------------------------------------------------------------------------------- 1 | # Parâmetros opcionais 2 | 3 | def somar(a, b, c=0): # Nesse caso, o "c" entra como um parâmetro opcional, pois se não for informado o valor de "c", ele irá receber o valor "0". 4 | s = a+b+c 5 | print(f'A soma vale {s}.') 6 | 7 | 8 | somar(3, 2, 5) 9 | somar(8, 10) # Não precisei informar o valor de "c", pois ele está como um parâmetro opcional. 10 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos04.py: -------------------------------------------------------------------------------- 1 | # Escopo de variáveis 2 | 3 | def funcao(): 4 | n1 = 4 # variável de escopo local. 5 | print(f'n1 dentro vale {n1}.') 6 | 7 | 8 | n1 = 2 # variável de escopo global. 9 | funcao() 10 | print(f'n1 fora vale {n1}.') 11 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos05.py: -------------------------------------------------------------------------------- 1 | # Escopo de variáveis 2 | 3 | def funcao(): 4 | global n1 # esse comando serve para considerar apenas o valor da variável de escopo global. 5 | n1 = 4 # variável de escopo local. 6 | print(f'n1 dentro vale {n1}.') 7 | 8 | 9 | n1 = 2 # variável de escopo global. 10 | funcao() 11 | print(f'n1 fora vale {n1}.') 12 | -------------------------------------------------------------------------------- /curso-em-video/aula21/aula21exemplos06.py: -------------------------------------------------------------------------------- 1 | # Uso de funções com retorno ("return"). 2 | 3 | def somar(a=0, b=0, c=0): 4 | s = a+b+c 5 | return s 6 | 7 | 8 | r1 = somar(3, 2, 5) 9 | r2 = somar(1, 7) 10 | r3 = somar(4) 11 | 12 | print(f'As somas deram: {r1}, {r2} e {r2}.') 13 | -------------------------------------------------------------------------------- /curso-em-video/aula23/aula23desa02.py: -------------------------------------------------------------------------------- 1 | """Crie um código em Python que teste se o site pudim está acessível pelo computador usado.""" 2 | 3 | import urllib 4 | import urllib.request 5 | 6 | try: 7 | site = urllib.request.urlopen('http://www.pudim.com.br') 8 | except urllib.error.URLError: 9 | print('Erro!') 10 | else: 11 | print('OK!') 12 | print(site.read()) # Apresenta as informações do site. 13 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana01/exapli02.py: -------------------------------------------------------------------------------- 1 | # Unidade 01: Introdução à programação Python 2 | # Exemplo de aplicação 2: Elabore um programa que solicite o nome do usuário e mostre uma mensagem de boas-vindas. 3 | 4 | nome = input("Por favor, digite o seu nome: ") 5 | print("Olá, seja bem-vindo à disciplina", nome) 6 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana01/exapli03.py: -------------------------------------------------------------------------------- 1 | # Unidade 01: Introdução à programação Python 2 | # Exemplo de aplicação 3: Elabore um programa que solicite o nome do usuário e mostre uma mensagem de boas-vindas, 3 | # utilizando como separador "=>" e como finalização três puladas de linha. 4 | 5 | nome = input("Por favor, digite o seu nome: ") 6 | print("Olá, seja bem-vindo à disciplina", nome, sep="=>", end="\n\n\n") 7 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana01/exfixa02.py: -------------------------------------------------------------------------------- 1 | # Unidade 01: Introdução à programação Python 2 | # Exemplo de fixação 2: Elabore um programa que solicite ao usuário, separadamente, seu nome e sobrenome 3 | # e mostre a mensagem: “Seu nome é Nome e o seu sobrenome é Sobrenome!!!”, com três pontos de exclamação 4 | # no final da frase, pulando linha. 5 | 6 | nome = input("Por favor, digite o seu nome: ") 7 | sobrenome = input("Por favor, digite o seu sobrenome: ") 8 | print("Seu nome é " + nome + " e seu sobrenome é " + sobrenome + "!!!\n") 9 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana02/exapli03.py: -------------------------------------------------------------------------------- 1 | # Unidade 02: Estruturas condicionais 2 | # Exemplo de aplicação 3: Elabore um programa que solicite ao usuário seu ano de nascimento e calcule sua idade. 3 | # Para ser mais assertivo, também deve perguntar se o usuário já fez aniversário neste ano e analisar a influência 4 | # dessa informação no cálculo da idade. 5 | 6 | ano_atual = 2022 7 | ano_nasc = int(input("Qual é o seu ano de nascimento? ")) 8 | aniversario = input("Você já fez aniversário neste ano (S/N)? ") 9 | if aniversario == "S": 10 | print("A sua idade é", ano_atual - ano_nasc) 11 | else: 12 | print("A sua idade é", (ano_atual - ano_nasc) - 1) 13 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana02/exfixa01.py: -------------------------------------------------------------------------------- 1 | # Unidade 02: Estruturas condicionais 2 | # Exercício de fixação 1: Crie um programa que pergunte a idade do usuário. Caso seja maior de idade, 3 | # deve mostrar uma mensagem informando que pode se inscrever para fazer o teste para tirar a carteira de motorista. 4 | 5 | idade = int(input("Digite a sua idade (em anos): ")) 6 | if idade >= 18: 7 | print("Você pode se inscrever para tirar a carteira de motorista") 8 | else: 9 | print("Você não pode se inscrever para tirar a carteira de motorista") -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana02/exfixa03.py: -------------------------------------------------------------------------------- 1 | # Unidade 02: Estruturas condicionais 2 | # Exercício de fixação 3: Crie um programa que solicite um número ao usuário e informe se é par ou ímpar. 3 | # Dica: para saber se um número é par ou ímpar, calcular o resto da divisão desse número por 2 (operador %). 4 | # Se o resultado for 0, o número será par; se for 1, será ímpar. 5 | 6 | numero = int(input("Digite um número inteiro qualquer: ")) 7 | if numero % 2 == 0: 8 | print("Esse número é par.") 9 | else: 10 | print("Esse número é ímpar.") 11 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana02/exfixa04.py: -------------------------------------------------------------------------------- 1 | # Unidade 02: Estruturas condicionais 2 | # Exercício de fixação 4: Crie um programa que solicite ao usuário o seu salário. Se o valor for inferior a R$ 5.000, 3 | # calcule um abono de fim de ano de 15%. Caso contrário, o abono será de 10%. 4 | # Informe ao usuário seu valor de abono de fim de ano. 5 | 6 | salario = float(input("Informe o seu salário mensal (sem o indicador de milhar): ")) 7 | if salario < 5000: 8 | print("O seu abono de fim de ano será:", salario*0.15) 9 | else: 10 | print("O seu abono de fim de ano será:", salario * 0.1) 11 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana02/exfixa05.py: -------------------------------------------------------------------------------- 1 | # Unidade 02: Estruturas condicionais 2 | # Exercício de fixação 5: Crie um programa que pergunte ao usuário em que turno trabalha. 3 | # Formato da entrada: M – manhã, T – tarde ou N – noite. Mostre a mensagem “Bom dia!”, “Boa tarde!”, “Boa noite!” 4 | # ou “Valor inválido!”, conforme o caso. 5 | 6 | turno = str(input("Informe o seu salário turno de trabalho (M/T/N): ")) 7 | if turno == "M": 8 | print("Bom dia!") 9 | elif turno == "T": 10 | print("Boa tarde!") 11 | elif turno == "N": 12 | print("Boa noite!") 13 | else: 14 | print("Informação inválida!") 15 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli03.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 3: Elabore um programa que solicite ao usuário seu nome e mostre cada uma das letras do 3 | # nome em uma linha diferente do console. 4 | 5 | nome1 = str(input('Digite o seu 1º nome: ')) 6 | for letra in nome1: 7 | print(letra) 8 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli04.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 4: Elabore um programa que solicite três números, some-os e exiba o resultado para o usuário. 3 | 4 | soma = 0 5 | for i in range(3): 6 | num = int(input('Digite o número ' + str(i + 1) + ' : ')) 7 | soma += num 8 | print('A soma dos números é:', soma) 9 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli05.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 5: Elabore um programa que calcule o fatorial de um número, exibindo a informação de como é 3 | # feito o cálculo. Exemplo: Fatorial de 5 é igual a 5*4*3*2*1. 4 | 5 | fatorial = 1 6 | expressao = "(cálculo: " 7 | num = int(input('Digite um número para o cálculo do fatorial: ')) 8 | for i in range(num, 0, -1): 9 | fatorial *= i 10 | expressao += str(i) 11 | if i > 1: 12 | expressao += " * " 13 | print('O valor do fatorial de {} é: {} {})'.format(num, fatorial, expressao)) 14 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli06.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 6: Elabore um programa que solicite ao usuário dez números e efetue a soma, exibindo o resultado. 3 | # Contudo, se em algum momento o número digitado for 0, deve interromper o laço, mostrando a soma apenas dos valores 4 | # informados até então. 5 | 6 | soma = 0 7 | for i in range(10): 8 | num = float(input('Digite o número ' + str(i + 1) + ': ')) 9 | if num == 0: 10 | break 11 | soma += num 12 | print('A soma dos números informados é: {:.2f}'.format(soma)) 13 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli07.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 7: Elabore um programa que solicite ao usuário dez números e efetue a multiplicação, exibindo o 3 | # resultado. No entanto, se em algum momento o número digitado for 0, deve pular esta iteração, para que o valor não seja zerado. 4 | 5 | mult = 1 6 | for i in range(10): 7 | num = float(input('Digite o número ' + str(i + 1) + ': ')) 8 | if num == 0: 9 | continue 10 | mult *= num 11 | print('O resultado da multiplicação é: {:.2f}'.format(mult)) 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli09.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 9: Elabore um programa que solicite ao usuário que digite indefinidamente números e efetue a 3 | # soma, parando apenas quando o usuário digitar o número 0. 4 | 5 | soma = 0 6 | num = -1 7 | while num != 0: 8 | num = float(input('Digite um número qualquer (quando quiser parar de somar, digite 0): ')) 9 | soma += num 10 | print('A soma dos números é: {:.2f}'.format(soma)) 11 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli10.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 10: Elabore um programa que solicite um número inteiro ao usuário, validando e imprimindo esse número. 3 | 4 | while True: 5 | try: 6 | num = int(input('Digite um número inteiro: ')) 7 | break 8 | except ValueError: 9 | print('Erro! Você não digitou um número inteiro!') 10 | print('Parabéns! Você digitou um número inteiro!') 11 | 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exapli12.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição 2 | # Exemplo de aplicação 12: Elabore um programa que solicite um número inteiro ao usuário, em um intervalo entre 1 e 5. 3 | 4 | while True: 5 | try: 6 | num = int(input('Digite um número inteiro entre 1 e 5: ')) 7 | if 1 <= num <=5: 8 | break 9 | else: 10 | print('Erro! O número deve estar entre 1 e 5!') 11 | except ValueError: 12 | print('Erro! Você não digitou um número inteiro entre 1 e 5!') 13 | print('Parabéns! Você digitou um número inteiro entre 1 e 5!') 14 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa01.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 1: Crie um programa que solicite ao usuário dez números, contando quantos são pares e quantos 3 | # são ímpares e informando ao final essas informações. 4 | 5 | cont_par = 0 6 | cont_impar = 0 7 | cont = 0 8 | while cont <= 9: 9 | num = float(input('Digite o número ' + str(cont + 1) + ' de 10: ')) 10 | cont = cont + 1 11 | if num % 2 == 0: 12 | cont_par += 1 13 | else: 14 | cont_impar += 1 15 | print('Dos 10 números digitados, {} são pares e {} são ímpares.'.format(cont_par, cont_impar)) 16 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa02.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 2: Crie um programa que peça ao usuário cinco números e informe qual é o menor e qual é o maior deles. 3 | 4 | menor = 1000000 5 | maior = -1000000 6 | cont = 0 7 | for i in range (5): 8 | num = float(input(('Digite o numero ' + str(cont + 1) + ' de 5: '))) 9 | cont = cont + 1 10 | if num < menor: 11 | menor = num 12 | if num > maior: 13 | maior = num 14 | print('O menor número é: {} e o maior número é: {}'.format(menor, maior)) 15 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa03.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 3: Crie um programa que receba um texto digitado pelo usuário e o imprima apenas com consoantes, 3 | # removendo as vogais. Observação: desconsiderar letras maiúsculas e acentos. 4 | 5 | consoantes = "" 6 | frase = str(input('Digite um texto qualquer: ')) 7 | for letra in frase: 8 | if letra.lower() not in "aeiou": 9 | consoantes = consoantes + letra 10 | print('O texto sem as vogais fica: {}'.format(consoantes)) 11 | 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa04.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 4: Crie um programa que solicite um número ao usuário e exiba a tabuada dele de 1 a 10, no formato: 3 | # Tabuada do n 4 | # n x 1 = n 5 | # n x 2 = 2n 6 | # e assim por diante. 7 | 8 | num = float(input('Digite um número qualquer para saber a sua tabuada: ')) 9 | print('Tabuada do {}'.format(num)) 10 | for i in range(11): 11 | mult = i * num 12 | print(i, 'x', num, '=', '{:.2f}'.format(mult)) 13 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa05.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 5: Crie um programa que peça dois números ao usuário. O primeiro será o numerador e o segundo, 3 | # o expoente. A saída do programa deve ser o resultado da operação: numerador elevado ao expoente. 4 | # Observação: não usar função interna que calcula automaticamente potência. 5 | 6 | numerador = float(input('Informe o valor do numerador: ')) 7 | expoente = float(input('Informe o valor do expoente: ')) 8 | print('O valor da potência de numerador {:.2f} e expoente {:.2f} é: {:.2f}'.format(numerador, expoente, (numerador ** expoente))) 9 | 10 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana03/exfixa06.py: -------------------------------------------------------------------------------- 1 | # Unidade 03: Estruturas de repetição. 2 | # Exercício de fixação 6: Crie um programa que peça para o usuário inserir um login e uma senha. Caso os valores sejam 3 | # iguais, informar que os dados são inválidos e pedir novamente as informações. Caso contrário, 4 | # exibir a mensagem "Bem-vindo ao sistema!". 5 | 6 | while True: 7 | login = str(input('Informe o seu login: ')) 8 | senha = str(input('Informe a sua senha: ')) 9 | if login == senha: 10 | print('Dados inválidos! login e senha são iguais! Redigite as informações.') 11 | else: 12 | break 13 | print('Bem-vindo ao sistema!') 14 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli01.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exercício de aplicação 1: Elabore um programa que solicite ao usuário cinco números, armazene-os em uma lista e exiba como resultado os dados 3 | obtidos.""" 4 | 5 | lista_numeros = [] 6 | for i in range(5): 7 | numero = float(input('Informe um número: ')) 8 | lista_numeros.append(numero) 9 | print('Os números digitados são: {}'.format(lista_numeros)) 10 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli03.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exercício de aplicação 3: Dada a lista de dados nums = [1, 4, 23, 11, 8], corra a lista usando um objeto range e imprima cada elemento 3 | numa linha.""" 4 | 5 | nums = [1, 4, 23, 11, 8] 6 | for num in nums: 7 | print(num) 8 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli04.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exercício de aplicação 4: Dada a lista de dados nums = [17, 33, 23, 11, 8, 15, 9], corra a lista e identifique o maior e o menor número.""" 3 | 4 | nums = [17, 33, 23, 11, 8, 15, 9] 5 | maior = nums[0] 6 | menor = nums[0] 7 | for num in nums: 8 | if num > maior: 9 | maior = num 10 | if num < menor: 11 | menor = num 12 | print('O maior número da lista é: {} e o menor número da lista é: {}'.format(maior, menor)) 13 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli05.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exemplo de aplicação 5: Dada a lista de dados nums = [17, 33, 23, 11, 8, 15, 9], ordene-a e mostre o resultado ao 3 | usuário.""" 4 | 5 | nums = [17, 33, 23, 11, 8, 15, 9] 6 | aux = 0 7 | for _ in range(len(nums) - 1): 8 | for i in range(len(nums) - 1): 9 | if nums[i] > nums[i+1]: 10 | aux = nums[i] 11 | nums[i] = nums[i+1] 12 | nums[i+1] = aux 13 | print(nums) 14 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli06.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exemplo de aplicação 6: Solicite ao usuário que digite três coordenadas (x, y), armazenando-as numa matriz 3 | bidimensional""" 4 | 5 | import time 6 | 7 | coordenadas = [] 8 | for i in range(3): 9 | x = int(input('\33[32mInsira um valor de x: ')) 10 | y = int(input('Insira um valor de y: \33[m')) 11 | coordenadas.append([x, y]) 12 | print() 13 | print('Construindo as matrizes...') 14 | time.sleep(3) 15 | print() 16 | print('As matrizes ficaram da seguinte forma: ') 17 | print() 18 | print(coordenadas) 19 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exapli08.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exemplo de aplicação 8: Dada a matriz m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], efetue a soma de todos os seus elementos 3 | e exiba o resultado.""" 4 | 5 | m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 6 | soma = 0 7 | for i in range(3): 8 | for j in range(3): 9 | soma += m[i][j] 10 | print() 11 | print('A soma dos elementos da matriz m é igual a {}'.format(soma)) 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana04/exfixa06.py: -------------------------------------------------------------------------------- 1 | # Unidade 04: Listas. 2 | """Exercício de fixação 6: dado o vetor nums = [3, 7, 2, 9, 5, 6], crie um programa que, em uma linha, calcule a média 3 | dos seus elementos.""" 4 | 5 | nums = [3, 7, 2, 9, 5, 6] 6 | media = sum(nums) / len(nums) 7 | print('O vetor é: {}'.format(nums)) 8 | print('A média dos números do vetor é: {:.2f}'.format(media)) 9 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana05/exapli02.py: -------------------------------------------------------------------------------- 1 | # Unidade 05: Estrutura de dados: tuplas e dicionários 2 | """Exemplo de aplicação 2: Elabore um programa que crie uma tupla contendo duas listas com dados, altere os dados da 3 | primeira lista e verifique se ocorre mudança de dados da tupla.""" 4 | 5 | tupla_com_lista = ([1, 2, 3], [4, 5, 6]) 6 | print(id(tupla_com_lista[0])) 7 | tupla_com_lista[0].append(9) 8 | print(tupla_com_lista) 9 | print(id(tupla_com_lista[0])) 10 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana05/exapli04.py: -------------------------------------------------------------------------------- 1 | # Unidade 05: Estrutura de dados: tuplas e dicionários 2 | """Exemplo de aplicação 4: Elabore um aplicativo que demonstre a necessidade de finalizar uma tupla de um único elemento 3 | com uma vírgula no fim.""" 4 | 5 | tupla1 = 'Brasil' 6 | print(type(tupla1)) 7 | tupla2 = ('Brasil',) 8 | print(type(tupla2)) 9 | # Como é possível ver, o simples fato de usar parênteses ao redor de um único dado não cria uma tupla. 10 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana05/exapli06.py: -------------------------------------------------------------------------------- 1 | # Unidade 05: Estrutura de dados: tuplas e dicionários 2 | """Exemplo de aplicação 6: Elabore um programa que simule o cadastro de telefones com dicionário como uma agenda, 3 | exibindo, ao final, o dicionário.""" 4 | 5 | agenda = {} 6 | print('*** Cadastro de telefones ***') 7 | while True: 8 | contato = str(input('Digite o nome do contato: ')).strip() 9 | telefone = str(input('Digite o telefone do contato: ')).strip() 10 | agenda[contato] = telefone 11 | if str(input('Deseja cadastrar um novo contato (S=sim/N=não): ').strip().upper()) == "N": 12 | break 13 | print(agenda) 14 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exapli03.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exemplo de aplicação 3: Elabore um programa que use uma função chamada somar(), que efetue a soma de uma quantidade 3 | aleatória de números informados, retornando o resultado da operação.""" 4 | 5 | def somar(*numeros): 6 | soma = 0 7 | for c in numeros: 8 | soma += c 9 | return soma 10 | valores = somar(2,3,4,5,8) 11 | print('A soma dos números é: {}.'.format(valores)) 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exfixa01.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exercício de fixação 1: Crie um programa que calcule, a partir de uma função, o fatorial de um número. 3 | Exemplo: Fatorial de 5 → 5! = 5.4.3.2.1. Observação: por propriedade, 0! = 1.""" 4 | 5 | def fatorial(numero): 6 | if numero == 0: 7 | return 1 8 | fat = 1 9 | for i in range(numero, 0, -1): 10 | fat *= i 11 | return fat 12 | numero = int(input('Digite um número inteiro para calcular seu fatorial: ')) 13 | fat = fatorial(numero) 14 | print(f'O fatorial de {numero} é {fat}.') 15 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exfixa02.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exercício de fixação 2: Crie um programa que calcule o fatorial de um número, mas de forma recursiva, ou seja, 3 | chamando a função fatorial de dentro dela mesma.""" 4 | 5 | def fatorial(numero): 6 | if numero == 0: 7 | return 1 8 | return numero * fatorial(numero - 1) 9 | numero = int(input('Digite um número inteiro para calcular seu fatorial: ')) 10 | fat = fatorial(numero) 11 | print(f'O fatorial de {numero} é {fat}.') 12 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exfixa03.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exercício de fixação 3: Crie um programa que receba uma lista de números e retorne a média.""" 3 | 4 | def media(*numeros): 5 | soma = 0 6 | for numero in numeros: 7 | soma += numero 8 | return soma / len(numeros) 9 | resultado = media(2, 5, 9, 4, 11) 10 | print(f'O valor da média é: {resultado}.') 11 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exfixa04.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exercício de fixação 4: documente a função fatorial() desenvolvida no exercício de fixação 1 3 | desta unidade.""" 4 | 5 | def fatorial(numero: int): 6 | """ 7 | Calcula o fatorial de um número 8 | 9 | :param numero: número base para o cálculo do fatorial. 10 | :return: resultado do cálculo do fatorial. 11 | """ 12 | if numero == 0: 13 | return 1 14 | fat = 1 15 | for i in range(numero, 0, -1): 16 | fat *= i 17 | return fat 18 | -------------------------------------------------------------------------------- /pucpr/ads/2022/raciocinio-computacional/semana06/exfixa50.py: -------------------------------------------------------------------------------- 1 | # Unidade 06: Funções 2 | """Exercício de fixação 5: documente a função media() desenvolvida no exercício de fixação 3 desta 3 | unidade.""" 4 | 5 | def media(*numeros): 6 | """ 7 | Calcula a média dos números passados para a função. 8 | 9 | :param numeros: lista de números. 10 | :return: valor da média calculada. 11 | """ 12 | soma = 0 13 | for numero in numeros: 14 | soma += numero 15 | return soma / len(numeros) 16 | resultado = media(2, 5, 9, 4, 11) 17 | print(f'O valor da média é {resultado}.') 18 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/02.py: -------------------------------------------------------------------------------- 1 | # Método print. 2 | 3 | print(12, 34) 4 | 5 | # Por padrão, o método print gera um espaço entre os 2 argumentos. Para alterar isso, usamos: sep="" 6 | print(12, 34, sep="") 7 | print(12, 34, sep="-") 8 | 9 | # Por padrão, o método print gera uma nova linha após a execução do comando. Podemos alterar isso usando: end="" 10 | print(12, 34, sep="", end="") 11 | print(56, 78, sep="") 12 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/03.py: -------------------------------------------------------------------------------- 1 | # Python possui tipagem dinâmica (reconhece se é número ou texto, por exemplo) e forte. 2 | 3 | # Caracter de escape \ 4 | print("O melhor \"desenvolvedor\" do Brasil") 5 | 6 | # Outra forma 7 | print('O melhor "desenvolvedor" do Brasil') 8 | print("O melhor 'desenvolvedor' do Brasil") 9 | 10 | # Mostrar o caracter de escape 11 | print(r"O melhor \desenvolvedor\ do Brasil") 12 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/04.py: -------------------------------------------------------------------------------- 1 | # Tipos primitivos de dados. 2 | 3 | # int 4 | print(11) 5 | print(type(11)) 6 | 7 | # float 8 | print(11.45) 9 | print(type(11.45)) 10 | 11 | # string 12 | print("Olá mundo!") 13 | print(type("Olá mundo!")) 14 | 15 | # bool 16 | print(10 == 10) 17 | print(10 == 11) 18 | print(True) 19 | print(False) 20 | print(type(True)) 21 | print(type(False)) 22 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/05.py: -------------------------------------------------------------------------------- 1 | print(1 + 1) 2 | 3 | # Concatenação 4 | print("a" + "b") 5 | # print("1" + 1) 6 | 7 | # Conversão de tipos (coerção, type convertion, tycasting, coercion) 8 | 9 | print(type(str(1))) 10 | 11 | print(type(int("1"))) 12 | print(int("1") + 1) 13 | 14 | print(type(float("1.2"))) 15 | print(float("1.2") + 1) 16 | 17 | print(bool("")) 18 | print(bool(" ")) 19 | print(type(bool(""))) 20 | print(type(bool(" "))) 21 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/06-exercicio.py: -------------------------------------------------------------------------------- 1 | # Crie as variáveis necessárias para que os prints funcionem de maneira correta. 2 | 3 | nome = "Valmir" 4 | sobrenome = "Moro" 5 | idade = 44 6 | ano_nascimento = 2023 - idade 7 | maior_de_idade = idade >= 18 8 | altura_metros = 1.70 9 | 10 | print("Nome:", nome) 11 | print("Sobrenome:", sobrenome) 12 | print("Idade:", idade) 13 | print("Ano de Nascimento:", ano_nascimento) 14 | print("É maior de idade?", maior_de_idade) 15 | print("Altura em metros:", altura_metros) 16 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/06.py: -------------------------------------------------------------------------------- 1 | # Variáveis. 2 | 3 | """ 4 | PEP 8: This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. for variables, use the function naming rules: lowercase with words separated by underscores as necessary to improve readability. 5 | """ 6 | 7 | nome = "Valmir" 8 | idade = 30 9 | maioridade = 18 10 | maior_de_idade = idade >= maioridade 11 | 12 | print(maior_de_idade) 13 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/08.py: -------------------------------------------------------------------------------- 1 | # Peculiariedades dos operadores matemáticos. 2 | 3 | # Operador: + 4 | concatenacao = "A" + "B" + "C" 5 | print(concatenacao) 6 | 7 | # Operador: * 8 | repeticao = "A" * 10 9 | print(repeticao) 10 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/09-exercicio.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calcule o IMC e imprima o resultado da seguinte forma: 3 | 4 | Nome Completo: Xxxxxx Xxxx 5 | Altura: X.XX metros 6 | Peso: XX Kg 7 | IMC: XX.XX 8 | """ 9 | 10 | nome_completo = "Valmir Moro" 11 | altura = 1.70 12 | peso = 70 13 | imc = peso / (altura * altura) 14 | # imc = peso / altura ** 2 15 | 16 | print("Nome Completo:", nome_completo) 17 | print("Altura:", altura) 18 | print("Peso:", peso) 19 | print("IMC:", imc) 20 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/09.py: -------------------------------------------------------------------------------- 1 | # Precedência dos operadores matemáticos. 2 | 3 | # Parênteses 4 | conta1 = 2 * (5 + 5) 5 | print("Conta1:", conta1) 6 | 7 | # Exponenciação (potência) 8 | conta2 = 2 ** 5 + 5 9 | print("Conta2:", conta2) 10 | 11 | # Multiplicação, divisão, divisão inteira e resto da divisão 12 | conta3 = 2 * 5 / 2 // 2 % 4 # Cálculos executados da esquerda para a direita 13 | print("Conta3:", conta3) 14 | 15 | # Adição e subtração 16 | conta4 = 2 + 5 - 3 + 10 17 | print("Conta4:", conta4) 18 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/10.py: -------------------------------------------------------------------------------- 1 | # Formatação de strings (f-strings). 2 | 3 | """ 4 | Calcule o IMC e imprima o resultado da seguinte forma: 5 | 6 | Nome Completo: Xxxxxx Xxxx 7 | Altura: X.XX metros 8 | Peso: XX Kg 9 | IMC: XX.XX 10 | """ 11 | 12 | nome_completo = "Valmir Moro" 13 | altura = 1.70 14 | peso = 70 15 | imc = peso / (altura * altura) 16 | # imc = peso / altura ** 2 17 | 18 | print(f"Nome Completo: {nome_completo}") 19 | print(f"Altura: {altura:.2f}m") 20 | print(f"Peso: {peso}Kg") 21 | print(f"IMC: {imc:.2f}") 22 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/11.py: -------------------------------------------------------------------------------- 1 | # Formatação de strings com o método "format". 2 | 3 | a = "A" 4 | b = "B" 5 | c = 1.1 6 | # Impressão no terminal: a = A | b = B | c = 1.1 7 | 8 | formato = "a = {} | b = {} | c = {:.2f}".format(a, b, c) 9 | # formato = "a = {1} | b = {0} | c = {2:.2f}".format(a, b, c) 10 | # formato = "a = {letraA} | b = {letraB} | c = {letraC:.2f}".format(letraA=a, letraB=b, letraC=c) 11 | # formato = "a = {letraB} | b = {letraA} | c = {letraC:.2f}".format(letraA=a, letraB=b, letraC=c) 12 | 13 | print(formato) 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/13.py: -------------------------------------------------------------------------------- 1 | # Condicionais. 2 | 3 | # if / else 4 | entrada = input("Você deseja 'Entrar' ou 'Sair'? ") 5 | 6 | if entrada == "Entrar": 7 | print("Você entrou no sistema!") 8 | else: 9 | print("Você saiu do sistema!") 10 | 11 | # if / elif / else 12 | # entrada = input("Você deseja 'Entrar' ou 'Sair'? ") 13 | 14 | # if entrada == "Entrar": 15 | # print("Você entrou no sistema!") 16 | # elif entrada == "Sair": 17 | # print("Você saiu do sistema!") 18 | # else: 19 | # print("Você não digitou nem 'Entrar', nem 'Sair'!") 20 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/14-exercicio.py: -------------------------------------------------------------------------------- 1 | primeiro_valor = input("Digite um valor qualquer: ") 2 | segundo_valor = input("Digite outro valor qualquer: ") 3 | 4 | if primeiro_valor > segundo_valor: 5 | print( 6 | f"O primeiro valor {primeiro_valor} é maior do que o segundo valor {segundo_valor}.") 7 | elif primeiro_valor < segundo_valor: 8 | print( 9 | f"O primeiro valor {primeiro_valor} é menor do que o segundo valor {segundo_valor}.") 10 | else: 11 | print( 12 | f"O primeiro valor {primeiro_valor} é igual ao segundo valor {segundo_valor}.") 13 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/14.py: -------------------------------------------------------------------------------- 1 | # Operadores relacionais (de comparação) em Python. 2 | 3 | # Maior 4 | maior = 2 > 1 5 | print("Maior:", maior) 6 | 7 | # Maior ou igual 8 | maior_ou_igual = 2 >= 2 9 | print("Maior ou igual:", maior_ou_igual) 10 | 11 | # Menor 12 | menor = 2 < 3 13 | print("Menor:", menor) 14 | 15 | # Menor ou igual 16 | menor_ou_igual = 2 <= 2 17 | print("Menor ou igual:", menor_ou_igual) 18 | 19 | # Igual 20 | igual = "a" == "a" 21 | print("Igual:", igual) 22 | 23 | # Diferente 24 | diferente = "a" != "a" 25 | print("Diferente:", diferente) 26 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/16.py: -------------------------------------------------------------------------------- 1 | # Operadores "in" e "not in". 2 | 3 | """ 4 | Strings no Python são iteráveis (pode-se navegar item a item) 5 | Exemplos: 6 | 0 1 2 3 4 5 7 | V a l m i r 8 | -6-5-4-3-2-1 9 | """ 10 | 11 | # Exemplos de iterações 12 | nome = "Valmir" 13 | print(nome[2]) 14 | print(nome[-4]) 15 | 16 | # nome = "Valmir" 17 | # print("m" in nome) 18 | # print("m" not in nome) 19 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/17.py: -------------------------------------------------------------------------------- 1 | # Interpolação básica de strings. 2 | 3 | """ 4 | Características: 5 | %s = string 6 | $d e %i = int 7 | %f = float 8 | %x e %X = hexadecimal minúsculo e maiúsculo respectivamente (ABCDEF0123456789) 9 | """ 10 | 11 | nome = "Valmir" 12 | preco = 1234.56 13 | 14 | frase = "%s, o preço é R$%d" % (nome, preco) 15 | # frase = "%s, o preço é R$%.2f" % (nome, preco) 16 | print(frase) 17 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/18.py: -------------------------------------------------------------------------------- 1 | # Formatação básica de strings. 2 | 3 | variavel = "ABCD" 4 | 5 | print(f"{variavel}") 6 | print(f"{variavel:*>10}") # esquerda 7 | print(f"{variavel:*<10}") # direita 8 | print(f"{variavel:*^10}") # centraliza a variável 9 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/20.py: -------------------------------------------------------------------------------- 1 | # Introdução ao try/except. 2 | 3 | try: 4 | numero = input("Digite um número inteiro: ") 5 | numero_int = int(numero) 6 | print(f"O número digitado foi: {numero}.") 7 | except ValueError: 8 | print("Erro! O valor informado não é um número inteiro.") 9 | # except Exception as error: 10 | # print(f"Erro! Ocorreu a seguinte exceção: {str(error)}.") 11 | finally: # Sempre será executado 12 | print("Fim da execução do código!") 13 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/21.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercício: faça um programa que peça ao usuário para digitar um número inteiro, informe se este número é par ou ímpar. Caso o usuário não digite um número inteiro, informe que não é um número inteiro. 3 | """ 4 | 5 | entrada = input("Digite um número inteiro qualquer: ") 6 | 7 | if entrada.isdigit(): 8 | entrada_int = int(entrada) 9 | if entrada_int % 2 == 0: 10 | print(f"O número {entrada_int} é par.") 11 | else: 12 | print(f"O número {entrada_int} é ímpar.") 13 | else: 14 | print(f"Erro! O valor {entrada} não é um número inteiro.") 15 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/22.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercício: faça um programa que pergunte a hora ao usuário e, baseando-se na informação, exiba a saudação apropriada. 3 | 4 | Dados: Bom dia (0-11 horas), Boa tarde (12-17 horas) e Boa noite (18-23 horas). 5 | """ 6 | 7 | entrada = input("Informe a hora atual (formato: HH): ") 8 | 9 | if entrada.isdigit(): 10 | hora_int = int(entrada) 11 | if 0 <= hora_int <= 11: 12 | print(f"Bom dia!") 13 | elif 12 <= hora_int <= 17: 14 | print(f"Boa tarde!") 15 | else: 16 | print(f"Boa noite") 17 | else: 18 | print(f"Erro! O valor {entrada} não é um número inteiro.") 19 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/23.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercício: faça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou menos escreva: "Seu nome é curto", se tiver entre 5 e 6 letras, escreva: "Seu nome é normal" e maior que 6 letras, escreva: "Seu nome é muito grande". 3 | """ 4 | 5 | nome = input("Digite o seu primeiro nome: ") 6 | 7 | if len(nome) <= 4: 8 | print("O seu nome é curto.") 9 | elif len(nome) <= 6: 10 | print("O seu nome é normal.") 11 | else: 12 | print("O seu nome é muito grande.") 13 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/24.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | # while 4 | while True: 5 | nome = input("Digite o seu nome: ") 6 | print(f"O seu nome é {nome}.") 7 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/25.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | # while 4 | while True: 5 | nome = input('Digite o seu nome (Para sair, digite "Pare"): ') 6 | 7 | if nome.upper() == "PARE": 8 | break 9 | else: 10 | print(f'O seu nome é {nome}.') 11 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/26.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | contador = 0 4 | 5 | while contador <= 10: 6 | print(contador) 7 | contador = contador + 1 8 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/27.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | contador = 0 4 | 5 | while contador <= 19: 6 | contador = contador + 1 7 | 8 | if contador == 10: 9 | continue # Pula um laço 10 | print(contador) 11 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/28.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | numero_linhas = 5 4 | numero_colunas = 5 5 | 6 | linha = 1 7 | 8 | while linha <= numero_linhas: 9 | coluna = 1 10 | 11 | while coluna <= numero_colunas: 12 | print(f'{linha=} {coluna=}') 13 | coluna += 1 14 | linha += 1 15 | 16 | print("Fim!") 17 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/30.py: -------------------------------------------------------------------------------- 1 | # Iteração de strings com o while. 2 | 3 | nome = input("Digite o seu nome: ") 4 | indice = 0 5 | 6 | while indice < len(nome): 7 | print(nome[indice]) 8 | indice += 1 9 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/34.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | # for 4 | palavra = "Tecnologia" 5 | 6 | for letra in palavra: 7 | print(letra) 8 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/35.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | # for/range(start, stop, step) 4 | numeros = range(1, 11, 1) 5 | for numero in numeros: 6 | print(numero) 7 | 8 | # numeros = range(1, 21, 2) 9 | # for numero in numeros: 10 | # print(numero) 11 | 12 | # Nesse caso, estou informando apenas o "stop" e o "step" automaticamente é 1 13 | # numeros = range(11) 14 | # for numero in numeros: 15 | # print(numero) 16 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/36.py: -------------------------------------------------------------------------------- 1 | # Estrutura de repetição. 2 | 3 | # for 4 | for i in range(10): 5 | if i == 2: 6 | print("Número 2 não será impresso!") 7 | continue 8 | print(i) 9 | # if i == 8: 10 | # print('"i" é igual a 8 e o "else" não sera executado!') 11 | # break 12 | else: 13 | print('"for" utilizado com sucesso!') 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/40.py: -------------------------------------------------------------------------------- 1 | # Comando for com listas. 2 | 3 | lista_nomes = ["Maria", "José", "Pedro", "Ana"] 4 | 5 | for nome in lista_nomes: 6 | print(nome) 7 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/41.py: -------------------------------------------------------------------------------- 1 | # Exercício: exiba os índices da lista. 2 | 3 | lista_nomes = ["Maria", "José", "Pedro", "Ana"] 4 | indices = range(len(lista_nomes)) 5 | 6 | for indice in indices: 7 | print(indice, lista_nomes[indice]) 8 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/44.py: -------------------------------------------------------------------------------- 1 | # Enumerate. 2 | 3 | # Enumera iteráveis (índices) 4 | relacao_nomes = "Maria", "José", "Pedro", "Ana" 5 | relacao_enumerada_nomes = enumerate(relacao_nomes) 6 | print(next(relacao_enumerada_nomes)) 7 | # print(list(enumerate(relacao_nomes))) 8 | # print(list(enumerate(relacao_nomes, start=5))) 9 | 10 | # for item in relacao_enumerada_nomes: 11 | # print(item) 12 | 13 | # for item in enumerate(relacao_nomes): 14 | # print(item) 15 | 16 | # for indice, nome in enumerate(relacao_nomes): 17 | # print(indice, nome) 18 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/46.py: -------------------------------------------------------------------------------- 1 | # Imprecisão do float. 2 | 3 | # import decimal 4 | numero1 = 0.1 5 | numero2 = 0.7 6 | soma1 = numero1 + numero2 7 | print(f"A soma é {soma1}.") 8 | # print(f"A soma é {soma:.2f}.") 9 | # print(round(soma, 2)) 10 | 11 | # Para uma precisão maior 12 | # numero3 = decimal.Decimal(0.1) 13 | # numero4 = decimal.Decimal(0.7) 14 | # soma2 = numero3 + numero4 15 | # print(f"A soma é {soma2}.") 16 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/47.py: -------------------------------------------------------------------------------- 1 | # Comandos "split" e "join" com strings e listas. 2 | 3 | frase = "Aprender a programar com Python é a melhor maneira de iniciar na carreira de Programador." 4 | 5 | # split 6 | # Por padrão, o "split" vai usar o espaço para separas as palavras 7 | lista_palavras = frase.split() 8 | print(lista_palavras) 9 | 10 | # lista_palavras = frase.split('a') 11 | # print(lista_palavras) 12 | 13 | # lista_palavras = frase.split('an') 14 | # print(lista_palavras) 15 | 16 | # for indice, frase1 in enumerate(lista_palavras): 17 | # print(lista_palavras[indice]) 18 | 19 | # join 20 | frase = "-".join(lista_palavras) 21 | print(frase) 22 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/48.py: -------------------------------------------------------------------------------- 1 | # Iterável dentro de outro iterável. 2 | 3 | dados = [["Maria", "Ana"], ["Helena"], [ 4 | "Luiz", "Pedro", "João", (10, 20, 30, 40, 50)]] 5 | 6 | print(dados) 7 | print(dados[2][1]) 8 | print(dados[2][3][4]) 9 | 10 | for informacao in dados[2][3]: 11 | print(informacao) 12 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/49.py: -------------------------------------------------------------------------------- 1 | """ 2 | Detalhes sobre o interpretador do Python. 3 | 4 | Comandos úteis do terminal 5 | 6 | 1) python --help: comando de ajuda do Python. 7 | 2) clear: limpa o terminal. 8 | 3) python --version (ou python -V): mostra a versão atual do Python. 9 | 4) python "nome_do_arquivo.py": executa o arquivo. 10 | 5) python (ou python -i): entra no modo interativo do python. 11 | 6) exit() (ou quit()): sai do modo interativo do python. 12 | 7) python -c "import this": mostra o "The Zen of Python, by Tim Peters. 13 | """ 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/50.py: -------------------------------------------------------------------------------- 1 | # Desempacotamento em chamadas de métodos e funções. 2 | 3 | nomes = ["Maria", "Pedro", "Ana", "José", "Lucia"] 4 | frase = "Desempacotamento em chamadas e funções." 5 | dados = "Joana", 44, "Casada", ["Rua X", 84340439, "Curitiba"], 2 6 | 7 | for nome in nomes: 8 | print(nome, end=" ") 9 | 10 | # print(*nomes) 11 | # print(*frase) 12 | # print(*dados) 13 | # print(*dados, sep="\n") 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/54.py: -------------------------------------------------------------------------------- 1 | # Argumentos nomeados e não nomeados em funções no Python. 2 | 3 | def soma(x, y, z): 4 | print(f"{x=}, {y=} e {z=} | x + y + z = {x + y + z}") 5 | # print(f"x={x}, y={y} e z={z} | x + y + z = {x + y + z}") 6 | 7 | 8 | soma(1, 2, 3) # Argumento não nomeado ou posicionais 9 | soma(2, 1, 4) # Tomar cuidado com a ordem 10 | soma(y=2, x=1, z=3) # Argumento nomeado 11 | 12 | # Recomendação: não usar argumentos não nomeados e argumentos nomeados na mesma função 13 | soma(2, 3, z=4) 14 | 15 | # Nomeado um argumento, os próximos obrigatoriamente precisam ser nomeados 16 | soma(2, y=3, z=5) 17 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/57.py: -------------------------------------------------------------------------------- 1 | # Retorno de função no Python. 2 | 3 | def soma1(a, b): 4 | resultado = a + b 5 | 6 | 7 | # O retorno será None, pois por padrão uma função no Python retorna None 8 | print(soma1(1, 2)) 9 | 10 | 11 | # def soma(a, b): 12 | # resultado = a + b 13 | # return resultado 14 | # # return a + b 15 | 16 | 17 | # print(f"A soma é {soma(1, 2)}.") 18 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/58-exercicio.py: -------------------------------------------------------------------------------- 1 | # Crie uma função que multiplique todos os argumentos não nomeados recebidos e retorne o total em uma variável, mostrando o seu valor. 2 | 3 | 4 | def multiplicacao(*args): 5 | total = 1 6 | for arg in args: 7 | total *= arg 8 | return total 9 | 10 | 11 | resultado = multiplicacao(5, 5, 5, 5, 5) 12 | 13 | print(f"O resultado da multiplicação é {resultado}.") 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/59.py: -------------------------------------------------------------------------------- 1 | # Exercício: crie uma função que calcular se o número é par ou ímpar. 2 | 3 | 4 | def par_impar(numero): 5 | return f"O número {numero} é par." if numero % 2 == 0 else f"O número {numero} é ímpar." 6 | 7 | 8 | resultado = par_impar(7) 9 | print(resultado) 10 | 11 | 12 | # def par_impar(numero): 13 | # if numero % 2 == 0: 14 | # return f"O número {numero} é par." 15 | # return f"O número {numero} é ímpar." 16 | 17 | 18 | # resultado = par_impar(8) 19 | # print(resultado) 20 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/75.py: -------------------------------------------------------------------------------- 1 | """ 2 | Filtro de dados em list comprehension. 3 | 4 | A list comprehension permite que você aplique uma condição de filtro diretamente durante a criação da nova lista. A condição é especificada após a expressão que você está aplicando a cada elemento da sequência. 5 | """ 6 | 7 | numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 8 | 9 | # Usando List Comprehension para criar uma nova lista com números pares 10 | numeros_pares = [x for x in numeros if x % 2 == 0] 11 | print(numeros_pares) 12 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/76.py: -------------------------------------------------------------------------------- 1 | """ 2 | List comprehension com mais de um loop for. 3 | 4 | Você pode usar list comprehensions com mais de um loop for para criar listas que envolvem iterações aninhadas sobre múltiplas sequências. Isso é útil quando você precisa combinar elementos de duas ou mais sequências de maneira coordenada. A sintaxe básica envolve aninhar os loops for uns dentro dos outros. 5 | """ 6 | 7 | lista1 = [1, 2, 3] 8 | lista2 = ['a', 'b'] 9 | 10 | combinacao_lista1_lista2 = [(x, y) for x in lista1 for y in lista2] 11 | print(combinacao_lista1_lista2) 12 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/84.py: -------------------------------------------------------------------------------- 1 | # yeld from no Python. 2 | 3 | def gerador1(): 4 | yield "A" 5 | yield "B" 6 | 7 | 8 | def gerador2(gerador1): 9 | yield from gerador1() 10 | yield "C" 11 | yield "D" 12 | 13 | 14 | resultado = gerador2(gerador1) 15 | 16 | print(next(resultado)) 17 | # print(next(resultado)) 18 | # print(next(resultado)) 19 | # print(next(resultado)) 20 | # print(next(resultado)) 21 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/88-modulo.py: -------------------------------------------------------------------------------- 1 | # Modularização no Python. 2 | 3 | def saudacao(nome): 4 | return f"Olá, {nome}!" 5 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/89-modulo.py: -------------------------------------------------------------------------------- 1 | # Comportamento singleton em modularizações no Python. 2 | 3 | saudacao = "Olá, Valmir!" 4 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/89.py: -------------------------------------------------------------------------------- 1 | """ 2 | Comportamento singleton em modularizações no Python. 3 | 4 | Em Python, o sistema de importação garante que um módulo seja importado apenas uma vez durante a execução de um programa. Isso significa que, mesmo se você importar o mesmo módulo de diferentes partes do seu código, Python garantirá que ele seja executado apenas uma vez e a mesma instância desse módulo será compartilhada em todos os lugares onde ele é importado. 5 | """ 6 | 7 | import aula89modulo 8 | 9 | print(aula89modulo.saudacao) 10 | 11 | for i in range(10): 12 | print(i) 13 | import aula89modulo 14 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/93.py: -------------------------------------------------------------------------------- 1 | # Crie um algoritmo para unir 2 listas. O resultado deve ser: [('Salvador', 'BA'), ('Ubatuba', 'SP'), ('Belo Horizonte', 'MG')]. 2 | 3 | cidades = ["Salvador", "Ubatuba", "Belo Horizonte"] 4 | estados = ["BA", "SP", "MG", "RJ"] 5 | 6 | # Verificação da menor lista 7 | min_length = min(len(cidades), len(estados)) 8 | 9 | for i in range(min_length): 10 | resultado = [(cidades[i], estados[i])] 11 | print(resultado, end='') 12 | 13 | # List comprehension para criar uma lista combinada 14 | # resultado = [(cidades[i], estados[i]) for i in range(min_length)] 15 | -------------------------------------------------------------------------------- /python-3-completo-udemy/1.arquivos-01-a-99/96.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercício: considerando duas listas de números inteiros ou floats, some os valores, retornando o resultado em uma nova lista. Caso uma lista seja menor do que a outra, considere a menor delas. 3 | """ 4 | 5 | lista_1 = [1, 2, 3, 4, 5] 6 | lista_2 = [1, 2, 3, 4] 7 | 8 | lista_3 = [a + b for a, b in zip(lista_1, lista_2)] 9 | print(lista_3) 10 | -------------------------------------------------------------------------------- /python-3-completo-udemy/3.arquivo-110/arquivo.txt: -------------------------------------------------------------------------------- 1 | What is Lorem Ipsum? 2 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. -------------------------------------------------------------------------------- /python-3-completo-udemy/3.arquivo-110/leitura_arquivo.py: -------------------------------------------------------------------------------- 1 | # Leitura de um arquivo no Python. 2 | 3 | arquivo = open( 4 | "/Users/valmirfilho/Downloads/python-3-completo-udemy/aula110/arquivo.txt", "r") 5 | 6 | # conteudo_completo_arquivo = arquivo.read() 7 | # print(conteudo_completo_arquivo) 8 | 9 | # conteudo_unica_linha_arquivo = arquivo.readline() 10 | # print(conteudo_unica_linha_arquivo) 11 | 12 | # conteudo_multiplas_linhas_arquivo = arquivo.readlines() 13 | # print(conteudo_multiplas_linhas_arquivo) 14 | 15 | arquivo.close() 16 | -------------------------------------------------------------------------------- /python-3-completo-udemy/4.arquivo-111/arquivo.txt: -------------------------------------------------------------------------------- 1 | What is Lorem Ipsum? 2 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. -------------------------------------------------------------------------------- /python-3-completo-udemy/5.arquivo-112/arquivo.txt: -------------------------------------------------------------------------------- 1 | What is Lorem Ipsum? 2 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. -------------------------------------------------------------------------------- /python-3-completo-udemy/7.arquivo-114/aula114.py: -------------------------------------------------------------------------------- 1 | # Exportação de um arquivo JSON para o Python. 2 | 3 | import json 4 | 5 | with open("/Users/valmirfilho/Downloads/python-3-completo-udemy/aula114/aula114.json", "r") as arquivo: 6 | dados_pessoais = json.load(arquivo) 7 | print(dados_pessoais) 8 | print(dados_pessoais["idade"]) 9 | -------------------------------------------------------------------------------- /python-3-completo-udemy/8.arquivo-116/lista_tarefas.json: -------------------------------------------------------------------------------- 1 | ["ESTUDAR", "LER", "TREINAR"] -------------------------------------------------------------------------------- /python-3-completo-udemy/9.arquivo-121/aula121b.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from aula121a import caminho_arquivo, Pessoa 4 | 5 | with open(caminho_arquivo, "r") as arquivo: 6 | pessoas = json.load(arquivo) 7 | 8 | p1 = Pessoa(**pessoas[0]) 9 | p2 = Pessoa(**pessoas[1]) 10 | 11 | print(p1.nome) 12 | print(p2.nome) 13 | -------------------------------------------------------------------------------- /python-3-completo-udemy/9.arquivo-121/classe.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "nome": "Valmir", 4 | "altura": 1.7, 5 | "peso": 70, 6 | "raca": "Branca", 7 | "idade": 44, 8 | "sexo": "M", 9 | "religiao": "Ateu", 10 | "possui_deficiencia": false 11 | }, 12 | { 13 | "nome": "Audi", 14 | "altura": 1.6, 15 | "peso": 50, 16 | "raca": "Branca", 17 | "idade": 44, 18 | "sexo": "F", 19 | "religiao": "Católica", 20 | "possui_deficiencia": false 21 | } 22 | ] -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao01.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 1: Faça um Programa que peça dois números e imprima o maior deles.""" 4 | 5 | num1 = float(input('Digite o 1º número: ')) 6 | num2 = float(input('Digite o 2º número: ')) 7 | if num1 > num2: 8 | print('{} é maior que {}'.format(num1,num2)) 9 | elif num1 < num2: 10 | print('{} é maior que {}'.format(num2,num1)) 11 | else: 12 | print('O {} e o {} são iguais'.format(num1,num2)) 13 | -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao02.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 2: Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.""" 4 | 5 | valor = float(input('Digite um número qualquer: ')) 6 | if valor > 0: 7 | print('O {} é um número positivo'.format(valor)) 8 | elif valor < 0: 9 | print('O {} é um número negativo'.format(valor)) 10 | else: 11 | print('Você digitou o número {}'.format(valor)) 12 | -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao03.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 3: Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra, escrever: F — Feminino, 4 | M — Masculino, Sexo Inválido.""" 5 | 6 | letra = str(input('Digita a letra "M" para sexo masculino ou "F" para sexo feminino: ')).strip().upper() 7 | if letra == 'M': 8 | print('M - Masculino') 9 | elif letra == 'F': 10 | print('F - Feminino') 11 | else: 12 | print('Sexo Inválido!!!') 13 | -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao06.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 6: Faça um Programa que leia três números e mostre o maior deles.""" 4 | 5 | numeros = [] 6 | for i in range(3): 7 | num = float(input('Digite um número qualquer: ')) 8 | numeros.append(num) 9 | print('O maior número digitado é o: {}'.format(max(numeros))) 10 | -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao09.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 9: Faça um Programa que leia três números e mostre-os em ordem decrescente.""" 4 | 5 | print() 6 | numeros = [] 7 | for i in range(3): 8 | num = float(input('\33[32mDigite um número: ')) 9 | numeros.append(num) 10 | print(sorted(numeros, reverse=True)) 11 | -------------------------------------------------------------------------------- /python-brasil/estrutura-decisão/exestrudecisao23.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de decisão. 3 | Exercício 23: Faça um Programa que peça um número e informe se o número é inteiro ou decimal. 4 | Dica: utilize uma função de arredondamento.""" 5 | 6 | num = float(input('Digite um número qualquer: ')) 7 | if num == int(num): 8 | print('O {} é um número inteiro'.format(num)) 9 | else: 10 | print('O {} é um número decimal'.format(num)) 11 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao01.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 1: Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e 4 | continue a pedir até que o usuário informe um valor válido.""" 5 | 6 | while True: 7 | nota = float(input('Digite uma nota entre 0 e 10: ')) 8 | if 0 <= nota <= 10: 9 | break 10 | else: 11 | print('Valor inválido! Digite novamente.') 12 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao02.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 2: Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, 4 | mostrando uma mensagem de erro e voltando a pedir as informações.""" 5 | 6 | while True: 7 | usuario = str(input('Digite o seu usuário: ')) 8 | senha = str(input('Digite a sua senha: ')) 9 | if usuario == senha: 10 | print('Erro! o usuário e a senha não podem ser iguais.') 11 | else: 12 | break 13 | print('Fim!') 14 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao06.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 6: Faça um programa que imprima na tela os números de 1 a 20, um abaixo do outro. Depois modifique o programa 4 | para ele mostrar os números um ao lado do outro.""" 5 | 6 | for c in range(1, 21): 7 | print(c) 8 | for c in range(1, 21): 9 | print(c, end=' ') 10 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao07.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 7: Faça um programa que leia 5 números e informe o maior número.""" 4 | 5 | numeros = [] 6 | for c in range(1, 6): 7 | n = float(input('Digite um número: ')) 8 | numeros.append(n) 9 | print(f'O maior número informado foi: {max(numeros)}.') 10 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao08.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 8: Faça um programa que leia 5 números e informe a soma e a média dos números.""" 4 | 5 | numeros = [] 6 | for c in range(1, 6): 7 | n = float(input('Digite um número: ')) 8 | numeros.append(n) 9 | print(f'A soma dos números informados é igual a: {sum(numeros)}.') 10 | print(f'A média dos números informados é igual a: {sum(numeros)/c}') 11 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao09.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 9: Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50.""" 4 | 5 | for c in range(1, 51, 2): 6 | print(c) 7 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao14.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 14: Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a 4 | quantidade de números impares.""" 5 | 6 | print() 7 | par = impar = 0 8 | for c in range(1, 11): 9 | n = int(input(f'Digite o {c}º valor: ')) 10 | if n % 2 == 0: 11 | par += 1 12 | else: 13 | impar += 1 14 | print() 15 | print(f'Você digitou {par} números pares e {impar} números ímpares.') 16 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao15.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 15: A série de Fibonacci é formada pela sequência 1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar 4 | a série até o n−ésimo termo.""" 5 | 6 | termo_1 = 0 7 | termo_2 = 1 8 | n = int(input('Quantos termos você quer mostrar? ')) 9 | contador = 3 10 | print(f'Os {n} primeiros termos são: {termo_1} → {termo_2}', end='') 11 | while contador <= n: 12 | termo_3 = termo_1 + termo_2 13 | print(f' → {termo_3}', end='') 14 | termo_1 = termo_2 15 | termo_2 = termo_3 16 | contador += 1 17 | print(' → Fim!') 18 | -------------------------------------------------------------------------------- /python-brasil/estrutura-repetição/exestrurepeticao24.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de estrutura de repetição. 3 | Exercício 24: Faça um programa que calcule o mostre a média aritmética de N notas.""" 4 | 5 | notas = [] 6 | contador = 0 7 | while True: 8 | nota = float(input('Digite a nota: ')) 9 | continuar = str(input('Deseja cadastrar mais uma nota? (S=sim/N=não): ')).strip().upper() 10 | notas.append(nota) 11 | contador += 1 12 | if continuar == 'N': 13 | print(f'A média aritmética das notas digitadas é igual a: {(sum(notas)/contador):.2f}') 14 | break 15 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq01.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 1: Faça um programa que mostre a mensagem "Alo mundo" na tela. 4 | 5 | print("Alo mundo") 6 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq02.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 2: Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número]. 4 | 5 | x = int(input("Informe um número: ")) 6 | print("O número informado foi: ", x) 7 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq03.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 3: Faça um Programa que peça dois números e imprima a soma. 4 | 5 | x1 = int(input("Informe o primeiro número: ")) 6 | x2 = int(input("Informe o segundo número: ")) 7 | print("A soma dos dois números é: ", x1+x2) 8 | 9 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq04.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 4: Faça um Programa que peça as 4 notas bimestrais e mostre a média. 4 | 5 | x1 = float(input("Informe a nota do 1º bimestre: ")) 6 | x2 = float(input("Informe a nota do 2º bimestre: ")) 7 | x3 = float(input("Informe a nota do 3º bimestre: ")) 8 | x4 = float(input("Informe a nota do 4º bimestre: ")) 9 | print("A sua média é: ", (x1+x2+x3+x4)/4) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq05.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 5: Faça um Programa que converta metros para centímetro. 4 | 5 | x = float(input("Informe o valor em metros para ser convertido em centímetros: ")) 6 | print("O valor em centímetros é: ", round((x*100))) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq06.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 6: Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. 4 | import math 5 | 6 | x = float(input("Informe o valor do raio do círculo: ")) 7 | y = (math.pi*(x**2)) 8 | print("O valor da área do círculo de raio",x,"é:","%.2f"%y) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq07.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 7: Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. 4 | 5 | x = float(input("Informe o valor de um dos lados do quadrado: ")) 6 | y = ((x**2)*2) 7 | print("O valor do dobro da área do quadrado de lado:",x,"é:","%.2f"%y) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq08.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 8: Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. 4 | # Calcule e mostre o total do seu salário no referido mês. 5 | 6 | x = float(input("Informe o quanto você ganha por hora: ")) 7 | y = float(input("Informe o número de horas trabalhadas no referido mês: ")) 8 | z = (x*y) 9 | print("O total do seu salário no referido mês é:","%.2f"%z) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq09.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 9: Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. 4 | 5 | temperatura = int(input("Informe a temperatura em graus Fahrenheit: ")) 6 | print("A temperatura em graus Celsius é:",round(((temperatura-32)/1.8))) 7 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq10.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 10: Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. 4 | 5 | temperatura = int(input("Informe a temperatura em graus Celsius: ")) 6 | print("A temperatura em graus Fahrenheit é:",round((temperatura*1.8+32))) 7 | -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq12.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial 3 | # Exercício 12: Tendo como dado de entrada a altura de uma pessoa, 4 | # construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura)-58 5 | 6 | altura = float(input("Informe a sua altura: ")) 7 | print("O seu peso ideal é:",72.7*altura-58) -------------------------------------------------------------------------------- /python-brasil/estrutura-sequencial/exestruseq13.py: -------------------------------------------------------------------------------- 1 | # Python Brasil 2 | # Lista de exercícios de estrutura sequencial. 3 | # Exercício 13: Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, 4 | # utilizando as seguintes fórmulas: para homens: (72.7*h)-58 e para mulheres: (62.1*h)-44.7. 5 | 6 | sexo = str(input('Informe o seu sexo (M/F): ')).strip().upper() 7 | altura = float(input('Informe a sua altura (em metros): ')) 8 | if sexo == 'M': 9 | print('O seu peso ideal é: {:.2f}'.format(72.7 * altura - 58)) 10 | else: 11 | print('O seu peso ideal é: {:.2f}'.format(62.1 * altura - 44.7)) 12 | -------------------------------------------------------------------------------- /python-brasil/funções/exfuncoes03.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de funcões. 3 | Exercício 3: Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos.""" 4 | 5 | 6 | def somar(a, b, c): 7 | s = a + b + c 8 | print(f'A soma dos 3 argumentos é igual a: {s}.') 9 | 10 | 11 | somar(a=int(input('Digite o 1º valor: ')), 12 | b=int(input('Digite o 2º valor: ')), 13 | c=int(input('Digite o 3º valor: '))) 14 | -------------------------------------------------------------------------------- /python-brasil/funções/exfuncoes04.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de funcões. 3 | Exercício 4: Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere "P", 4 | se o seu argumento for positivo, e "N", se o seu argumento for zero ou negativo.""" 5 | 6 | 7 | def rertorna(a): 8 | if a > 0: 9 | print('Resultado: "P"') 10 | else: 11 | print('Resultado: "N"') 12 | 13 | 14 | rertorna(int(input('Digite um número inteiro: '))) 15 | -------------------------------------------------------------------------------- /python-brasil/funções/exfuncoes05.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de funcões. 3 | Exercício 5: Faça um programa com uma função chamada somaImposto. A função possui dois parâmetros formais: taxaImposto, 4 | que é a quantia de imposto sobre vendas, expressa em porcentagem, e custo, que é o custo de um item antes do imposto. A 5 | função “altera” o valor de custo para incluir o imposto sobre vendas.""" 6 | 7 | 8 | def soma_imposto(taxa_imposto, custo): 9 | valor = custo + (custo * taxa_imposto/100) 10 | print(f'O valor de R${custo}, após a incidência da taxa de imposto de {taxa_imposto}%, é igual a: R${valor}.') 11 | 12 | 13 | soma_imposto(15, 1000) 14 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas01.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 1: Faça programa que leia um vetor de 5 números inteiros e mostre-os.""" 4 | 5 | numeros = [] 6 | for n in range(1, 6): 7 | numero = int(input(f'Informe o {n}º valor: ')) 8 | numeros.append(numero) 9 | print(f'Os valores digitados foram: {numeros}.') 10 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas02.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 2: Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa.""" 4 | 5 | numeros = [] 6 | for n in range(1, 11): 7 | numero = float(input(f'Digite o {n}º número: ')) 8 | numeros.append(numero) 9 | numeros.reverse() 10 | print(f'Os {len(numeros)} números digitados na ordem inversa são: {numeros}') 11 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas03.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 3: Faça um Programa que leia 4 notas, mostre as notas e a média na tela.""" 4 | 5 | notas = [] 6 | contador = 0 7 | for n in range(1, 5): 8 | nota = float(input(f'Digite a nota {n}: ')) 9 | notas.append(nota) 10 | contador += 1 11 | print(f'As notas digitadas foram: {notas}') 12 | print(f'A média das notas é: {sum(notas)/contador:.2f}.') 13 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas04.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 4: Faça um Programa que leia um vetor de 10 caracteres, e diga quantas consoantes foram lidas. 4 | Imprima as consoantes.""" 5 | 6 | consoantes = [] 7 | vogais = 'AEIOU' 8 | contador = 0 9 | for c in range(1, 11): 10 | caracter = str(input(f'Digite o caracter número {c}: ')).strip().upper() 11 | if caracter not in vogais: 12 | consoantes.append(caracter) 13 | contador += 1 14 | print(f'Foram digitadas {contador} consoantes.') 15 | print(f'As consoantes digitadas foram: {consoantes}.') 16 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas07.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 7: Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a multiplicação e os números.""" 4 | 5 | numeros = [] 6 | multiplicacao = 1 7 | for n in range(1, 6): 8 | numero = int(input(f'Digite o {n}º número: ')) 9 | numeros.append(numero) 10 | multiplicacao *= numero 11 | print(f'Os números digitados foram: {numeros}') 12 | print(f'A soma dos números é igual a: {sum(numeros)}.') 13 | print(f'A multiplicação dos números é igual a {multiplicacao}.') 14 | -------------------------------------------------------------------------------- /python-brasil/listas/exlistas09.py: -------------------------------------------------------------------------------- 1 | """Python Brasil 2 | Lista de exercícios de listas. 3 | Exercício 9: Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos 4 | elementos do vetor.""" 5 | 6 | numeros = [] 7 | for n in range(1, 11): 8 | numero = int(input(f'Informe o {n}º número inteiro: ')) 9 | numero = numero**2 10 | numeros.append(numero) 11 | print(f'A soma dos quadrados dos elementos digitados é igual a: {sum(numeros)}.') 12 | --------------------------------------------------------------------------------