Tiger1
Tiger1

Reputation: 1377

Iterative summation of output generated by a function in a for loop (python)

My goal is to sum the output generated from a code iteratively.

The code below can accurately compute the hamming distance between two strings, but does not sum up the distances across multiple strings. See sample strings below:

w=['ground', 'joint']
c=['gnoufd', 'johnt']

def hamming_distance(s1, s2):
    if len(s1)==len(s2):
        return sum(x1 != x2 for x1, x2 in zip(s1, s2))

for x,y in zip(w,c):
    for j in x:
        for k in y:
           l=hamming_distance(x, y)
    print l

The output of the above code is: 1 2 I tried using list comprehension, hoping I could get the output in a list and sum them up, but got erroneous output.

for x,y in zip(w,c):
    k=[hamming_distance(x,y) for j,k in zip(x,y)]
    print k

Desired output: 3---(the sum of the one and two above)

Any suggestions? thanks.

Upvotes: 0

Views: 1472

Answers (2)

Kevin
Kevin

Reputation: 76184

In this block:

for x,y in zip(w,c):
    for j in x:
        for k in y:
           l=hamming_distance(x, y)
    print l

you don't use j or k, so you can get rid of those loops.

for x,y in zip(w,c):
    l=hamming_distance(x, y)
    print l

This is more readily translated into a generator expression.

k = [hamming_distance(x, y) for x, y in zip(w,c)]
print k
print sum(k)

Output:

[2,1]
3

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142106

Instead of your for loop - just use map instead as such:

diff = map(hamming_distance, w, c)
# [2, 1]
print sum(diff)
# 3

Upvotes: 1

Related Questions