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))
10 Antworten
+ 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)
+ 2
Can you show us your attempt ?
+ 2
Andrex can you post it here so we can tale a look at it ?
+ 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)
+ 1
it works, many thanks!!!)
0
i have added my code, but it doesn't work correct
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))
0
Your code returns indexes 0, 3, but we need to return 0, 1
0
You're welcome 👌
0
Lothar, What I need to do to return indexes from "nums" array in your code? because your code return indexes from comb