Difference between revisions of "Python:Accumulate Checking an Array"

From Progzoo
Jump to: navigation, search
(Words beginning with s)
 
Line 105: Line 105:
 
   for v in a:
 
   for v in a:
 
     if not v.startswith("s"):
 
     if not v.startswith("s"):
       return True
+
       return False
   return False
+
   return True
 
]]></answer>
 
]]></answer>
 
</question>
 
</question>
 
{{Accumulator Tutorial}}
 
{{Accumulator Tutorial}}

Latest revision as of 16:49, 12 July 2017

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]