Monday, 22 December 2008

Python Madness

My Night at 3 AM: Hacking Python code to learn the language. That's a life! Here's what I've done so far:

1. Decimal to dual conversion:

import sys

def bd(x):
n = []
if x < 0:
return "Positive integer required"
elif x == 0:
return [0]
else:
while x > 0:
n.insert(0,x%2)
x = x/2
bd(x)
return n

if __name__ == "__main__":
try:
number = int(raw_input("Number: "))
print bd(number)
except ValueError:
sys.stderr.write("Integer required\n")


2. Basic truthtables:

def logicalAnd():
for valueOne in range(2):
for valueTwo in range(2):
print "%d %d %d"%(valueOne, valueTwo, valueOne and valueTwo)

def logicalOr():
for valueOne in range(2):
for valueTwo in range(2):
print "%d %d %d"%(valueOne, valueTwo, valueOne or valueTwo)

def logicalConditional():
for valueOne in range(2):
for valueTwo in range(2):
print "%d %d %d"%(valueOne, valueTwo, not valueOne or valueTwo)

def logicalBiconditional():
for valueOne in range(2):
for valueTwo in range(2):
print "%d %d %d"%(valueOne, valueTwo, valueOne is valueTwo)

if __name__ == "__main__":
op = raw_input("Connective: ")
if op == "and":
logicalAnd()
elif op == "or":
logicalOr()
elif op == "conditional":
logicalConditional()
elif op == "biconditional":
logicalBiconditional()
else:
print "Connective not known"


3. ASCII table. First column is the ASCII value, second column is the local interpretation, third column is the raw UTF-8 interpretation, fourth column is the hexadecimal value:

for element in xrange(256):
print "%s \t %s \t %s \t %s"%(element,%%
chr(element), str(tuple(chr(element)))%%
.strip("()'',"), chr(element).encode("hex"))


4. Perhaps a complicated dual to decimal program:

def reverseRange(input):
n = []
for i in range(len(input)-1,-1,-1):
n.append(i)
return n

def singleValues(input):
m = []
for i in input:
m.append(i)
return m

if __name__ == "__main__":
input = raw_input("Number: ")
rR = reverseRange(input)
sV = singleValues(input)
dN = 0
for i in range(len(sV)):
dN += int(sV[i])*2**int(rR[i])
print dN


This code works in 2.6.1

No comments: