On Mon, 14 Mar 2016 06:39 am, BartC wrote:

> class switch(object):
>      value = None
>      def __new__(class_, value):
>          class_.value = value
>          return True
> 
> def case(*args):
>      return any((arg == switch.value for arg in args))

That's quite a clever use of a class. By clever, I mean imaginative, not
necessarily smart.


> I used it in my benchmark to replace the if-else chain checking three
> lots of ranges:
> 
> 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


Ai-ai-ai-aiye! 

What a mess! See what happens when you write assembly language in
Python? :-)


Try this instead:

c = chr(c)
if 'A' <= c <= 'Z':
    upper += 1
elif 'a' <= c <= 'z':
    lower += 1
elif '0' <= c <= '9':
    digits += 1
else:
    other += 1


But even better:

if c.isupper():
    upper += 1
elif c islower():
    lower += 1
elif c.isdigit():
    digits += 1
else:
    other += 1


which will work correctly for non-ASCII characters as well.



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to