简体   繁体   中英

Maximum alternating sum in a number

Alternating sum is defined like this : 交替总和

I'm supposed to write a function which finds the maximum alternating sum with a specific length: for example the number 43805 has alternating sums with length 3:

4-3+8,
3-8+0,
8-0+5

An example of the function output: >>> altsum_digits(5**36, 12) 18

I wrote my code but for some reason I don't get the exact result, for the number 5**36 I get the answer 20 instead of 18, Can you please tell me what should I fix in my code?

Another question: let's define nplus, nminus, nmult as the number of adds, Subtractions and multiplication the function does each run, I'm supposed to write a Mathematical expression for each one the parameters according to the inputs n and d, I'm a beginner and I have no clue how to do this, I would really appreciate any help.

Here is my code:

def altsum_digits(n,d):
    c = [int(l) for l in str(n)]

    maxaltsum=0
    tmpmax=0
    for i in range(0,d):
       tmpmax=tmpmax+((-1)**(i)*c[i])


    it=(len(c)-d)
    for i in range(1,it):
        tmpmax=c[i+d-1]-(tmpmax-c[i-1])
        if (tmpmax)>maxaltsum:
            maxaltsum=tmpmax
    print(maxaltsum)

Based on simple debugging, I think your calculation of tmpmax based on previous tmpmax is incorrect, you missed a minus sign: use tmpmax=-c[i+d-1]-(tmpmax-c[i-1]) instead of tmpmax=c[i+d-1]-(tmpmax-c[i-1]) . Just think it through, it is logical. It is always very easy to get lost in the forest of alternating signs.

Of the three bugs mentioned in elias' answer and the comments (wrong initialisation of maxaltsum , wrong number of iterations in the second loop, and missing a - in the tmpmax calculation in the second loop), you can avoid ever running into at least the first one by using Python's builtins.

Whenever you have a problem that is "work out the maximum something ", and your way of doing it involves exhaustively searching all the possible somethings for the maximum, you can use Python's builtin function max . Here's how you would do it here using a Python generator:

def altsums(n, d):
    c = [int(l) for l in str(n)] 

    alt = 0
    for i in range(0,d):
       alt=alt+((-1)**(i)*c[i])

    yield alt

    it=(len(c)-d)
    for i in range(1,it):
        alt = -c[i+d-1]-(alt-c[i-1])
        yield alt

print(max(altsums(5**36, 12))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM