# Python core programming (second edition) Chapter 8 exercises complete answer [reprinted]

Source: Internet
Author: User

Due to my limited ability, the answer is not necessarily the best answer, but for reference only. In addition, because it is only a knowledge point, it may not be necessary to perform a complete data type check in the program. Only list the function part and the output part. You can call it by yourself. All questions are tested and available.

Source http://yazku.blog.163.com/

Def loop (f, t, I ):
'''8-2 Enter 3 numbers, from f to t, I is the step '''
For n in xrange (f, t + 1, I ):
Print n,

Def isprime (num ):
'''8-4 enter a number and return whether it is a prime number '''
# Prime number indicates the number that can only be divided by 1 and itself. Therefore, if count> 1 cannot be divided, it is the prime number.
# Why does count require num/2?
# Because 2 is the smallest even number, the obtained value is the maximum number of possible division of num,
# Num cannot be divided by an integer smaller than 2,
# If it is 1, it will not be reflected (the prime number can also be divisible by 1), and if it is greater than 2, it is not uncertain. If it is 3, and the input is 4, is efficiency always lower?
# It is easier to understand the 1 <count <num-1 method, but undoubtedly, count> num/2 is not possible to be divided out, these cycles are redundant
Count = num/2
While count> 1:
If num % count = 0:
Return False
Count-= 1
Return True

Def getfactors (num, addself = True ):
'''8-5 returns the approximate number of a number, including 1 and itself '''
# Addself indicates whether the approx. Includes itself
Count = num/2
Factors = []
While count:
If not num % count:
Factors. append (count ),
Count-= 1
Return Factors

Def primesplit (Num ):
'''8-6 prime factor factorization '''
# The so-called prime factor decomposition is to divide num into several prime numbers and multiply them.
# What we need is the product of which prime numbers is num to display these prime numbers.
# For example, if num = 20, [2, 2, 5] is returned.
# Analysis first, if the input num is a prime number, then the return value is 1 and itself.
# If it is not a prime number, then there must be 2 in the approx. What are the key issues?
# The above isprime and getfactors functions will be used here
Re = []
If isprime (Num): Re = [1, num]
Else:
Prime = 2
Count = num/2
# The prime number must be smaller than num/2
While Prime <count:
If num % prime = 0:
Num/= prime
Re. append (PRIME)
Continue
Prime + = 1
Return re

Def isperfect (Num ):
'''8-7 the total number is the sum of his approx. For example, the approximate number of 6 is 1, 2, 3 1 + 2 + 3 = 6 '''
If isprime (Num): Return 0
Else:
If sum (getfactors (Num, false) = num: return 1
Return 0

Def factorial (Num, step = 1 ):
'''8-8 factorial '''
# The factorial returns num! Is the product of all numbers from 1 to num, for example, 6! 1*2*3*4*5*6
# Add indicates the step of the class. The default value is 1.
# The factorial of 0 is 1.
# No factorial exists for negative numbers
# No factorial for Decimals
If not float (Num). is_integer (): Return false
If num <0: Return false
If num = 0 or num = 1: return 1
Else:
Re = 1
For I in xrange (1, num + 1, step ):
Re * = I
Return re

Def maid (num ):
'''8-9 fibonacci series. If num is specified, the return value of num '''
# Fibonacci series, such as, and 21
# That is to say, the next value is the first two and
If num <1 or int (num )! = Num: return False
If num = 1: return 1 # The first one is actually irregular. Only one 1 is returned. From the second one is 0 + + 1...
# Analysis:
#0 for 0th
# The first is 1.
# The second is 1 + 0 1
# The third is 1 + 1 2
# The fourth is 2 + 1 3
# The fifth is 2 + 3 5 5 = 3 + 2
# From this point of view, in fact, 2nd should be the third, because 0th is also
# I am doing this here, since the nth number is required, we know that N is the sum of N-1 and N-2, then we need to save it in the runtime
# N-1 and N-2 these two temporary variables N-2 I set to N1, N-1 I set to N2
Re = 0 # The 0th bits are 0
For I in xrange (num-1 ):
If Re = 0: N1, N2 = 0, 1
Re = N1 + N2
N1, N2 = n2, re
Return re

Def counteng (string ):
'''8-10 count the number of metachines, consonants, and words in a sentence, ignore special situations such as vowels and consonants '''
# If you want to deal with these special words, you need to have a special word table or rule. I will not do this, and it is not difficult to implement it.
# Train of Thought: match words. If the words comply with special rules or word lists, the number of [consonants] of the vowels is reduced by 1 or 1.
# Here I only need to process the number of A, E, I, O, u
# The so-called Number of words, especially in English, is easier. It can be separated by spaces.
Words = Len (string. Split ())
String = string. Upper () # Replace it with uppercase for ease
Yuans = FUS = 0
# Counting the number of vowels
For I in string:
# Only process those letters, not special symbols
# The ord of an uppercase vowel is, and 85.
# Uppercase letters: ord 65-90
N = ord (I)
If n in xrange (65,91 ):
If n in [, 85]:
Yuans + = 1
Else:
Fus + = 1
Return [yuans, fus, words]

Def inname ():
'''8-11 text processing, input English Name format: Last name, First Name
If the input format is First name LastName (that is, there is no comma)
So swap location, error prompt, number of errors recorded
After entering the name, the name list is displayed.
'''
# Analysis: the book first requires the user to enter the number of names. This is not natural. I enter q to exit.
Print 'Enter the English name, in the format of name. If the name is \ n, enter q to exit'
Names = []
Error = 0
While True:
Name = raw_input ('enter name: '). strip (). split (',')
If name  = '': continue
If len (name) = 1:
If name . lower () = 'q': break
Error + = 1
Print 'format error... correct should be the name, name \ n you have already wrong % d times. Fixed input... \ n' % error
Name = name . split ()
Name = name  + ',' + name 
Else:
Name = name . strip () + ',' + name . strip ()
Names. append (name)
For I in names:
Print I

Def out ():
'''8-12 input integer 1, integer 2, display a table, including decimal, binary, octal, hexadecimal, and ASCII '''
# ASCII 0-32 127 the 34 are controllers and do not need to be output
# No output is required for numbers over 127, because there is no corresponding ASCII
Num1 = int (raw_input ('enter begin value: '). strip ())
Num2 = int (raw_input ('enter end value: '). strip ())
# Dl, bl, ol, hl, and al indicate the width of each column.
DL, BL, ol, HL, Al = \
Len (STR (num2) + 5, Len (Bin (num2) + 3, Len (OCT (num2) + 4, Len (hex (num2) + 3
# Center the output title
Print 'dec '. center (DL), 'bin '. center (BL), 'oct '. center (OL), 'hex '. center (HL), 'ascii '. center (Al)
# Output horizontal line
Print '-' * (sum ([DL, BL, ol, HL, Al]) + 5)
ASCII =''
For I in xrange (num1, num2 + 1 ):
# ASCII is only displayed in this range
If 32 & lt; I <127: ASCII = CHR (I)
Print STR (I ). center (DL), Bin (I) [2:]. center (BL), OCT (I) [1:]. center (OL), Hex (I) [2:]. center (HL), ASCII. center (Al)
ASCII =''

Related Keywords:
Related Article

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.