Last active
February 13, 2017 03:43
-
-
Save denvaar/af12aeb6e6f40656af995dd6910e1678 to your computer and use it in GitHub Desktop.
Print out all pairs of numbers whose sum is equal to X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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: | |
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 e.g. | |
echo -e "1,2,3,4,6;5\n2,4,5,6,9,11,15;20\n1,2,3,4;50" | python3 numberpairs.py | |
""" | |
from sys import stdin | |
for line in stdin.readlines(): | |
l, n = line.strip().split(';') | |
n = int(n) | |
# only grab the numbers that are less than or equal to n | |
l = [int(i) for i in l.strip().split(',') if int(i) <= n] | |
while l: | |
last = l[-1] | |
x = n - last | |
i = 0 | |
found = False | |
while not found and i < len(l) - 1: | |
if l[i] == x: | |
print('{},{};'.format(l[i], last), end='') | |
found = True | |
i += 1 | |
if not found: | |
print('NULL', end='') | |
# to save time for next iteration, the list can be | |
# cut down to exclude the numbers used already. | |
l = l[i:len(l)-1] | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment