V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dreampython
V2EX  ›  Python

《Dive into python3》alphametics.py 代码请教

  •  
  •   dreampython · 2018-03-05 23:34:30 +08:00 · 2015 次点击
    这是一个创建于 2215 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题 1:为什么要按照以下顺序组合字母,stored_characters = ''.join(unique_characters)行不行,只是顺序不同

    stored_characters = ''.join(first_letters) +  \
        ''.join(unique_characters - first_letters) 
    

    问题 2: 为什么要排除前 n 个元素含有 zero 的排列?

    if zero not in guess[:n]: 
    

    代码如下:

    import re
    import itertools
    
    def solve(puzzle):
        words = re.findall('[A-Z]+', puzzle.upper())
        unique_characters = set(''.join(words))
        assert len(unique_characters) <= 10, 'Too many letters'
        first_letters = {word[0] for word in words}
        n = len(first_letters)
        stored_characters = ''.join(first_letters) +  \
        ''.join(unique_characters - first_letters)
        characters = tuple(ord(c) for c in stored_characters)
        digits = tuple(ord(c) for c in '0123456789')
        zero = digits[0]
        for guess in itertools.permutations(digits, len(characters)):
            if zero not in guess[:n]:
                equation = puzzle.translate(dict(zip(characters,guess)))
                if eval(equation):
                    return equation
    if __name__ == '__main__':
        import sys
        for puzzle in sys.argv[1:]:
            print(puzzle)
            solution = solve(puzzle)
            if solution:
                print(solution)
    
    2 条回复    2018-03-16 16:28:46 +08:00
    dreampython
        1
    dreampython  
    OP
       2018-03-08 19:33:40 +08:00
    自问自答(个人理解):
    问题 1:将 first_letters 放在前面是问题 2 的伏笔
    问题 2:排除前 n 个元素含有 zero 的排列,就是排除问题 1 中被排在前面的 first_letters 这些字符对应的数字不能为 0
    myhyperion
        2
    myhyperion  
       2018-03-16 16:28:46 +08:00
    我已有这个疑问,后来发现
    <code>
    >>> 01+1==2
    SyntaxError: invalid token
    </code>
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1733 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 16:39 · PVG 00:39 · LAX 09:39 · JFK 12:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.