Python calculates the number of book page statistics problem instance _python

Source: Internet
Author: User

This article is an example of Python Computing book page number statistics problem, is a Python program design of a more typical application example. Share to everyone for your reference. Specifically as follows:

Problem Description: For a given page number n, calculate how many digits are used in all page numbers 0,1,2,3,4...,9

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_FIV E = 0 
  num_six = 0 
  num_seven = 0 
  num_eight = 0 
  num_nine = 0 
  page_list = range (1,page_num + 1) 
  fo R 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 above code is slightly bloated, so the code is changed.

The revised code is as follows:

def count_num2 (page_num): 
  page_list = range (1,page_num + 1) Result 
  = [0 to I in range (Ten)] for 
  page in page_l IST: 
    page = str (page) for 
    i in range: 
      temp = page.count (str (i)) 
      result[i] + = temp return 
  result< C9/>print count_num2 (13)

This article example test run environment for Python2.7.6

The result of the program output is:

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

I hope this article will help you with your Python programming.

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.