Making a function according to a formula (Python) -


i having trouble question see on included image. little knowledge have in python struggling find out begin problem. in particular, how make function according formula? user must able enter values x_i , x_(i-1). answers appreciated. don't expect full answer, idea of how can begin this...

here question

let's break down. first, how 1 create function pathlength? this:

def pathlength(x, y):     return 42   # length 42 miles 

as can see, accepts x,y parameters specified in problem. rather compute answer, returns made-up answer. more on how find answer in minute.

the way user might invoke function so:

length = pathlength([0, 7, 9, 5, 2, 0], [0, 1, 3, 2, 2, 0]) 

as can see, i've passed list of x values , list of y values.

now know how declare function, , how invoke function, left math. problem says need sum terms of series. our first step create terms in convenient manner. series runs 1 n-1 (that is, summation has 1 fewer steps our data has.

to represent values, can use slice notation:

x[1:]  # x(i) values 1 n-1 x[:-1] # x(i-1) values 1-1 n-1-1 

and y.

it convenient have 2 x values , 2 y values related somehow. job zip:

zip(x[1:], x[:-1], y[1:], y[:-1]) 

zip produces list of tuples, each tuple variables related particular value of i.

now consider each value of i in turn:

for xi, xi1, yi, yi1 in zip(x[1:], x[:-1], y[1:], y[:-1]):     pass 

this loop iterates on of entries, no actual math.

now need use pythagorean formula determine two-d distances.

total_distance = 0 xi, xi1, yi, yi1 in zip(x[1:], x[:-1], y[1:], y[:-1]):     leg_distance = ((xi-xi1)**2+(yi-yi1)**2)**.5     total_distance = total_distance + leg_distance 

finally, need communicate value our caller:

def pathlength(x, y):     total_distance = 0     xi, xi1, yi, yi1 in zip(x[1:], x[:-1], y[1:], y[:-1]):         leg_distance = ((xi-xi1)**2+(yi-yi1)**2)**.5         total_distance = total_distance + leg_distance     return total_distance 

hmm. there way this. many loop constructs can replaced list comprehensions, can. try googling python list comprehension , python generators determine this does:

def pathlength(x,y):     return sum(         ((xi-xi1)**2+(yi-yi1)**2)**.5          (xi, xi1, yi, yi1) in zip(x[1:], x[:-1], y[1:], y[:-1])) 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -