题意:找出数组numbers中的两个数,它们的和为给定的一个数target,并返回这两个数的索引,注意这里的索引不是数组下标,而是数组下标加1。比如numbers={2,7,11,17}; target=9。那么返回一个元组(1,2)。这道题不需要去重,对于每一个target输入,只有一组解,索引要按照大小顺序排列。
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
def calc(temp,target):
for i in range(len(temp)):
for j in range(i+1,len(temp)):
if((temp[i]+temp[j])==target):
return i,j
return -1,-1
numbers=[2,7,11,17]
target = 9
i,j = calc(numbers,target)
print (i+1,j+1)
python中的两种循环
1.for …in …
2.while
要获取下标要用enumerate