0

I'm working on an assignment for my Python class and I'm super close to it being done but there's this one annoying issue that I can't seem to solve, but before I explain, here's my code:

import math as m
def distance(x1,y1,x2,y2):
    xdel=(x2-x1)**2
    ydel=(y2-y1)**2
    print(xdel, "is xdel")
    print(ydel, "is ydel")
    dist = m.sqrt(xdel+ydel)
    return dist
xl = []
yl = []
dists = []
while True:
    ux = input("X for coordinate (blank for exit): ")
    if ux == "":
        break
    ux = int(ux)
    uy = int(input("Y for coordinate: "))
    xl.append(ux)
    yl.append(uy)
for i in range(len(xl)-2):
        x2 = xl[i+1]
        y2 = yl[i+1]
        dist = distance(xl[i],yl[i],x2,y2)
        dists.append(float(dist))        
perimeter = sum(dists)
print(perimeter)

my list dists is not being appended by the last line of code in the for loop, I don't know why. I feel like I've exhausted my freshman coding tricks to solve this, so I turn to you, oh noble wizards of StackOverflow.

EDIT: The point of the script is to take pairs of coordinates on a 2d graph from the user, gets the distance of all the lines, and gives the perimeter of the polygon that the lines make up. Sorry if that was not clear in the question. but no matter what the input is it would appear the list is still not being populated.

  • what is your input? – bunbun Oct 18 '18 at 01:02
  • @bunbun I should have explained when asking, the point of the script is to take pairs of coordinates on a 2d graph from the user, gets the distance of all the lines, and gives the perimeter of the polygon that the lines make up. – user10521382 Oct 18 '18 at 01:05
  • Learn to debug. For example, add `print("i " + str(i))` as first line of the loop will give you a big hint on what happened – Adrian Shum Oct 18 '18 at 01:09
  • it is getting appended if you have 3 or more points, if you do `print(dists)` at the end, you can see some values in `dists`. Your code however, is not giving you the perimeter as you wanted – bunbun Oct 18 '18 at 01:11

2 Answers2

0

range(end) iterates in [0, end), not including the end

In this case, you want the last round of loop to have x1[i] and x2=x1[len(x)-1] where i is len(x1)-2

so you need range(len(x1)-1)

William Lee
  • 337
  • 4
  • 11
0

range(x) gives you sequence of number from 0 to x - 1

Assuming you have 10 elements in your list, what you want is having the for loop with i from 0 to 8, and for each loop calculate the distance between point i and i + 1.

Hence it should be for i in range(len(xl) -1):

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131