PythonChallenge 编程游戏-------第2关

recognize the characters. maybe they are in the book,
but MAYBE they are in the page source.
看到提示,Ctrl + U,查看了一下源代码,别用洞天。
<!--
find rare characters in the mess below:
-->

<!--
%%$@_$^__#)^)&!_+]!*@&^}@[@%]()%+$&[(_@%+%$*^@$^!+]!&_#)_*}{}}!}_]$[%}@[{_@#_^{*
..............
}!)$]&($)@](+(#{$)_%^%_^^#][{*[)%}+[##(##^{$}^]#&(&*{)%)&][&{]&#]}[[^^&[!#}${@_(
#@}&$[[%]_&$+)$!%{(}$^$}*
-->
想一想。。。。
找到,出现次数是最少的字符。
应该,在遍历的同时,创建一个字典,字符为key,字符出现的次数,为value。如果下一个字符在字字典key中,那么,就将对应的value值加1,如果不在,就增加一个值为1的键值对。
代码:
#! usr/bin/env python
import os
import sys


def findfile():
    path = os.path.abspath('second.txt')
    thefile = open(path,'r')
    content = thefile.read()
    thefile.close()
    return content

def count(thestr):
    countor = {'string':'num'}
    for i in thestr:
        if i in countor.keys():
            countor[i] +=1
        else:
            countor[i] = 1
    return countor

def lesschar(chardict,content):
    i = len(content)
    for n in range(len(chardict)):
        if i > n :
            i = n
        else:
            pass
    endstr = [n for n in chardict.keys() if chardict[n] == 1]
    return endstr


if __name__ == "__main__":
    content = findfile()
    chardict =  count(content)
    result = lesschar(chardict,content)
    print ''.join(result)


输出:
aeilquty


好像有一点不对的样子~,因为URL:
http://www.pythonchallenge.com/pc/def/aeilquty.html
根本就打不开,应该有错误。。。。。。
然后,没有想出来,查了一下,答案是 equality。
想一想,应该是字典的排序造成的。或者说,字典的没有排序。字典就是一个乱序的“键值对”容器。
重新用列表实现一下。

#! usr/bin/env Python

import os
import sys


def filefind():
    path = os.path.abspath('second.txt')
    thefile = open(path,'r')
    content = thefile.read()
    thefile.close()
    return content

def count(str):
    arry = []
    thestr = []
    for i in str:
        if i in thestr:
            n = thestr.index(i)
            arry[n][1] += 1
        else:
            thestr.append(i)
            arry.append([i,1])
    return arry

def theless(arry):
    j = len(arry)
    endstr = []
    for k in arry:
        if j >= k[1]:
            j = k[1]
        else:
            pass
    for i in arry:
        if i[1] == j:
            endstr.append(i[0])
        else:
            pass
    return endstr


if __name__ == "__main__":
    content = filefind()
    arry = count(content)
    result = theless(arry)
    print ''.join(result)

输出:
equality

第三关链接:
http://www.pythonchallenge.com/pc/def/equality.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值