def subString(array,n): items = [] # Pick starting point for Len in range(1,n + 1): # Pick ending point for i in range(n - Len + 1): # Print characters from current # starting point to current ending # point. j = i + Len - 1 combo = 0 for k in range(i,j + 1): combo += array[k] items.append(combo) return items # Driver program to test above function n = int(input()) #items = [0,0,0,0,0,0,0,0,0,0] #items = [7, -4, -2] items_string = input() items = [int(a) for a in items_string.split()] all_negative = True all_positive = True count_zeros = 0 for i in items: if i < 0: all_positive = False if i > 0: all_negative = False if i == 0: count_zeros += 1 if all_negative == True and count_zeros == 0: print(0) elif all_positive == True and count_zeros == 0: print(0) else: all = subString(items,len(items)) how_many = 0 arr_size = len(all) #for i in range( 0, arr_size - 2): # Fix the second element as A[j] # for j in range(i + 1, arr_size -1): # Now look for the third number # for k in range(j + 1, arr_size): # if all[i] + all[j] + all[k] == 0: # how_many += 1 for i in range(len(all) - 2): s = [] curr_sum = 0 - all[i] for j in range(i + 1, len(all)): required_value = curr_sum - all[j] if required_value in s: how_many += s.count(required_value) s.append(all[j]) print(how_many)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | def subString(array,n): items = [] # Pick starting point for Len in range(1,n + 1): # Pick ending point for i in range(n - Len + 1): # Print characters from current # starting point to current ending # point. j = i + Len - 1 combo = 0 for k in range(i,j + 1): combo += array[k] items.append(combo) return items # Driver program to test above function n = int(input()) #items = [0,0,0,0,0,0,0,0,0,0] #items = [7, -4, -2] items_string = input() items = [int(a) for a in items_string.split()] all_negative = True all_positive = True count_zeros = 0 for i in items: if i < 0: all_positive = False if i > 0: all_negative = False if i == 0: count_zeros += 1 if all_negative == True and count_zeros == 0: print(0) elif all_positive == True and count_zeros == 0: print(0) else: all = subString(items,len(items)) how_many = 0 arr_size = len(all) #for i in range( 0, arr_size - 2): # Fix the second element as A[j] # for j in range(i + 1, arr_size -1): # Now look for the third number # for k in range(j + 1, arr_size): # if all[i] + all[j] + all[k] == 0: # how_many += 1 for i in range(len(all) - 2): s = [] curr_sum = 0 - all[i] for j in range(i + 1, len(all)): required_value = curr_sum - all[j] if required_value in s: how_many += s.count(required_value) s.append(all[j]) print(how_many) |