Python Partition Calculator

I had been looking to do a little bit more hobby-coding, and I came across this simple math problem which can be solved with a cool recursive Python script.

A partition is a concept in number theory where a positive integer is written as a sum. For example, the only partition of 1 is (1). 2 has (2) and (1+1). 3 has (1+2), (1+1+1), and (3), and so on. Because it’s a sum, order is not important.

The problem of figuring out partitions is not difficult, but it is time-consuming and repetitive once you go beyond calculating all partitions for 4 or 5. Something that makes it a good candidate for automation. It also can be done with some recursion.

The first thing that needs to be done is a recursive call to calculate all the combinations of numbers that would form a partition. I’m going to return a list of lists, where each sublist is a partition. The obvious part to take care of first is the base case:

#returns a list of lists. Each sublist sums to the partition_goal 
def recursive_partition(partition_goal):
    return_list =[]
    if partition_goal==1:

Next, let’s take a look at when the partition_goal is some number larger than one. The first thing we’d need is to add a list consisting of just that number:

#returns a list of lists. Each sublist sums to the partition_goal 
def recursive_partition(partition_goal):
    return_list =[]
    if partition_goal==1:

Now we need to loop over all the cases where the lists are more complicated. Let’s take 3, because it’s pretty simple. Once we’ve added the single item list [3] in the step above, we need to add the integer 1 to all lists that add up to 3 – 1, the integer 2 to all lists that add up to 3 – 2 and so on.

#returns a list of lists. Each sublist sums to the partition_goal 
def recursive_partition(partition_goal):
    return_list =[]
    if partition_goal==1:
        for i in range(1,partition_goal):
            for j in recursive_partition(partition_goal - i):
    return return_list

So for each of the numbers in the i range, we are adding that number to every list we can create recursively (j) where that list sums to partition_goal – i. Lastly, we need to call our recursive method, and then remove all the sublists which are identical when unordered ([1,1,2] and [1,2,1] are just one partition of 4). We do this using the Counter module.

#returns a list of lists. Each sublist sums to the partition_goal 
def recursive_partition(partition_goal):
    return_list =[]
    if partition_goal==1:
        for i in range(1,partition_goal):
            for j in recursive_partition(partition_goal - i):
    return return_list

list_of_lists = recursive_partition(n)

counted = Counter(tuple(sorted(entry)) for entry in list_of_lists)


The variable counted actually gets a dictionary Python object, so I turned it into a list in the print statement. The keys of a Counter are tuples, so the end result is a list of tuples where every tuple is a partition. Lastly let’s make some interface changes so we can take command line arguments or ask the user for input.

from collections import Counter
import sys

n = 1
# partition goal
if len(sys.argv) > 1:
    n = sys.argv[1]
    n = int(input("What number do you want the partitions for?"))

#returns a list of lists. Each sublist sums to the partition_goal 
def recursive_partition(partition_goal):
    return_list =[]
    if partition_goal==1:
        for i in range(1,partition_goal):
            for j in recursive_partition(partition_goal - i):
    return return_list

list_of_lists = recursive_partition(n)

counted = Counter(tuple(sorted(entry)) for entry in list_of_lists)


And remember this is Python 3 notation. You can find this little project on Github here.



If you’ve been wondering where all my political blogging that I did last year has gone, I’ve transferred it over to a new blog to better separate personal stuff from political things.  I’m not linking it as to make it slightly harder for random prospective employers from the far future to find it. If you don’t know what my new blog is, just tweet at me or message me privately.

I enjoy videogames, but I often don’t have enough time to really indulge in them. I’ve had great experiences with past Blizzard games, and so when Overwatch came out in May, I decided to get it.

Not only do I not usually play video games, but I also don’t tend to play games when they first come out. I also like to stick to single-player, story-driven games (Portal, Arkham Asylum, Skyrim) and sometimes strategy games (Total War series, Civ V) or both (XCOM). And, of course, I tend to play these on a long delay, waiting for Steam sales to reduce the financial burden of my infrequent hobby. But in this case I decided to go for a multi-player game soon after it had come out.  Many have rightly stated that Overwatch is a Team Fortress 2 rip-off. Of course, I think people are far too protective of intellectual property anyway, and good rip-offs can be even better than the originals. Blizzard took the excellent gameplay ideas in Team Fortress 2, inserted their art and character backgrounds from their failed MMO Titan, and then created an amazingly fun and deep multi-player shooter.

Competitive role-based multi-player gaming is pretty fun. Trying to beat puzzles crafted by game designers is great too, but there’s something you can’t reproduce without battling against other people and their strategies. I always enjoyed player-vs-player parts of WoW, but part of it always came down to players who sank more time into the game got better weapons. This isn’t the case in Overwatch. Of course, this isn’t a new game genre either, but the creativity of what you can do and the absolute chaos you can fall into so easily is incredible. It’s just pure fun.

Blizzard also just did an incredible job with all the details apart from gameplay: the world is engaging and beautifully detailed, the game isn’t buggy at all, the point system is well crafted, the matching algorithms work quickly and efficiently, and the community dialogue has been amazingly transparent.  I don’t know what the game is like as a power player who wants to play competitively for dozens of hours a week, but I know for what I want as a casual gamer who will only sink a few hours into it a week, this game is essentially perfect. It’s also very easy to get into, and Blizzard has already started releasing additional content with no extra cost. If you haven’t played this game and were thinking about it, I can fully recommend it.

But this video game has also coincided with a renewal of board game popularity, not just in my life but in the entire market. This is somewhat surprising given the already mature market for games on computers, consoles, and mobile devices. Nonetheless here we are in the midst of a board game revolution. Somehow in the past year I’ve found myself playing Catan, Codenames, Escape: The Curse of the Temple, One Night Ultimate Werewolf, Avalon, and more. I’ve undoubtedly played more board games this year than any other year I’ve been alive. And I even dabbled in Go a bit this year as AlphaGo made headlines. I suspect this renewed interest in applied game theory in a fun setting contributed to me buying Overwatch.

Unlike other multi-player video games which might rely on grinding to give players an edge, these board games rely exclusively on luck and skill; time devoted doesn’t factor in besides how long it takes you to learn. To me it makes these games a fundamentally higher brain exercise than something like WoW or Skyrim could ever be.  For me personally, this is a pretty exciting way to see gaming go mainstream (In a related vein, I’ve really enjoyed Crash Course’s new Games series with Andre Meadows).

When you put games on this axis of simple tactics to complex strategies, it also becomes clear why so many people want to watch games like Counterstrike, League of Legends, Rocket League, or Overwatch rather than games like WoW, Minecraft, or Grand Theft Auto; games that require more learned skill, innate talent, and strategy are far more interesting to watch that games that rely on grinding. And if you move further along the axis towards complexity and strategy, you’ll start to run into competitive physical sports like basketball and soccer. Obviously strategy and complexity aren’t sufficient make games universally popular (cricket is fairly complex but isn’t very popular in America, american football has similar popularity issues in the rest of the world), but they are necessary. EconTalk had a great discussion this week regarding the development of sports into entertainment; 50 years ago the major sports of today were nothing like we know them. They have developed into much improved products, and it wasn’t just TV exposure; the sports are measurably better in every way. Rules, nutrition, training, professionalism, advertising, etc have all improved drastically. There’s no reason to think games beyond the physical won’t see similar growth over the next 50 years.

It’s also worth pressing that this gaming revolution is a sign that Things Are Pretty Much Ok (TM). Despite what you may be hearing, violence and terrorism is trending downwards, fewer people are living below $1 a day than ever before, and apparently despite the ongoing technological isolation of our society, social board games where people play face-to-face are doing better than they’ve ever done. Seriously, if we agree that developed countries have mostly solved lifting everyone above subsistence existence, we get to philosophical questions of human existence beyond survival. What should people be doing, what activities should they engage in? Enjoying social gatherings with strategic brain games, seems like a wonderful way to spend that time, and I think could provide a proxy for a type of win condition for economic policy.  The future of games isn’t just fun, it should be a major part of our culture for many years to come.

Duke's National Championship team went to the White House this year. Carolina couldn't make it. Public Domain Image.

Duke-Carolina Rivalry: Keeping Score

Tonight is the first of at least two meetings between Duke and UNC’s men’s basketball teams this year. I predicted Duke had a 60% chance to win at least one of these games, given the consensus that Carolina fields a better team this year. I think that’s still a bit of an underestimate, as that equates to Carolina having a 63% chance to win each game, which seems a bit high, given how competitive these games usually are.  Moreover, against common opponents this year, Duke is 7-3 to UNC’s 8-2.  Carolina certainly has the advantage at home tonight (and with only 6 Duke players playing more than 5 minutes), though it’s unlikely to be a blowout.

Let’s talk about the rivalry. Duke and Carolina have played 240 men’s basketball games against each other, with UNC currently winning the series 133-107.  But I contend this fact is not relevant because more distant sports results tend to fade from memory and importance over time.  It’s the most recent outcomes that everyone talks about…

2015 ncaa national championship

Duke's National Championship team went to the White House this year. Carolina couldn't make it. Public Domain Image.

Duke’s National Championship team went to the White House this year. Carolina couldn’t make it. Public Domain Image.

And last year, guess who not only won a national championship, but who also swept their rivals? The Blue Devils. Of course, dominance in the last year can’t define an entire rivalry, so let’s look at the last couple years. Since 2014, who has done better? Duke is up 3-1.  But what if what really matters is the last 3, 4, or 5 years? Duke 5-1, 6-2, 8-3. In fact, we can keep this trend going:

last <Y> years last <x> games Dating Back To Duke record
1  2 2015  2-0
2  4  2014  3-1
3  6  2013  5-1
4  8  2012  6-2
5  11  2011  8-3
6  13  2010  10-3
7  15  2009  10-5
8  17  2008  11-6
9  19  2007  11-8
10  21  2006  12-9
12  25  2004  15-10
14  31  2002  20-11
16  36  2000  24-12
18  42  1998  28-14
20  46  1996  29-17
25  58  1991  34-24
30  60  1986  39-31
35  71  1981  42-39
38  82  1978  47-45
39  85  1977  47-48

Duke has a winning record against Carolina over the last X years, where X is any number of years you’d care about.

Since UNC’s Class of 2019 was born, UNC is about 14-28 against Duke. Since their seniors were born, UNC is 21-29 against Duke. Their lives have been defined by an era of Blue Devil Dominance (for the first few years of current seniors’ lives, UNC did have a winning record against Duke, which means, as far as this rivalry in concerned, their glory days were during preschool, something they share with many other Tar Heels).

You might hear a stat on ESPN tonight that “dating back to 1977, this rivalry is tied!” That’s because you literally have to go back to 1977 to get a tie in the rivalry, Duke has been so dominant recently. But hey, if you count all the games going back to the Ford administration, the Tar Heels are right there with them!

So when Carolina fans brag about how their team is better for having gone undefeated in 1957, an era where lasers and zip codes hadn’t yet been invented, or having won 6 national titles to Duke’s 5 since they count that ultra-competitive 1924 season which was only retroactively declared a championship 20 years later, let them have this. They’ve been getting crushed by Duke for the last 38 years, it’s only fair.


2016 Predictions

How confident should we be? People tend to be overconfident.  One way to figure out if our confidence levels are correct is to test our calibration levels by making predictions and seeing how many of them pan out. Inspired by Slate Star Codex’s predictions, here are my predictions and accompanying confidence levels. For the sake of convenience I will choose from confidence levels of 50%, 60%, 70%, 80%, 90%, 95% or 99%. All predictions are by December 31, 2016 unless noted otherwise.

World Events

  1. Liberland will be recognized by <5 UN members: 99%
  2. Free State Project to reach goal of 20,000 people in 2016: 50%
  3. ISIS to still exist: 80%
  4. ISIS to kill < 100 Americans 2016: 80%
  5. US will not get involved in any new major war with death toll of > 100 US soldiers: 80%
  6. No terrorist attack in the USA will kill > 100 people: 80%
  7. Donald Trump will not be Republican Nominee: 80%
  8. Hillary Clinton to be Democratic nominee: 90%
  9. Republicans to hold Senate: 60%
  10. Republicans to hold House: 80%
  11. Republicans to win Presidential Election: 50%
  12. I will vote for the Libertarian Presidential Candidate: 70%
  13. S&P 500 level end of year < 2500: 70%
  14. Unemployment rate December 2016 < 6% : 70%
  15. WTI Crude Oil price < $50 : 80%
  16. Price of Bitcoin > $500:  60%
  17. Price of Bitcoin < $1000: 80%
  18. Sentient General AI will not be created this year: 99%
  19. Self-driving cars will not be available this year to purchase / legally operate for < $100k: 99%
  20. I will not be able to rent trips on self-driving cars from Uber/ Lyft: 90%
  21. Humans will not land on moon by end of 2016: 95%
  22. Edward Snowden will not be pardoned by end of Obama Administration: 80%


  1. Employed in current job:  90%
  2. I will have less than 300 Twitter followers: 60%
  3. I will have authored > 12 more blog posts by June 30, 2016:  50%
  4. to have >4,000 page loads 2016: 50%
  5. These predictions are underconfident: 70%


  1. Miami Heat make playoffs 2016:  80%
  2. Miami Heat will not make Eastern Conference Finals:  90%
  3. Duke basketball wins 1 game or more against UNC: 60%
  4. Duke basketball makes it to Round of 32 in NCAA Tournament: 70%
  5. Duke basketball does not make Final Four: 90%
  6. USA wins Olympic gold medal in basketball: 70%
  7. Kevin Durant will not be highest paid NBA player during 2016-17 season: 70%

Is Creative Culture Stagnating?

Spoiler warning for the new Star Wars movie.

I’ve read a few interesting pieces critical of The Force Awakens: Peter Suderman at Vox says TFA is a prime example of Hollywood’s nostalgia problem, there’s also a “nostalgia debate” around TFA at The Atlantic, and Ross Douthat at the NYT says TFA is a symptom of the decadence and cultural stagnation of our society.

I wondered if these people were having a romantic view of the past; has Hollywood just now started doing more sequels or have they always done so? I decided to take a look at the highest grossing movies from 1975-85 (when the original Star Wars trilogy came out) and compare it to the last 5 years. But it quickly became more complicated than I thought it would be; are sequels better or worse than remakes? Are movies based on books bad? Are movies based on comic book characters worse than movies based on books?  What about sequels of remakes of movies based on comic book characters?!  That sounds like the worst category, but it would include The Dark Knight, one of the best action blockbusters of the lack decade. Continue reading

Choosing Sides: College Football Edition

Building off of some of my reasoning in my NBA Finals post, I realized I needed a better system for deciding which teams to cheer for in college football. There are 128 college football teams in NCAA Division I Football Bowl Subdivision (known as FBS), and since each team only plays about 12 games a year, most teams do not play each other. Consequently, if you cheer for only one team, you end up only watching a small fraction of the available games, and you’ll never see most good teams play.  But since I like football and, as noted in the NBA Finals post, sports are much more fun when you have a narrative, I’ve decided to properly develop a system to dictate who I will cheer for in different games. This is especially useful with the upcoming conference championships today as well as the many bowl games later in the month.

The system is a pretty straightforward hierarchy, but since I don’t have strong enough feelings on all 128 FBS teams (or even most in the Power 5 conferences), I’ve divided the teams into 3 groups:

  • Group A is a ranked hierarchy of teams I will cheer for against all other teams, except those that are higher in Group A
  • Group Omega is a ranked hierarchy of all the teams I will always cheer against, except those that are higher in Group Omega.  You’ll notice it is larger than group A.
  • Group Meh is all the teams I don’t have strong feelings about. I will cheer against them when they play Group A, and for them when they play Group Omega. I won’t care when they play each other.

Continue reading

Let me be nice and clear

This is an article published today in Duke’s student newspaper.

The article advocates for the silencing of ideas we disagree with as long as our actions aren’t completely unconstitutional. Therefore, here is a list of responses to this article the author would approve of:

  1. Getting a counter protest together to scream about what a horrible person the author is.
  2. Targeting her with horrible facebook and twitter smear campaigns, declaring what a bad* person she is
  3. Stage a protest and circulate a petition to get the Chronicle and Duke to take down this column and stop the author from writing any more
  4. Create a committee to approve of all future columns before publication to make sure they do not contain any intolerant opinions.
  5. Circulate this column with future prospective employers of the author, threaten to make a big protest if the author is hired at a firm. Ruin the author’s chance of employment because we disagree with her opinion.

*insert your own creative adjectives here

If an angry mob did this to the author, it’s hard to see how she could say it was unfair. Nevertheless, I don’t believe we should be as mean and intolerant as the Constitution allows us to be. There is a great benefit to tolerance beyond the tolerance of law.  Therefore, if you do what the author has suggested, you will not be elevating the level of intellectual discourse; you will be shutting out part of it. Intolerance, like speech, is a tool. And there is no reason a tool can be used by only your side.  We should not be making it easier to stop speakers from having an open dialogue, to stop interactions with ideas we dislike, or to get people fired for unpopular opinions.  Groups of people who have not heard all sides of an argument are by definition uninformed, and uninformed mobs are not good arbiters of the merits of arguments.

Credit Michael Tipton, Used and Licensed under CC-BY-SA

The NBA Should Shorten Their Season


Did you know that the NBA has the best YouTube channel of any major North American sport? This is remarkable considering it is a distant third in terms of revenue.  It’s also a fascinating exercise in fan outreach, as the NBA actively encourages fan-made videos and other content while other sports use restrictive copyrights to make themselves the sole distributor of content. In addition to these policies (and the fact that I like basketball), it’s worth noting that while football is clearly the king of team sports in the US (especially if you include college football), there’s a risk that increased awareness of concussions and other injuries could cause football to lose out on revenue in the future. This could happen through changes in demand, with fewer people wanting to watch football, or changes in supply, as fewer athletes want to play. If you think it can’t happen, don’t forget that boxing used to be one of America’s most dominant sports.

Will this same fate happen to football? It’s impossible to know, but as a basketball fan, I hope the NBA is be prepared to try and take over that market space.  Before they are under the spotlight and the opportunity passes, they should implement some reforms. An important one would be the shortening of the season. Continue reading

Latin American Economies and Free Markets

Macroeconomics is a tricky beast. It’s easy to take data out of context to fit your narrative, but it’s always important to look at the data and consider what it means, whether it supports you point or not.

This first section is in response to a post on the internet about Chile and Pinochet. Continue reading

White Oak, Maryland
Seeding LEED, Public Domain image

David Friedman, Generic Drugs, Papal travels, and other links

I’ve got a couple interesting things in development, but in the meantime here are some links I’ve come across recently with some short analysis tacked on.

I don’t consider myself an anarcho-capitalist, although I agree with some of the arguments ancaps make.  I don’t find them too crazy if, for example, you accept the premise that even a well constrained government slowly escapes its constitutional shackles (debatable).  The result of this premise that the only option that would keep a government from expanding and infringing on freedom is to never have one at all. But I find it mostly uninteresting since I’m into politics and the political reality is that we have a government, we’ve had one for a long time, and we’re going to have one for quite some time into the future. Moreover, because I’m a consequentialist and most ancaps are deontological, some of the outrage at the government’s existence is also dulled. But despite all of that, this video by consequentialist anarcho-capitalist David Friedman summarizing his argument in The Machinery of Freedom (reviewed by Slate Star Codex here and more here) is excellent and well worth the 20 minute watch. Continue reading