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

求问,有没有比较快的、准确的计算方式?谢谢。

  •  1
     
  •   kingmo888 · 2022-11-25 15:12:58 +08:00 · 2146 次点击
    这是一个创建于 489 天前的主题,其中的信息可能已经有所发展或是发生改变。
    target_num = 15
    weights = {
        'A':0.6,
        'B':0.3,
        'C':0.1
        }
    single_num = {k:int(round(v*target_num, 0)) for k,v in weights.items()}
    

    其中 target_num(0~1000), weights 内部元素数量处于 1~N ( N<10 )且 values 之和为 1,

    要求最终 single_num 的 values 之和等于 target_num 。

    上述代码总会在某些权重下多一点或少一点。

    同时,基于上述要求的话,列表推导式之外还需要加判断代码,速度就慢了。

    请问有什么比较好的解决办法吗?

    谢谢。

    3 条回复    2022-11-25 16:13:56 +08:00
    paopjian
        1
    paopjian  
       2022-11-25 15:19:43 +08:00
    背包问题?
    zbatman
        2
    zbatman  
       2022-11-25 15:54:16 +08:00
    return null

    你就说快不快吧
    Huelse
        3
    Huelse  
       2022-11-25 16:13:56 +08:00
    参考 /t/895464

    建议确定精度后转整数计算
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3207 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 11:57 · PVG 19:57 · LAX 04:57 · JFK 07:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.