top of page

MARCOS DE TRABALHO

EXERCÍCIOS DE PYTHON

Who Loves AI - insta.jpg
Seguem 15 problemas de Python para diversão geral e mais umas dicas ao final dessa página!!!

Também tem um pdf com muitos problemas interessantes.

David Kopec, “Classic Computer Science Problems in Python”, Publisher: Manning, First Edition, March 15, 2019.

Problem 0:

 

About deciding whether we're prepared for the weather. 
 

I said that I'm safe from today's weather if...

I have an umbrella...
or if the rain isn't too heavy and I have a hood...
otherwise, I'm still fine unless it's raining and it's a workday

Please complete the code below:

have_umbrella = (False or True)
rain_level = (0, 1, 2) # 0 = is not raining; 1 = rain isn't too heavy; and  2 = rain is too heavy
have_hood = (False or True)
is_workday = (False or True)

###

# code...is_workday = True

###

print("prepared_for_weather = ", prepared_for_weather)

Problem 1:

 

If n is an integer greater than 0, n factorial (n!) is the product: n* (n-1) * (n-2) * ( n-3)… *

 

By convention, 0! = 1.

 

You must write a program that allows a user to enter an integer between 1 and 7. Your program must then compute the factorial of the number entered by the user.

 

Your solution MUST actually perform a computation (i.e., you may not simply print “5040” to the screen as a literal value if the input is 7).

Problem 2:

 

The Jones Trucking Company tracks the location of each of its trucks on a grid similar to an (x, y) plane. The home office is at location (0, 0). Read the coordinates of truck A and the coordinates of truck B and determine which is closer to the office.

 

Input: The first line of the data set for this problem is an integer representing the number of collections of data that follow. Each collection contains 4 integers: the x-coordinate and then the y-coordinate of truck A followed by the x-coordinate and then the y-coordinate of truck B.

Problem 3:

 

In this problem you must write a program that determines if two circles intersect each other. The input to your program will be the coordinates for the center of each circle, followed by the radius of each circle.

 

The output will state whether the circles overlap, do not overlap, or are tangential (i.e., tangential circles touch each other at just one common point).

 

Example 1:

Enter the coordinates and radius for circle 1: 10 10 3

Enter the coordinates and radius for circle 2: 10 6 1

The circles are tangential.

Problem 4:

 

The sum of the squares of the first ten natural numbers is,

1^2 + 2^2 + ... + 10^2 = 385

 

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^2 = (55)^2 = 3025

 

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025  -  385 = 2640.

 

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Problem 5:

 

Find the greatest product of five consecutive digits in the 50-digit number.

 

73167176531330624919225119674426574742355349194934

Problem 6:

 

“Bubble sort” is one of the classic sorting algorithm which is used to explain sorting during various computer and engineering courses

 

In “Bubble sort” algorithm we sort an unsorted array by starting from first element and comparing with adjacent element. If former is greater than later then we swap. And by doing this we get the largest number at the end after first iteration. So in order to sort “n” elements you require “n-1” iteration and almost “n-1” comparison.

Você é Porco ou Galinha?

There’s an old joke in the Scrum community. A chicken and a pig are walking down the road, and the chicken says, “Hey, Pig, I was thinking we should open up a restaurant.”

“What should we call it?” asks the pig.

“How about ‘Ham and Eggs’?”

“No thanks,” says the pig. “I’d be committed, but you’d only be involved!”

The idea in Scrum is that the “pigs” are the ones who are totally committed to the project and are responsible for its outcome. The “chickens” are the people who are informed of its progress, the stakeholders. On the wall in the Sentinel room is a pig-shaped bell. When it rings, the people who did what everyone said couldn’t be done know they’re being called. There’s another bell, the doorbell, but that’s for the chickens.

Jeff Sutherland (Co-creator of Scrum) and J.J. Sutherland,

“Scrum: The Art of Doing Twice the Work in Half the Time”,

Published by Crown Business, 2014.

Problem 7:

 

It is a simple card game called Higher or Lower. In this game, eight cards are randomly chosen from a deck. The first card is shown face up. The game asks the player to predict whether the next card in the selection will have a higher or lower value than the currently showing card. For example, say the card that’s shown is a 3. The player chooses “higher,” and the next card is shown. If that card has a higher value, the player is correct. In this example, if the player had chosen “lower,” they would have been incorrect.

 

If the player guesses correctly, they get 20 points. If they choose incorrectly, they lose 15 points. If the next card to be turned over has the same value as the previous card, the player is incorrect.

 

The program needs to represent a deck of 52 cards, which will be built as various lists. The value is a list of integers used for comparing cards (1, 2, 3, … 10, 11, 12, 13).

 

# Card constants

SUIT_LIST = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

RANK_LIST = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']

VALUE_LIST = [1, 2, 3, … 10, 11, 12, 13]

Problem 8:

 

Gambler's Ruin Problem:

Consider a gambler who starts with an initial fortune of $1 and bet on the outcomes of successive gambles. The gambler will either win $1 with the probability of p, 0 < p < 1 or will loss $1 with the probability of q, (q = 1 - p). It is assumed that the successive gambles are independent. The gambler’s objective is to end up winning $10 without getting ruined (running out of money). In any case, the gambler stops playing after winning $10 or getting ruined, whichever happens first.

 

What is the probability that the gambler will end up with $10?

Para ajudar os interessados nesse problema, deixo aqui a solução para o problema com p = 0.5. Então, a probabilidade de terminar com $10 começando com $1 e com p  = 0.5 é 10%. Você pode brincar e calcular qual a probabilidade de terminar com $20 começando com $1 e com p  = 0.7.

Problem 9:

 

A cylindrical tank with a hemispherical top, as shown in Figure below, is to be constructed that will hold 5.00E05 L when filled. Determine the tank radius R and height H to minimize the tank cost if the cylindrical portion costs $300/m2 of surface area and the hemispherical portion costs $400/m2.

imagem-cilindicar-tank.jpg
  1. ​Cylinder volume = 3.14 * (radius**2) * height

  2. Hemisphere volume = (2/3) * 3.14 * (radius**3)

  3. Cylinder surface area = 2 * 3.14  * radius * height

  4. Hemisphere surface area = 2 * 3.14  * (radius**2)

Problema 10:

 

Encontre a raiz da função f(x) = (x^3) -(9*x) + 3 entre 0 <= x <= 1 , utilizando o algoritmo da bissecção.

 

Este algoritmo consiste em identificar-se dois pontos, tais que f(a) e f(b) tenham sinais opostos, sendo então f(a) * f(b) < 0. A ideia é diminuir o intervalo [a ; b] através de repetidas divisões ao meio, de tal forma que o valor de “a” tenda ao valor de “b”, ou seja, que a função f(x) seja aproximadamente nula dentro de uma certa tolerância.

Problem 11:

 

Table 3.5 lists the profits to be made in each of four ventures as a function of the investment in the particular venture. Given a limited amount of money to allocate, the problem is to find the optimal investment allocation.

investment.jpg

Problem 12:

 

The knapsack problem is a particular type of integer program with just one constraint. Each item that can go into the knapsack has a size and a benefit. The knapsack has a certain capacity. What should go into the knapsack so as to maximize the total benefit? As an example, suppose we have three items as shown in Table 4, and suppose the capacity of the knapsack is 47.

knapsack-problem.jpg

Problem 13:

 

For a price of $1/gallon, the Safeco Supermarket chain has always, for 3 years, purchased 6 gallons of milk from a local dairy. Each gallon of milk is sold in the chain’s three stores for $2/gallon. The dairy must buy back for 50¢/gallon any milk that is left at the end of the day.

 

Unfortunately for Safeco, demand for each of the chain’s three stores is uncertain. Past data, accounted for 3 years, indicate that the daily demand at each store is as shown in the below table.

 

Safeco wants to allocate the 6 gallons of milk to the three stores so as to maximize the expected net daily profit (revenues less costs) earned from milk.

 

How Safeco should allocate the 6 gallons of milk among the three stores???

Referência.

http://fatihcavdur.home.uludag.edu.tr/docs/end3034/sdp.pdf

imagem percentagem galões de leite.jpg

OBS 1: É importante entender como foi cosntruída a Tabela de Probabilidades acima. Então vamos fazer uma breve explicação aqui. Para começo de conversa, vamos fazer as explicações somente para a Store 1. As explicações das outras 2 Stores seguem a mesma lógica. Então, para construir essa tabela de probabilidades para a Store 1, o dono começou a colocar todo dia, 3 galões de leite na Store 1 (vamos imaginar que foi durante muitos e muitos anos). Todo dia ele colocava 3 galões de leite. E registrava ao final do dia se haviam sido vendidos 3, 2 ou somente 1 galão. Assim foi construída a Tabela acima. Claro está que se forem alocados somente 2 galões para a Store 1 num determinado dia qualquer, a probabilidade de se venderem esses 2 galões ao final do dia é de 50%. E claro está também que se for alocado somente 1 galão para a Store 1 num determinado dia qualquer, a probabilidade de se vender esse galão ao final do dia é de 100%. A explicação do porque é 100% eu não vou colocar aqui. Essa explicação é bem simples.

OBS 2: Para facilitar o problema, vamos considerar as seguintes restrições:

1) Não se pode alocar mais de 3 galões de leite numa Loja. Pode-se alocar zero, mas não >  3; e

2) A soma de todos os galões alocados nas três lojas tem que ser igual a 6.

Para os interessados, a alocação que apresenta o maior valor esperado de lucro (receita menos custos) (expected daily profit) é 3 galões na Store 1; 3 galões na Store 2; e 0 galões na Store 3. Isso se eu não errei nos cálculos!!!

 

Se você achar um resultado diferente, mande para o meu e-mail, por favor, easodre@gmail.com.

O mais importante de tudo nesse problema é que a solução não é a alocação que apresenta o máximo valor esperado da riqueza (dinheiro). Mas sim aquele que apresenta o maior valor esperado da "utilidade" da riqueza (utility), conforme Teoria do Prospecto. Essa solução eu ainda não fiz.

Problem 14:

 

Write a program to find the shortest routing and distance between two Alabama cities using the following distance table.

 

You are not allowed to use any other manually computed distances in your program.

 

Alabaster-Birmingham 24 miles
Alabaster-Montgomery 71 miles
Birmingham-Huntsville 103 miles
Birmingham-Tuscaloosa 59 miles
Demopolis-Mobile 141 miles
Demopolis-Montgomery 101 miles
Demopolis-Tuscaloosa 65 miles
Mobile-Montgomery 169 miles
Montgomery-Tuscaloosa 134 miles

 

Example 1:
Enter city #1: Demopolis
Enter city #2: Birmingham
Shortest routing and distance:
Demopolis-Tuscaloosa-Birmingham, 124 miles

caminhos cidade do Alabama.jpg
Alabama_map-L.jpg
the algorithmic thinking - book -langtangen-2016.jpg
power up.jpg

Problem 15:

A companhia de aviação Benvoa vai comprar aviões a jato de passageiros, para viagens longas, médias e curtas (tipos Al, Am e Ac, respectivamente).

Os custos unitários, em milhões de R$ são para os tipos Al, Am e Ac, respectivamente, de 5.0, 3.8 e 2.0.

 

A administração da companhia autorizou a verba máxima de R$ 112.00 milhões para esse efeito.

Admite-se que os lucros anuais sejam de 310, 230 e 200 milhões de R$ com cada um dos tipos de avião Al, Am e Ac, respectivamente.

 

Haverá pilotos suficientes para pilotar, no máximo, 30 aviões novos.

 

Se apenas fossem comprados aviões Ac, os serviços de manutenção suportariam 40 aviões novos. Contudo, cada avião Am equivale a 4/3 de um avião Ac e cada avião Al a 5/3 de um avião Ac, no que diz respeito à manutenção.

 

A direção técnica é ainda de opinião que, por cada avião Ac que seja comprado, se comprem também pelo menos um avião Al ou um avião Am. Ou seja, Ac <= (Al + Am).

 

Por outro lado, selecionado um avião Al para comprar, também deverão ser comprados pelo menos 8 aviões Ac ou Am. Ou seja, para cada avião Al comprado, deve-se ter 8 aviões entre curtos e médios, por exemplo, (3 Ac´s + 5 Am´s), ou (6 Am´s + 2 Ac´s).

 

Com estes dados, a gestão da empresa deve decidir a quantidade de aviões de cada tipo a comprar, de modo a maximizar o lucro.

image how users see the programmers and vice versa.jpeg
imagem-2-slicy-linspace.png

Hans Petter Langtangen, “A Primer on Scientific Programming with Python”, 5th Edition, Springer, 2016.

Plotting multiple curves

import numpy as np
import matplotlib.pyplot as plt

 

def f1(t):
    var2 = np.exp(-1*(t**2))
    return (t**2)*var2
# end def f1(t):

def f2(t):
    var3 = (t**2)*f1(t)
    return var3
# end def f2(t):
    
t = np.linspace(0, 3, 51)

y1 = f1(t)
y2 = f2(t)

 

plt.plot(t, y1, 'r-')
plt.plot(t, y2, 'bo')
plt.xlabel('t')
plt.ylabel('y')

plt.legend(['t^2*exp(-t^2)', 't^4*exp(-t^2)'])

plt.title('Plotting two curves in the same plot')
plt.grid(True)
plt.show()

obs: A legenda do gráfico pode ser melhorada utilizando-se o seguinte comando:

        plt.legend(['$t^2e^{-t^2}$', '$t^4e^{-t^2}$']).

        Essa foi uma contribuição do colega Hugo Salvador <hugoesb@gmail.com>

Figure_1.png

Placing several plots in one figure

...

...

...

t3 = t[::4]
y3 = f2(t3)

plt.figure() # make separate figure
###
plt.subplot(2, 1, 1)
plt.plot(t, y1, 'r-', t, y2, 'bo')
plt.xlabel('t')
plt.ylabel('y')
plt.axis([t[0], t[-1], min(y2)-0.05, max(y2)+0.5])
plt.legend(['t^2*exp(-t^2)', 't^4*exp(-t^2)'])
plt.grid(True)
plt.title('Top figure')

#

plt.subplot(2, 1, 2)
plt.plot(t, y1, 'b-', t3, y3, 'ys')
plt.xlabel('t')
plt.ylabel('y')
plt.axis([0, 4, -0.2, 0.6])
plt.legend(['t^2*exp(-t^2)', 't^4*exp(-t^2)'])
plt.grid(True)
plt.title('Bottom figure')
###
plt.show()

 

Figure_2.png
bottom of page