Example of calculating the number of book pages in python

Source: Internet
Author: User
This article describes how to calculate the statistical number of a book page number in python. compared with the two examples, it describes the digital statistics technique, which is very practical, for more information about how to calculate the number of pages of a book in python, see the following example. it is a typical application in Python programming. Share it with you for your reference. The details are as follows:

Problem Description: For the given page number n, calculate the number of numbers 0, 1, 2, 3, 4, 9 used in all pages respectively

The instance code is as follows:

def count_num1(page_num):   num_zero = 0   num_one = 0   num_two = 0   num_three = 0   num_four = 0   num_five = 0   num_six = 0   num_seven = 0   num_eight = 0   num_nine = 0   page_list = range(1,page_num + 1)   for page in page_list:     page = str(page)     num_zero += page.count('0')     num_one += page.count('1')     num_two += page.count('2')     num_three += page.count('3')     num_four += page.count('4')     num_five += page.count('5')     num_six += page.count('6')     num_seven += page.count('7')     num_eight += page.count('8')     num_nine += page.count('9')   result = [num_zero,num_one,num_two,num_three,num_four,num_five,num_six,num_seven,num_eight,num_nine]   return result  print count_num1(13) 

The code above is a little bloated, so I changed the code.

The modified code is as follows:

def count_num2(page_num):   page_list = range(1,page_num + 1)   result = [0 for i in range(10)]   for page in page_list:     page = str(page)     for i in range(10):       temp = page.count(str(i))       result[i] += temp   return resultprint count_num2(13)

The testing environment of this example is Python2.7.6.

The program output result is:

[1, 6, 2, 2, 1, 1, 1, 1, 1]

I hope this article will help you with Python programming.

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.