Compare two arrays and find the nearest result - python-3.x

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"))

Related

Solving cars moving in multiple lanes simulation problem

I am trying to simulate cars moving in multiple lanes in python. The problem is like this:
The number of cars, the roadlength, the probability and vmax are all input values.
Rules:
1. If vi < vmax, increase the velocity vi of car i by one unit, that is, vi → vi + 1. This change models the process of acceleration to the maximum velocity.
2. Compute the distance to the next car in the same lane and the distance to the cars in both (if there are 2) lanes next to the car.
If d=max([d1,d2,d3]) and vi ≥ d, then reduce the velocity to vi = d − 1 to prevent crashes and switch lane to the lane where the distance to the next car is d (if there are multiple choose one at random or whichever you want).
Else (meaning there is at least one lane next to the car's lane or it could be the same lane that the car is in where d > vi) go in that lane and don't change the velocity of the car if there is more than one lane, pick one at random.
3. With probability p, reduce the velocity of a moving car by one unit: vi → vi − 1, only do this when v > 0 to avoid negative velocities
4. Update the position xi of car i so that xi(t + 1) = xi(t) + vi
Also the path of the cars is circular, meaning there will be cars in front and behind.
Below is my attempt to solve the problem. Don't get confused over the variables theta and r. theta is just the position and r is the lane.
My attempt:
from matplotlib import pyplot as plt
import random
import math
from matplotlib import animation
import numpy as np
from operator import attrgetter
roadLength = 100
numFrames = 200
nlanes = 3
numCars = 20
posss =[]
theta = []
r = []
color = []
probability = 0.5
vmax = 1
cars=[]
class Car:
def __init__(self, position, velocity, lane):
self.position = position
self.velocity = velocity
self.lane = lane
def pos(car,k):
rand = random.uniform(0,1)
if car[k].velocity < vmax:
car[k].velocity += 1
dist = 0
if car[k].lane == 1:
temp_lanes_between = [0,1]
if car[k].lane == nlanes and nlanes != 1:
temp_lanes_between = [-1 ,0]
if 1 < car[k].lane < nlanes:
temp_lanes_between = [-1 ,0, 1]
iterator = []
for p in range(k+1, numCars):
iterator.append(p)
#if car[k+1].position - car[k].position <= car[k].velocity and car[k].lane == car[k+1].lane:
for p in range(k):
iterator.append(p)
for s in iterator:
if car[s].lane - car[k].lane in temp_lanes_between:
temp_lanes_between.remove(car[s].lane - car[k].lane)
distance = min([abs((car[s].position - car[k].position) % roadLength), roadLength - abs((car[s].position - car[k].position) % roadLength)])
if dist < distance:
dist = distance
l = car[s].lane
if dist <= car[k].velocity:
break
if temp_lanes_between:
j=random.randrange(0, len(temp_lanes_between))
car[k].lane += temp_lanes_between[j]
if temp_lanes_between == [] and dist <= car[k].velocity:
car[k].velocity = dist - 1
car[k].lane = l
if rand < probability and car[k].velocity > 0:
car[k].velocity = car[k].velocity - 1
car[k].position = car[k].position + car[k].velocity
return car[k].position
for i in range(numCars):
cars.append(Car(i, 0, 1))
theta.append(0)
r.append(1)
color.append(i)
posss.append(i)
fig = plt.figure()
ax = fig.add_subplot(111)
point, = ax.plot(posss, r, 'o')
ax.set_xlim(-10, 1.2*numFrames)
ax.set_ylim(-2, nlanes + 3)
def animate(frameNr):
sort_cars = sorted(cars, key=attrgetter("position"))
for i in range(numCars):
pos(sort_cars,i)
for k in range(numCars):
theta[k]=cars[k].position
r[k]=cars[k].lane
print(theta)
print(r)
point.set_data(theta, r)
return point,
def simulate():
anim = animation.FuncAnimation(fig, animate,
frames=numFrames, interval=100, blit=True, repeat=False)
plt.show()
simulate()
I get error saying: "local variable 'l' referenced before assignment" in the line where car[k].lane = l . I know that they mean that l doesn't have any value and therefore I get this error. But I don't see how this is possible. Every time pos() is run it should always go through the line l = car[s].lane and there it gets assigned a value. Maybe there are more errors in the code above but I have really given it my best shot and I don't know what to do.
Thanks in advance!

How could I set the staring and ending points randomly in a grid that generates random obstacles?

I built a grid that generates random obstacles for pathfinding algorithm, but with fixed starting and ending points as shown in my snippet below:
import random
import numpy as np
#grid format
# 0 = navigable space
# 1 = occupied space
x = [[random.uniform(0,1) for i in range(50)]for j in range(50)]
grid = np.array([[0 for i in range(len(x[0]))]for j in range(len(x))])
for i in range(len(x)):
for j in range(len(x[0])):
if x[i][j] <= 0.7:
grid[i][j] = 0
else:
grid[i][j] = 1
init = [5,5] #Start location
goal = [45,45] #Our goal
# clear starting and end point of potential obstacles
def clear_grid(grid, x, y):
if x != 0 and y != 0:
grid[x-1:x+2,y-1:y+2]=0
elif x == 0 and y != 0:
grid[x:x+2,y-1:y+2]=0
elif x != 0 and y == 0:
grid[x-1:x+2,y:y+2]=0
elif x ==0 and y == 0:
grid[x:x+2,y:y+2]=0
clear_grid(grid, init[0], init[1])
clear_grid(grid, goal[0], goal[1])
I need to generate also the starting and ending points randomly every time I run the code instead of making them fixed. How could I make it? Any assistance, please?.
Replace,
init = [5,5] #Start location
goal = [45,45] #Our goal
with,
init = np.random.randint(0, high = 49, size = 2)
goal = np.random.randint(0, high = 49, size = 2)
Assuming your grid goes from 0-49 on each axis. Personally I would add grid size variables, i_length & j_length
EDIT #1
i_length = 50
j_length = 50
x = [[random.uniform(0,1) for i in range(i_length)]for j in range(j_length)]
grid = np.array([[0 for i in range(i_length)]for j in range(j_length)])

Python logic isn't yielding the correct answer and I'm having difficulty with developing the context

Values including height = 10, number = 2, and bounciness = 6 should come to 25.6 feet, but I'm getting 23.2 feet. Can someone help me understand where my logic is screwed up please?
import math
# User inputs are set up
height = int(input("Enter the height of the ball: "))
number = int(input("Enter the number of bounces of the ball: "))
bounciness = int(input("Enter the height for each successive bounce: "))
count = 0
# Calculation
for count in range(bounciness):
count = (height * bounciness)/100
distance = height + count
bounceSum = number * bounciness
total = count + distance + bounceSum
# Results
print("The ball has traveled a total distance of", total, "feet.")
If you look at the calculation in the for loop, this is what happens in the first iterations (and ones after that too):-
count = 10*6/100 = 0.6
distance = 10 + 0.6 = 10.6 (count is 0.6 here because of the line above)
bounceSum = 2*12 = 12
total = 0.6 + 10.6 + 12 = 23.2
The problem with the logic in your code is the variable count. There are 3 different definitions of it and they keep overwriting the other:
count = 0 above the for loop
count which ranges from 0 to bounciness-1
count = (height*bounciness)/100
I think I fixed it...
import math
# User inputs are set up
height = int(input("Hello, please enter the height of the ball: "))
number = int(input("Next, enter the number of bounces of the ball: "))
bounciness = int(input("Now enter the height for each successive bounce: "))
index = 0
# Calculation
for index in range(bounciness):
index = bounciness * 0.6
distance = height + (bounciness * number)
total = index + distance
# Results
print("The ball has traveled a total distance of", total, "feet.")
print("Good bye")

matplotlib.pyplot imshow() now shows a solid blue colour, no longer the colour rendering?

Further to my previous, helpfully addressed, question here
How to centre the origin in the centre of an imshow() plot
after some fiddling about with the some parameters, spyder now consistently shows a blank blue output. It is baffling!!
I've forced the dtype to be uint8 (I read this on a related question that this may be the cause) but to no avail.
EDIT: (Thanks to the rapid responses) here is the relevant code (from a larger program for modelling diffraction through a square aperture):
import numpy as np
import matplotlib.pyplot as plt
def expo(x,y,z,xp,yp,k):
"""
Function of the integrand in Eq. 5
"""
return np.exp((1j*k/(2*z))*(((x-xp)**2) + ((y-yp)**2)))
def square_2dsimpson_eval(a,b,n):
simp_eval = np.zeros((n+1,n+1))
deltap = (b-a)/n
xp = 0
yp = 0
w = np.zeros((n+1,n+1))
x=0
y=0
for h in range(n+1): #the first two for loops produce the 2d Simpson matrix of coeffecients
if h == 0 or h==n:
w[0,h] = 1
elif h%2 != 0:
w[0,h]=4
elif h%2 == 0:
w[0,h]=2
for g in range(n+1):
if g ==0 or g==n:
w[g,0]=1
elif g%2 != 0:
w[g,0]=4
elif g%2 == 0:
w[g,0]=2
for h in range(1,n+1):
for g in range(1,n+1):
w[h,g]=w[0,h]*w[g,0]
for h in range(0,n+1):
xp = h*deltap
for g in range(0,n+1):
yp = g*deltap
simp_eval[h,g] = expo(x,y,z,xp,yp,k) #the integrand
return (k/(2*np.pi*z))*((deltap**2)/9)*(np.sum(simp_eval*w))
n = 3.3
#this loop checks that user's N is even as required for Simpson's rule
while n % 2 != 0:
n = int(input("Type an even N value: "))
if n % 2 == 0:
break
else:
print("n must be even you noob!")
lam=float(input("Type light wavelength in mm: "))
k=(2*np.pi)/lam
z=float(input("Type screen distance, z in mm: "))
rho=float(input("Type rho in mm: "))
delta = 2/n
intensity = np.zeros((n+1,n+1),dtype='uint8')
for i in range(n+1):
x=-1+(i*delta)
for j in range(n+1):
y =-1+(j*delta)
intensity[i,j] = (abs(square_2dsimpson_eval(-rho/2,rho/2,n)))**2
print(intensity.dtype)
plt.imshow(intensity)
plt.show()
The plot has gone from this:
to this:
Thanks in advance.
Without Even knowing the code that produces either image, I can only say that the second image seems to be a cutout of the first image in a region where there is no data or data is close to or equal the minimum value.

select with bokeh not really working

I am using bokeh 0.12.2. I have a select with words. When i choose a word it should circle the dot data. It seems to work then stop. I am trying with 2 words, word1 and word2. lastidx is full of index.xc and yx are the location of the circle here is the code. This is working with one but not really if i change the value in the select:
for j in range(0,2):
for i in range(0,len(lastidx[j])):
xc.append(tsne_kmeans[lastidx[j][i], 0])
yc.append(tsne_kmeans[lastidx[j][i], 1])
source = ColumnDataSource(data=dict(x=xc, y=yc, s=mstwrd))
def callback(source=source):
dat = source.get('data')
x, y, s = dat['x'], dat['y'], dat['s']
val = cb_obj.get('value')
if val == 'word1':
for i in range(0,75):
x[i] = x[i]
y[i] = y[i]
elif val == 'word2':
for i in range(76,173):
x[i-76] = x[i]
y[i-76] = y[i]
source.trigger('change')
slct = Select(title="Word:", value="word1", options=mstwrd , callback=CustomJS.from_py_func(callback))
# create the circle around the data where the word exist
r = plot_kmeans.circle('x','y', source=source)
glyph = r.glyph
glyph.size = 15
glyph.fill_alpha = 0.0
glyph.line_color = "black"
glyph.line_dash = [4, 2]
glyph.line_width = 1
x and y are loaded with all the data here and I just pick the data for the word I select. It seems to work and then it does not.
Is it possible to do that as a stand alone chart?
Thank you
I figured it out: code here is just to see if this was working. This will be improved of course. And may be this is what was written here at the end:
https://github.com/bokeh/bokeh/issues/2618
for i in range(0,len(lastidx[0])):
xc.append(tsne_kmeans[lastidx[0][i], 0])
yc.append(tsne_kmeans[lastidx[0][i], 1])
addto = len(lastidx[1])-len(lastidx[0])
# here i max out the data which has the least
# so when you go from one option to the other it
# removes all the previous data circle
for i in range(0,addto):
xc.append(-16) # just send them somewhere
yc.append(16)
for i in range(0, len(lastidx[1])):
xf.append(tsne_kmeans[lastidx[1][i], 0])
yf.append(tsne_kmeans[lastidx[1][i], 1])
x = xc
y = yc
source = ColumnDataSource(data=dict(x=x, y=y,xc=xc,yc=yc,xf=xf,yf=yf))
val = "word1"
def callback(source=source):
dat = source.get('data')
x, y,xc,yc,xf,yf = dat['x'], dat['y'], dat['xc'], dat['yc'], dat['xf'], dat['yf']
# if slct.options['value'] == 'growth':
val = cb_obj.get('value')
if val == 'word1':
for i in range(0,len(xc)):
x[i] = xc[i]
y[i] = yc[i]
elif val == 'word2':
for i in range(0,len(xf)):
x[i] = xf[i]
y[i] = yf[i]
source.trigger('change')
slct = Select(title="Most Used Word:", value=val, options=mstwrd , callback=CustomJS.from_py_func(callback))
# create the circle around the data where the word exist
r = plot_kmeans.circle('x','y', source=source)
I will check if i can pass a matrix. Don't forget to have the same size of data if not you will have multiple options circled in the same time.
Thank you

Resources