Search This Blog

23 February 2015

Python Puzzle #1

I plan to publish a serie of Python puzzle, or challenges.
Mostly around data manipulation, they can be a great way to improve your python skills.
There is many ways to solve this, you can chose your style from:
  • best performance 
  • best readability 
  • least lines of code 
  • most obfuscated 

the goal is to pass the unit test(s).


import unittest


def dotted_to_dict(incoming):
    pass


class TestDottedToDict(unittest.TestCase):
    def setUp(self):
        self.dotted = [{'a': 1, 'b.e.f': 2, 'b.e.g': 9, 'c.a': 5, 'c.d': 10},
                       {'a': 6, 'b.f.f': 8, 'b.f.g': 0, 'c.a': None, 'c.d': 15},
        ]

        self.expected = [{'a': 1, 'b': {'e': {'f': 2, 'g': 9}}, 'c': {'a': 5, 'd': 10}},
                         {'a': 6, 'b': {'f': {'f': 8, 'g': 0}}, 'c': {'a': None, 'd': 15}},
        ]

    def testClasses(self):
        """
        """
        got = dotted_to_dict(self.dotted)
        self.assertEquals(got, self.expected)

Please comment if you feel the question is not clear enough.
Have fun!

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hello ! Cool idea. So for my first attempt, I went for readability (i.e., pythonicity). I think it behaves well, performance wise, because there is no obvious algorithmic improvement or waste (only scanning elements once, no structure copying). However, maybe the defaultdict can be sped up by using a less readable structure, not sure. Sorry for removing my first comment, the code did not format well in the comments, so here is the pastebin link

    In my second attempt, I went for coolness. I tried to implement a defaultdict which supported "." accessing, and then evaluating the assignments. That is pretty bad in terms of performance I would imagine (and confirmed by testing: 10 times slower according to timeit). Here is the pastebin link for this "fun" approach (really, this depends on what you consider to be "fun" in life, YMMV).



    ReplyDelete