I have a program which works with a for loop, but it's too slow, and I need to speed it up.
I have a reverse-sorted list of probabilities whose sum is 1. There are over 5 million items.
I want to take the highest probabilities, i.e. the first n items whose collective sum is 0.9999.
This was my code:
for b in sorted_list: new_list.append(b) if sum(new_list) > 0.9999: break Can anyone suggest a quicker method?
Thank you
Edit: I found that this question was asked before - stackexchange link
however, the suggestions all make use of loops so I don't think they will be any quicker. Someone at the end suggested a list comprehension. So I am going to google that and see what that means! Thank you
sum(new_list)every step makes your algorithm very inefficient. Instead, just keep score adding the appended element to the previous total.