Python exercise 013: Solving a + aa + aaa ......, Python

Source: Internet
Author: User

Python exercise 013: Solving a + aa + aaa ......, Python

[Python exercise 013]Evaluate the value of s = a + aa + aaa + aaaa + aa... a, where a is a number. For example, 2 + 22 + 222 + 2222 + 22222 (a total of 5 numbers are added at this time.

This question is not difficult. In fact, a + aa + aaa + aa... a can be converted to (a * 10 ** 0) + (a * 10 ** 1) + (a * 10 ** 2 )...... Then convert it to a * (10 ** 0 + 10 ** 1 + 10 ** 2 ......), So we can use two for loops.

Note: for 1st for loops, range () must be counted from 1, so that the first 2nd for loops can be cyclically at least once (if I = 0, then range (I) it cannot be recycled.

The Code is as follows:

A = int (input ('Enter the number a: ') count = int (input ('enter a few numbers and add them together :')) res = 0 # initialize the Final Solution for I in range (1, count + 1): # The number of cycles is the same as the input value, but starting from 1, the loop t = 0 # The temporary variable for j in range (I ): t = t + 10 ** j # Calculate 10 ** 0 + 10 ** 1 +... + 10 ** j res = res + (a * t) # Calculate a * tprint (res)

The output result is as follows:

Enter the number a: 5
Enter a few numbers to add: 4
6170

 

++

Source: getting started with programming languages: 100 typical examples [Python]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.