This blog is a record of the exercises of the Liao Xuefeng Python tutorial (i) __python

Source: Internet
Author: User
Tags generator
function parameters of the function"The following function allows you to compute a product of two numbers, and change it slightly to can receive one or more numbersand compute the product:
def product (x,y):
Return X*y

Because you can receive one or more parameters, you want to use a variable parameter when you think about defining a function

def product (*numbers):  #这个地方 *numbers is a variable parameter, inside the function numbers is actually a tuple sum=1 for number in
    numbers:
        Sum=sum*number return
    sum

def main ():
    sum=product (1,2,34)
    print ("The product's the numbers is {}". Format (sum))

main ()
Recursive Functions

Here is a point: the use of recursive functions, must have the conditions of termination, otherwise the program will continue to run ...
2. "Hanoi's movement can be implemented very simply using recursive functions."
Please write the move (n, a, B, c) function, it receives the parameter n, which represents the number of plates in column A, B, and C of the 3 pillars, and then prints out the method of moving all plates from A through B to C, such as Move (3, ' A ', ' B ', ' C ').
Expected output:
A–> C
A–> B
C–> B
A–> C
B–> A
B–> C
A–> C

The principle of Hanoi is simple:
When N=1, Direct: a->c, just one step.

When n=2, we can first put the small plate above from the a->b, and then the bottom of the market from the A->c, and finally the small plate from the b–>c, the total need for three steps.

When N=3, we can first move the top two plates to B according to the n=2 method, the above has been analyzed to need three steps, (in fact, it is also to move n plates from one place to another a realization, but here n=2,c into B), and then the bottom of the market from the A–>c , the last two dishes from the b–>c also need three steps, a total of seven steps.
·······

So the code that uses the recursive function is:

Step=0
def Move (n,a,b,c):
    Global Step
    if n==1:  #这个地方就是递归函数调用终止的条件
        Print (A, '--> ', c)
        Step=step+1
    Else: Move
        (n-1,a,c,b)  #把上面n-1 from A-->b move
        (1,a,b,c)    #把最下面一个从a-->c
        Move (n-1,b,a,c)  #把上面n-1 from B-->c

def main ():
    n=eval (Input ("Please input the numbers of the plates:") Move
    (n, ' A ', ' B ', ' C ')  #这里的A b C indicates
    the cylinder print ("The total steps to move the plates". Format (STE p))

main ()

Note: When you first start using the step variable to count, you find that even if you define the step variable outside, you will get an error:

unboundlocalerror:local variable ' step ' referenced before assignment
The solution refers to the advanced features of this blog

"Construct a list of 1, 3, 5, 7, ..., 99"

def add_list (n):
    l=[] for
    i in range (1,n,2):
        l.append (i) return
    L

def main ():
    n=eval (Input (" Please input the numbers: ")
    l=add_list (n)
    print (L)

main ()
slices

Using the slice operation, implement a trim () function, remove the trailing spaces of the string, and be careful not to invoke the Str strip () Method:

#去除一个字符串首尾空格
def main ():
    s=input ("Please input a string:")
    S0=trim (s)
    print ("The string Processed is "+s0"

def trimbegin (s):
    if s[0]!= ': return
        s
    else:
        trimbegin (s[1:])
    Print (s)

def trimend (s):
    if s[-1]!= ': return
        s
    else:
        trimend (S[:-1])

def trim (s):
    S1=trimbegin (s)
    s2=trimend (S1) return
    S2

Main ()

The code above is not working,,,, tomorrow, look again

Well, I made three mistakes:
First, to determine whether a character is a space using ', not ';
Second, you don't need to enclose quotes in an English string. Quotation marks are also a character and are non-empty, interesting
Finally, what I have been confused about yesterday is that recursive calls must have return values. Otherwise, it will only compute the value of the last called function, not return the function that called it in sequence, remember.

OK, here's the correct code (another example of the factorial of N, which is to emphasize that a recursive call requires a return value, otherwise the result of the final calculation will only return a none!)

#去除一个字符串首尾空格

def main ():
    s=input ("Please input a string:")
    S0=trim (s)
    print ("The String processed are" +S0

def trimbegin (s):
    if s[0]!= ': return
        s
    else: return
        trimbegin (s[1:])    #此处不加return会有错误 , Nonetype 
    print (s)

def trimend (s):
    if s[-1]!= ': return
        s
    else: return
        trimend (s[:-1 ]

def trim (s):
    S1=trimbegin (s)
    s2=trimend (S1) return
    S2

main () ' "
# Recursive call must have a return value, otherwise he will only calculate the last called the value of the function, and will not return to the previous call to the function ...
#比如你在计算n! Recursion is used, it should be written like this:
def factorial_n (n):
    if n==1: return
        1
    else: return
        n Factorial_n (n-1)

def main ():
    n=eval (Input ("Please input a number:")
    Result=factorial_n (n)
    Print ("The final result was {}". Format (Result))

main ()
' "

Well, it's done. iterations

Use an iteration to find the minimum and maximum value in a list and return a tuple:

Code:

def find_max_min (l): #查找一个列表中最大值和最小值的函数
    min=max=l[0] for
    x in L:
        if max<x:
            max=x for y in
    L:
        if min>y:
            min=y return
    min,max

def input_l (*numbers):  #其实这个函数不写也行, the main exercise is to construct a list using variable parameters
    l=[] For number in
    numbers:
        l.append (number) return
    L

def main ():
    #L =input_l (1,2,3) 
    l=[1,2,3,4,5]
    r=find_max_min (L)
    print (R)

main ()
List-generated

If the list contains both a string and an integer, because the lower () method does not have a string type, the listing generates an error, and using the built-in Isinstance function to determine if a variable is a string, modify the list generation. By adding an If statement, the list generation is guaranteed to execute correctly:

[S.lower () for S in [' SHJ ', ' djsjkdl ', ' ', ', ', ', ' DKLKFG '] if Isinstance (S,STR)]

It is important to note that the first item in the list-generation is the "template" for each element of the list, and only one item. Build Device

The construction of the Fibonacci sequence, which I wrote myself, did not use the generator code:
version 1

def fabonacci (num):
    n1=0
    n2=sum=1
    for I in range (num):
        print (sum,end= ')   #让print () output does not wrap automatically. But each two result adds a space
        sum=n1+n2   #数列中下一个值就是前两个数的和
        n1=n2       #更新n1, is actually the original N2
        n2=sum      #更新n2, is actually the original sum value

def main ():
    num=eval (Input ("Please input a number:")
    Fabonacci (num)

main ()

Version 2

#其实可以不用三个变量 Two variables enough
def fabonacci (num):
    a,b=0,1
    for I in range (num):
        print (b,end= ')
        a,b=b, A+b  #扎心了
def main ():
    num=eval (Input ("Please input a number:")
    Fabonacci (num)

main ()

Analysis is: (0) 1 1 2 3 5 8,,,,
1. First assign value a B
2. Output B (i.e. the first number of Fibonacci series)
3. Calculation of A+b
4. The second time a B
5. Repeat 2-4 steps

Version 3
The above Fabonacci () function to the generator, in fact, is to change the inside of the print () function to the yield () function, for the generator object, only need to use a for loop to take the value, or keep calling Next (g)

The #可以把上面写的fabonacci () function is changed to a builder
def fabonacci (num):
    a,b=0,1 for I in
    Range (num):
        #print (b)
        yield ( b)   the print () function in the #就是把上面的fabonacci () function is changed to the yield () function to
        a,b=b,a+b return
    "yeah!"

def main ():
    num=eval (Input ("Please input a number:")
    G=fabonacci (num)     #这样g就变成一个生成器 generator
    For N in G:          #对generator来说使用for loop to fetch value
        print (n,end= ') #为了让输出结果不自动换行  

main ()

After the code is run, a sequence of num numbers is given, but there is no return ' yeah! ' in the code, which can be used stopiteration

#下面这个版本可以让上面的return语句也输出, this requires the use of Stopiteration 

def fabonacci (num):
    a,b=0,1 for I in
    Range (num):
        Yield (b)
        a,b=b,a+b return
    "yeah!"

def main ():
    num=eval (Input ("Please input a number:")
    G=fabonacci (num) while
    True:
        try:
            n= Next (g)
            print (n,end= ')
        except stopiteration as E:
            print ("\nthe content is" +e.value)
            break

Main ()

About the Yang Hui's triangle, see each row as a list, try to write a generator, constantly output the next line of the list:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Can I say I really thought for a long time did not want to come out,,,
It turns out that there's really an IQ crush this stuff smile.jpg

Well, that's the list-builder and generator.

Attach the code directly, refer to this blog

#输出杨辉三角形, not using generator
def triangle (num):
    l=[1] for
    i in range (1,num+1):  #用来输出多行的
        print (L)     #首先输出第一行
        L=[l[j]+l[j+1] for J in Range (Len (L)-1)]  #使用列表生成式来生成下一行列表 (Generate next line with bank)
        L.insert (0,1)  # Because the first element of each line of the Yang Hui's triangle is 1
        l.append (1)    #末尾追加一个1

def main ():
    num=eval (Input ("Please input a number:")
    triangle (num)

main ()        

The list generated for the next row is generated here, and the generator is not used, and when I change print (L) to yield, I find that there is no way to add 1 to the end.
, the map_reduce function needs to be modified

Let's continue with an example, using the map () function and the reduce () function to turn the string into an integer and then perform the corresponding operation
The code is as follows:

 #版本1 ' #主要是利用map () function to convert a string to an int type, and then use the reduce () function to perform the corresponding function on these numbers from Functools import reduce # This function is mainly the function of the two integers into an integer, respectively, by the 10-digit and single digit def Add (x,y): Return x*10+y #这个函数是把字符和对应的数字组成一个key_value, using the dictionary Dictionary[key] for St R and INT Transformation def str_int (s): d={' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9} return D[s] def main (): RE Sult=reduce (Add,map (str_int, ' 123456 ')) #此处需要注意 ' 123456 ' is a string sequence that conforms to the criteria for map action: The first argument is a function, and the second argument is the Iterable object print ("the
        Final result was {} '. Format (Result) ' #版本2: from functools import reduce def finalfun (s): def Add (x,y):  Return X*10+y def str_int (s): d={' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8} return D[s] #return reduce (Add,map (str_int,s)) return to reduce (lambda x,y:10*x+y,map (str_int,s)) def main (): Result=f Inalfun (' 12344576 ') print ("The final result was {}". Format (Result)) main () 

"Using the map () function, the user entered the nonstandard English name, into the first letter uppercase, other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']: "
Why my code is so complicated, and I've been thinking about it for a long time,
So what can you eat to save your IQ? smile.jpg

The code is as follows:

#第一下题: The
#利用map () function, the user entered the nonstandard English name, into the first letter uppercase, other lowercase canonical names.

def normalize (s): for-
    ch in S:
        s1=s.upper ()   #把所有的字符都大写 for ch in

    s[1:]:
        s2=s.lower ()   # Put all the characters in lowercase

    s=s1[0]+s2[1:]     #然后只取上面的第一个字符 (because the initials are capitalized), go to the remaining characters below, return
    s


def main ():
    l=[' Sjkjf ', ' hdjdjhf ', ' HHKJDFK ']
    s=list (Map (normalize,l))
    print (s)

main ()

"The sum () function provided by Python can accept a list and sum, write a prod () function that accepts a list and takes advantage of reduce () quadrature"

The code is as follows

#第二小题
# Please write a prod () function that accepts a list and uses reduce () to accumulate from

functools import reduce

def prod (L):  #使用reduce () function adds Def product (x,y) to the number in a list
    :   #首先定义两个数相乘的函数 return
        x*y
    result=reduce (product,l) #使用reduce () function to sum the number in a list return to result

def main ():
    l=[]
    n=eval (input ("Please input a number:")  n is the number of lists you intend to enter for
    I in range (n):      #通过输入的数构建list列表
        num=eval (input ("Please input a series of numbers:") )
        l.append (num)
    Result=prod (L)
    print ("The final result was {}". Format (Result))

main ()

I also want to say that my IQ is really not enough. This one essay still tangled for so long, should not be to pick up on the operation of the code. Going crazy
The code is as follows:

 #第三小题 #利用map和reduce编写一个str2float函数, convert string ' 123.456 ' to floating-point number 123.456:from Functools import  Reduce def main (): s= ' 123.456 ' s=s.split ('. ') #s =[' 123 ', ' 456 '] s1=s[0] #s1 =[' 123 '] s2=s[1] #s2 =[' 456 '] #这就跟前面的操作一样了嘛, first define Str_int use the map () function to put each String into an integer, and then define the Add_1 () and add_2 () functions to use the reduce () function to change the discrete integer to a full number of hundred and a small tree d1=reduce (Add_1,map (STR_INT,S1)) #d1就是整数部分123 #d2 = Reduce (Add_2,map (STR_INT,S2)) #d2就是小数部分0.456 D2=reduce (Add_1,map (STR_INT,S2)) d=d1+d2*0.001 print ("The data p Roceed is {} ". Format (d)) def Str_int (s): d={' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6} return D[s] def add_1 (x,y): # The function is to generate the hundred number return x*10+y ' Def add_2 (x,y): #该函数是生成小数 return x+0.1*y ' main () 

The next example is the calculation of prime numbers, using the principle of the Io sieve method
It's a simple idea.
1. The first one to remove 1 of all natural numbers is 2, so 2 is a prime;
2. Then from this sequence, use 2 to remove all multiples of 2, that is, the odd number is left, so we can construct an odd sequence that begins with 3, Odd_all () note uses the yield () function to turn it into iterator
3. Then write a not_division () function to filter out the multiples of the first number in the Odd_all () sequence.
The odd sequence generated by 4.odd_all () is updated, then repeat step 3.

The code is as follows:

#输出一个序列范围内的所有素数
#距离上一次感受到智商被碾压仅仅是两个小时前, Mentality has collapsed 

def odd_all ():
    n=1 while
    True:
        n=n+2
        yield n

def not_division (n): return
    Lambda x:x%n>0

def prims ():
    n=2
    it=odd_all () while
    True:
        yield n
        n=next (IT)
        It=filter (Not_division (n), it)

def main (): For
    I in Prims ():
        If I <=30:
            print (i,end= ')
        else: Break

Main ()

"Number of numbers" refers to the same number from left to right and right-to-left reading, for example, 12321,909. Please filter out the number of returns using filter ()

The idea is very simple not to go into the details, ah, finally written out
The code is as follows:

#回数是指从左向右读和从右向左读都是一样的数, for example 12321,909. Please filter out the number of back

def Main ():
    l=[121,12332,12321,897878,9009]
    l1=list (filter (fun,l))    # Use filter to filter L using the fun function, which will be filtered after composing a list
    print (L1)   
    #L2 =reverse (L)
    #print (L2)

def fun (num):
    l1=l2 =[]

    for i in STR (num):   #对于每一个输入的数字, first convert it to a string, and then the for in loop is stored in the list
        l1.append (i)     #L1列表中就对每一个数字顺序存放
    #print (L1)

    L2=reverse (L1)      #调用自定义的reverse函数, turn the list just in order for

    I in range (len (L1)):   # The main thing here is to see whether the elements are equal, or not, by the list of sequential and in the reverse order: returns
            0 return
    1


def reverse (L):     l1[i]!=l2[i #反转列表中的元素
    l1=[] for
    i in L:
        l1.append (l[-1])   #总是先存列表的最后一个元素
        l=l[:-1]           # And then remove the last element of the list to save the second in the previous list for the next loop, and so on return
    L1

main ()
nonsense

, to filter the problem first written to this, tomorrow will be refueling ducks.

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.