Fast, recursion depth safe, list flattening for Python

I've been using Python at work a lot recently (yeah, I know, took me long enough) and finding it to be fantastically useful for all sorts of things.

Anyway, I found myself needing a mechanism for flattening nested container objects and a quick google search led me to a Right Foot In article on various flatten algorithms. Seeing as I needed something to work on containers that aren't tuples or lists and I'm not very good at leaving well enough alone, I went about trying to come up with my own method.

Here's what I've got so far:

def flatten_to_list(something):
    if not hasattr(something, '__iter__'):
        return [something]
    retlist = list(something)
    i = 0
    while i < len(retlist):
        while hasattr(retlist[i], '__iter__'):
            if not retlist[i]:
                retlist.pop(i)
                i -= 1
            else:
                retlist.insert(i, retlist[i].pop(0))
        i += 1
    return retlist

In at least one test case, my method appears to be faster than the best method in the Right Foot In article. I'm still wrestling with namespace issues relating to the use of timeit but I'll try to get some actual speed numbers and test cases up later.

UPDATE: I am an idiot. My code was faster because my test case exploited a degenerate case for the algorithm; the code below, which is much closer to the original at Right Foot In, is faster.

def flatten_to_list(something):
    if not hasattr(something, '__iter__'):
        return [something]
    retlist = list(something)
    i = 0
    while i < len(retlist):
        while hasattr(retlist[i], '__iter__'):
            if not retlist[i]:
                retlist.pop(i)
                i -= 1
            else:
                retlist[i:i + 1] = retlist[i]
        i += 1
    return retlist

Someone missed my connection

Here's a first for me: someone posted a "missed connection" about me on Craigslist. One of my roommates randomly found it.

Bloodhound - w4m - 23 (SOMA / south beach)

I met you Saturday night at Bloodhound. We pet the awesome Saint Bernard and talked about mobile media. You're pretty cool, and I'm sorry we didn't get to talk more. Thanks for making my Saturday night :)

Recollections on a Vegas Christmas

It's been a bit over a month since my brother and I drove to Vegas to spend Christmas weekend (plus a few days) with the rest of our family (who flew out). I was being lazy but it seems that I'm getting called out so here are my major recollections.

The water : The water in Vegas tastes terrible and is no good for rinsing. I don't think that I've dealt with worse tap water in the US before. I was quite happy to have refilled and brought my 5 gallon, road-trip, water jug before leaving San Francisco.

The drinking : In Vegas, there is booze everywhere and you can drink it anywhere on The Strip. Being able to wander from place to place while carrying drinks is quite convenient; I really enjoy partaking of public activities while carrying a drink or, to put it better, it's nice to have drinks without having to be cooped up in a bar. Then, of course, on top of the ability to wander with booze is how very easy it is to get an awful lot of the stuff: free drinks while gambling, drink specials all over the place, cheap convenience stores just across the street.

The hangover : Vegas leads to an almost perpetual state of hangover. I wasn't drinking enough to get a particularly bad hangover but between the drinking, the terrible water, and staying up late, I was definitely a below 100% most of the trip. P.S. Worth it.

The poker : I should never play poker with people that aren't my friends and I should never play poker where anyone expects me to drop more than $20-$40. I lost about $100 in under an hour (maybe half that) the first night we arrived. Fuck everything about Vegas poker.

The craps : Let me tell you about Christmas Day (parts of it at least). Christmas stuff happened; Dave and I hung out with the rest of the family; and we all went out for dinner at Pampas Churrascaria, which was phenomenally good. After dinner, we all wandered The Strip for a bit, lost a little money on a few things and then Dave and I split off from the rest of our family to continue adventuring on our own.

I had been in contact with my friend Gautham, who happened to concurrently be in Vegas, and we made plans to meet up later to play craps. While Dave and I were waiting for Gautham to be ready to hang out, we had a few more drinks, checked out the Vegas architecture (Luxor is awesome; Aria is gorgeous; MGM is strangely green), and generally wandered around. At some point, we grabbed ourselves a couple of Four Lokos (so terrible but so awesome) from a convenience store and, shortly thereafter, managed to properly get a hold of Gautham.

We met up with Gautham at the Aria and promptly decided that $25 was too high a minimum for craps. Keep in mind that I had never played craps before in my life. So we wandered over to the Bellagio to avail ourselves of their $10 minimum tables. Understanding the basic principle of craps (roll some dice, sevens are good opening rolls but bad otherwise) I mostly took my guidance from Gautham at first and started availing myself of free scotch & sodas. As I became slightly more inebriated and started to get the hang of the game, things became increasingly more entertaining. We had a pretty good table with some pretty fun folks around but, most importantly, we had a really good winning streak. At peak, I was probably up about $300-$400 and when we eventually cashed out, I was up about $200 and a handful of drinks.

The net : Between my poker losses, slot machine losses (shiny things are hard to resist), drink purchases, food purchases, roulette winnings, roulette losses, and craps winnings, I ended up leaving Vegas slightly (<$50) richer than when I arrived.

The guns : On our last full day in Vegas, Dave, Joe, our dad, and I went out to shoot some guns. At first we went to The Gun Store, which is advertised all over the place, but the line was atrocious (well over an hour, possibly two) so I fired up Yelp and found out about Las Vegas Gun Range & Firearm Center. We bailed on The Gun Store and found that the line at Las Vegas Fun Range & Firearm Center was a few minutes long.

I fired off a few clips from a 9mm pistol (don't recall the make or model) and a couple clips from an H&K MP5. Man oh man, let me tell you, the MP5 is a nice gun. Firing the MP5 fully automatic was kind of neat but being zombie survival minded, I rather preferred switching it to semi-automatic and going for accuracy.

The company : Vegas was awesome. Hanging out with Dave was awesome. Hanging out with Gautham was awesome. Having dinners with my family was nice. Going to the Valley of Fire with my family was neat. Hanging out with my family on the strip was not particularly awesome.

I'm pretty sure that, going forward, I am going to view Vegas as a place to go with friends but not family. I would say, if you're going to Vegas with family, plan to do some stuff with them and plan to ditch them the rest of the time.

Return : I'm probably going back with a bunch of Fort Awesome folks in April and I'm really looking forward to the trip.

I did NOT coin the term wiki-hole

Before making any claims to having coined a term, it is generally a good idea to check that no one else has used the term before. Having just spent three hours and change reading through articles on the Warhammer 40K Wiki (what can I say, I like super far future science fiction), I couldn't help but feel like I'd been stuck in a black hole of trivial knowledge. This wiki-triggered and wiki-fed hole in time was not a unique experience for me; I have fallen into these before on other wikis in the past.

Having freed myself, the term "wiki hole" came to mind as a perfect term to describe. Not wanting to make any (easily refutable) ridiculous claims, I performed a couple quick google searches (1 2) only to find that the term already exists. I can't say that I'm particularly surprised that someone else has already coined the term "wiki-hole"--it is phenomenally intuitive--but I am glad that my linguistic instincts were reasonable.

Will O' The Wisp

Continuing my earlier work in the realm of mixology, I would like to present my second cocktail invention. The invention of this cocktail is the result of playing around with gin, Chartreuse, St. Germain, and various other liqueurs in an attempt to make something tasty. This cocktail earns its name, Will O' The Wisp, from its faint, ghostly, green color.

Ingredients

  • 3/4 oz Green Chartreuse
  • 3/4 oz St. Germain
  • 3/4 oz White Vermouth
  • 1 dash Lavender Bitters
  • 3 oz Dry Gin
  • 1/4 oz Herbsaint or Absinth

Recipe

  1. Pour the Chartreuse, St. Germain, Vermouth, Bitters, and Gin into a cocktail shaker
  2. Pour the Herbsaint/Absinth into a chilled cocktail glass
  3. Swirl the cocktail glass, coating the sides, and pouring off any excess Herbsaint/Absinth
  4. Add ice to the cocktail shaker and shake
  5. Pour shaken cocktail into the prepared glass

Notes

The Herbsaint/Absinth can be skipped, though I don't recommend it. The Lavender Bitters are also optional but very highly recommended. I would recommend stirring this cocktail (instead of shaking) as the resulting beverage has a very different appearance.

SanFran to Vegas on one tank: or exactly why I love my car

My brother and I drove from San Francisco to Las Vegas yesterday where we met up with the rest of our immediate family for the whole Christmas thing. I don't really have an awful lot to say about the whole Christmas thing that I haven't said a great many times before and, although I could probably find things to say about Las Vegas, there is very little to say that capture the sheer je ne sais quoi of this place.

Really, to be entirely honest, this post exists solely so that I can gloat about the fact that I managed to drive from San Francisco to Las Vegas on less than one tank of fuel; I really do love my Volkswagen TDi.

The potato button is the apex of human technology

The potato button is the single greatest thing that mankind has ever achieved. Dwarfing sliced bread, slightly surpassing the Saturn V, and even edging out the Internet, the potato button expresses our unparalleled superiority over not just every other creature on this planet but over the primordial forces of nature themselves.

The potato button, for those that have not beheld its unmatched glory, is a button on our microwave that cooks potatoes. To experience the potato button's awesome power, one merely inserts one (or more) potato(es) into the microwave and pushes the potato button, just the potato button; one need not set a timer, choose a power level, or even, for that matter, push the start button. Some number of minutes after pushing the potato button, any raw potatoes one has inserted will emerge as baked potatoes (or a fantastically good facsimile thereof).

The glory of the potato button comes from the combined technological force that is microwaves, heat sensors, microcontrollers capable of handling feedback systems, and the modern cultivated potato. The potato button is a technological tour de force that turns a relatively straightforward food preparation task into a task that is so utterly trivial as to require nigh on no conscious thought whatsoever.

Now, it may be the case that I am being a little tongue-in-cheek by suggesting that the potato button is more significant than the moon landing but I do firmly believe that the potato button is an absolutely quintessential example of why technology exists. Technology exists to make the trivialize the tasks that we must otherwise perform so as to allow us to perform grander tasks. Technology, in general, is much like software, in specific, because it allows us to take tasks, abstract them, and build larger tasks from those abstracted components.

The sheer simplicity of cooking a potato with the push of a single button is a gigantic step toward removing time and thought from preparing food. I am not suggesting that we should abandon cooking altogether; cooking is fun and rewarding as a task and group experience. Imagine, however, a world where you never have to think about food preparation, except as a hobby. In Star Trek, most food is replicated as needed; imagine how much time and productivity is gained by the removal of the time needed to prepare food. Sure restaurants, cafeterias, or mess halls can serve much the same purpose of removing the need for food preparation but those do not let you eat at home; delivery services allow one to eat from home without taking time to prepare food but from an infrastructure standpoint do not scale well. The more that we can use technology to trivialize the tasks of our lives, the more time we have to push beyond our currently confines and step up the technological ladder toward the future.

Seriously though, potatoes are great and being able to completely cook a potato by pushing one button is amazing.

Ironhide

Some number of weeks ago, having discovered Maraschino liqueur, I concocted a variation on my beloved Manhattan. I have been meaning to write up the recipe here for a while but had been stuck on coming up with a name; I needed a name befitting a strong whiskey cocktail with connections to myself and the color red. Having thought for quite a while and come up with a bunch of names that were already taken by other cocktails, I settled on naming the drink after the grizzled, old Autobot, Ironhide. So, without further ado:

Ironhide recipe

  • 3 oz Bourbon whiskey
  • 3/4 oz Maraschino
  • 1/4 oz grenadine
  • 2 dashes Angostura bitters
  • 1 Maraschino cherry

Serve shaken or stirred with ice in a cocktail glass; garnish with the Maraschino cherry.

Notes

I have mostly been drinking these on the rocks, which is an acceptable but inferior variation. Being a Manhattan-like cocktail, up-high is really the correct way to serve an Ironhide.

Corn syrup based grenadine or "maraschino" cherries will ruin the flavors imparted by the bitters and Maraschino; you will make a better cocktail by skipping the grenadine and cherry than using cheap, fake ones.