Accumulators - mrprov12/DSPrep GitHub Wiki

accumulators:

PATTERN:

  Initialize an accumulator variable

  Repeat:
      Modify the accumulator variable

  When the above loop terminates, accumulator has the correct value

examples:

#int:
num_list = [1, 2, 3, 4, 5]

num_sum = 0
for num in num_list:
    num_sum += num

print(num_sum)


#float:
num_list = [1.6, -2.25, 3.61, 4.01, 5.93]

num_sum = 0.0
for num in num_list:
    num_sum += num

print(num_sum)

#bool flags:
lst = [23, 42, 86, 92, 93, 94]

has_value_over_90 = False
for val in lst:
    if val > 90:
        has_value_over_90 = True
        break

print(has_value_over_90)

#list
num_list = [2, 12, 12, 1, 24, 10, 19, 17, 8, 8, 25, 14, 12, 4, 23, 14, 18, 13, 0, 15, 22, 8, 5, 12, 6]

altered_num_list = []
for num in num_list:
    if num % 2 == 0:
        altered_num_list.append(num**2)
    else:
        altered_num_list.append(num**3)

#flattened nested lists
mixed_list = ['word', [1, 2, 3, 4, 5], 43, 90.0]
flattened = []

for item in mixed_list:
    if isinstance(item, list):
        for nested_item in item:
            flattened.append(nested_item)
    else:
        flattened.append(item)

#parallell lists:   
  #enumerate
    def polynomial(coefs, x):
    res = 0
    n = len(coefs) - 1 # The degree of the polynomial

    for idx, val in enumerate(coefs):
        res += val * x**(n - idx)

    return res


  #zip     
    odds = []
    lst_a = [1, 32, 15, 7, 3, 9, 16, 13, 22, 8]
    lst_b = [51, 6, 25, 2, 18, 19, 21, 14, 4, 11]

    for a, b in zip(lst_a, lst_b):
        if a % 2 == 1:
            odds.append(a)
        if b % 2 == 1:
            odds.append(b)

  #set
    x = set()
    for i in <some_iterable_object>:
       x.add(i)