CODING

As I mentioned on my main page, I've been getting into coding. Here's some stuff I'm particularly happy with. Feel free to use any of these in your own project, but I'd appreciate it if you left a comment in there linking back here. I'd also love to hear about the project you plan on using it in, my askbox is always open! ;3c


FIBONACCI GENERATOR Python

This cute li'l piece of code prints the Fibonacci sequence, one number at a time. I'm fairly proud of how small I got this thing. The number of iterations can be changed by modifying the range of the for loop.

x,y = 0,1
for i in range(10):
print(x)
x,y = y,x+y

REN'PY PRONOUN ENGINE Ren'Py

Something I wrote to let a player input their pronouns in Ren'py; default options are he/him, she/her, and they/them, but the main draw of the system is that players can input custom pronouns as well. Supports up to 5 different sets of pronouns, and includes an example of how to use it in dialogue options.

To use: Call or jump to label pronounselect, but make sure to set bookmark to a string containing the label you want it to return to after running.

label start:
$ prns = []
$ bookmark = "wherever you plan to go next"
call pronounselect

label pronounselect: ## this is the label you have to call if you wanna initialize the process of setting pronouns

python:
prnstring = ""
if len(prns) == 0:
prnstring = "None"
else:
prnstring = ""
for i in prns:
prnstring += i[0] + "/" + i[1] + ", "
prnstring = prnstring[:-2]
nvl clear

menu:
"Current pronouns: [prnstring]"

"He/him" if len(prns) < 5:
$ prns.append(["he","him","his","his","himself"])
call pronounselect

"She/her" if len(prns) < 5:
$ prns.append(["she","her","her","hers","herself"])
call pronounselect

"They/them" if len(prns) < 5:
$ prns.append(["they","them","their","theirs","themself"])
call pronounselect

"Custom pronouns" if len(prns) < 5:
call .pronouncustomise

"Remove pronouns" if len(prns) > 0:
call .pronounremove

"Done" if len(prns) > 0:
python:
renpy.jump(bookmark)

label .pronounremove:
if len(prns) == 0:
"No pronouns to remove!"
call pronounselect
python:
for i in range(0,5):
if i < len(prns):
globals()["prns"+str(i+1)] = prns[i][0] + "/" + prns[i][1]
else:
globals()["prns"+str(i+1)] = ""

menu:
"Remove [prns1]" if len(prns) >=1:
python:
del prns[0]
"Remove [prns2]" if len(prns) >=2:
python:
del prns[1]
"Remove [prns3]" if len(prns) >=3:
python:
del prns[2]
"Remove [prns4]" if len(prns) >=4:
python:
del prns[3]
"Remove [prns5]" if len(prns) >=5:
python:
del prns[4]
"Done":
call pronounselect
python:
del prns1 ## can i get a hurray for neatly pruned variables
del prns2
del prns3
del prns4
del prns5
call .pronounremove

label .pronouncustomise:

python: ## this is the part where the player enters a custom set of pronouns, with clarification in brackets
temp = []
temp.append(renpy.input("Subjective: (who picked up the box? ... did)", length=11)) ## length is 11 cause i figure the longest pronoun anyone will need is 'theirselves'
temp.append(renpy.input("Objective: (who picked up the box? it was ...)", length=11)) ## feel free to change the length if you think otherwise tho
temp.append(renpy.input("Dep. possessive: (whose box is that? it's ... box)", length=11))
temp.append(renpy.input("Indep. possessive: (whose box is that? it's ...)", length=11))
temp.append(renpy.input("Reflexive: (ends in -self)", length=11))
prns.append(temp)

return

####### EXTRA INFO #######
##
## -Pronouns can be called by simply doing prns[set][0-4], depending on which pronoun set and which grammatical role you want/need
## -You can add the suffix ".capitalize()" to make the first letter uppercase if you want to use the pronoun to start a sentence
## -You can also use a random function to vary the pronoun set used, just try to keep it locally consistent to avoid confusion
##
## Example of how to use pronouns?:
## setused = 0
## print("\"Whose kitchen does " + prns[setused][0] + " do " + prns[setused][3] + " dishes in?\" \"" + prns[setused][4].capitalize() + ", obviously.\"")

## This line is here to make it easier to copy :33c

COLLATZ + REVERSE COLLATZ CONJECTURE Python

Two functions I wrote to run through the Collatz conjecture, both ways; Collatz() takes a single int as an argument, then if it's even it divides it by two, if it's odd it multiplies by three and adds one, and continues until it's reached 1, and then returns all the steps it took to get there in a list. reverseCollatz() also takes a single int, but this time it calculates every number which is that many steps away from one.

(also, this would probably make for quite a fun code golf challenge! if you want to, you can try to write a function which outputs the same result, but using fewer character; the par for Collatz() is 129 and that of reverseCollatz is 136, both including the def line but excluding spaces)

def Collatz(startn):
n = startn
list = []
while n != 1:
list.append(n)
if n%2==0:
n = n // 2
else:
n = 3*n + 1
list.append(n)
return list

def reverseCollatz(c):
a, b = [1], []
for i in range(0,c):
for n in a:
b.append(2*n)
if n%6==4 and n != 4:
b.append((n-1)//3)
a, b = b, []
return(a)

print(Collatz(329))
## Returns all steps needed to get to 1 using the Collatz conjecture
print(reverseCollatz(25))
## Returns all numbers which take 25 steps to reach 1 using the Collatz conjecture

ROMAN NUMERAL CONVERTER Python

Slightly hard to interpret 'cause it's the result of a round of code golf, but it works a charm, and I decided to put it here because I figured it might come in handy in the future.

def rM(n,i,p):
s=n//p
l=["","0","00","000","01","1","10","100","1000","02"]
return "".join([i[int(x)] for x in l[s]])

def rN(n):
s,t=n,""
while s>1000:
s -= 1000
t += "M"
t += rM(s,"CDM",100)
s %= 100
t +=rM(s,"XLC",10)
s %= 10
t += rM(s,"IVX",1)
return(t)

And, of course, the encoder wouldn't be quite complete without a matching decoder, similarly fresh from a round of code golf.

def dM(i,p):
global s
n=''
for x in s:
if x in i:
n+=str(i.index(x))
else:
break
s=s[len(n):]
l=["","0","00","000","01","1","10","100","1000","02"]
return(p*l.index(n))

def dN(n):
global s
t,s=0,n
while s[0]=="M":
t+=1000
s=s[1:]
t+=dM("CDM",100)
t+=dM("XLC",10)
t+=dM("IVX",1)
return(t)

RANDOM CARD GENERATOR Python

A couple functions to generate a random card, several random cards, or a coin flip. You can prevent duplicate cards by feeding it a list of the cards you've already drawn; the drawCards() function also keeps track of drawn cards internally by default.

Notes:
- Due to a nigh-unsolvable issue with the duplicate card handler, any card that appears several times in the deck (i.e. most Uno cards) becomes slightly more likely to be drawn if it's been drawn before.
- Current available decks are: French, Tarot, TarotNA (=no major arcana), and Uno

import random

def coinflip(opt1=True,opt2=False):
if random.randint(0,1) == 1:
return(opt1)
else:
return(opt2)

def randCard(deck,jokers=False,inverse=False,extrachecklist=[],decks=1,j1name="Red Joker",j2name="Black Joker"):
if type(jokers) != bool:
print("Error: jokers argument must be a boolean")
if type(inverse) != bool:
print("Error: inverse argument must be a boolean")
if type(extrachecklist) != list:
print("Error: extrachecklist argument must be a list")
deckSize = 0
suits = []
ordinals = []
extracards = []
outptform = "$1 of $2"
if deck == "French":
suits = ["Clubs","Hearts","Spades","Diamonds"]
ordinals = ["Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"]
elif deck == "Tarot" or deck == "TarotNA":
suits = ["Swords","Cups","Wands","Pentacles"]
ordinals = ["Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"]
if deck == "Tarot":
extracards = ["0: The Fool","I: The Magician","II: The High Priestess","III: The Empress","IV: The Emperor","V: The Hierophant","VI: The Lovers","VII: The Chariot","VIII: Justice","IX: The Hermit","X: Wheel of Fortune","XI: Strength","XII: The Hanged Man","XIII: Death","XIV: Temperance","XV: The Devil","XVI: The Tower","XVII: The Star","XVIII: The Moon","XIX: The Sun","XX: Judgement","XXI: The World"]
elif deck == "Uno":
suits = ["Red","Yellow","Green","Blue"]
ordinals = ["0","1","1","2","2","3","3","4","4","5","5","6","6","7","7","8","8","9","9","Skip","Skip","Reverse","Reverse","Draw Two","Draw Two"]
extracards = ["Wild","Wild","Wild","Wild","Draw Four","Draw Four","Draw Four","Draw Four"]
outptform = "$2 $1"
else:
print("Error: Invalid deck!")
print("Valid decks are: French, Tarot, TarotNA, Uno")
if jokers:
extracards.append(j1name)
extracards.append(j2name)
decksize = len(suits) * len(ordinals) + len(extracards) -1
drawn = ""
drawattempts = 0
while drawn == "":
cardn = random.randint(0, decksize)
if cardn + len(extracards) <= decksize:
suit = suits[cardn // len(ordinals)]
card = ordinals[cardn % len(ordinals)]
drawn = outptform.replace("$1",card).replace("$2",suit)
else:
drawn = extracards[cardn-decksize]
card = drawn
if len(extrachecklist) == decksize + 1:
print("All cards occupied!")
return
if extrachecklist != [] and sum([1 for p in extrachecklist if drawn in p]) >= (decks*sum([1 for p in (ordinals+extracards) if p == card])):
drawn = ""
pass
else:
break
if inverse and coinflip():
drawn += " (Inverted)"
return(drawn)

def randCards(deck,num,unique=True,decks=1,jokers=False,inverse=False,extrachecklist=[]):
templist,drawn = [],""
while len(templist) < num:
if unique:
templist.append(randCard(deck,jokers,inverse,extrachecklist+templist,decks))
else:
templist.append(randCard(deck,jokers,inverse))
return templist

QUINE Python

After watching a particularly interesting talk by Dylan Beattie on YouTube, I managed to more than halve the length of my quine, getting it to precisely 100 characters. (There's supposed to be a single empty line at the end to truly work, but the html doesn't seem to want to show it.)

o,q=r"""o,q=r$,'\u0022'*3
print(o.replace('$',q+o+q,1))""",'\u0022'*3
print(o.replace('$',q+o+q,1))

HUFFMANN ENCODER/DECODER Python

Compresses a string using a Huffmann tree; Huffmann() returns a tuple containing an encoded string and a dict, deHuffmann() decodes the string using the dict it's given, and hTreeVis() can be used to visualise your Huffmann tree if you want to try doing it by hand. I might try and add a function that checks for repeated character sequences later.

import math
def hG(sblst,prog):
o,i,p=sblst[0],sblst[1],prog
if type(o)==str:
huffmannDict[o]=prog+"0"
elif type(o)==list:
hG(o,prog+"0")
if type(i)==str:
huffmannDict[i]=prog+"1"
elif type(i)==list:
hG(i,prog+"1")

def Huffmann(txt):
global huffmannDict
s,y,l,huffmannDict="","",[],{}
for i in txt:
if i not in y:
y += i
for i in y:
l.append([i,txt.count(i)])
while len(l)>1:
l=sorted(l,key=lambda x: x[1],reverse=True)
i,ii=l[-2],l[-1]
t=[[i[0],ii[0]],i[1]+ii[1]]
del l[-2],l[-1]
l.append(t)
del i, ii, t
l=l[0][0]
hG(l,"")
for i in txt:
s += huffmannDict[i]
return((s,huffmannDict))

def deHuffmann(txt,dic):
s,t="",txt
lr = {dic[i]:i for i in dic}
while len(t)<0:
ln = 1
while t[:ln] not in lr:
ln += 1
s += lr[t[:ln]]
t = t[ln:]
return(s)

def hTreeVis(dic):
l = sorted([[i,dic[i]] for i in dic],key=lambda x: len(x[1]))
m = len(l[-1][1])
for i in range(0,m+1):
n,o = [x for x in l if len(x[1])==i],[]
for j in range(0,2**i):
k = bin(j)[2:].zfill(i)
if k in [x[1] for x in n]:
o.append(n[[x[1] for x in n].index(k)])
elif [x for x in l if x[1].startswith(k)] == []:
o.append(" ")
else:
o.append("*")
print(" "*(2**(m-i)-1)+"".join([x[0]+" "*(2**(m-i+1)-1) for x in o]))

BASS TAB GENERATOR Python

This program can turn a simple piano roll (formatted into a list of notes and spaces) into bass tabs. Notes are formatted as (modifier)+note+octave, modifiers being ^ for sharp and _ for flat.

base={'E2': '40', 'F2': '41', '^F2': '42', '_G2': '42', 'G2': '43', '^G2': '44', '_A2': '44', 'A2': '45', '^A2': '46', '_B2': '46', 'B2': '47', 'C3': '48', '^C3': '49', '_D3': '49', 'D3': '50', '^D3': '51', '_E3': '51', 'E3': '52', 'F3': '53', '^F3': '54', '_G3': '54', 'G3': '55', '^G3': '56', '_A3': '56', 'A3': '57', '^A3': '58', '_B3': '58', 'B3': '59', 'C4': '60', '^C4': '61', '_D4': '61', 'D4': '62', '^D4': '63', '_E4': '63', 'E4': '64', 'F4': '65', '^F4': '66', '_G4': '66', 'G4': '67', '^G4': '68', '_A4': '68', 'A4': '69', '^A4': '70', '_B4': '70'}
proll=[]

last5frets = [0]
l5fa = round(sum(last5frets)/len(last5frets))
si = [["e",40],["a",45],["d",50],["g",55]]

etrc, atrc, dtrc, gtrc = "","","",""
for note in proll:
etrc += "-"
atrc += "-"
dtrc += "-"
gtrc += "-"
if note != " ":
note = int(base[note])
fret,strg = min([(note-x[1],x[0]) for x in si if x[1] <= note],key=lambda x:abs(x[0]-l5fa))
last5frets.append(fret)
if len(last5frets)>5:
last5frets = last5frets[1:]
globals()[strg+'trc'] = globals()[strg+'trc'][:-1] + str(fret)

print("G: "+gtrc)
print("D: "+dtrc)
print("A: "+atrc)
print("E: "+etrc)

SIERPINSKI TRIANGLE GENERATOR Python

Another attempt at a code golf hole; this one generates Sierpinski triangles. You can change the size of the triangle by changing the value of o, but be aware that the size of the generated data increases exponentially.

import math
def t(x):
m,s=x.splitlines(),''
n=math.ceil(len(m[-1])/2)
for i in m:
s+=n*" "+i+n*" "+"\n"
for i in m:
s+=i+" "+i+"\n"
return(s)

a,o="▲",5
for i in range(o):
a= t(a)
print(a)

PUNCHED TAPE/CARD GENERATOR Python

These functions generate punch cards/punched tape that, as far as i'm aware, would genuinely work in old computers if you were to reproduce them physically. The tape is encoded in 7-bit ASCII, with a row of sprocket holes (represented by interpuncts) between the 3rd and 4th bits, and a parity bit in the 8th position; the card is encoded using DEC 029.

def pTape(j,ln=80):
m=[]
while len(j)>0:
m.append(j[0:ln])
j=j[ln:]
for msg in m:
bin=[format(i, '08b') for i in bytearray(msg, encoding ='ascii')]
print(len(msg)*"-")
for i in range(1,4):
print("".join([x[7-i] for x in bin]).replace("1","●").replace("0"," "))
print(len(msg)*"·")
for i in range(4,8):
print("".join([x[7-i] for x in bin]).replace("1","●").replace("0"," "))
print("".join([str(x.count("1")%2) for x in bin]).replace("1","●").replace("0"," "))
print(len(msg)*"-")

def pCard(msg):
d={' ': '', '&': '&', '-': '-', '0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', 'A': '&1', 'B': '&2', 'C': '&3', 'D': '&4', 'E': '&5', 'F': '&6', 'G': '&7', 'H': '&8', 'I': '&9', 'J': '-1', 'K': '-2', 'L': '-3', 'M': '-4', 'N': '-5', 'O': '-6', 'P': '-7', 'Q': '-8', 'R': '-9', '/': '01', 'S': '02', 'T': '03', 'U': '04', 'V': '05', 'W': '06', 'X': '07', 'Y': '08', 'Z': '09', ':': '28', '#': '38', '@': '48', "'": '58', '=': '68', '"': '78', '[': '&28', '.': '&38', '<': '&48', '(': '&58', '+': '&68', '^': '&78', '!': '-28', '$': '-38', '*': '-48', ')': '-58', ';': '-68', '\\': '-78', ']': '028', ',': '038', '%': '048', '_': '058', '>': '068', '?': '078'}
m=[]
while len(msg)>0:
m.append(msg[0:80].ljust(80," ").upper())
msg=msg[81:]
print(84*"-")
for j in m:
for i in ["&","-","0","1","2","3","4","5","6","7","8","9"]:
n = (i if i.isdigit() else " ")
print("| "+"".join([u"\u25A0" if i in d[x] else n for x in j])+" |")
print(84*"-")

PRIME FACTORIZER Python

Breaks a number down into its prime factors, and returns them in a tidy list.

def pF(n):
l=[]
for i in range(2,int(n**.5)+1):
if n%i==0:
l.append(i)
l+=pF(n//i)
break
if len(l)==0:
return [n]
return l

ARRAY RANDOMIZER JavaScript

All the other functions I found for this online were way too verbose, so I decided to make something decidedly simpler. This function should randomise any array you feed it pretty well.

Across old bark
The quiet shade
It's always dark
In the ancient glade

function shuffle(list){
for (let i = 0; i < 3*list.length; i++) {
list.splice(Math.floor(Math.random() * list.length), 0, list.shift());
}
return list;
}

LANTERNFISH LIFESIM Python

This code was made to solve a code advent day, and probably won't be useful for much else, but hot damn, if I didn't get up off my chair and do a cheesy fist-pump when I finally got a flash of insight.

j="your input here"
l=[j.count(str(n)) for n in range(0,7)]
e=[0,0,0]
for i in range(0,256):
e[2]+=l[0]
l+=[l.pop(0)]
l[6]+=e.pop(0)
e+=[0]
print(sum(e+l))

SEA CUCUMBER SIMULATOR Python

And so, this year's code advent comes to an end. It's been a lot of fun. Here's my solution to the last day of 2021. Merry Christmas!

inpt = """(your input here)"""
count = 0
inpt = [[j for j in i] for i in inpt.split("\n")]
print("Frame",count)
for i in inpt:
print("".join(i))
print()
moved = [""]
while len(moved)>0:
moved = []
simMove = []
y = 0
while y<len(inpt):
x=0
while x<len(inpt[y]):
if inpt[y][x]==">" and inpt[y][(x+1)%len(inpt[y])]=="." and [x,y] not in moved and [(x+1)%len(inpt[y]),y] not in simMove:
inpt[y][x]="."
inpt[y][(x+1)%len(inpt[y])]=">"
moved += [[x,y],[(x+1)%len(inpt[y]),y]]
simMove += [[x,y]]
x+=1
y+=1
y = 0
simMove = []
while y<len(inpt):
x=0
while x<len(inpt[y]):
if inpt[y][x]=="v" and inpt[(y+1)%len(inpt)][x]=="." and [x,y] not in moved and [x,(y+1)%len(inpt)] not in simMove:
inpt[y][x]="."
inpt[(y+1)%len(inpt)][x]="v"
moved += [[x,(y+1)%len(inpt)]]
simMove += [[x,y]]
x+=1
y+=1
count += 1
print("Frame",count)
for i in inpt:
print("".join(i))
print()

INTCODE PARSER Python

More AOC stuff! This is a parser for the Intcode language used in a bunch of 2019 AOC days. I'm planning on making a variant of the language sometime, but for now this is a pretty cool language too.

## Initialization
code = #code as string here
inputs = #input as string here
code = eval("["+code+"]")
code += [0]*(1500-len(code))
inputs = eval("["+inputs+"]")
opcodes = {}
pointer = 0
relbase = 0
running = True
class parser:
def __init__(self,code,length):
self.code = code
self.length = length
def run(self,args):
line = self.code
argTypeGet = args[0]//100
for i in range(1,self.length+1):
if argTypeGet%10==0:
line = line.replace("$"+str(i),"code["+str(args[i])+"]")
elif argTypeGet%10==1:
line = line.replace("$"+str(i),str(args[i]))
elif argTypeGet%10==2:
if not line.startswith("global relbase"):
line = "global relbase\n"+line
line = line.replace("$"+str(i),"code["+str(args[i])+"+relbase]")
argTypeGet = argTypeGet//10
exec(line)

## Opcode dictionary
opcodes.update({1:parser("$3 = $1 + $2",3)})
opcodes.update({2:parser("$3 = $1 * $2",3)})
opcodes.update({3:parser("$1 = inputs.pop(0)",1)})
opcodes.update({4:parser("print($1)",1)})
opcodes.update({5:parser("global pointer\nif $1!=0:\n pointer = $2-3",2)})
opcodes.update({6:parser("global pointer\nif $1==0:\n pointer = $2-3",2)})
opcodes.update({7:parser("if $1<$2:\n $3 = 1\nelse:\n $3 = 0",3)})
opcodes.update({8:parser("if $1==$2:\n $3 = 1\nelse:\n $3 = 0",3)})
opcodes.update({9:parser("global relbase\nrelbase += $1",1)})
opcodes.update({99:parser("global running\nrunning = False",0)})

## Running the actual program
while running:
i = opcodes[code[pointer]%100]
i.run(code[pointer:pointer+i.length+1])
pointer += i.length+1

LIST FLATTENER Python

I get the feeling I'm going to be coming back to this one a lot, especially for handling recursive functions: this function removes sublists from a list by merging them into the main list, and does so recursively.

def flatten(lst):
result = []
for item in lst:
if type(item) == list:
result += flatten(item)
else:
result.append(item)
return result

NUMBER SPIRAL GENERATOR Python

This nigh-unreadably compact (code golf, yadda yadda) program creates a number spiral, which I felt could be done best by writing a function to find the value of a position with a given X and Y. Miraculously, after only some minor tweaks, it turned out that I'd generalized my work enough for it to work on other sizes! Just plug any number into the "size" value and it'll spit out a grid of that size.
Warning: function only works on integer numbers. Trying to use the function on a float will void warranty, catch your computer on fire, and/or throw a TypeError. Probably just the latter.

import math
size = 0

def spiralize(x,y):
d=2*min(min(x+1,size-1-x),min(y,size-y))
a=2*size-1-d
if x<y:
x,y,d,a=size-1-x,size-2-y,d-1,a+1+1/(d-1)
return x+y+int(d*a)

[print(" ".join([str(spiralize(x,y)).rjust(math.ceil(math.log(size**2,10))," ") for x in range(size)])) for y in range(size)]
## Obligatory comment to make that list comprehension monstrosity copyable.

TEXT COMPRESSOR Python

These functions can be used to compress text down to a smaller size. It's not terribly resource-efficient in working, but it can crunch stuff down pretty small.

class compString:
def __init__(self,val,key,eff,skInd,skVal):
self.val = val
self.key = key
self.eff = eff
self.skInd = skInd
self.skVal = skVal

def compress(inpt):
orglen = len(inpt)
repls = {}
for i in range(100):
i=chr(i+33)
if i in inpt:
repls.update({i:i})
continue
syll = set()
for length in range(2,10):
for index in range(len(inpt)-length):
syll.add(inpt[index:index+length])
syll = {snippet:(len(snippet)*inpt.count(snippet)-len(snippet)-3) for snippet in syll if inpt.count(snippet)>1}
if len(syll)>0:
syll = max([i for i in syll],key=lambda x: syll[x])
inpt = inpt.replace(syll,i)
repls.update({i:syll})
else:
break
skInd = "".join([i for i in repls])
skVal ="|".join([repls[i] for i in repls])
eff = (len(inpt)+len(skInd)+len(skVal))/orglen
replset = {i:repls[i] for i in repls if i!=repls[i]}
return compString(inpt,replset,eff,skInd,skVal)

def decompress(val,key):
for i in list(key)[::-1]:
val = val.replace(i,key[i])
return val

TRINARY INTEGER WEIGHT Python

Had a good afternoon of fun figuring this puzzle out; the way I was first posed it was to find a proof that any integer weight could be weighed exactly with a set of weights consisting of exactly one weight of mass 3^n for every whole number n. I'm not sure if I did it quite right, but the function weight() should output a valid equation for any integer you put in. You get the stern() (Signed TERNary) function as well, 'cause the weight function needs it to work.

def stern(n):
res = ""
NIALO = True
while n>0 or NIALO:
d = n%3
if d==2:
d="T"
n+=3
res = str(d) + res
n=n//3
NIALO = False
return res

def weigh(n):
ts = list(stern(n))[::-1]
ls,rs = [str(3**i) for i in range(len(ts)) if ts[i]=="1"],[str(n)]+[str(3**i) for i in range(len(ts)) if ts[i]=="T"]
return (" + ".join(ls) or "0")+" = "+" + ".join(rs)

MINECRAFT SKIN UPDATER Python

This program takes a pre-1.8 skin and makes a copy that you can use in 1.8 and onwards. It uses some more advanced libraries though.

import PIL, os
suffix = "-big"
imgname = "[name of file]"
path = "[path]"

def roll_half(im):
xsize, ysize = im.size
delta = xsize//2
part1 = im.crop((0, 0, delta, ysize))
part2 = im.crop((delta, 0, xsize, ysize))
im.paste(part1, (xsize - delta, 0, xsize, ysize))
im.paste(part2, (0, 0, xsize - delta, ysize))
return im

def vflip(im):
xsize, ysize = im.size
res = PIL.Image.new("RGBA", im.size)
for row in range(xsize):
res.paste(im.crop((row,0,row+1,ysize)),(xsize-(row+1),0,xsize-row,ysize))
return res

if path.endswith("/"):
path = path[:-1]
os.chdir(path)
img = PIL.Image.open(path+"/"+imgname)
img = img.crop((0,0,64,64))

newname = imgname.split(".")
newname[0]+=suffix
newname = ".".join(newname)

img.paste(roll_half(img.crop((0,20,16,32))),(16,52,32,64))
img.paste(roll_half(img.crop((40,20,56,32))),(32,52,48,64))
img.paste(vflip(img.crop((4,16,8,20))),(20,48,24,52))
img.paste(vflip(img.crop((8,16,12,20))),(24,48,28,52))
img.paste(vflip(img.crop((44,16,48,20))),(36,48,40,52))
img.paste(vflip(img.crop((48,16,52,20))),(40,48,44,52))

img.save(newname)

NUMBERS GAME SOLVER Python

As seen on Countdown (but sadly lacking a witty acronym); plug in a board of numbers and the goal and this program will try to find a way to get to that number, using any number on the board at most once and only using multiplication, addition, subtraction, and division. Shows the ten best solutions; methods for solutions 2-10 are shown using reverse polish notation.

import re

board = [100,25,1,6,8,10]
goal = 925
nums = [[board[i],str(board[i]),2**i] for i in range(len(board))]

def iterate():
global nums
newnums = []
for x in range(len(nums)-1):
for y in range(x+1,len(nums)):
if (nums[x][2]&nums[y][2])==0:
newnums += [[nums[x][0]+nums[y][0],nums[x][1]+" "+nums[y][1]+" +",nums[x][2]+nums[y][2]]]
newnums += [[nums[x][0]*nums[y][0],nums[x][1]+" "+nums[y][1]+" *",nums[x][2]+nums[y][2]]]
nx,ny = sorted([x,y],key = lambda x: nums[x][0])
if nums[nx][0]==nums[ny][0]:
newnums += [[1,(nums[nx][1]+" ")*2+"/",nums[nx][2]+nums[ny][2]]]
else:
newnums += [[nums[ny][0]-nums[nx][0],nums[ny][1]+" "+nums[nx][1]+" -",nums[nx][2]+nums[ny][2]]]
if nums[ny][0]%nums[nx][0]==0:
newnums += [[nums[ny][0]//nums[nx][0],nums[ny][1]+" "+nums[nx][1]+" /",nums[nx][2]+nums[ny][2]]]
nums += newnums

iterate()
iterate()
iterate()
nums = sorted(nums,key = lambda x: abs(goal-x[0]))

best = nums[0]
print("Best solution:")
print(best[0],"("+str(abs(goal-best[0]))+" away)")
best = best[1]
while not best.isdigit():
m=re.finditer(r"\d+ \d+ \D",best)
for x in m:
o=x.group().split()
res = str(int(eval(o[0]+o[2]+o[1])))
print(o[0],o[2],o[1],"=",res)
best=best.replace(x.group(),res)

print("Other solutions:")
for i in nums[1:10]:
print(str(i[0])+":","("+str(abs(goal-i[0]))+" away)",i[1])