Difference between revisions of "Python:Accumulate Multiple Values"

From Progzoo
Jump to: navigation, search
(Odds and evens)
Line 62: Line 62:
 
   for v in list:
 
   for v in list:
 
     if v % 2 ==0:
 
     if v % 2 ==0:
       evens = evens + v
+
       evens = evens + 1
 
     else:
 
     else:
       odds = odds + v
+
       odds = odds + 1
 
   return [odds,evens]
 
   return [odds,evens]
 
</answer>
 
</answer>

Revision as of 16:33, 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]