Cellular Automaton-Python for Programmer : UC Berkeley SelfPace Course

好久没上CSDN了噢,今天觉得无论如何得学一下python了,捣鼓了一晚,好弱啊~~ 在这贴个代码,以备忘。

----------------------------------
题外话:这学期要设计基于FPGA的CPU,我组设计很大程度参考MIPS架构,发现UCB 61C的CPU设计部分的课件(注:itunes U是有视频的,不过看视频比较耗时。。)还是很给力的哈哈。进一步发掘资料,发现还有很多好资源哈哈。其中SelfPace Course就是非常好的资源,建议CSDN的朋友们多看看。这学期还有在做编译器实现(系里采用的是stanford 的cool 语言方案 CS143)和B/S的数据库应用系统的专题实验,有在做相关东西的同学大家多交流。
---------------------------------

UCB Selfpace course: python for  
                             Project 1: Cellular Automaton

author: JRH @XJTU
2012-3-25

s= ''
times= 50
ruleNumber= 30

def  D2Binary8bit(i):
   def  Denary2Binary(n):
    bStr= ''
     if n== 0: return  '0'
     while n> 0:
      bStr= str(n% 2)+bStr
      n=n>> 1
     return bStr

   def  plusZero(s):
     while  8len(s)> 0:
      s= '0'+s 
     return s
  s=Denary2Binary(i)
  strTemp=plusZero(s)
   #print i
   return strTemp

ruleBinary=D2Binary8bit(ruleNumber)
#print "ruleBinary is"
#print ruleBinary

def  rule(bit1,bit2,bit3):
   if bit1== 1  and bit2== 1  and bit3== 1: return ruleBinary[ 0]
   if bit1== 1  and bit2== 1  and bit3== 0: return ruleBinary[ 1]
   if bit1== 1  and bit2== 0  and bit3== 1: return ruleBinary[ 2]
   if bit1== 1  and bit2== 0  and bit3== 0: return ruleBinary[ 3]
   if bit1== 0  and bit2== 1  and bit3== 1: return ruleBinary[ 4]
   if bit1== 0  and bit2== 1  and bit3== 0: return ruleBinary[ 5]
   if bit1== 0  and bit2== 0  and bit3== 1: return ruleBinary[ 6]
   if bit1== 0  and bit2== 0  and bit3== 0: return ruleBinary[ 7]

def  update():
  temp= ''
  temp=temp+ '1'
   global times
   global s
  each= 2
   while each<times* 2+ 1:
    temp = temp+ str(rule( int(s[each- 2]), int(s[each- 1]), int(s[each])))
    each+= 1
  temp=temp+ '1'
  s=temp
   return temp



def  ini() : 
  t= 0
   global s
   while t< times* 2+ 1:
     if t==times:
      s+= '1'
      t+= 1
     else:
      s+= '0'
      t+= 1
   print s


def  main():
   print  "P1", times* 2 + 1,times+ 1
  ini()
  index= 0
   while index < times:
     print update()
    index+= 1

if __name__== '__main__':main()


-----------------------------------

对times和ruleNumber变量进行修改,可以得到不同规则(ruleNumber)下不同迭代次数(times)的结果:

如将times=3 , ruleNumber=30,本程序输出为:

 P1 7 4
 0001000
 1011101
 1010001
 1011011

程序输出为这样的格式,只要利用linux 的 > 到bpm文件(Portable Bitmap),即可制作一副由该Cellular Automaton 产生的图像了。下面简要介绍一下bpm:

 Portable Bitmap Format   例如,一个7*3 的bpm图像


第一行内容:  P1  宽  长

P1 7 3
0001000
0011100
0110010

---

下面将程序的输出重定向到 rule30.bpm文件中:

$ python project1.py > rule30.pbm

成功后即可用一般的图像查看软件查看该图像了。 还可有修改times和ruleNumber,产生更多图案。更多Cellular Automaton 内容,请参考http://atlas.wolfram.com/TOC/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值