Hello, I’m Yue Chuang. This article is my private education students, the question, the topic difficulty is very simple, interested can have a look.
Subject scope
Homework 7:
Writing a function to compute the product of one or an unspecified number of numbers (Exercises 8-6, Fundamentals of Python Programming and Applications)
1. Function interface definition:
def caculate(*t)
Copy the code
The * parameter t accepts multiple parameter members, which are expected to be of integer or floating point type. Linke: www.aiyc.top/126.html
The use of the * args
*args and **kwargs are primarily used for function definitions. You can pass an indefinite number of arguments to a function. It is not known in advance how many arguments the function user will pass to you, so use these two keywords in this scenario. * ARgs is used to send a variable number of arguments to a function that are not key-value pairs. Here’s an example to help you understand this concept:
def test_var_args(*args) :
print(args)
print(type(args))
test_var_args('yasoob'.'python'.'eggs'.'test')
# output
('yasoob'.'python'.'eggs'.'test')
<class 'tuple'>
Copy the code
We can see that the data type we get is a tuple.
def test_var_args(f_arg, *argv) :
print("first normal arg:", f_arg)
for arg in argv:
print("another arg through *argv:", arg)
test_var_args('yasoob'.'python'.'eggs'.'test')
# output
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test
Copy the code
* ARgs: You can call it something else, but we’ll stick with args
I hope this clears up all your confusion. So let’s talk about ** Kwargs
The use of the * * kwargs
**kwargs allows you to pass key-value pairs of variable length as arguments to a function. If you want to handle named arguments in a function, you should use **kwargs.
def greet_me(**kwargs) :
print(kwargs)
print(type(kwargs))
for key, value in kwargs.items():
print("{0} = = {1}".format(key, value))
Print ("{1} == {0}". Format (key, value)) # print("{1} == {0}"
greet_me(name="yasoob", gzh='aiyuechuang', the_public='AI yue")
# output
{'name': 'yasoob'.'gzh': 'aiyuechuang'.'the_public': 'AI yue"}
<class 'dict'>
name= =yasoob
gzh= =aiyuechuang
the_public= =AIYue"Copy the code
Now you can see how we can handle a key-value pair argument in a function. This is the basis of ** Kwargs, and you can see how it works. Now let’s talk about how you can use *args and **kwargs to call a function that takes a list or dictionary.
use*args
和 **kwargs
To call the function
Now we’ll see how to call a function using *args and **kwargs. Suppose you have a little function like this:
def test_args_kwargs(arg1, arg2, arg3) :
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
Copy the code
As you can imagine, if there are many parameters, then the code is not very concise. You can use *args or **kwargs to pass arguments to this small function. Here’s how to do it:
# use *args first
>>> args = ("two".3.5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
# now use **kwargs:
>>> kwargs = {"arg3": 3."arg2": "two"."arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3
Copy the code
Standard parameter and* args, * * kwargs
The order in which it is used
So if you want to use all three arguments in a function at the same time, this is the order:
some_func(fargs, *args, **kwargs)
Copy the code
When to use them?
It really depends on your needs. The most common use case is when writing function decorators. It can also be used to make monkey patching. Monkey patch means modifying some code while the program is running. Let’s say you have a class with a function called get_info that calls an API and returns the corresponding data. If we want to test it, we can replace the API calls with some test data. Such as:
import someclass
def get_info(self, *args) :
return "Test data"
someclass.get_info = get_info
Copy the code
I’m sure you can imagine some other use cases as well.
2, the referee test procedure example:
s = input().split() # take the input string, split it by space, and store it in a list. The list members are strings
t = [float(x) for x in s] Use list derivation to convert all the members of list S to float numbers and store them in another list T
print("%.4f" % caculate(*t))
Copy the code
3. Input sample:
3 2 1
Copy the code
4. Output example:
6.0000
Copy the code
5, Coder
def caculate(*t) :
product = 1
for value in t:
product *= value
return product
Copy the code
6-3 Print all palindrome primes in the specified range (Python Programming Basics and Applications, Exercises 8-7) (6 marks)
A palindrome prime is a number that is both prime and palindrome. For example, 131 is both a prime and a palindrome. Please implement the following two functions to help the test program to perform the following functions: Enter a positive integer N from the keyboard and print all palindrome primes from 1 to N inclusive, one in a row.
A palindrome prime is an integer n (n≥11) read from left to right and from right to left: the result has the same value and is a prime “prime”, that is, n is called a palindrome prime. “1. Implementation Method”
There are no palindromic primes for even digits except 11. Four, six, eight… Numbers do not exist as palindromic primes. There are no even palindrome primes because the palindrome numbers with four or more even digits are divisible by 11. The first few palindrome primes: 11,101,131,151,181,191,313,353,373,383,727,757,787,797,919,929… There were 1 two-digit palindrome primes, 15 three-digit palindrome primes, 93 five-digit palindrome primes, 668 seven-digit palindrome primes and 5172 nine-digit palindrome primes.
1. Function interface definition:
def isPrime(num) :
def reverseNumber(num) :
Copy the code
IsPrime () is used to determine whether the integer num isPrime, returning True if it is, and False otherwise. ReverseNumber () is used to return the reverse of the integer num, 123 for 321 and 23 for 320.
2, the referee test procedure example:
N = int(input()) Get the number and convert it to an integer, and the N is a range
for n in range(1, N+1) :# range is closed on the left and open on the right, it doesn't get to the end of the number so you need + 1, and then loop through that range.
if isPrime(n) and reverseNumber(n) == n:
print(n)
Copy the code
3. Input sample:
400
Copy the code
4. Output example:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
Copy the code
5, Coder
1. Judgment method of prime numbers:
A natural number greater than 1 cannot be divisible by any natural number (2, 3, 5, 7, etc.) except 1 and itself. In other words, the number has no factors other than 1 and itself. Method one:
# the user enters a number
num = int(input(Please enter a number:))
# Prime numbers greater than 1
if num > 1:
# check factor
for i in range(2, num):
if (num % i) == 0: # must be divided by a number less than num to see if it is divisible
print(num,"Not prime.")
print(i, "Multiply", num//i, "Yes", num) If it is divisible, it is also possible to use //.
break
else:
print(num, "Is prime.")
# If the number entered is less than or equal to 1, it is not prime
else:
print(num, "Not prime.")
Copy the code
Method 2:
from math import sqrt
def is_prime(n) :
if n == 1:
return False
for i in range(2.int(sqrt(n))+1) :if n % i == 0:
return False
return True
Copy the code
** Method three:
def isPrime(num) :
if num == 1:
return 0
elif num == 2:
return 2
else :
from math import sqrt
active = True
for i in range(2.int(sqrt(num))+1) :if num % i == 0:
active = False
if active:
return num
else:
return 0
Copy the code
2. Integer inversion
Answer:First of all, how do you invert an integer? – use the stack? Or turn an integer into a string and then invert the string? These two ways are ok, but not good. In fact, we just need to get the end of the whole number. Take 12345 as an example, first get 5, then get 4, then 3,2,1, we can in this order to reverse concatenate a number, also can achievereverseThe effect. How do I get the end number? Easy to do, with modular operation can be.“Just do the mod operation”
1, 12345%10 get 5, then 12345/10 2, 1234%10 get 4, then 1234/10 3, 123%10 get 3, then 123/10 4, 12%10 get 2, You take 12/10, you take 5, you take 1 percent 10 to get 1, you take 1/10
So it looks like we’re done with a loop, and the loop says x is greater than 0 but that’s not true, because we’re ignoring negative numbers and the loop says while(x! =0), whether positive or negative, according to the above continuous /10 operation, will eventually become 0, so judge the termination condition is! =0 with modulo and division, numbers like 12300 can also be solved perfectly.
Looks like we’ve solved the problem:
def reverseNumber(num) :
res = 0
while(num ! =0):
tmp = num % 10
res = res * 10 + tmp
num = int(num / 10)
return res
if __name__ == '__main__':
print(reverseNumber(3456))
Copy the code
6-4 Integer digit sum (Higher Education Society, Fundamentals and Applications of Python Programming, Exercise 8-3) (4 marks)
Write a function that takes a positive integer as an argument and returns the sum of its digits.
1. Function interface definition:
def digitSum(v)
Copy the code
V is an input integer (positive integer); The function returns an integer whose value is the sum of v’s digits.
2, the referee test procedure example:
a = int(input())
print(digitSum(a))
Copy the code
3. Input sample:
291
Copy the code
4. Output example:
12
Copy the code
5, Coder
def digitSum(a) :
num_list = list(str(a))
tmp = 0
for i in num_list:
# tmp = tmp + int(i)
tmp += int(i)
return tmp
Copy the code
def digitSum(v) :
num_list = list(str(v))
a = 0
for i in range(0.len(num_list)):
a += int(num_list[i])
return a
Copy the code
Given this number, if it is in actual development, it is necessary to judge whether the input number is pure numbers.
F (I) = 1/2 + 2/3 + 3/4 +… + I /(I +1) + I /(I +1)
Write a function to calculate f(I) = 1/2 + 2/3 + 3/4 +… + I/(I + 1).
1. Function interface definition:
def f(i) :
Copy the code
I is a positive integer and returns the result as a floating point number.
2, the referee test procedure example:
v=int(input())
print("%.4f" % f(v))
Copy the code
3. Input sample:
5
Copy the code
4. Output example:
3.5500
Copy the code
5, Coder
def f(i) :
result = 0
for x in range(i+1):
current_num = x / (x + 1)
result += current_num
return result
Copy the code
Homework to 8:
6-1 Define and Implement the BODY mass Index category (Python Programming Basics and Applications, Exercise 9-3) (4 marks)
The following BMI category “**Body Mass Index” is designed to calculate Body Mass Index. The index is equal to weight in kilograms divided by height in meters squared.The corresponding criteria are shown in the figure below.
1. BMI Interface Definition:
class BMI:.Copy the code
A) name B) age C) height D) weight The getBMI() function returns the calculated BODY mass index; GetStatus () returns the evaluation, and the value should be one of ultralight/standard/overweight/obese.
2, the referee test procedure example:
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval((2, 2 'pow)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
Copy the code
sName = input(a)Enter a name
iAge = int(input()) # Input age
fHeight = eval(input()) # Enter the height, expected to be a floating point number in meters
fWeight = eval(input()) Enter the weight, expected to be a floating point number in kilograms
bmi=BMI(sName,iAge,fHeight,fWeight) # instantiate the BMI class
print("Name:",bmi.name)
print("Age:",bmi.age)
print("BMI = %.3f" % bmi.getBMI())
print("Result =",bmi.getStatus())
Copy the code
3. Input sample:
Alex
27
1.75
68
Copy the code
4. Output example:
Name: Alex
Age: 27
BMI = 22.204Result = standardCopy the code
5, Coder
class BMI:
def __init__(self,sName,iAge,fHeight,fWeight) :
self.name=sName
self.age=iAge
self.height=fHeight
self.weight=fWeight
def getStatus(self) :
m=fWeight/(fHeight**2)
if m<18:
return ("Lightweight")
elif m>=18 and m<25:
return ("Standard")
elif m>=25 and m<27:
return ("Overweight")
else:
return ("Obesity")
def getBMI(self) :
n=fWeight/(fHeight**2)
return n
Copy the code
6-2 Define and implement the Book class and its __del__ function (Fundamentals of Python Programming and Applications) (3 marks)
There are many books in the library. Please define a class named Book. The attributes of this class include title (string), isbn (string), unit price (float); The constructor of this class takes the title, isbn, and unit price parameters and takes them into object initialization. The del() function of this class prints the following information to the terminal: Book Destroyed – Title, isnumero, unit price Note: Unit price is kept two decimal places.
1. Class interface definition:
class Book:.Copy the code
2, the referee test procedure example:
sName = input(a)# Enter a title
sNo = input(a)# Enter the isbn
fPrice = float(input()) Input unit price
b = Book(sName,sNo,fPrice)
b = None Trigger the execution of the __del__ method of the b object
Copy the code
3. Input sample:
Python programming basics and applications888-999
43.678
Copy the code
4. Output example:
Book Destroyed -Python programming basics and Application,888-999.43.68
Copy the code
5, Coder
class Book:
def __init__(self,name,No,price) :
self.sName=name
self.sNo=No
self.fPrice=price
def name(self) :
return self.sName
def number(self) :
return self.sNo
def price(self) :
return self.fPrice
def __del__(self) :
print("Book destroyed-%s,%s,%.2f" %(self.sName,self.sNo,self.fPrice))
Copy the code
After an object is created, the Python interpreter calls the __init__() method by default. When an object is deleted, the Python interpreter also calls a method by default, which is the __del__() method. In Python, it is rare for developers to destroy objects directly (the del keyword should be used if necessary). Python’s memory management mechanism does the job quite well. That is, either a manual call to del or an automatic collection by Python triggers the __del__ method to execute:
import time
class Animal(object) :
# init method
It will be called automatically after the object is created
def __init__(self, name) :
print('the __init__ method is called')
self.__name = name
# destructor method
When an object is deleted, it is automatically called
def __del__(self) :
print("The __del__ method is called")
print("The %s object is immediately killed..." % self.__name)
# create object
dog = Animal(Happy Dog)
# delete object
del dog
cat = Animal(Persian cat)
cat2 = cat
cat3 = cat
print("-- Delete cat object now")
del cat
print("-- Delete cat2 object now")
del cat2
print("-- Delete cat3 object now")
del cat3
print("Program will be over in two seconds.")
time.sleep(2)
Copy the code
6-3 Designing quadratic Equations with one Variable (Fundamentals and Applications of Python programming, Exercises 9-4) (4 marks)
Design a Root class to compute the roots of ax+bx+c=0. The getDiscriminant() method returns b-4AC getRoot1() and getRoot2() returns two roots of the equation. Where, getRoot1() returns the root corresponding to:GetRoot2 () returns a root corresponding to:
1. Class interface definition:
class Root:
def __init__(self,a,b,c) :.Copy the code
2, the referee test procedure example:
a=float(input()) Please enter the quadratic coefficient
b=float(input()) Please enter the coefficient of the first term
c=float(input()) Please input the constant term coefficient
root=Root(a,b,c)
if root.getDiscriminant()>0:
print("{:.2f}".format(root.getRoot1()))
print("{:.2f}".format(root.getRoot2()))
elif root.getDiscriminant()==0:
print("{:.2f}".format(root.getRoot1()))
else:
print("No Root!")
Copy the code
3. Input sample:
2.1
10.2
3.0
Copy the code
4. Output example:
-0.31
-4.54
Copy the code
5, Coder
from math import sqrt
class Root:
def __init__(self, a, b, c) :
self.two = a
self.one = b
self.cs = c
def getDiscriminant(self) :
return b ** 2 - 4 * a * c
def getRoot1(self) :
m = b ** 2 - 4 * a * c
n = b * (-1) + sqrt(m)
return n / (2 * a)
def getRoot2(self) :
m = b ** 2 - 4 * a * c
n = b * (-1) - sqrt(m)
return n / (2 * a)
Copy the code
6-4 Design a stock class (Higher Education Society, Fundamentals of Python Programming and Applications, Exercise 9-6) (4 marks)
Design a class named Stock to represent the Stock of a company, including the following contents: 1) Stock code, Stock name, the Stock price of the previous day, the Stock price of the day four private attributes; 2) Constructor, need to initialize code, name, previous price, current price and other attributes; 3) Return the stock name of the get method; 4) The get method that returns the stock symbol; 5) Get and set the previous day’s stock price; 6) Get and set the current stock price; 7) The getChangePercent() method returns the percentage change from the previous day’s closing price to the current price; 8). Documentation string, the content is :”Stock Information Class” Note: For the name and parameter requirements of each method, please refer to the test program.
1. Class interface definition:
class Stock:.Copy the code
2, the referee test procedure example:
# 4 private attributes: stock code, stock name, stock price of the previous day and stock price of the day;
sCode = input(a)Enter the ticker symbol
sName = input(a)Enter the stock name
priceYesterday = float(input()) # Enter the previous day's stock price
priceToday = float(input()) # Enter today's stock price
# class: Stock
s = Stock(sCode,sName,priceYesterday,priceToday) Initialize the code
print("Code.", s.getCode())
print("Name:", s.getName())
print("Yesterday price :%.2f\n Today price :%.2f" % (s.getPriceYesterday(),s.getPriceToday()))
s.setPriceYesterday(50.25)
print("Corrected yesterday's price to :%.2f" % 50.25)
print("% change in price :%.2f%%" % (s.getChangePercent()*100))
print(Stock.__doc__)
Copy the code
3. Input sample:
601318China's ping an63.21
64.39
Copy the code
4. Output example:
Code:601318Name: China Ping an Yesterday price:63.21Today's price:64.39Revised yesterday's price to:50.25Percentage change in price:28.14%
Stock Information Class
Copy the code
5, Coder
class Stock:
'''Stock Information Class'''
def __init__(self, sCode, sName, priceYesterday, priceToday) :
self.sCode = sCode
self.sName = sName
self.priceYesterday = priceYesterday
self.priceToday = priceToday
def getCode(self) :
return self.sCode
def getName(self) :
return self.sName
def getPriceYesterday(self) :
return self.priceYesterday
def getPriceToday(self) :
return self.priceToday
def setPriceYesterday(self, new) :
self.priceYesterday = new
def setPriceToday(self, new) :
self.priceToday = new
def getChangePercent(self) :
return (self.priceToday - self.priceYesterday) / self.priceYesterday
Copy the code
6-5 design Shape base class and Circle, Rectangle inheritance class (” Python Programming Basics and Applications “Exercises 9-7) (5 marks)
Create a base class Shape that includes:
-
Property named sName (graphic name);
-
The constructor should initialize the sName attribute.
Rectangle class for Shape, including:
-
Length and width;
-
The Shape constructor calls the Shape constructor and initializes the length and width properties.
-
The getArea() member function calculates and returns the rectangle area.
Design Shape inheritance class Circle, including:
-
Radius attribute;
-
The constructor calls the Shape constructor and initializes the radius property.
-
The getArea() member function calculates and returns the circular area.
Note: Please read the sample test procedure to understand the interface requirements for the class.
1. Class interface definition:
class Shape:.class Rectangle(Shape) :.class Circle(Shape) :.Copy the code
2, the referee test procedure example:
s1 = Shape("shape0")
s = input(a)# rectangle name
w = float(input()) Width of rectangle
h = float(input()) Height of rectangle
r1 = Rectangle(s,w,h)
s = input(a)# the name of the circle
r = float(input()) # Radius of the circle
c1 = Circle(s,r)
print(s1.sName)
print("Rectangle %s area: %.2f" % (r1.sName,r1.getArea()))
print("Circle %s area: %.2f" % (c1.sName,c1.getArea()))
Copy the code
3. Input sample:
Jupyter
12.1
9.9
Moon
3.3
Copy the code
4. Output example:
Shape0 rectangular Jupyter area:119.79Circular Moon area:34.21
Copy the code
5, Coder
from math import pi
Create a base class Shape that includes:
class Shape:
def __init__(self, sName="") :
# attribute named sName (graphic name);
The constructor should initialize the sName attribute.
self.sName = sName
Rectangle class = Rectangle class = Rectangle class
class Rectangle(Shape) :
# length, width;
The Shape constructor calls the Shape constructor and initializes the length and width attributes.
def __init__(self, sName=' ', h=0.0, w=0.0) :
Shape.__init__(self, sName="")
self.h = h
self.w = h
self.sName = sName
The # getArea() member function calculates and returns the area of the rectangle.
def getArea(self) :
return h * w
# Create a Shape extension class Circle, including:
class Circle(Rectangle) :
# radius attribute;
The constructor calls the Shape constructor and initializes the radius property.
def __init__(self, sName=' ', r=0.0) :
Shape.__init__(self, sName="")
self.r = r
self.sName = sName
The # getArea() member function calculates and returns the circular area.
def getArea(self) :
area = pi * r ** 2
return area
Copy the code
6-6 Design the student class, using the class object attribute to record the number of student objects
Create a Student class named Student:
-
Use a class object property named count to record the number of Student objects;
-
Constructor for the initial chemistry number and name, and increment the count attribute by 1;
-
The destructor (del) subtracts the class object attribute count by one.
Note: Please read the sample test procedure to understand the interface requirements for the class.
1. Class interface definition:
class Student.Copy the code
2, the referee test procedure example:
n = int(input()) # Enter the number of students, the number is greater than 1
s = []
for i in range(n):
s.append(Student("Code"+str(i),"Name"+str(i)))
del s[0] # delete a student, causing count to decrease by 1
print("Number of students :",Student.count)
for x in s:
print(x.code,x.name)
Copy the code
3. Input sample:
3
Copy the code
4. Output example:
Student Number:2
Code1 Name1
Code2 Name2
Copy the code
5, Coder
Create a Student class named Student:
class Student:
# use class object property named count to count the number of Student objects;
count = 0
def __init__(self, scode, sname) :
# create the initial chemical number and the name of the function and increment count by 1;
self.code = scode
self.name = sname
Student.count += 1
The destructor (__del__) subtracts the class object attribute count by 1.
def __del__(self) :
Student.count = Student.count - 1
Copy the code
6-7 Design counting set class to record the number of times each element is added to the set
Inherit from the set type and design a subtype called CountedSet. By overloading some functions of type SET, CountedSet can count and record the total number of times each element is put into the collection. Learn about the interface to this class through the judge test program.
1. Class interface definition:
class CountedSet(set) :.Copy the code
2, the referee test procedure example:
s = CountedSet()
while True: # q indicates the end of input
v = input(a)Enter a string
if(v! ="q"):
s.add(v)
else:
break
# Convert collection to list, sort incremental output
t = sorted(list(s))
print("Number of element values")
for x in t:
print(x,"-",s.getCount(x))
print("Number of elements in set :".len(s))
Copy the code
3. Input sample:
a
b
a
q
Copy the code
4. Output example:
The corresponding output is given here. Such as:
Number of element values a minus2
b - 1Number of elements in the set:2
Copy the code
5, Coder
class CountedSet(set) :
def __init__(self) :
set.__init__(self)
self.jishu = {}
def add(self, x) :
set.add(self, x)
self.jishu[x] = self.jishu.get(x, 0) + 1
def getCount(self, x) :
return self.jishu[x]
Copy the code