myDict={"pizzaHut" : ["PizzaHut", [155, 407], [1100, 2200], "halal", "fast-food", [10.00, 30.00], "Hawaiian Ala-Carte ($10.80)"],
"starbucks" : ["Starbucks Coffee", [155, 407], [700, 2200], "halal", "beverages", [6.00, 11.00], "Vanilla Latte ($6.70)"],
"subway" : ["Subway", [155, 407], [800, 2100], "halal", "fast-food", [5.00, 10.00], "Chicken Teriyaki Sandwich ($6.70)"]}
x = input("What is the x-coordinate of your location?")
y = input("What is the y-coordinate of your location?")
i want to find the distance of the different eateries from the location input by the user, how do i do that? Really new to python so i dont know how to start
datalist = list(myDict.values())
destinationList = []
for i in datalist:
destinationList.append([i[0],i[1]])
distance = []
def distance (x, y,destinationList):
for element in destinationList:
x1 = element[1][0]
y1 = element[1][1]
distance.append((((x1-x)**2)+((y1-y)**2))**0.5)
print(distance)
but this doesn't work.
The output should be a list of 3 calculated distance of user location from the 3 eateries
The complete code
myDict={"pizzaHut" : ["PizzaHut", [155, 407], [1100, 2200], "halal", "fast-food", [10.00, 30.00], "Hawaiian Ala-Carte ($10.80)"],
"starbucks" : ["Starbucks Coffee", [155, 407], [700, 2200], "halal", "beverages", [6.00, 11.00], "Vanilla Latte ($6.70)"],
"subway" : ["Subway", [155, 407], [800, 2100], "halal", "fast-food", [5.00, 10.00], "Chicken Teriyaki Sandwich ($6.70)"]}
x = int(input("What is the x-coordinate of your location?\n"))
y = int(input("What is the y-coordinate of your location?\n"))
datalist = list(myDict.values())
destinationList = []
for i in datalist:
destinationList.append([i[0],i[1]])
distance = []
def find_distance(x, y,destinationList):
for element in destinationList:
x1 = element[1][0]
y1 = element[1][1]
distance.append((((x1-x)**2)+((y1-y)**2))**0.5)
print(distance)
find_distance(x,y,destinationList)
Related
I have been trying to create a polar bar chart in python for quite some time. After some research I managed to get the results that I wanted. Well, almost. There're still a couple thing that I don't know how to do.
I include my code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FixedLocator
from operator import add
#DATA MANIPULATION
dataset = pd.read_csv('Controls.csv', delimiter=";")
dataset.astype({'Rating':'float'})
#print(dataset.dtypes)
categories = dataset['Category'].drop_duplicates()
controls = dataset['Control'].drop_duplicates()
categ_avg = []
control_average = []
#Average for controls
for category in categories:
avg = 0
for index, item in dataset.iterrows():
if item['Category'] == category:
avg += item['Rating']
categ_avg.append(avg)
avg = 0
for control in controls:
avg = 0
for index, item in dataset.iterrows():
if item['Control'] == control:
avg += item['Rating']
control_average.append(avg)
avg = 0
average = [total / 5 for total in categ_avg]
avgdf = pd.DataFrame({
'Category' : categories,
#'Controls' : controls,
'Average' : average
})
#PLOTTING
#Compute pie slices which is the number of unique controls
N = len(controls)
#theta = np.linspace(0, 2 * np.pi, N, endpoint=False)
theta = [0]
for cat in categories:
if cat == 'CAT-A':
theta.append( theta[-1] + (2 * np.pi/N * 2) )
else:
theta.append( theta[-1] + (2*np.pi / N) )
print(theta)
#Compute the filling axis
mid_theta = []
for cat in categories:
if cat == 'CAT-A':
mid_theta.append( 2 * np.pi/N )
else:
mid_theta.append( 2 * np.pi / N / 2 )
mid_theta = list(map(add,theta, mid_theta))
print(mid_theta)
radii = avgdf['Average']
#width = theta[1] - theta[0]
width = []
for i in range(0, len(avgdf['Average'])):
width.append(theta[i+1] - theta[i])
fig = plt.figure()
fig.patch.set_facecolor('white')
fig.patch.set_alpha(0.5)
#Draw X labels
ax = fig.add_subplot(111, projection='polar')
ax.set_xticks(theta)
# Draw ylabels
ax.set_rlabel_position(0)
ax.set_yticks([1, 2, 3, 4, 5])
ax.set_yticklabels(["1", "2", "3", "4", "5"], color="black", size=8)
ax.set_ylim(0, 5)
#colors = plt.cm.hsv(theta/2/np.pi)
bars = ax.bar(mid_theta, radii, width=width, bottom=0.0)
#Labels
for bar, angle, label in zip(bars, mid_theta, avgdf["Category"]):
# Labels are rotated. Rotation must be specified in degrees :(
rotation = np.rad2deg(angle)
# Flip some labels upside down
alignment = ""
if angle >= np.pi/2 and angle < 3*np.pi/2:
alignment = "right"
rotation = rotation + 180
else:
alignment = "left"
# Finally add the labels
ax.text(
x=angle,
y=5.5,
s=label,
ha=alignment,
va='center')
#Use custom colors and opacity
for r, bar in zip(avgdf['Average'], bars):
bar.set_facecolor(plt.cm.viridis(r/5.))
bar.set_alpha(0.5)
plt.show()
When I execute it I obtain the following graph: Resulting graph
What I'm trying to achieve is:
I would like to color the ring number 4 in green.
I would like to remove the degrees from the outer ring. I only want to see my categories not the 0, 144º...
I really appreciate the help.
Thanks you.
Create a list of colours with as many colours as you have polar bars.
c = ['blue', 'blue', 'blue', 'green', 'blue', 'blue']
bars = ax.bar(
x=angles,
height=heights,
width=width,
color=c,
linewidth=2,
edgecolor="white")
The sum of two numbers is 20. If each number is added to its square root, the product of the two sums is 155.55. Use Secant Method to approximate, to within 10^(-4), the value of the two numbers.
Based on http://campus.murraystate.edu/academic/faculty/wlyle/420/Secant.htm
#inital guess
x1 = 10
x2 = 50
Epsilon = 1e-4
#given function
def func(x):
return abs(x)**0.5 * (abs(x)+20)**0.5 - 155.55
y1 = func(x1)
y2 = func(x2)
#loop max 20 times
for i in range(20):
ans = x2 - y2 * (x2-x1)/(y2-y1)
y3 = func(ans)
print("Try:{}\tx1:{:0.3f}\tx2:{:0.3f}\ty3:{:0.3f}".format(i,x1, x2, y3))
if (abs(y3) < Epsilon):
break
x1, x2 = x2, ans
y1, y2 = y2, y3
print("\n\nThe numbers are: {:0.3f} and {:0.3f}".format(ans, ans+20))
Based on Your Title
This code works well in most of the cases. Taken from Secant Method Using Python (Output Included)
# Defining Function
def f(x):
return x**3 - 5*x - 9
# Implementing Secant Method
def secant(x0,x1,e,N):
print('\n\n*** SECANT METHOD IMPLEMENTATION ***')
step = 1
condition = True
while condition:
if f(x0) == f(x1):
print('Divide by zero error!')
break
x2 = x0 - (x1-x0)*f(x0)/( f(x1) - f(x0) )
print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))
x0 = x1
x1 = x2
step = step + 1
if step > N:
print('Not Convergent!')
break
condition = abs(f(x2)) > e
print('\n Required root is: %0.8f' % x2)
# Input Section
x0 = input('Enter First Guess: ')
x1 = input('Enter Second Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')
# Converting x0 and e to float
x0 = float(x0)
x1 = float(x1)
e = float(e)
# Converting N to integer
N = int(N)
#Note: You can combine above three section like this
# x0 = float(input('Enter First Guess: '))
# x1 = float(input('Enter Second Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))
# Starting Secant Method
secant(x0,x1,e,N)
Python 3.6. I don't understand why my plots are so smashed like this inside each part of the grid. Width is ok, they are stuck by two as i wanted, and space between each block is also ok. But i didn't find what i could change to change the size of the y axis.
Here is my code:
def graphiqueLigneDate(listeDates, listeOrdonnees, nomOrdonnees, axe, labelLigne):
# -- Variables utiles
listeTicks = []
step = 5
for i in range(int(len(listeDates)/step)+1):
listeTicks.append(listeDates[step*i][:-5])
# -- Configurer graphique ---
axe.plot([i for i in range(1,len(listeDates)+1)], listeOrdonnees, label = labelLigne)
axe.set_ylabel(nomOrdonnees)
axe.set_xlabel('Date')
axe.set_xticks([i for i in range(1,len(listeDates)+1,5)])
axe.set_xticklabels(listeTicks)
axe.legend()
fig = plt.figure(figsize=(6,5))
fig.suptitle('Volume vs Prix', size=18)
plt.subplots_adjust(top=0.9, wspace=0.1, hspace=0.5)
nbreDeMots = len(listeMots)
heightRatiosListe = [1] * nbreDeMots
grille = gridspec.GridSpec(nbreDeMots, 2, height_ratios = heightRatiosListe)
i = 0
for mot in listeMots:
gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = grille[i], hspace = 0)
j = 0
for cellule in gs:
ax1 = fig.add_subplot(cellule)
if j % 2 == 0:
ax1.tick_params(axis='x',which='both', direction='in' , bottom='on',top='off', labelbottom='off')
ax1.set_ylabel('Volume')
ft.graphiqueLigneDate(listeBonnesDates, dicoVolume[mot], 'Volume Tweet', ax1, mot)
else:
ax1.set_xlabel('Date')
ax1.set_ylabel('Prix')
ft.graphiqueLigneDate(listeBonnesDates, dicoSpot[mot], 'Volume Tweet', ax1, mot)
j += 1
i +=1
fig.tight_layout()
fig.show()
Thanks !
I am trying to make a function where it find the slope and y int of a Line from two points, and return it to a list.
def find(p1, p2):
However I'm having trouble finding out how the user would input in a coordinate for p1 as (2,10) and p2 (4,16) when there are only two input parameters?
In Python 3, input() returns a string, so you can ask the user to enter a number in a certain format, then parse it into a tuple of the two coordinates:
p = input('Enter a point as #,#: ')
p = tuple(int(x) for x in p.split(','))
print('p =',p)
Result:
Enter a point as #,#: 10,12
p = (10, 12)
You can break the two components apart with the following to do a calculation:
x,y = p
Or just use p[0] and p[1] to access the first and second coordinates.
Tie it all together with:
def get_point():
p = input('Enter a point as #,#: ')
p = tuple(int(x) for x in p.split(','))
return p
def find(p1,p2):
x1,y1 = p1
x2,y2 = p2
# do calculation
# return result
p1 = get_point()
p2 = get_point()
result = find(p1,p2)
So, I have this exercise where I have to find the nearest pharmacy from the coordinate inputted by the user, but i don't know how to.
I have a file with the coodinates from each pharmacy, like this:
300 200
10 56
25 41
90 18
70 90
100 50
And when the user input his coordinate ("20 88" in the example) i should tell him the coordinate from the nearest one. I'll write what I already have, but my codes are in Brazilian Portuguese, so i hope you can help me.
# Sub-programa
def fazTudo():
dados = open("texto.txt", "r")
linha = dados.readline()
if linha == "":
return "Arquivo de Farmácias está vazio!!!"
else:
for i in range(6):
distancia = []
vetor = dados.readline()
x, y = vetor.split()
distanciaX = x
distanciaY = y
distancia = distanciaX, distanciaY
# Programa Principal
entrada = (input().split(" "))
fazTudo()
It seems that the current stage you're at is reading the distances from the file.
From there, what you would want to do is find compare the users inputted location to the location of each pharmacy. Finding the smallest displacement in both the X and Y co-ordinates should get you the closest pharmacy. But since you want distance, you would want to convert the displacement value to distance by getting the absolute.
Here is a solution that I thought of:
# Find the closest distance to the pharmacies from a text file.
def closest_distance(raw_input_location):
nearest_pharmacy = [0, 0]
user_x_y = raw_input_location.split(" ")
with open("filename.txt") as f:
locations = f.read().splitlines()
if not locations:
return "Pharmacy list is empty!!!"
else:
for index, row in enumerate(locations):
x_y = row.split(" ")
delta_x = abs(int(user_x_y[0]) - int(x_y[0]))
delta_y = abs(int(user_x_y[1]) - int(x_y[1]))
if index == 0:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
elif delta_x < nearest_pharmacy[0] & delta_y < nearest_pharmacy[0]:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
# Returns the distance required to goto the closest pharmacy
return str(nearest_pharmacy[0]) + " " + str(nearest_pharmacy[1])
# Prints out the closest distance from the inputted location
print(closest_distance("20 88"))