search

Home  >  Q&A  >  body text

python循环题目求1-2+3-4+5 ... 99的所有数的和

怎么求呢??想不出

阿神阿神2770 days ago4736

reply all(6)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:19:08

    can be calculated like this:

    >>> num = 0
    >>> for i in range(100):
    ...     if i % 2 == 0:
    ...         num = num - i
    ...     else:
    ...         num = num + i
    ...
    >>> num
    50

    In addition, since it is the first number minus the last number, the sum between the two values ​​is -1, and 99/2=49.5. Therefore, there are 49 pairs in total, and the result is -49, and then combined with 99 Adding together we get 99-49=50

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:19:08

    After a cursory look, the previous answers all used forloops. Personally, I think you should use them less if you can, and try to reduce the time to O1.
    Suppose the parameter is n, which is the largest number, and both are greater than 0, here it is 99

    n result
    1 1
    2 -1
    3 1
    4 -2
    5 3
    6 -3

    When n is an odd number, the result is positive, result = ((n - 1) / 2) * (-1) + n
    When n is an even number, the result is negative, that is, result = (n / 2) * (-1)
    So, the answer is out. .

    def compute(n):
        if n % 2 is 1:
            return int(((n - 1) / 2) * (-1) + n)
        else:
            return int((n / 2) * (-1))

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:19:08

    >>> rslt=0
    >>> for n in range(1,100):
        rslt += n*(-1,1)[n&1]
    
        
    >>> rslt
    50

    >>> sum(( n*(-1,1)[n&1] for n in range(1,100) ))
    50

    reply
    0
  • 阿神

    阿神2017-04-18 10:19:08

    >>> sum((sum(range(1, 100)[::2]), -sum(range(1, 100)[1::2])))
    >>> 50
    >>> # functools和itertools是你最强大的利器。

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:19:08

    Code

    # 定义输出字符串
    aaa = ''
    # 定义计算结果
    bbb = 0
    
    for i in range(1,100):
        aaa += str(i)
        if i % 2 == 0:
            aaa += '+'
            bbb -= i
        else:
            aaa += '-'
            bbb += i
    print('字符串输出: \r\n %s \r\n计算结果: \r\n %s' % (aaa.rstrip('-'), bbb))

    Results

    字符串输出: 
    
     1-2+3-4+5-6+7-8+9-10+11-12+13-14+15-16+17-18+19-20+21-22+23-24+25-26+27-28+29-30+31-32+33-34+35-36+37-38+39-40+41-42+43-44+45-46+47-48+49-50+51-52+53-54+55-56+57-58+59-60+61-62+63-64+65-66+67-68+69-70+71-72+73-74+75-76+77-78+79-80+81-82+83-84+85-86+87-88+89-90+91-92+93-94+95-96+97-98+99- 
    
    计算结果: 
    
     50

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:19:08

    
    def get_sum(lo, hi):
        return sum(range(lo, hi+1, 2)) + sum(range(lo+1, hi, 2))

    reply
    0
  • Cancelreply