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**19importsys
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': raiseValueError("--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 += 1return factors+[number]if factors else[]if__name__ == "__main__":
iflen(sys.argv)==2:
try: factors = factor(int(sys.argv[1]))exceptValueError, e: print e
else: print '['+', '.join(str(f)for f in factors)+']' if factors else"prime"else:
for x inrange(18):
number = int('1'*(x+1))printprint number
try: factors = factor(number)exceptValueError, e: print e
else: print '['+', '.join(str(f)for f in factors)+']' if factors else"prime"
i made this for a guy named eep for his philosophy of "absolute relativity". it uses Pygame.
importsys, 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"notinglobals():
depthspeeds = [random.uniform(minspeed, maxspeed)for x inxrange(depths)]
black = 0, 0, 0class circle:
def__init__(self, angle, depth, distance):
self.radius = height/2**depth/2self.depth = depth
self.angle = angle
self.distance = distance
self.angleinc = math.atan2(depthspeeds[depth],distance)ifself.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.angleincifself.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
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 == []: breakif line1[0]==word:
dict.seek(0)while True:
line2 = dict.readline().split()if line2==[]: breakif line2[0][:2]=="##": continuefor 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: breakelse:
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
importsys
text = ' '.join(sys.argv[1:])ifnot text:
text = raw_input()
nonalphas = [(p, c)for(p, c)in enumerate(text)ifnot c.isalpha()]
capitals = [p for p, c in enumerate(text)if c.isupper()]for sh inxrange(-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.pyimport pygame, time, sys
p = map(int, ''.join(sys.argv[1:]).split(':'))
s = p.pop()if p: s += p.pop()*60if 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
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.
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.
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 decoratorfor attr indir(cls):
obj = getattr(cls, attr)if iscallable(obj)andnot attr.startswith("__"):
setattr(cls, attr, obj.im_func)return cls
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.
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?
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 = xrangedefxrange(s, e, i):
n = (e-s)/i
for y in ox(n+1):
r = s+(e-s)/n*y
if r > e:
breakif r==int(r):
r=int(r)
yield r