Tuesday, November 30, 2004

Python code for the Loaded Dice Problem

Here's my code for the Loaded Dice problem, posted earlier. No, it doesn't exactly conform to the problem specification for input and output. Then again, I'm very lazy. This code was just to test whether my algorithm was correct.


def generate_table(list1, list2):
list3=[]
if len(list2)>len(list1):
templist=list1
list1=list2
list2=templist

padlist=[]
for i in range(len(list2)-1):
padlist.append(0)

list1.reverse()
list1.extend(padlist)
list1.reverse()
list1.extend(padlist)

list2.reverse()

for i in range(len(list1)-len(list2)+1):
sum=0
for j in range(len(list2)):
sum=sum+(list1[i+j]*list2[j])
list3.append(sum)

return list3


def test1():
list1=[1,1,1,1,1,1]
list2=[1,1,1,1,1,1]
list3=[1,4,1,1,1,1]
list4=[1,1,1,1,4,1]
list5=[1,1,20,1]
list6=[1,1,50,1,1,50,1,1,1,1,50,1]
list7=[1,1,1,1,1,1,1,200,1,1,1,1,1,1,1,200,200,200,1,1]

inputlist=[list1,list2,list3,list4,list5,list6,list7]

final_table=generate_table(inputlist[0],inputlist[1])

for i in range(2,len(inputlist)):
final_table=generate_table(final_table,inputlist[i])

return final_table