Python:Accumulate Checking an Array

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

Jump to: navigation, search

You can use an accumulator to check if some condition is true for every element. For example we can check that every element is equal to 10. The array {10, 10, 10} would pass the test and return true, the array {10, 12, 10} would fail the test and return false.

acc = True;
for v in a:
  if v!=10:
    acc = False
return acc

We can do a little better than that. As soon as we find one value that is false there is no need to look at the rest of the array. We can "short circuit" the evaluation by returning immediately we find a false.

for v in a:
  if v!=10:
    return False
return True


All 1s

Return true if every element is equal to 1, otherwise return false.



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

Any ones

Return true if 1 occurs in the array, otherwise return false.


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

Words beginning with s


Return true if every element starts with the letter "s", otherwise return false.

f({"sock","shoe","spats"})    -> true
f({"silver","gold"})          -> false
f({"swim","swam","swan"})     -> true
f({"saturday","sunday"})      -> true


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