Python finds the sum of the first n terms of a string (a+aa+aaa+aaaa+...+aaa...aaa)

Write a function to calculate the value of the first n terms of an expression of the form a+aa+aaa+aaaa+…+aaa…aaa, where a is a natural number less than 10

def demo1(a,n):
    assert type(a) == int and 0<=a<10, 'a must be integer between 1 and 9'
    a = str(a)
    return sum(eval(a*i)for i in range(1,n+1))

def demo2(a,n):
    a = str(a)
    return sum(map(lambda i :eval(a*i),range(1,n+1)))

print(demo1(1,3))
print(demo2(5,4))

This function accepts two parameters: a represents a natural number less than 10 in the expression, and n represents the sum of the first n terms of the expression to be calculated. The implementation idea of ​​the function is as follows:

  1. First, we initialize three variables: result, current_term, and current_sum. Among them, result represents the sum of the first n terms of the expression, current_term represents the value of the current term, and current_sum represents the sum of all terms before the current term.
  2. We then use a loop to calculate the sum of the first n terms of the expression. The loop starts at 2, because the first item is a itself.
  3. In the loop, we first calculate the value of the current item and then add it to the sum of all items before the current item.
  4. After the loop ends, we return the sum of all items before the current item as the result.

Digitally

To numerically calculate the value of the first n terms of an expression of the form a+aa+aaa+aaaa+…+aaa…aaa, you can use mathematical formulas.

  • First, each item can be written as a * (10^n-1)/(10-1), where n is the current number of items. The denominator of this formula is 9, so you can directly use 9 for calculation.
  • Then, add the values ​​of each term to get the result you are looking for.

code show as below:

def demo3(a,n):
    sum = 0
    for i in range(1, n+1):
        sum += a * (10**i - 1) // (10-1)
    return sum

print(demo3(1,3))

It should be noted that the time complexity of this method isO(n), but due to the use of mathematical formulas, the calculation Faster. In addition, the code of this method is relatively concise and easy to understand and maintain. Therefore, in practical applications, priority can be given to using mathematical formulas for calculations.

string mode

To calculate the value of the first n items of an expression in the form a+aa+aaa+aaaa+…+aaa…aaa using string methods, you can convert each item into a string and then concatenate the strings.

  • First, you need to enter the values ​​of a and n, where a is a natural number less than 10, and n is the number of addition terms.
  • Use a string variable s to save the value of the current item, and update s in the loop, from a to aa to aaa, etc.
  • Then, convert the string of each item into an integer and add them to get the desired result.

code show as below:

def demo4(a,n):
    sum = 0
    s = ''
    for i in range(1, n+1):
        s += str(a)
        sum += int(s)
    return sum

print(demo4(5,4))

It should be noted that an empty string s needs to be used in the loop to save the value of the current item, and s will be updated in each loop. In addition, you need to convert the string of each item into an integer and add it to get the final result. The time complexity of this method is O(n^2) because each loop requires string concatenation and integer conversion. If you want to optimize the time complexity, you can consider using mathematical formulas for calculations, or using other string manipulation methods.

Other methods (not recommended)

In addition, there is a way to calculate the first n values ​​of this expression using strings.

a = int(input('输入相加数a: '))
n = int(input('输入相加个数: '))
s = '0'
for i in range(n):
    s += '+' + str(a) * (i+1)
print(eval(s))

The time complexity of this method is alsoO(n^2), because each loop requires string splicing and expression Evaluate the formula. In addition, there is a certain security risk in using the eval function to evaluate expressions, because the eval function can execute arbitrary code. Therefore, in practical applications, it is not recommended to use this method for calculation.

Summarize

To sum up, to calculate the value of the first n items of an expression in the form a+aa+aaa+aaaa+…+aaa…aaa, you can use the string method a> for calculation, or you can use mathematical formula for calculation.

  • Code in string format is more readable and easy to understand and maintain, but has higher time complexity;
  • Mathematical formulas have shorter code and lower time complexity, but are less readable.

Therefore, in practical applications, it is necessary to choose the appropriate method according to the specific situation.

Guess you like

Origin blog.csdn.net/weixin_56433857/article/details/131257406
aaa