finding the slop and y intercept of a line - python-3.x

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)

Related

Generalize the construction of a Greek-Roman Matrix - Python

I wrote a python program that has as input a matrix, in which, each element appears in each row and column once. Elements are only positive integers.
e.g.
0,2,3,1
3,1,0,2
1,3,2,0
2,0,1,3
Then i find all possible traversals. They are defined as such:
choose an element from the first column
move on to the next column and
choose the element that is not in the same line from previous elements in traversal and the element has not the same value with previous elements in traversal.
e.g.
0,*,*,*
*,*,*,2
*,3,*,*
*,*,1,*
I have constructed the code that finds the traversals for matrices 4x4, but i have trouble generalizing it for NxN matrices. My code follows below. Not looking for a solution, any tip would be helpful.
import sys # Import to input arguments from cmd.
import pprint # Import for a cool print of the graph
import itertools # Import to find all crossings' combinations
# Input of arguments
input_filename = sys.argv[1]
# Create an empty graph
g = {}
# Initialize variable for the list count
i = 0
# Opens the file to make the transfer into a matrix
with open(input_filename) as graph_input:
for line in graph_input:
# Split line into four elements.
g[i] = [int(x) for x in line.split(',')]
i += 1
# Initialize variable
var = 0
# Lists for the crossings, plus rows and cols of to use for archiving purposes
f = {}
r = {}
c = {}
l = 0
# Finds the all the crossings
if len(g) == 4:
for x in range (len(g)):
for y in range (len(g)):
# When we are in the first column
if y == 0:
# Creates the maximum number of lists that don't include the first line
max_num = len(g) -1
for z in range (max_num):
f[l] = [g[x][y]]
r[l] = [x]
c[l] = [y]
l += 1
# When on other columns
if y != 0:
for z in range(len(g)):
# Initializes a crossing archive
used = [-1]
for item in f:
# Checks if the element should go in that crossing
if f[item][0] == g[x][0]:
if g[z][y] not in f[item] and z not in r[item] and y not in c[item] and g[z][y] not in used:
# Appends the element and the archive
f[item].append(g[z][y])
used.append(g[z][y])
r[item].append(z)
c[item].append(y)
# Removes unused lists
for x in range (len(f)):
if len(f[x]) != len(g):
f.pop(x)
#Transfers the value from a dictionary to a list
f_final = f.values()
# Finds all the combinations from the existing crossings
list_comb = list(itertools.combinations(f_final, i))
# Initialize variables
x = 0
w = len(list_comb)
v = len(list_comb[0][0])
# Excludes from the combinations all invalid crossings
while x < w:
# Initialize y
y = 1
while y < v:
# Initialize z
z = 0
while z < v:
# Check if the crossings have the same element in the same position
if list_comb[x][y][z] == list_comb[x][y-1][z]:
# Removes the combination from the pool
list_comb.pop(x)
# Adjust loop variables
x -= 1
w -= 1
y = v
z = v
z += 1
y += 1
x += 1
# Inputs the first valid solution as the one to create the orthogonal latin square
final_list = list_comb[0]
# Initializes the orthogonal latin square matrix
orthogonal = [[v for x in range(v)] for y in range(v)]
# Parses through the latin square and the chosen solution
# and creates the orthogonal latin square
for x in range (v):
for y in range (v):
for z in range (v):
if final_list[x][y] == g[z][y]:
orthogonal[z][y] = int(final_list[x][0])
break
# Initializes the orthogonal latin square matrix
gr_la = [[v for x in range(v)] for y in range(v)]
# Creates the greek-latin square
for x in range (v):
for y in range (v):
coords = tuple([g[x][y],orthogonal[x][y]])
gr_la[x][y] = coords
pprint.pprint(gr_la)
Valid traversals for the 4x4 matrix above are:
[[0123],[0312],[3210],[3021],[1203],[1032],[2130],[2301]]

Python - Using arange to plot points leading to duplicate points

I am attempting to create an array of 2D points from a set of vertices by using the arange function and numpy.stack to populate a list and then convert it into an array at the end.
I then take these points and plot them in matplotlib in a second program. Unfortunately instead of being a series of lines forming boxes as I'd expected it seems many of the lines have been double-counted or not counted at all.
The code to write the array is as follows:
import numpy as np
objectradius = 4
objectspace = 2 #Must be half the objectradius
boundingvertex = [180,180],[180,-180],[-180,-180],[-180,180] #The vertices of the corners of the objects They must be given in clockwise or anti-clockwise order
box1vertex = [-120,-120],[-120,-80],[40,-80],[40,-120]
box2vertex = [-120,0],[-160,0],[-160,160],[-120,160]
box3vertex = [-80,-40],[-40,-40],[-40,120],[-80,120]
box4vertex = [80,-120],[160,-120],[160,80],[80,80]
vertexlist = boundingvertex + box1vertex + box2vertex + box3vertex + box4vertex
vertices = np.asarray(vertexlist) #Converts vertices list to array
segments = []
for i in range (5): #For each object
objectnum = i + 1
for k in range(4): #For each corner vertex
start = vertices[objectnum + k]
end = vertices[objectnum + (k+1)%4]
if start[0] == end[0]: #If they have equal x
if start[1]<end[1]: #If the start point is bigger (more positive) than the end it will fail, so we have to reorder the points
#print(i,k)
#print(start,end,"equal x")
templist = np.arange(start[1],end[1],objectspace) #Evenly spaces points between the two points
pointnumber = np.size(templist)
if pointnumber == 0:
print(i,k,"went wrong here")
break
coord = np.full(pointnumber,start[0]) #Makes an equally long array of the x co-ordinate
newlist = np.stack((templist,coord),axis=-1) #Takes the templist points and adds the x co-ordinate onto them.
segments.append(newlist)
#print (segments)
else:
#print(i,k)
#print(start,end,"equal x")
templist = np.arange(end[1],start[1],objectspace)
pointnumber = np.size(templist)
if pointnumber == 0:
print(i,k,"went wrong here")
break
coord = np.full(pointnumber,start[0])
newlist = np.stack((templist,coord),axis=-1)
segments.append(newlist)
#print (segments)
else:
if start[0]<end[0]:
#print(i,k)
#print(start,end,"equal x")
templist = np.arange(start[0],end[0],objectspace)
pointnumber = np.size(templist)
if pointnumber == 0:
print(i,k,"went wrong here")
break
coord = np.full(pointnumber,start[1])
newlist = np.stack((coord,templist),axis=-1)
segments.append(newlist)
#print (segments)
else:
#print(i,k)
#print(start,end,"equal x")
templist = np.arange(end[0],start[0],objectspace)
pointnumber = np.size(templist)
if pointnumber == 0:
print(i,k,"went wrong here")
break
coord = np.full(pointnumber,start[1])
newlist = np.stack((coord,templist),axis=-1)
segments.append(newlist)
#print (segments)
segments.append(vertices)
finalpoints = np.asarray(segments)
From this code I copy pasted the array values from each element of finalpoints into a text file which is then read by the second program to plot the points.
When the second program is run and the points are plotted the result looks like this sample screenshot. Clearly the vertices are being plotted correctly but the arange points have not. Any assistance is greatly appreciated.

I believe I am not properly calling / returning functions in my program

I can't get this to run correctly, and I have to use 3 functions with their purposes being those of which I have them set to.
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return area, perimeter
def main():
area,perimeter = ap()
print("With a length of", l ."and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
This should work
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return l, w, area, perimeter
def main():
l,w,area,perimeter = ap()
print("With a length of", l ,"and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
I've made two changes: passing l and w in ap() function and accessing them in main() function.
Heyo,
I can see a number of issues with your code:
The first print statement in your main function seems to be calling variables that don't exist within that function's scope. You'll need to return the values of l and w from ap() in addition to area and perimeter. There's also a slight typo in the parameters of this statement (a . where a , should be).
Your perimeter calculation is a bit off. It's multiplying 2 by 1 instead of 2 by l, rendering l useless.
The inputs your code is requesting only returns string values rather than numerical ones. You'll need to pass those into either an int() or float() and return the results of those functions if you want to be able to calculate anything.

Smoothing values (neighbors between 1-9)

Instructions: Compute and store R=1000 random values from 0-1 as x. moving_window_average(x, n_neighbors) is pre-loaded into memory from 3a. Compute the moving window average for x for the range of n_neighbors 1-9. Store x as well as each of these averages as consecutive lists in a list called Y.
My solution:
R = 1000
n_neighbors = 9
x = [random.uniform(0,1) for i in range(R)]
Y = [moving_window_average(x, n_neighbors) for n_neighbors in range(1,n_neighbors)]
where moving_window_average(x, n_neighbors) is a function as follows:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
# To complete the function,
# return a list of the mean of values from i to i+width for all values i from 0 to n-1.
mean_values=[]
for i in range(1,n+1):
mean_values.append((x[i-1] + x[i] + x[i+1])/width)
return (mean_values)
This gives me an error, Check your usage of Y again. Even though I've tested for a few values, I did not get yet why there is a problem with this exercise. Did I just misunderstand something?
The instruction tells you to compute moving averages for all neighbors ranging from 1 to 9. So the below code should work:
import random
random.seed(1)
R = 1000
x = []
for i in range(R):
num = random.uniform(0,1)
x.append(num)
Y = []
Y.append(x)
for i in range(1,10):
mov_avg = moving_window_average(x, n_neighbors=i)
Y.append(mov_avg)
Actually your moving_window_average(list, n_neighbors) function is not going to work with a n_neighbors bigger than one, I mean, the interpreter won't say a thing, but you're not delivering correctness on what you have been asked.
I suggest you to use something like:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
mean_values = []
for i in range(n):
temp = x[i: i+width]
sum_= 0
for elm in temp:
sum_+= elm
mean_values.append(sum_ / width)
return mean_values
My solution for +100XP
import random
random.seed(1)
R=1000
Y = list()
x = [random.uniform(0, 1) for num in range(R)]
for n_neighbors in range(10):
Y.append(moving_window_average(x, n_neighbors))

Fraction to Mixed Number in String Format

My function should take a string, which is a basic x/y fraction, and convert that into a mixed fraction as a string, a b/c where a is an integer and b/c is an irreducible fraction.
Here is my code:
from fractions import Fraction
def mixed_fraction(s):
s = x.numerator / y.denominator
a = s
after_decimal = (a-int(a))[1:]
dec_2_frac = Fraction(after_decimal)
b = b.numerator
c = c.denominator
if y > 0:
return "{} {}/{}".format(a, b, c)
else:
return "ZeroDivisionError: division by zero"
Here is my error:
NameError: global name 'x' is not defined
Fundamentally, I can easily see how x is not defined properly, but I cannot wrap my head around how to denote x as corresponding numerator x of x/y. My senses tell me that I will need to go through the same debugging for y, thus I've attempted to define both on line 3. I'm simply stuck. Please help!
MJ
from fractions import gcd
def mixed_fraction(s):
a = s.split('/')
x = float(a[0])
y = float(a[1])
if y == 0:
return "ZeroDivisionError: division by zero"
z = (x/y)
if z < 1:
return s
if z==int(z):
return int(z)
a = int(x) % int(y)
g = gcd(int(y), a)
a = a / g
y = y / g
return "%s %s / %s" % (int(z), a, int(y))

Resources