Exercise: Week 3-3.1-2

Define the function twonums_sum(n, lst), finds in the list lst whether there is a sum of two numbers equal to n, if any, returns a subscript of two numbers, otherwise returns -1.

For an ordered list that does not contain duplicate numbers [1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 18, 19, 20, 21, 29, 34, 54, 65 ], input n from the keyboard, call the function twonums_sum() to output the subscripts of the two numbers that satisfy the condition (you only need to find one set and ensure one of them to be as small as possible), and output "not found" if all the numbers do not satisfy the condition.

n = int(input("Enter a number: "))
lst = [1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 18, 19, 20, 21, 29, 34, 54, 65]
result = []

def twonums_sum(n, lst):
    for i in lst:
        x = n - i
        if x in lst:
            result.append((lst.index(i), lst.index(x)))
    if len(result) > 0:
        result.sort()
        print(result[0])
    else:
        print("Not found")

twonums_sum(n, lst)

[Reference Code]

def twonums_sum(n, lst):
     d = {}
     for i in range(len(lst)):
          d[lst[i]] = i    # create number-subscript pair
     for i in range(len(lst)):
          if n - lst[i] in d:
               return i, d[n-lst[i]]             
     return -1


lst = [1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 18, 19, 20, 21, 29, 34, 54, 65]
n = int(input())
result = twonums_sum(n, lst)
if result == -1:
    print("not found")
else:
    print(result)

00:21:07

2019-11-28

猜你喜欢

转载自www.cnblogs.com/petitherisson/p/11944829.html