0

How to return indices of two numbers that sum of these numbers equal to 9?

for example: array [2, 7, 11, 15], and it is necessary to return index [0] and index [1] because sum of it equal 9. my code: nums = [2, 7, 11, 15] comb = [(x+y) for x in nums for y in nums if x!=y] offset = 0 for item in comb: if item==9: offset += 1 print(enumerate (x))

22nd Jan 2020, 9:56 AM
Andrey Shintar
Andrey Shintar - avatar
10 Respostas
+ 5
I am not quite sure what you suppose to get by "print(enumerate(x)", but this expression is not valid, becuase enumerate can only be used with iterables. May be this can help you: nums = [2, 7, 11, 15] comb = [(x+y) for x in nums for y in nums if x!=y] offset = 0 for ind, item in enumerate(comb): if item==9: offset += 1 print(ind)
22nd Jan 2020, 10:20 AM
Lothar
Lothar - avatar
+ 2
Can you show us your attempt ?
22nd Jan 2020, 9:57 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Andrex can you post it here so we can tale a look at it ?
22nd Jan 2020, 10:05 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Maybe something like this? nums = [7,11,2,15,-2] l = len(nums) for i in range(l): for j in range(l): if i != j and nums[i] + nums[j] == 9: print(i, j)
22nd Jan 2020, 10:37 AM
Ipang
+ 1
it works, many thanks!!!)
22nd Jan 2020, 10:50 AM
Andrey Shintar
Andrey Shintar - avatar
0
i have added my code, but it doesn't work correct
22nd Jan 2020, 10:03 AM
Andrey Shintar
Andrey Shintar - avatar
0
nums = [2, 7, 11, 15] comb = [(x+y) for x in nums for y in nums if x!=y] offset = 0 for item in comb: if item==9: offset += 1 print(enumerate (x))
22nd Jan 2020, 10:15 AM
Andrey Shintar
Andrey Shintar - avatar
0
Your code returns indexes 0, 3, but we need to return 0, 1
22nd Jan 2020, 10:31 AM
Andrey Shintar
Andrey Shintar - avatar
0
You're welcome 👌
22nd Jan 2020, 10:53 AM
Ipang
0
Lothar, What I need to do to return indexes from "nums" array in your code? because your code return indexes from comb
22nd Jan 2020, 2:16 PM
Andrey Shintar
Andrey Shintar - avatar