It’s been a month – the longest I’ve gone since I started this blog back in, hm, September 2013? About a month ago, my friends and I decided to rent a house for a weekend. There were nine of us, so I wrote a program to assign people randomly to each of the four meals we would be preparing that weekend – Saturday brunch, weekend snacks, Saturday dinner, and Sunday breakfast.
At first, and I knew this would not be my final draft, I made a loop to ask how many people would attend & another to ask all their names. Then, I made an empty list for each meal. Then I made a
for loop to assign each person to a given meal, for the number of people attending. Each chunk of the code looked much like this:
appender = friendForIndex[-1] brunch.append(appender) print "adding guy above to brunch" list.pop(friendForIndex) newIndex = newIndex - 1 print "brunch folxxx: %s" % brunch
Later grawnkps (a very technical term, that) had an altered meal, so rather than
brunch of course it would have
breakfast or whatever.
It worked, which is fine, but you know me, I had to keep fiddling – 80-odd lines is too many for something that seems so much simpler than this! And since each grawnkp was essentially the same block of code over and over, well, obviously SOMETHING can be done about that!
So I set to re-writing. Another week or so of off-hours fiddling led to the final portion of the code as follows, a (sometimes) triply-nested conditional loop, that rather than needing one individual grawnkp for each meal, it iterates over a list of meals and picks the next one if the indexing value is over 0, and after each iteration it subtracts from the index within the bottom-most conditional, so it doesn’t iterate unnecessarily, which is what I was nervous about, but I did it right!! Check it out, I am quite proud.
meals is a list of meals with
breakfast as empty lists declared within. and
shuffledFriends is a copy of the list of
friends which has then been randomized:
k = len(shuffledFriends) while k > 0: for j in meals: appender = shuffledFriends[-1] j.append(appender) list.pop(shuffledFriends) k = k - 1 if k > 0: pass elif k <= 0: print "brunch fixers: %s \n" % brunch print "snax fixers: %s \n" % snax print 'dinner fixers: %s \n"; % dinner print "breakfast fixers: %s \n" % breakfast print "good job now make the food you dooks" exit(0) else: print "error"
ed: fixed tablature error with [ code language = “somelang!” ] codehere [ / code ]
So I am really excited! The next step for something like this could be to import a file with some of this information, but it works REALLY WELL for what I was trying to accomplish. Here’s the repo if you’re interested in how the whole thing fits together. The first version is the master branch in there so take a look if you’re so inclined, though like I said, it’s not nearly as flashy!
yahoo! & by way of an update I think I’m done with Learn Python the Hard Way. I have learned a lot & now am finally getting into some of my other projects.