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
CupCupFun
V2EX  ›  Python

数字之和与它的取反可以被它们之间的差(绝对值)整除。比如 45 这个数字 (45+54)%|45-54| == 0,要求时输出第满足条件的第 n 个数字的值. 我用下面的代码实现了但是速度很慢,有什么办法可以优化么?

  •  1
     
  •   CupCupFun · 2020-06-15 21:23:05 +08:00 · 1051 次点击
    这是一个创建于 1420 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```python
    def sum_dif_rev(n):
    #反转数字
    def revers_num(num):
    l = list(str(num))
    l.reverse()
    return int(''.join(l))
    times = 0
    i = 45
    while True:
    if abs(i-revers_num(i)) == 0:
    i = i+1
    continue
    if (i + revers_num(i))%(abs(i-revers_num(i))) == 0:
    times = times + 1
    #输出第 n 个数字的值
    if times == n:
    return i
    i = i+1
    ```
    CupCupFun
        1
    CupCupFun  
    OP
       2020-06-15 21:26:40 +08:00
    突然发现格式有问题,编辑的时候有缩进的,是一定要用 md 编辑才能正确显示缩进么?
    necomancer
        2
    necomancer  
       2020-06-16 04:01:14 +08:00
    def nextNum():
    ....i = 0
    ....while True:
    ........inv = int(str(i)[::-1])
    ........if i != inv and ((i+inv) % (i-inv) ==0):
    ............yield i
    ........i += 1

    for i, num in enumerate(nextNum()):
    ....if i == n: # stop at nth
    ........break
    ....print(num)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3353 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:21 · PVG 19:21 · LAX 04:21 · JFK 07:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.