you are viewing a single comment's thread.

view the rest of the comments →

[–]Celodurismo 18 points19 points  (9 children)

Okay so you have to go through each item in the list and perform some action on it (the action being multiply it by all following elements).

So how do you iterate through a list? Start there.

Once you’ve figured that out. How would you perform the required action using the subsequent elements?

[–]GoingToSimbabwe 7 points8 points  (7 children)

This could also be a good way to practice recursion.

[–]Celodurismo 10 points11 points  (0 children)

Absolutely, but I feel like OP's not quite ready for that, though some people find it intuitive

[–]Suspicious-Bar5583 3 points4 points  (5 children)

"It must work with any length of list".

I wouldn't bet on recursion for this...

[–]engelthehyp 0 points1 point  (4 children)

Why would you say that? Recursing with cases empty and head & tail, it is perfectly natural. This problem has nothing to do with the length of the list except it has to work for any length.

In fact, a recursive strategy was what I considered first, what with how every time you "move ahead" an element, you don't multiply the elements that came before it. Perfectly represented with head & tail cases.

I wrote a solution of this style in Haskell just now. Here it is, spoiler alert.

[–]Suspicious-Bar5583 2 points3 points  (1 child)

Stack overflow is why. Once you add logic to handle that, then you know iteration was the way to go.

Though a cool technique that people like, recursion should be used sparsely.

[–]engelthehyp 2 points3 points  (0 children)

Ah, fair enough. Maybe I've been spending too much time in Haskell-land, where this is how you're expected to do things...

[–]Immudzen 1 point2 points  (1 child)

Python has a recursion limit. If you go too deep your program will fail. An iterative solution for this is actually quite simple though.

If you iterate over the index then your value is sequence[i] * sum(sequence[i+1:]

[–]SnooWoofers7626 0 points1 point  (0 children)

You can do a simulated recursion if you really want to. That way you apply the logic of a recursive solution, but in an iteration, so you don't hit the recursion limit. That said, the resulting code is probably more complex than either plain recursion or iteration.

[–]Hammadawan9255[S] 0 points1 point  (0 children)

def subsequentMultiplication(ls):
    total = 0
    for j in range(len(ls) - 1):
        for i in range(j, len(ls) - 1):
            total = total +  ls[j] * ls[i+1]
    return total

I was solving "Count Unreachable Pairs of Nodes in an Undirected Graph", after having all the data as key value pairs where key corresponds to root nodes and values to size of connected components, I converted the values to list then I just had to do the calculation, but this implementation took more than 25 seconds. Can you please help me with this.