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

test text

Any ones

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

.

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

test text

Words beginning with s

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