Python:Accumulate Adding and Counting

From Progzoo
Revision as of 16:21, 12 July 2017 by Andr3w (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Using an accumulator to add.

The variable list is an array, it holds several integers. For example it might be the list [1,2,3,4].

You can iterate over a list, every time you visit an element of the list you do something to the accumulator acc

In this example, for every member v of the list you add that member to the accumulator using the code

acc = acc + v;


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to count.

Use the accumulator to count the number of items in the list:


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to multiply.

Use the accumulator to find the product of items in the list:


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to max.

Use the accumulator to find the largest item in the list:


[Font] [Default] [Show] [Resize] [History] [Profile]

Count Twos.

Use the accumulator to find the number of twos in the list: Count on a condition


[Font] [Default] [Show] [Resize] [History] [Profile]

Count Non-Twos.

Use the accumulator to find number other than 2:

f({1,1,1,1})             -> 4
f({2,2,2})               -> 0
f({1,1,1,1,1})           -> 5
f({4,2,6,0,0})           -> 4


[Font] [Default] [Show] [Resize] [History] [Profile]

Count the big numbers

Use the accumulator to count all numbers larger than 1:


[Font] [Default] [Show] [Resize] [History] [Profile]

Add the big numbers

Use the accumulator to sum all numbers larger than 1:


[Font] [Default] [Show] [Resize] [History] [Profile]