Alejandro A
Alejandro A

Reputation: 1190

Iterating a list to apply a function to each element from current position

Let's say I have a list with the following values:

values=['foo','bar','lorem','ipsum']

I want that for every element of the list, iterates the entire list adding up the length of the current item + all the other lengths. This is done by a function that does the following:

def sum_length(first_string,second_string):
    return len(first_string)+len(second_string)

My code looks like this

for i,_ in enumerate(values):
    counter=i
    while counter < len(values):
        print(sum_length(values[i],values[counter]))
        counter+=1

So the first iteration would be

1. len('foo') + len('bar')
2. len('foo') + len('lorem')
3. len('foo') + len('ipsum') 

Second:

1. len('bar') + len('lorem')
2. len('bar') + len('ipsum')

This is not very effective with very big lists or more complex functions, how could I improve my running time?

Upvotes: 0

Views: 425

Answers (2)

Max Smirnov
Max Smirnov

Reputation: 603

With given example here is the solution:

from itertools import combinations

for (w1, w2) in combinations(values):
    print(len(w1) + len(w2))

In terms of optimization you can first convert your values list to list of their lengths and then do the script but without calling len

Upvotes: 2

Ryuga
Ryuga

Reputation: 128

values=['foo','bar','lorem','ipsum']
print(sum(len(i) for i in values))

is this what ur looking for?

Upvotes: 0

Related Questions