Difference between revisions of "Python:Accumulate Adding and Counting"

From Progzoo
Jump to: navigation, search
(Created page with "<shell lang='py'><![CDATA[ QcQ ll = [ [1,1,1,1], [2,2,2], [1,1,1,1,1], [4,2,6,0,0] ] for l in ll: print "%-26s -> %-25s" % (str(l),str(f(l)))...")
(No difference)

Revision as of 16:12, 12 July 2017

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]