Python论坛  - 讨论区

标题:回复 :Re[10]: [python-chinese] 趣味问题――号码分配――修订代码

2004年04月27日 星期二 16:02

liux at gdcn.com liux at gdcn.com
Tue Apr 27 16:02:57 HKT 2004

An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20040427/f12f20cd/attachment.html
-------------- next part --------------
# -*- coding: gbk -*-
# file codeBall.py
#/*********************************
# \class codeBall
# \brief 	[python-chinese] ȤζÎÊÌ⡪¡ªºÅÂë·ÖÅäÊÔ½â
# \version 1.0  04427	liux at gdcn.com ԭʼÌá³ö£¬ÏÖÔÚÒÔ×·½Ê½½â¾ö
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string
import outputLog,PnC

class playCodeBall:
    def __init__(self):
        self.log=""
    def __repr__(self):# Àà×ÔÊö¶¨Òå
        print("Zoom.Quiet ×·½Ê½½øÐÐÕýÈ·½â´ðÊä³ö\n ¿ÉÒÔ×÷ΪÆäËü½âµÄÑéÖ¤")
        return self.log
    def filter(self,seq,order):        
        seqCB = []
        length = len(order)
        tag = 0
        for item in seq:
            for i in range(length):
                #if(i == int(item[i-1])):
                if(i == int(item[i]) - 1):
                    print "bad CodeBall> %s at [%s] = %s"%(item,i,item[i])
                    break
                else:
                    if(i+1 == length):
                        tag = 1                    
            if(1==tag):
                seqCB.append(item)
                #print item
                tag = 0
        return seqCB

if __name__ == '__main__':      # ×Ô²âÊÔ
    tryPnC = PnC.permutation()            # imported by other programs as well
    if(tryPnC):
        #½¨Á¢ÐòÁÐ
        order="123456"
        seq = list(order)
        #Éú³ÉÅÅÁÐ
        p = tryPnC.permute(seq)        
        #Í桪¡ª¹ýÂ˳öÇÐÌâµÄ
        CB = playCodeBall()
        result = CB.filter(p,order)
        #Êä³öÕýÈ·µÄÐòÁе½Îļþ
        exp = outputLog.exporter()
        exp.exportArray(result)
        exp.writeInFile("CodeBall.log")
        print "µ±¹ÞÓÐ %s ¸öʱ,È«²¿ %s ÖÖÅÅÁÐÖÐ,ºÏÌâµÄΪ:%s ÖÖ!"%(len(order),len(p),len(result))
    else:
        print("\"\"")
    
    
-------------- next part --------------
# -*- coding: gbk -*-
# file outputLog.py
#/*********************************
# \class outputLog
# \brief 	½á¹ûÊý¾ÝÊä³öÖ§³Ö
# \version 1.0  04427	Ö§³Ö×Ö´®£¬ºÍÊý×éÊä³ö£¡
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string

class exporter:
    def __init__(self):
        self.log=""
    def __repr__(self):# Àà×ÔÊö¶¨Òå
        return self.log
    def writeInFile(self,fname):
        open(fname,"w").write(self.log)
        print("³É¹¦Êä³öÊý¾Ýµ½Îļþ:%s"%fname)
        
    def exportArray(self,seq):
        for i in seq:
            self.log += i+"\n"
        return self.log
    def exportTxt(self,txt):
        self.log += txt
        return self.log

if __name__ == '__main__':      # ×Ô²âÊÔ
    exp = exporter()            # imported by other programs as well
    if(exp):
        import PnC
        tryPnC = PnC.permutation()
        seq = list("1234")
        p = tryPnC.permute(seq)
        exp.exportArray(p)
        exp.writeInFile("exp.log")
        
        #open("PnC.log","w").write(PnC.export)
    else:
        print("\"\"")
    
    
-------------- next part --------------
# -*- coding: gbk -*-
# file PnC.py
#/*********************************
# \class PnC
# \brief 	permutation and combination ÅÅÁÐ×éºÏ Êä³ö
# \version 1.0  04427	ʹÓÃ"Ò»ÇдÓÓÎÏ·¿ªÊ¼ - ChinesePython Wiki"µÄ¼¼ÇÉ
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string
import outputLog

class permutation:
    def __init__(self):
        self.log=""
        self.export=""
    def __repr__(self):# Àà×ÔÊö¶¨Òå
        return self.log
    def permute_O_n(self,seq, index):
        seqc = seq[:]
        seqn = [seqc.pop()]
        divider = 2
        while seqc:
            index, new_index = divmod(index,divider)
            seqn.insert(new_index, seqc.pop())
            divider += 1
        return ''.join(seqn)
    def permute(self,seq):
        seqn = [seq.pop()]
        while seq:
            newseq = []
            new = seq.pop()
            #print "seq:",seq,'seqn', seqn ,'new', new
            for i in range(len(seqn)):
                item = seqn[i]
                for j in range(len(item)+1):
                    newseq.append(''.join([item[:j],new,item[j:]]))
            seqn = newseq
            #print 'newseq',newseq
        return  seqn

if __name__ == '__main__':      # ×Ô²âÊÔ
    tryPnC = permutation()            # imported by other programs as well
    if(tryPnC):
        seq = list("1234")
        #for i in range(30):
            #print tryPnC.permute_O_n(seq, i)
        p = tryPnC.permute(seq)
        #print len(p)
        #for i in p:
        #    print i
        #open("PnC.log","w").write(PnC.export)
        exp = outputLog.exporter()
        exp.exportArray(p)
        exp.writeInFile("PnC.log")        
    else:
        print("\"\"")
    
    
-------------- next part --------------
_______________________________________________
python-chinese list
python-chinese at lists.python.cn
http://python.cn/mailman/listinfo/python-chinese

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2004年04月27日 星期二 16:15

Who Bruce whoonline at msn.com
Tue Apr 27 16:15:26 HKT 2004

把我的程序也贴上来给大家参考,顺便演示一下yield的用法(记得前一段时间有人问
过),:-)
用这个程序算10个球得出来的结果是1334961:

比较简短,就不放附件里了。

def f(l,start=1):
    if len(l)==0:yield ""
    else:
        tmp=""
        for x in l:
            if x == start:continue
            for y in f(filter(lambda z:z!=x,l),start+1):
                yield str(x)+y

def main():
    ans=[]
    for x in f(range(1,5),1):
        print x
        ans.append(x)
    print 'total:',len(ans)

main()



>From: liux at gdcn.com
>Reply-To: python-chinese at lists.python.cn
>To: "Zoom.Quiet" <zoomq at infopro.cn>, python-chinese at lists.python.cn
>Subject: 回复:Re[10]: [python-chinese]趣味问题――号码分配――修订代码
>Date: Tue, 27 Apr 2004 16:02:57 +0800
>
><< codeBall.py >>
><< outputLog.py >>
><< PnC.py >>
>_______________________________________________
>python-chinese list
>python-chinese at lists.python.cn
>http://python.cn/mailman/listinfo/python-chinese
>_______________________________________________
>python-chinese list
>python-chinese at lists.python.cn
>http://python.cn/mailman/listinfo/python-chinese

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20040427/78fe6ae8/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2004年04月27日 星期二 17:59

Zoom.Quiet zoomq at infopro.cn
Tue Apr 27 17:59:41 HKT 2004

Hollo Who:

  嗯嗯…………"""
返回一个迭代器,称为生成器迭代器,或者更常用的,生成器。通过重复地调用生成器的next()方法来运行生成器的函数体,直到抛出一个异常...
"""
yield 是用以将普通函式,声明为 构造函式的?!
为什么不用class.... 学习中!
非常精美哪!

随手使用文件输出修改了一下子,
并加入计时,进行效率比较:

]python codeBall.py

 run at: 2004-04-27 17:43:02
 end at: 2004-04-27 17:43:03
 本次运行共用时 0.547000169754秒
成功输出数据到文件:CodeBall.log
当罐有 8 个时,全部 40320 种排列中,合题的为:14833 种!

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

]python CBfilter.py

 run at: 2004-04-27 17:42:44
 end at: 2004-04-27 17:42:50
 本次运行共用时 6.25秒
成功输出数据到文件:CBfilte.log

不会吧!在下最笨的方法居然会快捷一些?
大家评评理,不可能的吧!

在下的测试环境:
Python 2.3.3 (CJK) (#51, Feb 13 2004, 21:18:21) [MSC v.1200 32 bit (Intel)] on win32

--------[ AIDA32 (c) 1995-2002 Unlimited Possibilities ]--------
    Version                                           AIDA32 v2.00
    Author                                            fiery at freemail.hu
    Homepage                                          http://hardware.jatekok.hu/aida32/
    Report Type                                       Quick Report
    Computer                                          ZQSTUDIO (ZqStudio)
    Generator                                         Administrator
    Operating System                                  Microsoft Windows Server 2003 Server (Enterprise Edition) 5.2.3790 (.NET Beta)
--------[ CPU ]------------
    CPU Properties:
      CPU Type                                          Intel Pentium 4A, 2525 MHz (6.25 x 404)
      CPU Alias                                         Northwood, A80532
      L1 Trace Cache                                    12K Instructions
      L1 Data Cache                                     8 KB
      L2 Cache                                          0
--------[ Memory ]-------

    Physical Memory:
      Total                                             255 MB
      Used                                              200 MB
      Free                                              54 MB
      Utilization                                       79 %

嗯嗯!在Linux 中再试一试:
++++++++++++++++++++++++++++++++++++++++++++++++
Python 2.3.3 (#1, Feb 12 2004, 22:21:49)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2

PII 266 128Mb; RedHat 8.0 
++++++++++++++++++++++++++++++++++++++++++++++++
[Zoomq at redhat8 zCodeBall]$ python codeBall.py

 run at: 2004-04-27 18:03:10
 end at: 2004-04-27 18:03:17
 本次运行共用时 6.66619110107秒
成功输出数据到文件:CodeBall.log
当罐有 8 个时,全部 40320 种排列中,合题的为:14833 种!

[Zoomq at redhat8 zCodeBall]$ python CBfilter.py

 run at: 2004-04-27 18:03:55
 end at: 2004-04-27 18:04:25
 本次运行共用时 30.2400951385秒
成功输出数据到文件:CBfilte.log

没有天理哪!
难道Python 喜欢笨伯?

在下只是组织了一下子,最直接的排除法,
先生成所有排列,然后过滤去不吻合的是也乎是也乎…………

/******** [2004-04-27]16:40:42 ; you wrote:

Who Bruce> 把我的程序也贴上来给大家参考,顺便演示一下yield的用法(记得前一段时间有人问
Who Bruce> 过),:-)
Who Bruce> 用这个程序算10个球得出来的结果是1334961:

Who Bruce> 比较简短,就不放附件里了。

Who Bruce> def f(l,start=1):
Who Bruce>     if len(l)==0:yield ""
Who Bruce>     else:
Who Bruce>         tmp=""
Who Bruce>         for x in l:
Who Bruce>             if x == start:continue
Who Bruce>             for y in f(filter(lambda z:z!=x,l),start+1):
Who Bruce>                 yield str(x)+y

Who Bruce> def main():
Who Bruce>     ans=[]
Who Bruce>     for x in f(range(1,5),1):
Who Bruce>         print x
Who Bruce>         ans.append(x)
Who Bruce>     print 'total:',len(ans)

Who Bruce> main()



>>From: liux at gdcn.com
>>Reply-To: python-chinese at lists.python.cn
>>To: "Zoom.Quiet" <zoomq at infopro.cn>, python-chinese at lists.python.cn
>>Subject: 回复:Re[10]: [python-chinese]趣味问题――号码分配――修订代码
>>Date: Tue, 27 Apr 2004 16:02:57 +0800
>>
>><< codeBall.py >>
>><< outputLog.py >>
>><< PnC.py >>
>>_______________________________________________
>>python-chinese list
>>python-chinese at lists.python.cn
>>http://python.cn/mailman/listinfo/python-chinese
>>_______________________________________________
>>python-chinese list
>>python-chinese at lists.python.cn
>>http://python.cn/mailman/listinfo/python-chinese



********************************************/

-- 
Free as in Freedom

 Zoom.Quiet                           

#=========================================#
]Time is unimportant, only life important![
#=========================================#

sender is the Bat!2.02 CE
-------------- next part --------------
# -*- coding: gbk -*-
# file CBfilter.py
#/*********************************
# \class CBfilter
# \brief 	[python-chinese] 趣味问题――号码分配试解
# \version 1.0  04427	Who Bruce 原始提出;Zoomq Class 化
# \author Who Bruce
# \attention 	Released under GNU Lesser GPL library license
#*********************************/
import sys, os,string
import outputLog

class CBfilter:
    def __init__(self):
        self.log=""
    def __repr__(self):# 类自述定义
        print("Who Bruce 的精巧方式 解答输出")
        return self.log
    
    def f(self,l,start=1):
        if len(l)==0:yield ""
        else:
            #tmp=""
            for x in l:
                if x == start:continue
                for y in self.f(filter(lambda z:z!=x,l),start+1):
                    yield str(x)+y
    
    def play(self,order):
        ans=[]
        seq = range(1,order+1)
        for x in self.f(seq,1):
            self.log += x+"\n"
            #print x
            ans.append(x)
        #print 'total:',len(ans)
        self.log += '\ntotal:%s'%len(ans)
        return self.log

if __name__ == '__main__':      # 自测试
    playCB = CBfilter()         
    if(playCB):
        #玩――直接处理出结果!
        import timer
        watch= timer.timer()
        watch.start()
        result = playCB.play(8)
        print(watch.stop())
        #输出正确的序列到文件
        exp = outputLog.exporter()
        exp.exportTxt(result)
        exp.writeInFile("CBfilte.log")
        #print "当罐有 %s 个时,全部 %s 种排列中,合题的为:%s 种!"%(len(order),len(p),len(result))
    else:
        print("\"\"")
    
-------------- next part --------------
# -*- coding: gbk -*-
# file codeBall.py
#/*********************************
# \class codeBall
# \brief 	[python-chinese] 趣味问题――号码分配试解
# \version 2.0  04427	16:22 liux at gdcn.com fixed
# \version 1.0  04427	liux at gdcn.com 原始提出,现在以最笨方式解决
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string
import outputLog,PnC

class playCodeBall:
    def __init__(self):
        self.log=""
    def __repr__(self):# 类自述定义
        print("Zoom.Quiet 最笨方式进行正确解答输出\n 可以作为其它解的验证")
        return self.log
    def filter(self,seq,order):        
        seqCB = []
        length = len(order)
        tag = 0
        for item in seq:            
            for i in range(length):
                #if(i == int(item[i-1])):
                # 0427;16:22 liux at gdcn.com fixed
                if(i == int(item[i]) - 1):
                    #print "bad CodeBall> %s at [%s] = %s"%(item,i,item[i-1])
                    break
                else:                    
                    if(i+1==length):
                        tag = 1                    
            if(1==tag):
                seqCB.append(item)
                #print item
                tag = 0
        return seqCB

if __name__ == '__main__':      # 自测试
    tryPnC = PnC.permutation()            # imported by other programs as well
    if(tryPnC):
        #建立序列
        import timer
        watch= timer.timer()
        watch.start()
        order="12345678"
        seq = list(order)
        #生成排列
        p = tryPnC.permute(seq)        
        #玩――过滤出切题的
        CB = playCodeBall()
        result = CB.filter(p,order)
        print(watch.stop())
        #输出正确的序列到文件
        exp = outputLog.exporter()
        exp.exportArrayCB(result)
        exp.writeInFile("CodeBall.log")
        print "当罐有 %s 个时,全部 %s 种排列中,合题的为:%s 种!"%(len(order),len(p),len(result))
    else:
        print("\"\"")
    
    
-------------- next part --------------
# -*- coding: gbk -*-
# file outputLog.py
#/*********************************
# \class outputLog
# \brief 	结果数据输出支持
# \version 1.1  04427	数组的数码球输出辅助 exportArrayCB ...
# \version 1.0  04427	支持字串,和数组输出!
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string

class exporter:
    def __init__(self):
        self.log=""
    def __repr__(self):# 类自述定义
        return self.log
    def writeInFile(self,fname):
        open(fname,"w").write(self.log)
        print("成功输出数据到文件:%s"%fname)
        
    def exportArrayCB(self,seq):
        foo = ""
        for i in range(len(seq[0])):
            foo +=str(i+1)
        self.log += foo
        self.log +="\n"+"~"*27+"\n"
        for i in seq:
            self.log += i+"\n"
        self.log +="-"*27+"\n"
        self.log += foo
        return self.log
    def exportArray(self,seq):
        for i in seq:
            self.log += i+"\n"
        return self.log
    def exportTxt(self,txt):
        self.log += txt
        return self.log

if __name__ == '__main__':      # 自测试
    exp = exporter()            # imported by other programs as well
    if(exp):
        import PnC
        tryPnC = PnC.permutation()
        seq = list("1234")
        p = tryPnC.permute(seq)
        exp.exportArrayCB(p)
        exp.writeInFile("exp.log")
        
        #open("PnC.log","w").write(PnC.export)
    else:
        print("\"\"")
    
    
-------------- next part --------------
# -*- coding: gbk -*-
# file PnC.py
#/*********************************
# \class PnC
# \brief 	permutation and combination 排列组合 输出
# \version 1.0  04427	使用"一切从游戏开始 - ChinesePython Wiki"的技巧
# \author Zoom Quiet (zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par
# \return
# \sa
#*********************************/

import sys, os,string
import outputLog

class permutation:
    def __init__(self):
        self.log=""
        self.export=""
    def __repr__(self):# 类自述定义
        return self.log
    def permute_O_n(self,seq, index):
        seqc = seq[:]
        seqn = [seqc.pop()]
        divider = 2
        while seqc:
            index, new_index = divmod(index,divider)
            seqn.insert(new_index, seqc.pop())
            divider += 1
        return ''.join(seqn)
    def permute(self,seq):
        seqn = [seq.pop()]
        while seq:
            newseq = []
            new = seq.pop()
            #print "seq:",seq,'seqn', seqn ,'new', new
            for i in range(len(seqn)):
                item = seqn[i]
                for j in range(len(item)+1):
                    newseq.append(''.join([item[:j],new,item[j:]]))
            seqn = newseq
            #print 'newseq',newseq
        return  seqn

if __name__ == '__main__':      # 自测试
    tryPnC = permutation()            # imported by other programs as well
    if(tryPnC):
        seq = list("1234")
        #for i in range(30):
            #print tryPnC.permute_O_n(seq, i)
        p = tryPnC.permute(seq)
        #print len(p)
        #for i in p:
        #    print i
        #open("PnC.log","w").write(PnC.export)
        exp = outputLog.exporter()
        exp.exportArray(p)
        exp.writeInFile("PnC.log")        
    else:
        print("\"\"")
    
    
-------------- next part --------------
# -*- coding: gbk -*-
# file timer.py
#/*********************************
# \class timer
# \brief    通用Python 程序运行计时器
# \version 1.0  04427	for 数码球游戏
# \author Zoom.Quiet ( zoomq at itcase.com)
# \attention 	Released under GNU Lesser GPL library license
# \par usage
#   \li 声明 :watch = timer()
#   \li 跑秒 :watch.start()
#   \li 计时 :watch.stop()
# \note 只要将watch.start();watch.stop() 分别插入到想测试的代码前后就可以了!

#*********************************/
import sys,os,string,time

class timer:
    def __init__(self):
        self.log=""
    def __repr__(self):# 类自述定义
        print("利用Python 内含time 模块进行代码计时!")
        return self.log
    
    def start(self):
        self.start= time.time()
        self.log += "\n run at:"+time.strftime(" %Y-%m-%d %X",time.localtime(self.start))
        return self.log
    
    def stop(self):
        self.stop= time.time()
        self.log += "\n end at:"+time.strftime(" %Y-%m-%d %X",time.localtime(self.stop))
        self.log += "\n 本次运行共用时 %s秒"% (self.stop-self.start)
        return self.log

if __name__ == '__main__':      # 自测试
    watch = timer()        
    if(watch):
        import CBfilter
        playCB = CBfilter.CBfilter()            # imported by other programs as well
        watch.start()
        result = playCB.play(8)
        print(watch.stop())
        #print result
    else:
        print("\"\"")
    

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号