Python Simple Instance Training (21~30) __python

Source: Internet
Author: User
Tags case statement chr ord

21. Title: decompose a positive integer into decomposition. For example: Enter 90, print out 90=2*3*3*5.

Program analysis: N to decompose decomposition, you should find a minimum prime number k, and then complete the following steps:

(1) If this prime number is equal to n, then the process of decomposing decomposition is finished and printed out.

(2) if n!=k, but n can be divided by K, you should print out the value of K, and n divided by the quotient of K, as a new positive integer you n, repeat the first step.

(3) If n cannot be divisible by K, then repeat the first step using k+1 as the value of K.

Note : To know the format of this function, in fact, is formatted, and print almost, specific reference to http://www.jb51.net/article/63672.htm

Method One: Use only loops

#-*-Coding:utf-8-*-
while True:
    n = input ("Please enter a number:")
    #这里有逗号是为了保证它输出后不自动换行, same as
    print ' {} = '. Format (n) , 
    #判断你输入的是不是正确格式
    if not isinstance (n, int) or n <= 0:
        print ' Please enter a correct number! ' 
    #如果你是输入的是 1, that only outputs 1
    if n in [1]: 
        print ' {} '. Format (n) while  
    n >= 2: For
        I in range (2,n + 1):
            if n% i = = 0:
                n/= i      #n equals n/i
                if n = 1: 
                    print I,
                else:     # index must be prime
                    print ' {} * '. for Mat (i),
                break
    print     #换行咯

Method Two: Defining functions

#-*-Coding:utf-8-*-
def reducenum (n):
    print ' {} = '. Format (n),
    if not isinstance (n, int) or n <= 0: 
  print ' Please enter a correct number! '
        Exit (0)
    elif n in [1]:
        print ' {} '. Format (n)
    while n. [1]: # Loop guarantees recursion for
        I in range (2, n + 1):
            If n% i = = 0:
                n/= I # n equals n/i
                if n = 1: 
                    print i 
                else: # I must be prime
                    print ' {} * '. Format (i), 
  
   break

Reducenum (+)
Reducenum (9)
  
    Output:  2 * 2 * 5 * 5
    9 =  3 * 3

Method Three: Use list append function, here just output all x's factor in the form of list

#-*-Coding:utf-8-*-while
True:
    x = input ("Pls input a number:")
    ret = [] While
    x > 1: For
        v. in Range (2,x + 1):
            if x% v = 0:
                ret.append (v)
                x/= v
                break
    print ret

    output:
        pls input a number: 9
        [3, 3]

Description: In fact, the two methods are similar, no difference.

22. Title: Find the value of S=A+AA+AAA+AAAA+AA...A, where a is a number. For example 2+22+222+2222+22222 (there are 5 numbers added at this time), several numbers are added with keyboard control.

Program Analysis: The key is to calculate each item

#-*-Coding:utf-8-*-
Tn = 0
Sn = [] #用来存储数字个数
n = Int (raw_input (' Enter the number of digits you want to add n =: ')  #控制你要相加的次数 
  a = Int (raw_input (' input number A =: ')    #真正要加的数字 for
count in range (n):
    tn = tn + a 
    a = a *
    Sn.ap Pend (TN) #每加一个数就放在Sn列表中
    print Tn

    #lambda这个函数比较强大, for specific use you can see data
Sn = reduce (lambda x,y:x + y,sn)
Print Sn
Enter the number of numbers you want to add n =: 5
input number A =: 6
6
666
6666
66666
74070

Functions to use:

The reduce BUILTIN function in 1.python is a two-dollar operation function, he used all of the data in a data set (linked list, tuple, etc.) to do the following: Func () to the function in reduce (must be a two-dollar operation function) to first manipulate the 1th, 2 data in the set , the results are then calculated with the third data using the Func () function, and finally a result is obtained.

Specific reference to http://blog.csdn.net/SeeTheWorld518/article/details/46975857

2.lambda function, see connection http://blog.csdn.net/mtbaby/article/details/53099072

23. Title: If a number is exactly equal to the sum of its factors, this number is called the "finished number". For example 6=1+2+3. program to find out all the numbers within 1000.

Program Analysis: Please refer to the Program Python practice example 14. As long as in the back with the judgment conditions can be, note, to the output factor when add 1, pay attention to the problem, 1 is any number of factors, so can not be missed

#-*-coding:utf-8-*-import random import time while true:x = Random.randint (1,1000) #因为后面求质数要修改x的值, so save the X for a spare s = x factors = [1] #1是任何数的因子 while x > 1: #上限取值可以是x, that is, the factor can also be x itself, which we all know Get for V. in range (2,x + 1): if x% v = 0:factors.append (v) #找到了当前的最小 Factor, reset continues to find the next eligible minimum factor x/= v #由于break是跳出当前的循环, so the break here is jump out of for loop break p Rint "All factors are%s, so"% (factors), if sum (factors) = = S: #这里就是判断函数了 print "%d is the end of"% (s) else:print "%d Not the end of the number "% (s) time.sleep (1) #为防止程序卡顿, I sleep for a second. Output a 
Output:
    all factors are [1, 2, 2, 2, 31], so: 248 is not the end of
    all factors are [1, 2, 2, 2, 73], so: 584 is not the end of
    all factors are [1, 823], so: 823 is not the end of
    all Factor is [1, 281], so: 281 is not the end of
    all factors is [1, 467], so: 467 is not the end of
    all factors are [1, 2, 359], so: 718 is not the end of
    all factors are [1, 2, 7, 47], so: 6 58 is not the end of
    all the factors are [1, 751], so: 751 is not the end of
    all factors are [1, 3, 71], so: 213 is not the end of the number
...

24. Title: Two table tennis teams compete, each with three people. A team for three a,b,c, Team B for x,y,z three people. The list of the matches has been decided by lottery. The team was asked about the list of the matches. A said he does not and X, C said he does not and x,z, please compile a program to find the list of three teams.

Program Analysis: It's good to understand mathematically, but here's to convert the letters to ASCII code.

#-*-Coding:utf-8-*-

for I in Range (Ord (' X '), ord (' z ') + 1):
    for J in Range (Ord (' X '), ord (' z ') + 1):
        If I!=  J:
            for K in range (Ord (' X '), ord (' z ') + 1):
                if (i!= K) and (J!= k):
                    if (I!= ord (' X ')) and (K!= ord (' X ')) and (k!= Ord (' Z ')):
                        print ' order is a--%s\t B--%s\tc--%s '% (Chr (i), Chr (j), Chr (k))

25. Topic: There is a fractional sequence: 2/1,3/2,5/3,8/5,13/8,21/13 ... Find out the sum of the first 20 items of this series.

Procedure analysis: Please grasp the change rule of numerator and denominator. As you can see, the denominator is the Fibonacci sequence.

Method One: The sum of the numerator denominator of the first fraction is the molecule of the second number.

#-*-Coding:utf-8-*-

a = 2.0       #第一个数的分母
B = 1.0       #第一个数的分子
s = 0         #前20项的和
for N in range (1, : s + = A/b
    t = a      #先把分子保存到t a = a
    + b  #分子是前一个分数的分子分母之和
    b = t      #分子分母交换
print S

Method Two:

#-*-Coding:utf-8-*-

a = 2.0
B = 1.0
s = 0.0
for n in range (1,21):
    s + + A/b
    b,a = A, A + b
  print s

Method Three:

#-*-Coding:utf-8-*-

a = 2.0
B = 1.0
L = [] for
N in range (1,21):
    b,a = a,a + b
    l.append (A/ b)
print reduce (lambda x,y:x + y,l)

26. Title: ask for 1+2!+3!+...+20! and.

Program Analysis: This program just turns the cumulative into a tired multiply. Think about how factorial counts. N!=nx (n-1) x (n-2) x (n-3) x...x1, so you need only one traversal, multiply the numbers within N, and then add them up.

Method One:

#-*-Coding:utf-8-*-

n = 0
s = 0
t = 1 for
n in range (1,21):
    t *= n   #这里t就是20以内每个数的阶乘 
  
   s + = t   #把每次得到的阶乘值加到s
print ' 1! + 2! + 3! + ... + 20! =%d '% s
  

Method Three: Here, using the method of defining a function, use the SUM function.

#-*-Coding:utf-8-*-

s = 0
L = range (1,21)
def op (x):
    r = 1 for
    i in range (1,x + 1):
        R *= i
  
   return r

s = SUM (map (op,l))  
print ' 1! + 2! + 3! + ... + 20! =%d '% s
  
Output: 1! + 2! + 3! + ... + 20! = 2561327494111820313

Here is the use of the map () function:

Very simply, the first parameter receives a function name, and the second parameter receives an iterative object

#-*-coding:utf-8-*-
ls = [1,2,3]
rs = map (str, LS)
#打印结果 [' 1 ', ' 2 ', ' 3 ']

lt = [1, 2, 3, 4, 5, 6]
  def Add (num): return
    num + 1

rs = map (add, lt)
print Rs 
#打印结果 [2,3,4,5,6,7]

27. Title: Use recursive method to find 5!.

Program Analysis: Recursive formula: fn=fn_1*4! Recursive method is to call themselves.

#-*-Coding:utf-8-*-
def jiecheng (n):
    if n <= 1: Return
        1
    else: return
        n * Jiecheng (n-1) 
  print Jiecheng (5)

output: 120

28. Title: The 5 characters entered will be printed in reverse order.

Method one: Using recursive function to call the way

#-*-coding:utf-8-*-

def output (s,l):
    if l==0:
        return
    print (S[L-1))
    output (s,l-1)

s = raw_ Input (' Input a string: ')
L = Len (s)
output (s,l)
    Output: Input a string:1234
         4
         3
         2
         1

Method Two: Using the reverse function

#-*-Coding:utf-8-*-
a = [1,2,3,4,5]
a.reverse ()
print a

    or:

#-*-coding:utf-8-*-
s = List (raw_input (' Input a string: ')
s.reverse ()
print S

28. Topic: 5 people sat together and asked how old the five were. He said he was 2 years older than the 4th. Asked the 4th man's age, he said he was 2 years older than the 3rd. Ask the third person, and say two years older than the 2nd. Ask the 2nd person, say two years old than the first one. Finally asked the first person, he said is 10 years old. How old is the fifth person, please?

Program Analysis: Using recursive method, recursion is divided into two stages of back-push and recursion. To know the age of the fifth person, you need to know the age of the fourth person, and so on, push to the first person (10 years), and then push backwards.

Method One: This is very simple, it is every cycle plus 2, Cycle 4 times is good.

#-*-Coding:utf-8-*-
x = Ten for
i in range (1,5):
    x = x + 2
print X

Method Two: Methods of defining functions

#-*-Coding:utf-8-*-
def Age (n):
    If n = 1: 
        x = ten
    else: 
        x = Age (n-1) + 2 return
    x
print Age (5)

29. Title: a 5-digit number, to determine whether it is a palindrome number. That is 12321 palindrome number, the same as the million digits, 10 bits and thousands of the same.

Program Analysis: This five-digit number is separated from the middle, according to the symmetry to cut, and then compare whether equal.

#-*-Coding:utf-8-*-
a = Int (raw_input ("Please enter a number:")
x = str (a)
flag = True for

i in range (len (x)/2): C12/>if X[i]!= x[-i-1]:  #如果不相等, jump straight out of the loop, directly judge not palindrome number
    flag = False break
if flag:
    print "%d is a palindrome number ! "% a
else:
    print"%d is not a palindrome number! "% A
Output:
    Please enter a number:
    15651
    15651 is a palindrome number!

30. Title: Please enter the first letter of the week to determine the day of the week, and if the first letter is the same, continue to judge the second letter.

Program Analysis: Use Case statement is better, if the first letter is the same, then judge the second letter with the case statement or if statement. Wow, this problem should be very simple AH ~ ~ First Look at the words of the week have what "Monday Tuesday Wednesday Thursday Friday Saturday", all Only "T" and "S" to determine the second letter.

 #-*-Coding:utf-8-*-letter = raw_input ("Please input:") #while letter!= ' Y ': If letter = = = ' S ': print (' Please input second letter: ') letter = raw_input ("Please input:") if
            Letter = = ' A ': print (' Saturday ') elif letter = = ' U ': print (' Sunday ') Else: Print (' data error ') elif letter = = ' F ': print (' Friday ') elif letter = = ' M ': print (' Mo

        Nday ') elif letter = = ' T ': print (' Please input second letter ') Letter = raw_input ("Please input:")
        If letter = = ' U ': print (' Tuesday ') elif letter = = ' h ': print (' Thursday ') Else:print (' data error ') elif letter = = ' W ': print (' Wednesday ') else:print (' d ATA error ') 
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.