• Complex keys in dictionaries in Python

    Let’s imagine you want to store list or dictionary as a key in python dict. And you are going to write the code like this:

    dict_key = {'a': 3, 'b': 2}
    stat = {}
    stat[dict_key] = 1

    It’s a bad code because your are trying to use mutable object as a key in dictionary. And Python will check it and this code will throw an error:

    TypeError: unhashable type: 'dict'

    Let’s consider how to use complex objects and data structures as dict keys in Python.

    python programming python-tips
  • Priority Queues and Heaps in Python

    Let’s imagine that you want to solve the following problem:

    • You have tasks to process which are pushing to some queue
    • Every task has priority and and some information for processing
    • Every task should be processed according to it’s priority

    Priority Queue

    Data structure that can handle such tasks with priorities is called Priority Queue. How can we impelemnt it? We can place tasks to array but processing N tasks could take O(N^2) time which isn’t a good idea for a real application.

    Fortunatelly there is a very well known O(N log N) solution for this problem. Let’s have a look how to do it in Python.

    python programming python-tips
  • Sorting in Java

    You probably know that in order to sort array in Java you should use Arrays.sort. But do you know what algoritms are used inside?

    If we open implementaion we’ll see that for primitive arrays Dual Pivot QSort is used. That’s a modified QSort that splits array into three peaces instead of two in QSort. While Time Sort is used for Objects which is an upgraded version of Merge Sort.

    Let’s do some experiments and sort primitive array int[] and and array of objects Integer[]. Also let’s sort ArrayList<Integer> using Collections.sort.

    java programming java-tips
  • Named tuples in Python

    Today I want to talk about tuples. Code with tuples usually looks like this:

    def calculate_invoice():
        days = 14
        cost = 14 * 30
        return (days, cost, "Additional Information")
    
    days, cost, info = calc()

    Tuples are very convenient, epecially in scripts and prototypes. But it’s hard to read large code with tuples.

    What should we use instead, Classes?

    python programming python-tips
  • Welcome!

    Hi all, this is my personal blog. You’ll find a lot of usefull information in my blog about Programming and Data Science. Some tips for better language usage, tips how to pass code interview, overview of state-of-the-art approaches in ML and other usefull information

    blog programming

subscribe via RSS