Mercurial > hg > config
comparison python/example/array_sum.py @ 837:5ba219864529
add example program
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Mon, 27 Mar 2017 14:05:29 -0700 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
836:0fa456446fea | 837:5ba219864529 |
---|---|
1 #!/usr/bin/env python | |
2 | |
3 """ | |
4 given a `value` and an array, | |
5 if the sum of two numbers in the array | |
6 total the value, return `True` | |
7 (exit 0): | |
8 | |
9 ./array_sum.py 3 1 2 4 # YES! because 1+2=3 | |
10 | |
11 ./array_sum.py 4 1 2 5 6 # NO! | |
12 """ | |
13 | |
14 import argparse | |
15 import sys | |
16 | |
17 | |
18 def sum_of_two(value, *array): | |
19 | |
20 start = 0 | |
21 end = len(array) - 1 | |
22 complements = [] | |
23 while start < end: | |
24 start_val = array[start] | |
25 end_val = array[end] | |
26 _sum = start_val + end_val | |
27 if _sum == value: | |
28 complements.append((start_val, end_val)) | |
29 end -= 1 | |
30 start +=1 | |
31 continue | |
32 if _sum > value: | |
33 end -= 1 | |
34 else: | |
35 start += 1 | |
36 return complements | |
37 | |
38 | |
39 def main(args=sys.argv[1:]): | |
40 | |
41 parser = argparse.ArgumentParser(description=__doc__) | |
42 parser.add_argument('value', type=int) | |
43 parser.add_argument('array', type=int, nargs='+') | |
44 options = parser.parse_args(args) | |
45 | |
46 retval = sum_of_two(options.value, *options.array) | |
47 | |
48 print (retval) | |
49 | |
50 sys.exit(0 if retval else 1) | |
51 | |
52 | |
53 if __name__ == '__main__': | |
54 main() |