Difference between revisions of "Python:Accumulate Multiple Values"

From Progzoo
Jump to navigation Jump to search
Line 132: Line 132:
     if v<2:
     if v<2:
       sm = sm+1
       sm = sm+1
     elsif v>4:
     elif v>4:
       lg = lg+1
       lg = lg+1

Latest revision as of 17:36, 12 July 2017

You can use more than one accumulator in the same loop.

Find the average

Use two accumulators, sum and count. Return the two values in a string.

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

Odds and evens

Use two accumulators, odd and evens to count the number of odd numbers and the number of even numbers. Return the two numbers in a string separated by a space.

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

More odd than even?

Return the word "odd" if the number of odd numbers is bigger than the number of even numbers. Return the word "even" otherwise.

The list {1,3,5,8,6} returns "odd" because there are 3 odds and only 2 evens.

f([1,1,1,1])             -> odd
f([1,2,3,4,5,6])         -> even
f([-1,1,-1,1,-1])        -> odd
f([1,2,101,4,-1])        -> odd
f([4,2,6,1,1])           -> even  

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

Small, medium, large

  • Numbers less than 2 are small.
  • Numbers greater than 4 are large.
  • Other numbers are medium.
f({1,1,1,1})             -> [4, 0, 0]
f({1,2,3,4,5,6})         -> [1, 3, 2]
f({-1,1,-1,1,-1})        -> [5, 0, 0]
f({1,2,101,4,-1})        -> [2, 2, 1]
f({4,2,6,1,1})           -> [2, 2, 1]

Return the number of small, medium and large numbers.

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