Пример #1
0
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0

        # https://docs.python.org/2/library/itertools.html
        # takewhile()	pred, seq	seq[0], seq[1], until pred fails
        # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
        from itertools import takewhile as tw

        s = str.lstrip()

        sign = list(tw(lambda x: x in '+-', s))

        digits = list(tw(lambda x: x in '0123456789', s[1:] if sign else s))

        try:
            result = int((sign[0] if sign else "") + "".join(digits))
        except Exception:
            return 0

        return max(min(result, 2**31 - 1), -2**31)
Пример #2
0
def common_url_prefix(urls):
    def same(values):
        return all(v == values[0] for v in values[1:])

    from six.moves.urllib import parse
    parsed = [parse.urlparse(url) for url in urls]

    # We need the same protocol and netloc (host/port), otherwise there
    # is not a common prefix.
    if not same([u[:2] for u in parsed]):
        return None

    # If we get here, it means we have a shared protocol and netloc, so
    # now we just compare paths.
    from itertools import takewhile as tw
    parts = zip(*[p.path.split('/') for p in parsed])
    commonpath = '/'.join(x[0] for x in tw(same, parts))

    res_parts = parsed[0][:2] + (commonpath, '', '', '')
    res = parse.urlunparse(res_parts)
    if res[-1] != '/':
        res += '/'
    return res
Пример #3
0
# itertools.starmap tests
starmap = itertools.starmap

assert list(starmap(pow, zip(range(3), range(1,7)))) ==  [0**1, 1**2, 2**3]
assert list(starmap(pow, [])) == []
assert list(starmap(pow, [iter([4,5])])) == [4**5]
with assert_raises(TypeError):
    starmap(pow)


# itertools.takewhile tests

from itertools import takewhile as tw

t = tw(lambda n: n < 5, [1, 2, 5, 1, 3])
assert next(t) == 1
assert next(t) == 2
with assert_raises(StopIteration):
    next(t)

# not iterable
with assert_raises(TypeError):
    tw(lambda n: n < 1, 1)

# not callable
t = tw(5, [1, 2])
with assert_raises(TypeError):
    next(t)

# non-bool predicate
Пример #4
0
"""The 5-digit number, 16807=7^5, is also a fifth power. Similarly,
the 9-digit number, 134217728=8^9, is a ninth power.

How many n-digit positive integers exist which are also an nth power?

"""
from itertools import count, chain, takewhile as tw

ans = len(list(chain.from_iterable(tw(lambda x: len(x) > 0,
                                      (list(filter(lambda x: len(str(x)) == n,
                                                   (m**n for m in range(1,10))))
                                       for n in count(1))))))

print(ans)
Пример #5
0
def beginning_zeros(number: str) -> int:
    return sum(1 for _ in tw(lambda n: n == '0', number))
Пример #6
0
def end_zeros(num: int) -> int:
    return sum(1 for _ in tw(lambda ch: ch == '0', str(num)[::-1]))