Subscribe: Ned Batchelder's blog
Added By: Feedage Forager Feedage Grade B rated
Language: English
child nth  child  coverage  day  file  find  list  lists  loop  loops  nat  new  nth child  nth  pairs  people  tuple  tuples 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Ned Batchelder's blog

Ned Batchelder's blog

Ned Batchelder's personal blog.


Computing primes with CSS


I've been working on a redesign of this site, so doing more CSS, finally internalizing Sass, etc. During my reading, the nth-child pseudo-class caught my eye. It's oddly specific, providing syntax like "p:nth-child(4n+3)" to select every fourth paragraph, starting with the third. It isn't an arbitrary expression, it has to be of the form An+B, where A and B are integers, possibly negative. An element is selected if it is the An+B'th child of its parent, for some value of n ≥ 0.It struck me that this is just enough computational power to compute primes with a Sieve of Eratosthenes, so I whipped up an demonstration (see it live here):


1 2 3 4 ... 996 997 998 999
The code has only linear sequences of numbers. There are spans for 1 through 999, the candidate numbers. These are arranged so that the number N is the Nth child of their containing div. The CSS has nth-child styles for 2 through 32, the possible factors.The Sieve will hide numbers that are determined not to be primes with a "display: none" rule. A first-child selector hides 1, which is typical, seems like you always have to treat 1 specially when looking for primes. The other selectors for the display:none rule select the multiples of each number in turn. "nth-child(2n+4)" will hide elements 4, 6, 8, and so on. "nth-child(3n+6)" will hide 6, 9, 12, and so on.So CSS has two features that together are just enough to implement the Sieve. The nth-child selector accomplishes the marking of factors. The overlapped application of separate rules implements the multiple passes, one for each factor.Of course, I didn't write this file by hand, I wrote a Python program to do it. It's pretty simple, I won't clog up this post with the whole thing. But, it was my first use of a new feature in Python 3.6: f-strings. The loop that writes the nth-child selectors looks like this:for i in range(2, 33):     print(f"span:nth-child({i}n+{2*i}),") The f"" string has curly-bracketed expressions in it which are evaluated in the current scope. This string in Python 3.6:f"span:nth-child({i}n+{2*i})" is equivalent to this in previous Pythons:"span:nth-child({i}n+{i2})".format(i=i, i2=2*i) It felt really natural to use this new feature, and really convenient. [...]

Don't follow me on Instagram


This summer I started taking pictures and posting them on Instagram. It started with a conversation with my son Max, and his assertion that posting more than one picture a day on Instagram was Instaspam. That constraint appealed to me. I like the idea of photography as a way of attending to what I am seeing. So I started trying to look around me to find interesting shots for Instagram posts.

My summer has been different than I expected, so I've had chances to look around places I didn't expect to be. Ironically, thinking about what can go on Instagram can be a way to focus on the here-and-now. You have to see what is immediately around you in order to get a shot.

Normally, thinking about stuff to post on a social network can be the furthest thing from being in the moment. You're thinking about how people will react to your tweet, or who will look at your Facebook status. It's easy to fall into second-guessing what will get the biggest response. You spend time going back to look at what happened to your recent activity.

I have mixed stances toward different social media. I like Twitter, and like having followers. I want my tweets to get widely retweeted. I ignore Facebook, except to find out what my sons are up to. Pinterest and Snapchat might as well not exist. Now I'm putting pictures on Instagram, but not to get followers or tons of likes. The photos have no message, I rarely put any words on them. If I can post a picture I like, and have one other person like it, that's enough.

If you want to follow someone good on Instagram, my brother is an actual photographer who knows what he is doing. Follow him!

Walks in the morning


The summer is wrapping up, and it's been a strange one. On July 4th weekend, we discovered a serious bruise on Nat's chest. We took him to the emergency room to have it properly documented so we could make a formal investigation. The doctor there told us that Nat had a broken rib, and what's more, he had another that had healed perhaps a year ago.

Nat is 26, and has autism. We tried asking him what had happened, but his reports are sketchy, and it's hard to know how accurate they are. We moved him out of his apartment, and back home with us. We ended his day program. He'd had a good experience at a camp in Colorado a few years ago, so we sent him back there, which was expensive, and meant two Colorado trips for us.

The investigation has not come up with any answers. A year ago, he had been acting oddly, very still and reluctant to move. Then, we couldn't figure out why, but now we know: he had a broken rib.

We've found a new day program for Nat which seems really good. It starts full-time on Monday. During the last month, we've been cobbling together things for Nat to do during the day. He has a lot of energy and likes walking, so I've switched my exercise from swimming to doing early-morning walks with Nat before work.

Parenting is not easy. No matter what kind of child(ren) you have, there are challenges. You have to understand their needs, decide what you want for them, and try to make a match. You have to include them in the many forces that shape your days and your life.

This summer has been a challenge that way, figuring out how to fit this complicated man into our day. The walks have been something Nat and I do together, one of the few things we both enjoy. I'll be glad to be back to my swimming routine, but I'm also glad to have had this expansion of our walking together, something that used to only happen on weekends.


We still have to find a place for Nat to live, and we have to make sure the day program takes hold in a good way. I know this is not that last time Nat will need our energy, worry, and attention, and I know we won't always know when those times are coming. This is what it means to be his parent. He needs us to plan and guide his life.

And he needs to walk in the morning.

Lists vs. Tuples


A common beginner Python question: what's the difference between a list and a tuple?The answer is that there are two different differences, with complex interplay between the two. There is the Technical Difference, and the Cultural Difference.First, the things that are the same: both lists and tuples are containers, a sequence of objects:>>> my_list = [1, 2, 3] >>> type(my_list) >>> my_tuple = (1, 2, 3) >>> type(my_tuple) Either can have elements of any type, even within a single sequence. Both maintain the order of the elements (unlike sets and dicts).Now for the differences. The Technical Difference between lists and tuples is that lists are mutable (can be changed) and tuples are immutable (cannot be changed). This is the only distinction that the Python language makes between them:>>> my_list[1] = "two" >>> my_list [1, 'two', 3] >>> my_tuple[1] = "two" Traceback (most recent call last):   File "", line 1, in  TypeError: 'tuple' object does not support item assignment That's the only technical difference between lists and tuples, though it manifests in a few ways. For example, lists have a .append() method to add more elements to the list, while tuples do not:>>> my_list.append("four") >>> my_list [1, 'two', 3, 'four'] >>> my_tuple.append("four") Traceback (most recent call last):   File "", line 1, in  AttributeError: 'tuple' object has no attribute 'append' Tuples have no need for an .append() method, because you can't modify tuples.The Cultural Difference is about how lists and tuples are actually used: lists are used where you have a homogenous sequence of unknown length; tuples are used where you know the number of elements in advance because the position of the element is semantically significant.For example, suppose you have a function that looks in a directory for files ending with *.py. It should return a list, because you don't know how many you will find, and all of them are the same semantically: just another file that you found.>>> find_files("*.py") ["", "", "", ""] On the other hand, let's say you need to store five values to represent the location of weather observation stations: id, city, state, latitude, and longitude. A tuple is right for this, rather than a list:>>> denver = (44, "Denver", "CO", 40, 105) >>> denver[1] 'Denver' (For the moment, let's not talk about using a class for this.) Here the first element is the id, the second element is the city, and so on. The position determines the meaning.To put the Cultural Difference in terms of the C language, lists are like arrays, tuples are like structs.Python has a namedtuple facility that can make the meaning more explicit:>>> from collections import namedtuple >>> Station = namedtuple("Station", "id, city, state, lat, long") >>> denver = Station(44, "Denver", "CO", 40, 105) >>> denver Station(id=44, city='Denver',&#x[...]

Breaking out of two loops


A common question is, how do I break out of two nested loops at once? For example, how can I examine pairs of characters in a string, stopping when I find an equal pair? The classic way to do this is to write two nested loops that iterate over the indexes of the string:s = "a string to examine" for i in range(len(s)):     for j in range(i+1, len(s)):         if s[i] == s[j]:             answer = (i, j)             break   # How to break twice??? Here we are using two loops to generate the two indexes that we want to examine. When we find the condition we're looking for, we want to end both loops.There are a few common answers to this. But I don't like them much: Put the loops into a function, and return from the function to break the loops. This is unsatisfying because the loops might not be a natural place to refactor into a new function, and maybe you need access to other locals during the loops. Raise an exception and catch it outside the double loop. This is using exceptions as a form of goto. There's no exceptional condition here, you're just taking advantage of exceptions' action at a distance. Use boolean variables to note that the loop is done, and check the variable in the outer loop to execute a second break. This is a low-tech solution, and may be right for some cases, but is mostly just extra noise and bookkeeping. My preferred answer, and one that I covered in my PyCon 2013 talk, Loop Like A Native, is to make the double loop into a single loop, and then just use a simple break.This requires putting a little more work into the loops, but is a good exercise in abstracting your iteration. This is something Python is very good at, but it is easy to use Python as if it were a less capable language, and not take advantage of the loop abstractions available.Let's consider the problem again. Is this really two loops? Before you write any code, listen to the English description again:How can I examine pairs of characters in a string, stopping when I find an equal pair?I don't hear two loops in that description. There's a single loop, over pairs. So let's write it that way:def unique_pairs(n):     """Produce pairs of indexes in range(n)"""     for i in range(n):         for j in range(i+1, n):             yield i, j s = "a string to examine" for i, j in unique_pairs(len(s)):     if s[i] == s[j]:         answer = (i, j)         break Here we've written a generator to produce the pairs of indexes we need. Now our loop is a single loop over pairs, rather than a double loop over indexes. The double loop is still there, but abstraced away inside the unique_pairs generator.This makes our code nicely match our English. And notice we no longer have to write len(s) twice, another sign that the original code wanted refactoring. The unique_pairs generator can be reused if we find other places we want to iterate like this, though remember that multiple uses is not a requirement for writing a function.I know this technique seems exotic. But it really is the best solution. If you still feel tied to[...] 4.2

2016-07-27T08:35:00-05:00 4.2 is done.

As I mentioned in the beta 1 announcement, this contains work from the sprint at PyCon 2016 in Portland.

The biggest change since 4.1 is the only incompatible change. The "coverage combine" command now will ignore an existing .coverage data file, rather than appending to it as it used to do. This new behavior makes more sense to people, and matches how "coverage run" works. If you've ever seen (or written!) a tox.ini file with an explicit coverage-clean step, you won't have to any more. There's also a new "--append" option on "coverage combine", so you can get the old behavior if you want it.

The multiprocessing support continues to get the polish it deserves:

  • Now the concurrency option can be multi-valued, so you can measure programs that use multiprocessing and another library like gevent.
  • Options on the command line weren't being passed to multiprocessing subprocesses. Now they still aren't, but instead of failing silently, you'll get an error explaining the situation.
  • If you're using a custom-named configuration file, multiprocessing processes now will use that same file, so that all the processes will be measured the same.
  • Enabling multiprocessing support now also enables parallel measurement, since there will be subprocesses. This reduces the possibility for error when configuring

Finally, the text report can be sorted by columns as you wish, making it more convenient.

The complete change history is in the source. 4.2 beta 1

2016-07-05T20:39:00-05:00 4.2 beta 1 is available.

This contains a few things we worked on during a day of sprinting at PyCon 2016 in Portland. Thanks to my fellow sprinters: Dan Riti, Dan Wandschneider, Josh Williams, Matthew Boehm, Nathan Land, and Scott Belden. Each time I've sprinted on, I've been surprised at the number of people willing to dive into the deep end to make something happen. It's really encouraging to see people step up like that.

What's changed? The biggest change is the only incompatible change. The "coverage combine" command now will ignore an existing .coverage data file, rather than appending to it as it used to do. This new behavior makes more sense to people, and matches how "coverage run" works. If you've ever seen (or written!) a tox.ini file with an explicit coverage-clean step, you won't have to any more. There's also a new "--append" option on "coverage combine", so you can get the old behavior if you want it.

A new option lets you control how the text report is sorted.

The concurrency option can now be multi-valued, if you are using multiprocessing and some other concurrency library, like gevent.

The complete change history is in the source.

This isn't going to be a long beta, so try it now!

Math factoid of the day: 54


54 can be written as the sum of three squares in three different ways:

7² + 2² + 1² = 6² + 3² + 3² = 5² + 5² + 2² = 54

It is the smallest number with this property.

Also, a Rubik's cube has 54 colored squares.

Loudest guy in the room


I just got back from PyCon 2016, and it was a giant summer camp love-fest as usual. But I've been thinking about a subtle and unfortunate dynamic that I saw a few times there.

In three different cases, I was with a group of people, and one person in particular had a disproportionate amount of air-time. They were different guys each time, but they just had a way of being the one doing more talking than listening, and more talking than others. In some cases, they were physically loud, but I don't always mean literally the loudest.

These weren't bad people. Sometimes, they were explicitly discussing the need to include others, or improve diversity, or other good impulses. They weren't trying to dominate the space, and they might even be surprised to hear that they were.

But I found myself cringing watching their interactions with others. Even when they thought they were being encouraging, I felt like they were subtly pushing others aside to do it. Keep in mind, this was at PyCon, one of the most explicitly inclusive places I frequent.

I'm a successful white guy, so I know it can be very easy to slip into the alpha male stance. Sometimes people expect it of me. It can be hard to tamp down the impulse to hold forth, letting others have the spotlight. But it's important, and a good exercise for yourself. It's fine to be able to be at the front of the room, but you should be able to turn it off when needed, which is more often than you would think.

Sometimes, this was in a men-only setting. It's great to be aware of the gender gap, but there are other kinds of gaps to consider also: non-native speakers, introverts, beginners, outsiders of various sorts. There are lots of reasons people might be quiet, and need a little room.

Ask questions instead of making statements. Stay quiet, and see what happens. Listen rather than speak. Even when it seems no one is going to say anything, wait longer than you are comfortable. See what happens. Leave space.

Next time you are in a group of people, look around and try to figure out who is the loudest guy in the room. If you aren't sure, then maybe it's you.

PyCon 2016: Machete-mode debugging


I gave a talk today at PyCon 2016: Machete-Mode Debugging. I went over time, but people really liked it. Amazingly, the video was available within six hours!

Gratifyingly, a talk later in the day referenced the phrase "machete-mode debugging," so maybe it will catch on.