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

关于 leetcode 的的 1103 题目

  •  
  •   18870715400 · 2020-08-09 21:28:27 +08:00 · 2192 次点击
    这是一个创建于 1353 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的解法

    def distributeCandies(candies: int, num_people: int):
        ans = [0] * num_people
        i = 1
        while 1:
            person = (i % num_people) - 1
            ans[person] += i
            candies -= i
            if (i + i) >= candies:
                print("i+1:{}   candies:{}".format(i+1, candies))
                person = ((i + 1) % num_people) - 1
                ans[person] += candies
                break
            else:
                i += 1
        return ans
    
    res = distributeCandies(7, 4)
    
    print(res)
    
    最后出来的结果:
    
    i+1:3   candies:4
    [1, 2, 4, 0]
    

    答案是错误的, 为什么在 i = 2 的时候还是会进入到 if 的判断里面去, 我已经打印出来了, i+1 = 3 candies=4 但是 if (i+1) >= candies 还是为 True ,为什么呢

    附上正确答案

    def distributeCandies(candies: int, num_people: int):
        ans = [0] * num_people
        i = 1
        while 1:
            person = (i % num_people) - 1
            ans[person] += i
            candies -= i
            i += 1
            if i >= candies:
                print("i:{}   candies:{}".format(i, candies))
                person = i % num_people - 1
                ans[person] += candies
                break
    
        return ans
    
    
    res = distributeCandies(7, 4)
    
    print(res)
    
    2 条回复    2020-08-09 22:22:28 +08:00
    chenstack
        1
    chenstack  
       2020-08-09 22:20:03 +08:00
    第一段的
    if (i + i) >= candies:
    应该是打错了,i + 1 打成来 i + i,两个 i 了
    18870715400
        2
    18870715400  
    OP
       2020-08-09 22:22:28 +08:00
    @chenstack 笔误了, 低级了, 谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1494 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:11 · PVG 01:11 · LAX 10:11 · JFK 13:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.