概述
Description:
You are given a sorted array of positive integers and a number 'X'. Print out all pairs of numbers whose sum is equal to X. Print out only unique pairs and the pairs should be in ascending order
Input sample:
Your program should accept as its first argument a filename. This file will contain a comma separated list of sorted numbers and then the sum 'X', separated by semicolon. Ignore all empty lines. If no pair exists, print the string NULL eg.
1,2,3,4,6;5 2,4,5,6,9,11,15;20 1,2,3,4;50
Output sample:
Print out the pairs of numbers that equal to the sum X. The pairs should themselves be printed in sorted order i.e the first number of each pair should be in ascending order .e.g.
1,4;2,3 5,15;9,11 NULL
解题方案:
if __name__ == "__main__":
argv = sys.argv
inf = open(argv[1],'r')
while True:
line = inf.readline()
if len(line) == 0:
break
ll = line.split(';')
arr = ll[0].split(',')
X = int(ll[1])
n = len(arr)
dic = {}
tmp = []
for i in range(0,n):
dic[arr[i]] = int(arr[i])
for i in range(0,n):
y = X - dic[arr[i]]
if y < dic[arr[i]]:
continue
if dic.get(str(y),-1) == y:
s = arr[i] + ',' + str(y)
tmp.append(s)
if len(tmp) != 0:
print ';'.join(tmp)
else:
print 'NULL'
最后
以上就是靓丽小蚂蚁为你收集整理的Number Pairs(Python版)Description:Input sample:Output sample:解题方案:的全部内容,希望文章能够帮你解决Number Pairs(Python版)Description:Input sample:Output sample:解题方案:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复