From 35e2780fea6a366eefce70b5041b7486f86fb57d Mon Sep 17 00:00:00 2001 From: Mari Wahl Date: Sat, 3 Jan 2015 23:23:35 -0500 Subject: [PATCH] simple examples --- .../find_largest_sum.py | 58 +++++++++++++++++++ .../math_arrays_and_strings/find_sum_ints.py | 35 +++++++++++ 2 files changed, 93 insertions(+) create mode 100755 src/extra_interview_problems/math_arrays_and_strings/find_largest_sum.py create mode 100755 src/extra_interview_problems/math_arrays_and_strings/find_sum_ints.py diff --git a/src/extra_interview_problems/math_arrays_and_strings/find_largest_sum.py b/src/extra_interview_problems/math_arrays_and_strings/find_largest_sum.py new file mode 100755 index 0000000..bc106d4 --- /dev/null +++ b/src/extra_interview_problems/math_arrays_and_strings/find_largest_sum.py @@ -0,0 +1,58 @@ +#!/usr/bin/python + +'''You are given an array of integers (both positive and negative). Find the contiguous +sequence with the largest sum. Return the sum.''' + + +def find_largest_sum(array): + ''' + >>> find_largest_sum([-1, 2, -3, 5, 3, 1, -16, 7, 1, -13, 1]) + 9 + >>> find_largest_sum([]) + 0 + >>> find_largest_sum([1]) + 1 + ''' + if not array: return 0 + p1, p2 = 0, 1 + all_sums = set() + sum_ = array[p1] + + while p1 < p2 and p2 < len(array): + if sum_ + array[p2] < 0: + all_sums.add(sum_) + p2 += 1 + p1 = p2 + sum_ = 0 + sum_ += array[p2] + p2 += 1 + all_sums.add(sum_) + return max(all_sums) + + + +def find_largest_sum_simple(array): + ''' + >>> find_largest_sum_simple([-1, 2, -3, 5, 3, 1, -16, 7, 1, -13, 1]) + 9 + >>> find_largest_sum_simple([]) + 0 + >>> find_largest_sum_simple([1]) + 1 + ''' + max_sum, sum_ = 0, 0 + + for item in array: + sum_ += item + if max_sum < sum_: + max_sum = sum_ + elif sum_ < 0: + sum_ = 0 + return max_sum + + + + +if __name__ == '__main__': + import doctest + doctest.testmod() \ No newline at end of file diff --git a/src/extra_interview_problems/math_arrays_and_strings/find_sum_ints.py b/src/extra_interview_problems/math_arrays_and_strings/find_sum_ints.py new file mode 100755 index 0000000..480a46f --- /dev/null +++ b/src/extra_interview_problems/math_arrays_and_strings/find_sum_ints.py @@ -0,0 +1,35 @@ +#!/usr/bin/python + +'''Design an algorithm to find all pairs of integers within an array + which sum to a specified value.''' + +from collections import defaultdict + +def find_ints_sum(array, sum_): + ''' + >>> find_ints_sum([4, 5, 3, 5, 2, 8, 1], 9) + set([(5, 4), (1, 8)]) + >>> find_ints_sum([1, 2], 5) + set([]) + >>> find_ints_sum([1], 1) + 'Not enough values' + ''' + if len(array)< 2: + return "Not enough values" + + dict = defaultdict() + pairs = set() + + for i in array: + if (sum_ - i) in dict: + pairs.add((i, sum_ -i)) + else: + dict[i] = True + + return pairs + +# if the array was sorted, we could do this with two pointers + +if __name__ == '__main__': + import doctest + doctest.testmod() \ No newline at end of file