Getting Started with Python - Practice Questions

Title: Find two numbers in the array numbers, their sum is a given number target, and return the index of these two numbers, note that the index here is not the array subscript, but the array subscript plus 1. For example numbers={2,7,11,17}; target=9. then returns a tuple (1,2). This problem does not need to be deduplicated. For each target input, there is only one set of solutions, and the indices should be arranged in order of size. 
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Two kinds of loops in python  1.for
...in ... 
2.while 
to get the subscript, use enumerate

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324419868&siteId=291194637