我是靠谱客的博主 靓丽小蚂蚁,这篇文章主要介绍Number Pairs(Python版)Description:Input sample:Output sample:解题方案:,现在分享给大家,希望可以做个参考。

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

解题方案:

import sys

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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(150)

评论列表共有 0 条评论

立即
投稿
返回
顶部