Computer Science Week 4: Bins

This week was … kind of slow. We talked about sorting values into bins.

Bins

Let’s imagine that you have 1,000 numbers from 0 to 10, and I want you to sort them into 10 equally sized bins. How would you do this?

The naïve thing to do would be to sort each number like this:


bins = [0,0,0,0,0,0,0,0,0,0]

for number in numbers: if number < 1: bins[0] += 1 continue elif number < 2:

. . .

else:
    bins[9] += 1
    continue

That is, to write out every possible option in a big if-then-else statement. The problem is that this approach doesn’t scale well. What if I wanted them sorted into 1,000 buckets? It would be extremely tedious to write this using the same approach. So what did the professor ask us to do instead? Let me introduce you to the bisect module. A module is like a collection of useful functions and variables and classes and whatnot, all bound together for easy distribution. bisect comes built into python, I believe. It contains several useful functions, but the one that we’re going to use is called bisect_left. bisect_left takes a list and a thing, and tells you how far into the list you have to go to find a thing bigger than the first thing, minus one.

Now, we can write something like this:


import bisect

bins = [0]*10 for number in numbers: bins[min(len(bins), bisect.bisect_left(range(10), number))] += 1 —-

Much shorter, and we can change the number of bins by messing around with the range call.

Classes

After talking about bins, and doing an exercise involving histograms, we moved on to Classes. In python, remember how there were different types of things, like lists, ints, stringss, functions, et cetera? A class is a type of thing. Python let’s us define our own types, and make them do things. Here’s an example:


class Animal: def init(self, name): self._name = name

  def __str__(self):
      return "A " + self._name

This class can be used like this:


a = Animal() # Creates a new Animal print str(a) # Turns the Animal into a string and prints it. —-

The __init__ function tells us how to make a new thing of a class, and the __str__ function tells us how to turn it into a string. There are a bunch of other special functions too, but not all functions in a class need to be special. One of the most useful things about classes is their ability to bundle information and functions together, so that the functions can rely on the information being there without having to worry about keeping a bunch of different versions separate.

That’s all this week, but I hope to see you again next Sunday. Happy coding!