Axel Rodriguez
Axel Rodriguez

Reputation: 33

How can I perform a function for loop and output a sum in Python 3.x?

I have an assignment that requires using a single "for" statement to calculate the manhattan and euclidian distances of two data sets. I'm also required to define the data sets and zip them as shown in the code. I'm very new to Python, and any tips on how to print the sum of the abs(x-y) function would be greatly appreciated!

I'd like the output to read "Manhattan Distance: 22.5"

Here is what I've tried

UserXRatings = [1,5,1,3.5,4,4,3]
UserYRatings = [5,1,5,1,1,1,1]    

for x, y in zip(UserXRatings, UserYRatings):
   print("Manhattan distance: ", abs(x-y))

Upvotes: 2

Views: 167

Answers (2)

AlokThakur
AlokThakur

Reputation: 3741

You can use sum to get desired result-

print("Manhattan distance: ",sum(abs(x-y) for x,y in zip(UserXRatings, UserYRatings)))
#It should print - Manhattan distance:  22.5

Upvotes: 2

Deacon
Deacon

Reputation: 3803

You're close. What you're doing is printing the value of abs(x-y) each time through the loop. You should probably store the sum of the values as you go through the loop, then print it once at the end:

Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> UserXRatings = [1,5,1,3.5,4,4,3]
>>> UserYRatings = [5,1,5,1,1,1,1]
>>>
>>> z = 0  # Initialize the variable to store the running total.
>>> for x, y in zip(UserXRatings, UserYRatings):
...     z = z + abs(x-y)  # Calculate the running total of `abs(x-y)`.
...
>>> print("Manhattan distance: ", z)
Manhattan distance: 22.5
>>>

Upvotes: 1

Related Questions