Hacker News new | past | comments | ask | show | jobs | submit login

    def switch(match, dictionary, default="no match"):
        for key in dictionary.keys():
            if match in key:
                switch.last_match = key
                return dictionary.get(key)
        return default
Using “in” rather than “==“ here seems odd to me, is that intentional?

i.e I’d expect switch(‘abc’, {‘a’: 1}, default=“default”) to return “default”, but under this code it’d return 1, no?




You got that containment backwards;

  switch('a', {'abc': 1}, 'default') #returns 1
... but you're not wrong, that's godawful. But from the context of the article, they're optimizing for the case where multiple cases evaluate to the same answer. It would make more sense to write

  switch('a', {('a','b','c'): 1}, 'default') #returns 1
I'd optimize for performance, personally:

  def switch(match, dictionary, default="no match"):
    return dictionary.get(match, default)


It's not even thread safe.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: