enter image description hereI need help to optimize my code for huge lists with approx. 10000000 elements. Is there a way to improve my algorithm or should I try to build a new one using a completely different approach? Task: given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
def sum_pairs(ints, s):
lst1 = []
for n in ints:
if n in lst1:
return [s-n, n]
lst1.append(s-n)
lst3 = list(range(1,10000000))
sum_pairs(lst3, 20000000)
*Times out :(
#Using set() every time we add new item to the list doesn't help
def sum_pairs(ints, s):
lst1 = []
for n in ints:
lst2 = set(lst1)
if n in lst2:
return[s-n, n]
lst1.append(s-n)
-
\$\begingroup\$ What is the purpose of the code? \$\endgroup\$Ted Brownlow– Ted Brownlow2021年01月20日 18:07:42 +00:00Commented Jan 20, 2021 at 18:07
-
\$\begingroup\$ Btw you should tag this as python \$\endgroup\$my_stack_exchange_account– my_stack_exchange_account2021年01月20日 19:22:53 +00:00Commented Jan 20, 2021 at 19:22
-
\$\begingroup\$ I mean that you should just completely take the lst1 list out of the program and use a set instead. \$\endgroup\$my_stack_exchange_account– my_stack_exchange_account2021年01月20日 19:29:48 +00:00Commented Jan 20, 2021 at 19:29
-
2\$\begingroup\$ Please replace the top image with a code block containing equivalent text. \$\endgroup\$Reinderien– Reinderien2021年01月20日 20:17:58 +00:00Commented Jan 20, 2021 at 20:17
1 Answer 1
You could use a set as lst1 instead of a list. Every time you check if n is in lst1, it’s \$ O(n) \$ time complexity. Using a set instead will lower that to \$ O(1) \$.
-
1\$\begingroup\$ Correct answer in last example is [3, 7], not [5, 5] because 7 appears in the list of integers before second "5" \$\endgroup\$Luca Brasi– Luca Brasi2021年01月20日 19:13:28 +00:00Commented Jan 20, 2021 at 19:13
-
\$\begingroup\$ You’re right, somehow I misread it. Nvm, all you need is to use a set instead of a list. Then it should work. \$\endgroup\$my_stack_exchange_account– my_stack_exchange_account2021年01月20日 19:16:35 +00:00Commented Jan 20, 2021 at 19:16
-
1\$\begingroup\$ Thank you, I completely forgot about sets as distinct data types, remembered only function call, nevermind that :) \$\endgroup\$Luca Brasi– Luca Brasi2021年01月20日 19:46:52 +00:00Commented Jan 20, 2021 at 19:46