#encoding =utf-8
# 11-3 function. In this exercise, we will implement the Max () and Min () built-in functions.
# (a) write a max2 () function with two elements to return a larger and smaller element, a simple () kernel min2 (). They should be able to
# works with any Python object. For example, Max2 (4,8) and min2 (4,8) each return 8 and 4 each time.
# (b) Create a new function My_max () and My_min () that uses consider in part A to refactor Max () and Min (). These letters
# number returns a maximum and minimum value in a non-empty queue, respectively. They can also take a parameter set as input. Use numbers and strings to
# Test your solution.
Def max2 (A, B):
If a > B:
Return a
Else
Return b
Def min2 (A, B):
If a > B:
Return b
Else
Return a
Print Max2 (4,8)
Print min2 (4,8)
#返回队列的最大最小值
Alist = [1,2,3,4,5,6,5,4,3,2]
def mymax (list):
For I in range (len (alist)):
If i = = 0:
max = Alist[i]
max = Max2 (Max,alist[i])
Return Max
def mymin (list):
For I in range (len (alist)):
If i = = 0:
min = Alist[i]
min = min2 (Min,alist[i])
return min
Print Mymax (alist)
Print Mymin (alist)
#enumerate参数为可遍历的变量, such as a string, list, etc; The return value is the enumerate class
For i,j in Enumerate (alist):
Print I,j
print ' 11-6 '
# 11–6. Variable length parameters. The next function called printf (). There is a value parameter, a format string. The rest is the root.
# variable parameters to display on standard output according to the values on the formatted string, the values in the format string allow special strings
# format operation indicator, such as%d,%f, etc. Tip: The solution is trivial----do not need to implement the string operator functionality, but you need to
# to display the action in string format (%)
#变长参数有默认参数, * tuple implements non-keyword default parameters, * * Dictionary-implemented keyword default parameters
def printf (ARG, *nkw):
For Eachnum in nkw:
Print arg% Eachnum,
printf ('%d ', 2,3.4,5)
printf ('%f ', 2,3.4,5)
#非关键字可变参数 tuples *
def tuple (arg1,arg2= ' B ', *therest):
print ' Formal arg1: ', arg1
print ' Formal arg2: ', arg2
For Eacharg in Therest:
print ' Another arg: ', Eacharg
Tuple (' abc ')
Tuple (23,4)
Tuple (AT, ' abc ', ' XYZ ', 456)
# 11–7. Use map () for functional programming. Given a pair of lists of the same size, such as [1, 2, 3] and
# [' abc ', ' Def ', ' Ghi ',....], merge two markers into a single table of tuples consisting of each list element so that I
# Our results look like this: {[(1, ' abc '), (2, ' Def '), (3, ' Ghi '), ...}. (Although this problem is intrinsically and
# A question in the sixth chapter is similar, when two solutions have no direct connection) then create another solution with the zip built-in function.
#map (func, parameter) returns the mapped value of all parameters
print ' 11-7 '
AList1 = [1,2,3,4,5]
AList2 = [' abc ', ' Def ', ' Ghi ', ' jkl ', ' MnO ']
Print map (NONE,ALIST1,ALIST2)
# 11–8. Functional programming with filer (). Use exercise 5-4 to determine the leap year using the code you gave. Update your code One
# side He becomes a function if you haven't done that yet. Then write a code to give a list of the year and return a
# There is a list of leap years. Then turn it into a list resolution.
#filter (func, parameter) returns a parameter of 1, filtering
Def is_runyear (year):
if (year%4 = = 0 and year%100! = 0) or (year%400 = = 0):
Return 1
Else
return 0
Alist = [1996,2000,2001,2002,2003,2004,1900]
Print filter (is_runyear,alist)
print [n for n in alist if Is_runyear (n)]
# 11–9. Use reduce () for functional programming. Review the 11.7.2 section, explaining how to use the reduce () number set of tired
# Add the code. Modify it to create a function called average () to calculate a simple average of each set of numbers.
Alist = [1,3,5,7,9]
def average (list):
sum = reduce ((lambda x,y:x+y), alist)
Return Sum/len (alist)
Print average (alist)
# 11–11. Use map () for functional programming. Write a use file name and by removing all the rows in each row and the end of the empty
# White to "clean" the file. Read in the original file and write a new file, create a new one or overwrite the existing one.
# give your users a choice to decide which one to execute. Convert your solution to use list parsing.
#每一行输入保存到1. txt, read 1.txt processing files,
#每行输入保存到文件1. Txt
"'----------iterate over the file---------------'"
f = open (' 2.txt ', ' R ')
lines = F.readlines ()
def func (s):
S.split ()
For Eachline in lines:
Print Eachline,len (eachline)
Print Len (Eachline.split ())
Print map (func,eachline)
str1 = ' 12345 '
str2 = ' Efghi '
Print map (NONE,STR1)
def chuli (line):
return Line.strip ('/n ')
Filename= ' 2.txt '
F=open (filename, ' R ')
Lines=f.readlines ()
F.close ()
Choosen=0
While not choosen:
File_choose=raw_input ("Which file would you save? Choose:
(N) EW file
(O) LD file
‘‘‘)
Choose=file_choose.strip () [0].lower ()
If choose not in ' no ':
print ' Choose Invalid '
Elif choose== ' n ':
File=raw_input (' Enter your new file name: ')
Choosen=1
Else
File=filename
Choosen=1
F=open (file, ' W ')
For line in Map (chuli,lines):
F.write ('%s/n '%line)
F.close ()
# "--------------------Output to File-------------"
# filename = raw_input (' Enter file name: ')
# fobj = open (filename, ' W ')
# #会覆盖原文件
# for Eachline in lines:
# Print Eachline,
# fobj.write ('%s%s '% (LINE1,OS.LINESEP))
# 11–13. Use reduce () for functional programming and recursion. In the 8th, we see the factorial of N or n! as
# The product of all numbers from 1 to N.
# (a) write a simple compact function named Mult (x, y) with X, Y and return their product in one minute.
# (b) Calculate the factorial using the mult () function you created in a and reduce.
# (c) completely discard the use of mult () and replace it with the LAMDA expression.
# (d) In this chapter, we describe a recursive solution to find n! with the Timeit () function you completed in the above question,
# and give the three version factorial function timing (iterative, reduce () and recursive
def mult (x, y):
Return X*y
#q求5!
Print reduce (Mult,range (1,6))
Print reduce (lambda x,y:x*y,range (1,6))
Python core Programming Chapter 11 function exercises