Some homework that I have been struggling on mainly because I am unsure how to proceed. I have all the formulas I need but I haven't been able to find a useful online tutorial for how to get the necessary information out of a 2-tuple.
print (pathLength2d ([(0,0), (1,1)]))
import math
def length (v):
""" Length of a vector in 2-space.
Params: v (2-tuple) vector in 2-space
Returns: (float) length
"""
number = 0
for i in range(len(str(v))):
number += v[i]**2
return math.sqrt(number)
I know that's an error as it's trying to multiply an index of (0,0) by itself. I'm not asking for a full out solution, but a pointer in the right direction.
Thanks!
Could you provide a runnable snippet, and the full traceback that it produces? You first line of code calls a function you haven't defined, and I'm not sure what you're passing to length() or the exception you're having.
You can iterate directly over the tuple. Try:
for x in (1, 2):
print(x)
If you know list comprehensions, you can use the sum function on one, and turn your function into one line of code. Otherwise you can drastically simplify your loop.
(Sep-29-2016, 10:55 PM)micseydel Wrote: [ -> ]Could you provide a runnable snippet, and the full traceback that it produces? You first line of code calls a function you haven't defined, and I'm not sure what you're passing to length() or the exception you're having.
My bad. Basically we have to cut the program up into sections. I finally got it to output but I cannot:
1) Find a use for the length function
2) Am off by a slight margin, probably some float issue
import math
def length (v):
""" Length of a vector in 2-space.
Params: v (2-tuple) vector in 2-space
Returns: (float) length
"""
return math.sqrt(v[0]**2 + v[1]**2) #Returning the square of the coordinates.
def dist (P,Q):
""" Distance in 2-space.
Params:
P (2-tuple): a point in 2-space
Q (2-tuple): another point in 2-space
Returns: (float) dist (P,Q)
"""
return math.sqrt((Q[0]-P[0]) + (Q[1] - P[1])) #Returning two point's lengths added.
def pathLength2d (pt):
"""Length of a 2-dimensional path.
Standard length as measured by a ruler.
Params: pt (list of 2-tuples): path in 2-space
Returns: (float) length of this path
"""
newNumber = 0 #Saving my answer into a new value.
for i in range(len(pt)): #Iterate over the length of the tuple.
newNumber += dist(pt[0],pt[-1]) #I add the first and last coordinate of the tuple using the formula.
return math.sqrt(newNumber) #Now that I think about it, this sqrt probably shouldn't be here...
print (pathLength2d ([(0,0), (1,1)])) #Root of 2
Solved it. I overthought the program a ton.
Python will very simply parse out everything for you (this is called 'unpacking'). Of course this only works for fixed-length items but his is the case here.
>>> (x1,y1),(x2,y2)=[(0,1), (2,3)]
>>> print x1,y1,x2,y2
0 1 2 3