Python Challenge-Level 1

本文详细解析了Python挑战中的Level1问题,通过多种方法实现文本转换,并提供了完整代码实现,帮助读者理解并解决类似编码问题。

http://www.pythonchallenge.com/pc/def/map.html

http://wiki.pythonchallenge.com/index.php?title=Level1:Main_Page

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#Level1_Sol1.py
import string
text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
def Sol1():
    #First, load the text and create a translation table.
    #string.ascii_lowercase: The lowercase letters 'abcdefghijklmnopqrstuvwxy'. This value is not locale-dependent and will not change.
    table = string.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:]+string.ascii_lowercase[:2])
    print "table is ", repr(table), "\nlen(table) is ", len(table), "\ntype(table) is ", type(table)
    print "------------------------"
    #Now, we apply the translation table on the string.
    newstr1 = string.translate(text, table)
    print "newstr1 is ", newstr1
    print "------------------------"
    #Alternatively, just use the translate on the "text" variable.
    newstr2 = text.translate(table)
    print "text is ", text
    print ">>>>>>>>>>>>>>>>>>>>>>>>"
    print "newstr2 is ", newstr2
def Sol2():
    '''
        Solved without translate
    '''
    tmp_str = ""
    for x in text:
        if ord(x) >= ord('a') and ord(x) <= ord('z'):
            tmp_str += chr((ord(x) + 2 - ord('a'))%26 + ord('a'))
        else:
            tmp_str += x
    print "tmp_str is ", tmp_str
def Sol3():
    '''
        Similar to Sol2() but with some of 2.5's nested ternary operators
    '''
    for x in text:
        print chr(ord(x) if ord(x)+2 < ord('a') else ord(x) + 2 if ord(x)+2 < ord('z') else ord(x) - 24),
def Sol4():
    '''
        With a dictionary
    '''
    """
    zip([iterable, ...])zip()是python的一个内建函数,它接受一系列可迭代的对象作为参数,可把两个或多个序列中的相应项合并在一起,将对象中对应的元素打包成一个个tuple元组,然后返回由这些tuples组成的list(列表)。若输入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)
    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [7,8,9,0]
    >>> zipped = zip(a,b)
    >>> zipped
    [(1, 4), (2, 5), (3, 6)]
    >>> zipped = zip(a,b,c)
    >>> zipped
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    >>> zip(a,c)
    [(1, 7), (2, 8), (3, 9)]
    >>> zip(*zipped)
    [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
    
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    cypher = dict(zip(string.lowercase, string.lowercase[2:] + string.lowercase[:2]))
    #dict.get(key, default=None)对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default的值。注意,参数default的默认值为None.
    print "cypher is ", cypher
    print "".join(cypher.get(c,c) for c in text)
        
if __name__ == '__main__':
    #Sol1()
    #Sol2()
    #Sol3()
    Sol4()

Do by myself:

str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
lists = str.split()
list1 = []
for str1 in lists:
    str2 = ''
    for ch in str1:
        if ch == '.' or ch == '\'' or ch == '(' or ch == ')':
            str2 += ch
        else:
            str2 += chr(ord(ch)+2)
    str2 = str2.replace('{','a')
    str2 = str2.replace('|','b')
    list1.append(str2)
print(" ".join(list1))

转载于:https://my.oschina.net/u/1178546/blog/165808

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值