The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)
Christian Gollwitzer
auriocus at gmx.de
Sun Mar 13 17:26:22 EDT 2016
Am 13.03.16 um 20:39 schrieb BartC:
> switch(c)
> if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),
> ord("G"),ord("H"),ord("I"),ord("J"),ord("K"),ord("L"),
> ord("M"),ord("N"),ord("O"),ord("P"),ord("Q"),ord("R"),
> ord("S"),ord("T"),ord("U"),ord("V"),ord("W"),ord("X"),
> ord("Y"),ord("Z")):
> upper+=1
> elif case(ord("a"),ord("b"),ord("c"),ord("d"),ord("e"),ord("f"),
> ord("g"),ord("h"),ord("i"),ord("j"),ord("k"),ord("l"),
> ord("m"),ord("n"),ord("o"),ord("p"),ord("q"),ord("r"),
> ord("s"),ord("t"),ord("u"),ord("v"),ord("w"),ord("x"),
> ord("y"),ord("z")):
> lower+=1
> elif case(ord("0"),ord("1"),ord("2"),ord("3"),ord("4"),ord("5"),
> ord("6"),ord("7"),ord("8"),ord("9")):
> digits+=1
> else:
> other+=1
>
> It worked, but took 110 seconds; 80 seconds without the ord's and
> comparing strings (but I still think it's perverse that integer ops are
> slower than string ops).
I assume you run this in a big loop. What about a single hash-table lookup?
from collections import Counter
counts=Counter()
for c in whatever:
counts[c]+=1
upper=sum(counts[x] for x in range(ord('A'), ord('Z')+1)
lower=sum(counts[x] for x in range(ord('a'), ord('z')+1)
....
I think this is equally readable as the switch version, and should be
much faster.
Christian
More information about the Python-list
mailing list