On 13/03/2016 01:10, Mark Lawrence wrote:
On 12/03/2016 23:57, BartC wrote:
[switch statements]
How does Python manage without them? Is it really necessary to declare
hundreds of individual variables and assign a value to each? (And risk
someone assigning a new value to them.)
That they might lead to more efficient code is secondary, but definitely
a bonus (essential though when used in a switch statement).
It is 2016. Programmer time, and hence money, are far more important
than runtime speed in the vast majority of cases.
Exactly why having ready-made solutions is preferable to everyone
hacking their own solutions to switch.
There are plenty of
working recipes for switch in Python. I'll leave you to quote a few as
you are such an expert in the Python programming language.
I've seen a few. Here's one that uses:
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))
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
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).
But 110 or 80 seconds, the original Python was 3.6 seconds. (Probably,
someone could tweak it to work with ranges, but this is extra programmer
effort that you say is too valuable to waste on such matters.)
(An actual 62-way if-elif chain took 25 seconds in Python 3.
You might care not about speed, but it's something when the fastest
solution in a language with built-in switch, and /still interpreting a
byte-code at a time/, is 1000 times faster than the 80-second version
above.)
--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list