Lecture Notes on 30 Nov 2012 def canBalance (nums): total = sum (nums) partial_sum = 0 for i in range (len(nums)): partial_sum += nums[i] if (partial_sum == total - partial_sum): return True return False def main(): print (canBalance([1, 1, 1, 2, 1])) print (canBalance([2, 1, 1, 2, 1])) print (canBalance([10, 10])) main() ################################################# def fix34 (nums): a = nums[:] for i in range (len(a)): if (a[i] != 3): pass else: for j in range (len(a)): if ((a[j] == 4) and (a[j - 1] != 3)): a[j], a[i + 1] = a[i + 1], a[j] break return a def main(): print (fix34([1, 3, 1, 4])) print (fix34([1, 3, 1, 4, 4, 3, 1])) print (fix34([3, 2, 2, 4])) main() ######################################################### def linearIn (outer, inner): idx_out = 0; idx_in = 0; while ((idx_out < len(outer)) and (idx_in < len(inner))): if (outer[idx_out] > inner[idx_in]): return False elif (outer[idx_out] < inner[idx_in]): idx_out = idx_out + 1 else: idx_out = idx_out + 1 idx_in = idx_in + 1 if (idx_in < len(inner)): return False else: return True; def main(): print (linearIn([1, 2, 4, 6], [2, 4])) print (linearIn([1, 2, 4, 6], [2, 3, 4])) print (linearIn([1, 2, 4, 4, 6], [2, 4])) main() ################################################################### def isSubList (a, nums): size = len(a) for i in range (len(nums) - size + 1): b = nums[i:i+size] if (a == b): return True return False def maxMirror (nums): max_size = 0 for i in range (len(nums)): for j in range (len(nums), i, -1): a = nums[i:j] a.reverse() if (isSubList(a, nums)): if (len(a) > max_size): max_size = len(a) return max_size def main(): print (maxMirror([1, 2, 3, 8, 9, 3, 2, 1])) print (maxMirror([1, 2, 1, 4])) print (maxMirror([7, 1, 2, 9, 7, 2, 1])) main() ########################################################## def maxSpan (nums): span = 0 limit_i = len(nums) limit_j = limit_i - 1 for i in range (limit_i): for j in range (limit_j, -1, -1): if (nums[i] == nums[j]) and ((j - i + 1) > span): span = j - i + 1 break return span def main(): print (maxSpan([1, 2, 1, 1, 3])) print (maxSpan([1, 4, 2, 1, 4, 1, 4])) print (maxSpan([1, 4, 2, 1, 4, 4, 4])) main() ############################################################### def seriesUp (n): a = [] for i in range (1, n + 1): for j in range (1, i + 1): a.append (j) return a def main (): print (seriesUp(3)) print (seriesUp(4)) print (seriesUp(2)) main()