easy way to remember Python's precedence order.

| | Add comment | Trackbacks (0)

a good way to remember Python's order of operations:

a = lambda: b or c and not d in e is f != g == h < i | j ^ k & l << m + n * o ** p ** -q



the entire line is evaluated right-to-left. 

(** is put in there twice to show that it's right-associative.)

factoring large numbers

| | Add comment | Trackbacks (0)

this program will factor numbers up to 10e19 in almost no-time

requires a file of prime numbers, the file i have is about 530MB.

##by Richard A. Nichols III, 2007
## 
##factor() returns the factorization of a given number.
## 
##primes.txt should be a newline-separated list of all prime numbers to
##an arbitrary limit.  i got my primes from
##http://primes.utm.edu/lists/small/millions/ and converted them to the above
##format.
## 
##it runs pretty fast up until numbers in the order of 10**19
 
import sys
inf = open('primes.txt','r')
primes = [int(inf.readline())]
primesset = set(primes)
 
def factor(number, factors=[], lpi=0):
  global primes, primesset
  if number in primesset:
    return factors+[number] if factors else []
  sqrt = int(number ** .5)
  pi = lpi
  prime = primes[pi]
  while prime <= sqrt:
    if pi==len(primes):
      p = inf.readline()
      if p=='' or p=='\n': raise ValueError("--Cannot factor because the prime numbers list has been exhausted--")
      prime = int(p)
      primes += [prime]
      primesset.add(prime)
    else:
      prime = primes[pi]
    if number % prime == 0:
      return factor(number/prime, factors+[prime], pi)
    pi += 1
  return factors+[number] if factors else [] 
 
 
if __name__ == "__main__":
 
 
  if len(sys.argv)==2:
    try: factors = factor(int(sys.argv[1]))
    except ValueError, e: print e
    else: print '['+', '.join(str(f) for f in factors)+']' if factors else "prime"
  else:
    for x in range(18):
      number = int('1'*(x+1))
      print
      print number
      try: factors = factor(number)
      except ValueError, e: print e
      else: print '['+', '.join(str(f) for f in factors)+']' if factors else "prime"
 
 

ex:

D:\projects\py>factor.py 0923840284985
[5, 59, 107, 1193, 24533]

running factor.py with no parameter will execute a demonstration 

 

absrel

| | Add comment | Trackbacks (0)

i made this for a guy named eep for his philosophy of "absolute relativity".  it uses Pygame.

import sys, pygame, math, random
 
size = width, height =  512, 512
minradius = 2
maxspeed = 1
minspeed = -1
#depthspeeds = [1,1,1,1,1,1,1,1,1,1]
 
#edit any of those numbers you wish.
#speeds may be negative or positive. negative is counterclockwise.
#you must have at least log height/minradius base 2 numbers in depthspeeds.
#comment out the depthspeeds line to randomize.
#maxspeed and minspeed are only used if depthspeeds are randomized.
 
depths = int(math.log(height/minradius, 2))
random.seed()
if "depthspeeds" not in globals():
  depthspeeds = [random.uniform(minspeed, maxspeed) for x in xrange(depths)]
black = 0, 0, 0
 
class circle:
  def __init__(self, angle, depth, distance):
    self.radius = height/2**depth/2
    self.depth = depth
    self.angle = angle
    self.distance = distance
    self.angleinc = math.atan2(depthspeeds[depth],distance)
    if self.depth < depths-1:
      self.child1 = circle(math.pi/2, depth+1, height/2**depth/4)
      self.child2 = circle(math.pi*1.5, depth+1, height/2**depth/4)
 
  def docircle(self, pivotx, pivoty):
    posx = pivotx+self.distance*math.cos(self.angle)
    posy = pivoty+self.distance*math.sin(self.angle)
    pygame.draw.circle(screen, (255,255,255), (posx, posy), self.radius, 1)
    self.angle += self.angleinc
    if self.depth < depths-1:
      self.child1.docircle(posx, posy)
      self.child2.docircle(posx, posy)
 
pygame.init()
screen = pygame.display.set_mode(size)
 
maincircle = circle(0, 0, 0)
 
while pygame.event.poll().type != pygame.QUIT:
  screen.fill(black)
  maincircle.docircle(width/2, height/2)
  pygame.display.flip()
 
#by Richard A. Nichols III
 
 

 

phonic anagrams

| | Add comment | Trackbacks (0)

shows an anagram of a given word, but works using phonems instead of letters.

requires the cmu phonic dictionary (freely downloadable).  might use an old version;just replacethe version number.

 
import re
word = raw_input("ENTER YOUR WORD: ").upper()
dict = open("cmudict.0.6d","r")
while True:
  line1 = dict.readline().split()   
  if line1 == []: break
  if line1[0]==word:
    dict.seek(0)
    while True:
      line2 = dict.readline().split()
      if line2==[]: break
      if line2[0][:2]=="##": continue
      for phonemes3, phonemes5, p in (([re.sub("\d","",x) for x in line1[1:]], [re.sub("\d", "", x) for x in line2[1:]], 0), (line1[1:][:], line2[1:], 1)):
        for phoneme in phonemes5:
          if phoneme in phonemes3: phonemes3.remove(phoneme)
          else: break
        else:
          print ("\n"+line2[0], "*")[p],
 
 

results with *'s are results that have not only the same phonems, but the same phonems with the same emphasis. 

ex:

ENTER YOUR WORD: littering

'TIL *
ARE(2) *
EARL
EARLE
EARLL
ENGLERT *
ER *
ERL
ERLING
ERR(2)
ERTE
EURE
IL *
ILL *
ING *
INGER *
IT *
IT'LL(2) *
IT(2) *
LING *
LINGER(2) *
LIT *
LITT *
LITTER *
LITTERING *
LUHR
LYNG *
NG(2) *
OR(2) *
TER
TIL *
TILL *
TILLER *
TILLING *
TING *
TO(2) *
UR

 

textshift.py

| | Add comment | Trackbacks (0)

A fun way of ciphering text

import sys
text = ' '.join(sys.argv[1:])
if not text:
  text = raw_input()
nonalphas = [(p, c) for (p, c) in enumerate(text) if not c.isalpha()]
capitals = [p for p, c in enumerate(text) if c.isupper()]
for sh in xrange(-10, 11):
  if sh:
    text3 = [c for c in text.lower() if c.isalpha()]
    text3 = text3[sh:] + text3[:sh]
    for p, c in nonalphas:
      text3.insert(p, c)
    for p in capitals:
      text3[p] = text3[p].upper()
    print ''.join(text3)



enter a sentence, and then select the cipher with the offset that looks best

 ex:

D:\projects\py>textshift.py
This is the day that the Lord hath made.
Rdha th mad eth isis the Dayt hatt helo.
Dhat hm ade thi sist hed Ayth atth elor.
Hath ma det his isth eda Ytha tthe lord.
Athm ad eth isi sthe day That thel ordh.
Thma de thi sis thed ayt Hatt helo rdha.
Hmad et his ist heda yth Atth elor dhat.
Made th isi sth eday tha Tthe lord hath.
Adet hi sis the dayt hat Thel ordh athm.
Deth is ist hed ayth att Helo rdha thma.
Ethi si sth eda ytha tth Elor dhat hmad.
Hisi st hed ayt hatt hel Ordh athm adet.
Isis th eda yth atth elo Rdha thma deth.
Sist he day tha tthe lor Dhat hmad ethi.
Isth ed ayt hat thel ord Hath made this.
Sthe da yth att helo rdh Athm adet hisi.
Thed ay tha tth elor dha Thma deth isis.
Heda yt hat the lord hat Hmad ethi sist.
Eday th att hel ordh ath Made this isth.
Dayt ha tth elo rdha thm Adet hisi sthe.
Ayth at the lor dhat hma Deth isis thed.

 

timer

| | Add comment | Trackbacks (0)

#timer.py
 
 
import pygame, time, sys
p = map(int, ''.join(sys.argv[1:]).split(':'))
s = p.pop()
if p: s += p.pop()*60
if p: s += p.pop()*3600
time.sleep(s)
pygame.mixer.init(11025)
pygame.mixer.Sound('d:\\utils\\ringin.wav').play(1)
time.sleep(10)
 

and a batch file that goes..

@echo off
@echo current time is %TIME%
start d:\python26\pythonw \utils\timer.py %*

example:

D:\>timer 4:00
current time is  5:41:52.74
D:\>timer 4
current time is  5:41:56.07
D:\>timer 4:10:00
current time is  5:42:05.34

calculator

| | Add comment | Trackbacks (0)

from __future__ import division
import sys
from math import *
print eval(' '.join(sys.argv[1:]))

and then i have a batch file that goes:

@echo off
if "%1"=="" goto calc
d:\python26\python d:\utils\calc.py %*
goto end
:calc
calc.exe
:end

ex:

C:\>calc 12*sin(1)
10.0976518177

C:\>

 

truth tables

| | Add comment | Trackbacks (0)

names = "false nor xleft nleft xright nright xor nand and nxor right nxright left nxleft or true".split()
lookup = dict(map(reversed, enumerate(names)))
prompt = "<logic gate> <operator> <logic gate>: "
 
print
while 1:
  try:
    tables = table1, table2, table3 = raw_input(prompt).lower().split()
    rtable1, rtable2, rtable3 = map(lookup.get, tables)
  except:
    raise SystemExit
  r = sum((x*(bool(rtable2 & (1<<(3-((bool(rtable1 & x) * 2) + bool(rtable3 & x)))))) for x in [1, 2, 4, 8]))
  print '%s %s %s == %s' % (table1.capitalize(), table2, table3.capitalize(), names[r].capitalize())
 

just an experiment i wanted to try where you can do a logical operation on two truth tables and get a truth table back.  

there are 16 truth tables and 16 operations, giving 4096 possible inputs and 16 possible outputs.

ex:

<logic gate> <operator> <logic gate>: and xor or
And xor Or == Xor

i also have a whole separate module just for helping to custom-make a set of names to use for the 16 truth tables by passing parameters, but it's not finished yet.

 

one-liner permutator

| | Add comment | Trackbacks (0)

perms = lambda a: a[1:] and [c+r for i, c in enumerate(a) for r in perms(a[:i]+a[i+1:])] or a
 
 

ex:
>>> perms = lambda a: a[1:] and [c+r for i, c in enumerate(a) for r in perms(a[:i]+a[i+1:])] or a
>>> perms("hello")
['hello', 'helol', 'hello', 'helol', 'heoll', 'heoll', 'hlelo', 'hleol', 'hlleo', 'hlloe', 'hloel', 'hlole', 'hlelo', 'hleol', 'hlleo', 'hlloe', 'hloel', 'hlole', 'hoell', 'hoell', 'holel', 'holle', 'holel', 'holle', 'ehllo', 'ehlol', 'ehllo', 'ehlol', 'eholl', 'eholl', 'elhlo', 'elhol', 'ellho', 'elloh', 'elohl', 'elolh', 'elhlo', 'elhol', 'ellho', 'elloh', 'elohl', 'elolh', 'eohll', 'eohll', 'eolhl', 'eollh', 'eolhl', 'eollh', 'lhelo', 'lheol', 'lhleo', 'lhloe', 'lhoel', 'lhole', 'lehlo', 'lehol', 'lelho', 'leloh', 'leohl', 'leolh', 'llheo', 'llhoe', 'lleho', 'lleoh', 'llohe', 'lloeh', 'lohel', 'lohle', 'loehl', 'loelh', 'lolhe', 'loleh', 'lhelo', 'lheol', 'lhleo', 'lhloe', 'lhoel', 'lhole', 'lehlo', 'lehol', 'lelho', 'leloh', 'leohl', 'leolh', 'llheo', 'llhoe', 'lleho', 'lleoh', 'llohe', 'lloeh', 'lohel', 'lohle', 'loehl', 'loelh', 'lolhe', 'loleh', 'ohell', 'ohell', 'ohlel', 'ohlle', 'ohlel', 'ohlle', 'oehll', 'oehll', 'oelhl', 'oellh', 'oelhl', 'oellh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh']

 

conway's game of life using pygame

| | Add comment | Trackbacks (0)

simple conway's game of life simulator, with garbage collector

currently just  puts random spots on the board, then starts simulating
ideally i should have it be able to read Golly files.

i made this so that i could see what happens if you modify cells with the mouse during real-time, instead of pausing it while you're pressing the mouse button as Golly does.  the results were disappointingly uninteresting, although if i made it able to read Golly files and loaded a static pattern it would probably get more interesting. 

another idea i have is to line all four sides with a wall that reflects anything.. is that possible? is there such a wall in GOL?

another enhancement i would want to make is so that you can shrink and expand the viewing window and if you expand it it uncovers cells you previously hadn't seen.

import random, pygame, time
 
bs = bw, bh = 50, 50
cw = 10
fps = 10
 
invfps = 1.0/fps
ss = sw, sh = bw*cw, bh*cw
lcells = set()
dcells = set()
 
pygame.init()
s = pygame.display.set_mode(ss)
 
def lcadd(x, y):
  lcells.add((x, y))
  for x2, y2 in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)):
    if not (x+x2, x+y2) in lcells:
      dcells.add((x+x2, y+y2))
  pygame.draw.rect(s, (255, 255, 255), (x*cw, y*cw, cw, cw))
 
for t in xrange((bw*bh)/2):
  x = random.randint(0, bw)
  y = random.randint(0, bh)
  lcadd(x, y)  
 
while pygame.event.poll().type != pygame.QUIT:
  then = time.time()
    
  if pygame.mouse.get_pressed()[0]:
    px, py = pygame.mouse.get_pos()
    cx, cy = px/cw, py/cw
    if (cx, cy) in lcells:
      dcells.add((cx, cy))
      lcells.remove((cx, cy))
    else:
      lcadd(cx, cy)
      dcells.discard((cx, cy))
      
  pygame.display.flip()
  for (x, y) in tuple(lcells):
    n = sum(((x+x2, y+y2) in lcells for (x2, y2) in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))))
    if n not in (2, 3):
      lcells.remove((x, y))
      dcells.add((x, y))
      pygame.draw.rect(s, (0, 0, 0), (x*cw, y*cw, cw, cw))
 
  for (x, y) in tuple(dcells):
    n = sum(((x+x2, y+y2) in lcells for (x2, y2) in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))))
    if n == 3:
      lcadd(x, y)
      dcells.remove((x, y))
      lcells.add((x, y))
 
  # garbage collector
  dct = ()
  ldct = len(dct)
  i = 0
  while time.time()-then < invfps and i < ldct:  
    (x, y) = dct[i]
    if not any(((x+x2, y+y2) in lcells for (x2, y2) in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)))):
      dcells.remove((x+x2, y+y2))
    i += 1
  time.sleep(invfps-time.time()+then)
 

The animation is jerky for some reason and I don't know why]

@staticclass

| | Add comment | Trackbacks (0)

decorator to make all objects in a class static methods.

i haven't tested this

it probably won't work on python 2.6. for some reason 2.6 doesn't seem to like .im_func
i should probably just use staticmethod() anyway instead of using im_func.

def staticclass(cls): #to be used as a decorator
  for attr in dir(cls):
    obj = getattr(cls, attr)
    if iscallable(obj) and not attr.startswith("__"):
      setattr(cls, attr, obj.im_func)
  return cls

singleton decorator

| | Add comment | Trackbacks (0)

a way to make singleton classes, by simply using a "singleton" function as a decorator.

it only works with new-style classes (ones that inherit "object")

i might be able to make one that works on old-style classes by making it a metaclass instead of a function, but i'm not sure it's worth it. 

instead of silently returning the same object if you instantiate the class more than once, it returns an error. this is because I believe that if you're intending to make a singleton and you instantiate it more than once, you're probably doing something wrong and you should probably find out.

def singleton(cls):
  def spewerr(*args, **kwargs):
    raise ValueError("Can't make duplicate instance of singleton %s" % cls.__name__)
  def newnew(*args, **kwargs):
    cls.__new__ = staticmethod(spewerr)
    return object.__new__(*args, **kwargs)
  cls.__new__ = staticmethod(newnew)
  return cls

i could have used the more conventional form of using a set of classes that have already been instantiated, but i like this better because it's a) clever, and b) self-contained.

note that using @singleton doesn't give you an instance.  you have to make your own instance.

should i make it so that you can delete a singleton's single object and then instantiate a new one?

should i make @singleton return an instance?

 

 

non-integer xrange

| | Add comment | Trackbacks (0)

they always complain that you can't do xrange with non-integers because there would be some sort of ambiguity in where it stops due to rounding errors.
i don't agree.  here's one that works perfectly, by me:

from __future__ import division
ox = xrange
def xrange(s, e, i):
  n = (e-s)/i
  for y in ox(n+1):
    r = s+(e-s)/n*y
    if r > e:
      break
    if r==int(r): 
      r=int(r)
    yield r

 

 

 

the easy way to import

| | Add comment | Trackbacks (0)

class x:
  def __getattr__(self, name):
    return __import__(name)
x = x()
 
 

ex:

>>> from funcs import *
>>> x.math.sin(1)
0.8414709848078965

so if you use a lot of individual functions from a lot of different libraries you don't have to bother to import each one

 

window function

| | Add comment | Trackbacks (0)

window function

def window(seq, wsize, inc=1):  for x in xrange(0, len(seq)-wsize+1, inc):    yield seq[x:x+wsize]

ex:
window(range(100), 5, 5)   would return [0,1,2,3,4], [5,6,7,8,9], etc.

window(range(100), 5) would return [0,1,2,3,4], [1,2,3,4,5], etc.

window(range(100), 5, 7) would return [0,1,2,3,4], [7,8,9,10,11], etc.

 

 

1 2  Next»