H. Chase Stevens Logo

Most Common Tags

  1. programming
  2. python
  3. code
  4. philosophy
  5. evolution
  6. game design
  7. probability
  8. video games
  9. genetic algorithms
  10. government



Posts with tag "code":

Plotting Simple Functions in 3 Lines with Python

posted on: Tuesday, March 6, 2012 (11:13 am) by Chase Stevens

You can hardly even tell that I took a course on functional programming last semester.

import turtle
eq = "(x ** 2) / 1.5"
map((lambda x: turtle.setx(x[0]) or turtle.sety(x[1])),[(n,(eval(eq.replace("x","(" + str(n) + ")")))) for n in range(0,100)])

Tags: code, lambda, math, programming, python

Fermat's Primality Test

posted on: Sunday, January 22, 2012 (4:03 pm) by Chase Stevens

Recently, I was reading about some sample interview questions used (at some point) by Google. One such question was "what are the first 10 consecutive digits of e that form a prime number?" Curious, I went to Wikipedia and looked up some primality tests that I could run on 10-digit prime candidates (if you'll forgive the pun) from e. One such test was Fermat's Primality Test, which can be used to probabilistically assess a number's primality (it fails on Carmichael numbers, et alia). I've written up a short python script which runs the test on the numbers 1 to 100 using computed probable primes as possible coprimes and returns all probable primes.


def test(end):
    candidates = range(1,end+1)
    primes = list()
    for candidate in candidates:
        prime = True
        for prime in primes:
            if candidate % prime:
                test_result = ((prime ** (candidate - 1)) % candidate)
                print "Candidate: %s, Prime: %s, Result:%s" %(candidate,prime,test_result)
                if test_result != 1:
                    prime = False
        if prime:
    return primes


Of course, the astute reader will notice that the above program exhaustively checks each candidate for primality for coprimality with all other probable primes, meaning that even simple trial division would be considerably faster. However, a quick modification to the program that only tested against a fixed number of random probable primes would lead to an increase in efficiency.

Tags: code, math, number theory, probability, programming, python

Editing Metadata as a Spreadsheet

posted on: Thursday, December 15, 2011 (10:13 pm) by Chase Stevens

A friend of mine was talking to me recently about how she wished iTunes let her edit song metadata more easily, as if she were editing a spreadsheet in Excel or OpenOffice. Drawing on this as inspiration, I've written a little python script that gets all music files (as specified in the list file_types) from a folder (and all subfolders), exports their metadata to a Comma Separated Value file, and then takes all changes made to that file and applies them to the tracks. As with my xml playlist downloader, you'll need the ID3 library for python installed.


import fnmatch
import os
import Tkinter
import tkFileDialog
import ID3
from tkMessageBox import showinfo

root = Tkinter.Tk()
folder = tkFileDialog.askdirectory(title="Please select a music directory.")

matches = []
file_types = ['mp3','aiff']
for root, dirnames, filenames in os.walk(folder):
    for filename in reduce((lambda x,y: x + y), [fnmatch.filter(filenames, ('*.' + filetype)) for filetype in file_types]):
        matches.append(os.path.join(root, filename))

output = 'Title,Artist,Album,Track,Year,File Location (Do Not Alter)\n'
for song in matches:
    line = ''
    id3info = ID3.ID3(song)
    columns = [id3info.title,id3info.artist,id3info.album,id3info.track,id3info.year,song]
    for column in columns:
        line += '"' + str(column) + '",'
    line = line[:-1] + '\n'
    output += line

filename = tkFileDialog.asksaveasfilename(defaultextension='.csv',filetypes=[('All Files','.*'),('Comma Separated Values File','.csv')])
f = open(filename,'w')

showinfo("File Created","Your CSV file has been created and is ready for you to edit. After you have done so and saved, please click 'OK'.")

f = open(filename,'r')
f.readline() #Removing column titles
for line in f.readlines():
    columns = line.split(',')#0:title,1:artist,2:album,3:track,4:year,5:location
    id3info = ID3.ID3(columns[5])
    id3info['TITLE'] = columns[0]
    id3info['ARTIST'] = columns[1]
    id3info['ALBUM'] = columns[2]
    id3info['TRACKNUMBER'] = columns[3]
    id3info['YEAR'] = columns[4]

showinfo("Success","Song metadata has been successfully updated.")

Tags: code, csv, metadata, mp3, music, programming, python, tagging, tkinter

'Tis the Season for Shoddily Parsing XML

posted on: Monday, December 12, 2011 (6:14 pm) by Chase Stevens

Here's a little something I wrote up to download and tag a bunch of mp3s (of the Christmas song variety) from a jwplayer xml playlist. If you'd like to download from other playlists, simply change xml_url (and perhaps localdir, if you'd like to download your music to somewhere a little more accessible). You'll need to have this ID3 library installed.


import urllib
import urllib2
import os
import ID3
xml_url = "http://pinochan.net/overbooru/xmas/playlist.xml"
localdir = "C:\\Xmas_Music"
webdir = xml_url[::-1][xml_url[::-1].find('/'):][::-1]
    print "Downloading to", localdir
    print "Creating download directory", localdir
    xml_page = urllib2.urlopen(xml_url)
    print "Error opening playlist URL."
print "Parsing XML"
xml = xml_page.read().replace("\t","").replace("\n","")
tracks = xml.split('')[1:]
track_dict = dict()
def get_elem(xml,tag):
    start_tag = "<" + tag + ">"
    end_tag = ""
    return xml[(xml.find(start_tag)+len(start_tag)):xml.find(end_tag)]
down_count = 0
for track in tracks:
    track_id = get_elem(track,"location")
    track_dict[track_id] = dict()
    print "%s:" %track_id
    track_dict[track_id]['Artist'] = get_elem(track,"creator").replace("'","'").replace("&","&")
    print "\t Artist: %s" %track_dict[track_id]['Artist']
    track_dict[track_id]['Title'] = get_elem(track,"title").replace("'","'").replace("&","&")
    print "\t Title: %s" %track_dict[track_id]['Title']
    track_dict[track_id]['URL'] = webdir + track_id
    if not track_id in os.listdir(os.getcwd()):
        print "\t File not found in directory, downloading now."
            print "\t Download complete, editing metadata."
            down_count += 1
            print "\t Could not download %s, moving on to next file." % track_dict[track_id]['URL']
            id3info = ID3.ID3(track_id)
            id3info['TITLE'] = track_dict[track_id]['Title']
            id3info['ARTIST'] = track_dict[track_id]['Artist']
            print "\t Done editing metadata: %s" %id3info
            print "\t There was an error editing metadata."
        print "\t File already in directory."
print "Downloaded %s files." %down_count
print "%s files in %s." %(len(os.listdir(os.getcwd())),os.getcwd())
print "Press Enter to exit."

Tags: code, jwplayer, metadata, mp3, music, programming, python, tagging, xmas, xml

Exporting Color Scheme Designer Palettes to Paint.Net

posted on: Saturday, November 19, 2011 (10:59 am) by Chase Stevens

If you're like me and use the excellent tool over at Color Scheme Designer in conjunction with Paint.Net, you may have grown frustrated with creating palettes one color at a time by copy-pasting hex values. No longer! Below, please find a short python application I wrote (which even uses a fancy and unnecessary GUI) to create Paint.Net palettes from Color Scheme Designer palettes. Just export your Color Scheme Designer palette to text, copy what the site gives you, paste it into the application, and click "convert and save". The resulting file is ready to import into Paint.Net at your leisure.

from Tkinter import *
from tkFileDialog import asksaveasfilename as save
from tkMessageBox import showinfo as disp

def convert():
    intext = str(text.dump(1.0, END))
    intext = intext.split(' = ')
    colorlist = list()
    for ss in intext:
        if ss[0] == '#':
    filename = save(defaultextension='txt',initialdir='\%HOMEPATH\%\\My Documents\\Paint.NET User Files\\Palettes')
    palette = open(filename, 'w')
    for color in colorlist:
        palette.write('FF%s\n' %color)
    disp('File Saved', 'File successfully saved as %s.' %filename)
root = Tk()
menubar = Menu(root)
menubar.add_command(label="Convert and Save", command=convert)
menubar.add_command(label="Quit", command=quit)
scroll = Scrollbar(root)
scroll.pack(side=RIGHT, fill=Y)
text = Text(root, wrap=WORD, yscrollcommand=scroll.set)

Tags: code, color, design, internet, programming, python, tkinter, web, web design