第5章-10.两数之和 (30分)(列表实现和字典实现)

给定一组整数,还有一个目标数,在给定这组整数中找到两个数字,使其和为目标数,如找到,解是唯一的。找不到则显示 "no answer"。输出的下标按从小到大排序。用一重循环加字典实现。

输入格式:

在一行中给出这组数。 在下一行输入目标数

输出格式:

在一行中输出这两个数的下标,用一个空格分开。

输入样例1:

在这里给出一组输入。例如:

2,7,11,15
9
 

输出样例1:

在这里给出相应的输出。例如:

0 1
 

输入样例2:

在这里给出一组输入。例如:

3,6,9
10
 

输出样例2:

在这里给出相应的输出。例如:

no answer
用字典实现
 1 # 两数之和-用字典实现
 2 # Author: cnRick
 3 # Time  : 2020-4-4
 4 nums = list(map(int,input().split(',')))
 5 n = int(input())
 6 resultDict = dict()
 7 isNoAnswer = True
 8 for i in nums:
 9     resultDict[i] = n - i
10 for i,j in resultDict.items():
11     if j in nums:
12         print("{:d} {:d}".format(nums.index(i),nums.index(j)))
13         isNoAnswer = False
14         break
15 if isNoAnswer == True:
16     print("no answer")
17     

用列表实现

 1 # 两数之和-用字典实现
 2 # Author: cnRick
 3 # Time  : 2020-4-4
 4 nums = list(map(int,input().split(',')))
 5 n = int(input())
 6 resultDict = dict()
 7 isNoAnswer = True
 8 for i in nums:
 9     resultDict[i] = n - i
10 for i,j in resultDict.items():
11     if j in nums:
12         print("{:d} {:d}".format(nums.index(i),nums.index(j)))
13         isNoAnswer = False
14         break
15 if isNoAnswer == True:
16     print("no answer")
17     

参考代码:https://blog.csdn.net/weixin_45948920/article/details/104706570

原文地址:https://www.cnblogs.com/dreamcoding/p/12630678.html