[Tutor] Customized endswith/startswith version

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Aug 10 19:46:54 CEST 2005



> This is just an example, in my application I don't need to check strings
> against a huge number of cases. If however it would happen, how to
> modify startswith in order to make it accept a list instead of a simple
> string?
>
> [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])]


Hello,


Conceptually, we can define our own true/false functions ("predicates")
to help make it easy to express this.

As a concrete example, let's simplify the problem a bit.  Let's say that
we'd like to show all numbers between 0-100 that are divisible by two,
three, and five:

#######
def divisibleBy(m, n):
    """Returns true if m is divisible by n."""
    return m % n == 0

def divisibleByTwoThreeAndFive(x):
    return divisibleBy(x, 2) and divisibleBy(x, 3) and divisibleBy(x, 5)

print [n for n in range(100) if divisibleByTwoThreeAndFive(n)]
#######


We don't have something builtin that tells us if a number is divisible by
two, three, and five: we can define our own functions to do this.
divisibleBy() tells us if one number is divisible by another, and we can
use that to help us.

But it might seem weird that we have a custom function to take those three
hardcoded numbers.  divisibleByTwoThreeAndFive() is a bit of a mouthful.
Let's fix that: we'll add one more parameter that takes a list of
arguments:

#######
def divisibleByAll(n, listOfNumbers):
    """Returns true if n is divisible by all of the numbers in
    listOfNumbers."""
    for divisor in listOfNumbers:
        if not divisibleBy(n, divisor):
            return False
    return True
#######


And now we can say:

#######
print [n for n in range(100) if divisibleByAll(n, [2, 3, 5])]
#######


Does this make sense?  Please feel free to ask more questions about this.



More information about the Tutor mailing list