Python topic counseling-topics and topics

Python topic counseling-topics and topics

Hello, I am Yuechuang. This is a question and answer question for my private tutor. The difficulty of the question is very simple, so you can check it out if you are interested.

Question range

Assignment 7:

6-2 Write a function to calculate the product of one or more unspecified numbers (Higher Education Society, "Python Programming Fundamentals and Applications" Exercise 8-6) (4 points)

1. Function interface definition:

DEF caculate ( * T ) to copy the code

The parameter t marked with * accepts multiple parameter members, and the parameter members are expected to be of integer or floating point type. Knowledge points explain Linke: www.aiyc.top/126.html

Usage of *args

*args
with
**kwargs
Mainly used for function definition. You can pass an unlimited number of parameters to a function. The indeterminate meaning here is: I don't know in advance how many parameters the function user will pass to you, so these two keywords are used in this scenario.
*args
Is used to send a
variable number of parameter lists that are not key-value pairs to a function. Here is 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 code

We can find that the data type of the data obtained is 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 code

*args: You can change it to another name by yourself, but we write it by convention: args

I hope this solves all your confusion. Then let's talk about

**kwargs

** Usage of kwargs

**kwargs
Allows you to pass key-value pairs of variable length as parameters to a function. If you want to handle named parameters 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)) # The second one is mainly used to let students understand format greet_me(name= "yasoob" , gzh= 'aiyuechuang' , the_public= 'AI ' ) # Output { 'name' : 'yasoob' , 'gzh' : 'aiyuechuang' , 'the_public' : 'AI ' } < Class ' dict '> name == yasoob GZH == aiyuechuang the_public == the AI Wyatt record duplicated code

Now you can see how we deal with a key-value pair parameter in a function . This is

**kwargs
Foundation, and you can see how useful it is. Next let s talk about how you use
*args
with
**kwargs
To call a function whose parameters are lists or dictionaries.

use
*args
with
**kwargs
To call the function

So now we will see how to use

*args
with
**kwargs
To call a function. Suppose, you have such a small function:

DEF test_args_kwargs ( arg1, arg2, arg3 ): Print ( "arg1:" , arg1) Print ( "arg2:" , arg2) Print ( "arg3:" , arg3) copy the code

It can be imagined that if there are many parameters, the code is not very concise. you can use

*args
or
**kwargs
Let's pass parameters to this little function. Here is how to do it:

# First use *args >>> 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 parameters and
*args, **kwargs
In the order of use

Then if you want to use all three parameters at the same time in the function, the order is as follows:

some_func (fargs, * args, ** kwargs) copying the code

When to use them?

It really depends on your needs. The most common use case is when writing function decorators. In addition, it can also be used for monkey patching. Monkey patching means to modify certain code at runtime. For example, you have a class with a name called

get_info
The function will call an API and return the corresponding data. If we want to test it, we can replace the API call with some test data. E.g:

import someclass def get_info ( self, *args ): return "Test data" someclass.get_info = get_info Copy code

I'm sure you can also imagine some other use cases.

2. Sample referee test procedure:

s = input ().split() #Accept the input string and split it by spaces, store it in the list, the list members are string type t = [ float (x) for x in s] #Use list derivation to put list s the members of all converted into a floating-point number, into another list t Print ( "% .4f" % caculate (* t)) copy the code

3. Input sample:

. 3 2 . 1 duplicated code

4. Output sample:

6.0000Copy code

5. Coder

def caculate ( *t ): product = 1 for value in t: product *= value return productCopy code

6-3 Print all palindrome prime numbers within the specified range (Gaojiaosha, "Python Programming Fundamentals and Applications" Exercises 8-7) (6 points)

Knowledge point: a palindrome prime number refers to a number that is both a prime number and a palindrome number . For example, 131 is both a prime number and a palindrome number. Please implement the following two functions to help the test program complete the following functions: input a positive integer N from the keyboard, and print all palindrome prime numbers from 1 to N (including N) , one per line.

A palindrome prime refers to reading an integer n (n 11) from left to right and from right to left: the result value is the same and is a prime number "prime number" , that is, n is called a palindrome prime. "1. Implementation method"

Except for 11, there are no palindrome prime numbers for even-digit numbers . 4 digits, 6 digits, 8 digits... there are no palindrome prime numbers. Since palindrome numbers of four or more even digits are divisible by 11, there is no palindrome prime number of even digits. "2. Determine the digits of the input number" The first few palindrome prime numbers: 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929... There are 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 code

isPrime() num True , False reverseNumber() num 321 123 320 23

2

N = int(input()) # N for n in range(1, N+1): # range + 1 if isPrime(n) and reverseNumber(n) == n: print(n)

3

400

4

2 3 5 7 11 101 131 151 181 191 313 353 373 383

5 Coder

1

1 1 2, 3, 5, 7 1

# num = int(input(" : ")) # 1 if num > 1: # for i in range(2, num): if (num % i) == 0: # num print(num," ") print(i, " ", num//i, " ", num) # // break else: print(num, " ") # 1 else: print(num, " ")

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

**

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

2

12345 5 4 3 2 1

1 12345 % 10 5 12345/10 2 1234 % 10 4 1234/10 3 123 % 10 3 123/10 4 12 % 10 2 12/10 5 1 % 10 1 1/10

x>0 while(x!=0) /10 0 !=0 12300


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))

6-4 Python 8-3 (4 )

1

def digitSum(v)

v v

2

a = int(input()) print(digitSum(a))

3

291

4

12

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
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

6-5 f(i) = 1/2 + 2/3 + 3/4 + ... + i/(i+1) Python 8-4 (4 )

f(i) = 1/2 + 2/3 + 3/4 + ... + i/(i+1)

1

def f(i):

i

2

v=int(input()) print("%.4f" % f(v))

3

5

4

3.5500

5 Coder

def f(i) : result = 0 for x in range(i+1): current_num = x/(x + 1) result += current_num return result

8:

6-1 Python 9-3 (4 )

BMI **Body Mass Index ** kg) ( )

1 BMI

class BMI: ...

name age height weight kg getBMI() getStatus() ///

2

>>>x = 7 >>> eval( '3 * x' ) 21 >>> eval('pow(2,2)') 4 >>> eval('2 + 2') 4 >>> n=81 >>> eval("n + 4") 85
sName = input() # iAge = int(input()) # fHeight = eval(input()) # fWeight = eval(input()) # bmi=BMI(sName,iAge,fHeight,fWeight) # BMI print("Name:",bmi.name) print("Age:",bmi.age) print("BMI = %.3f" % bmi.getBMI()) print("Result =",bmi.getStatus())

3

Alex 27 1.75 68

4

Name: Alex Age: 27 BMI = 22.204 Result =

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 (" ") elif m>=18 and m<25: return (" ") elif m>=25 and m<27: return (" ") else: return (" ") def getBMI(self): n=fWeight/(fHeight**2) return n

6-2 Book __del__ Python 9-4 (3 )

Book del() Book destroyed- , ,

1

class Book: ...

2

sName = input() # sNo = input() # fPrice = float(input()) # b = Book(sName,sNo,fPrice) b = None # b __del__

3

Python 888-999 43.678

4

Book destroyed-Python ,888-999,43.68

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))

python __init__() python __del__() python ( del ) Python , del python __del__

import time class Animal(object): # # def __init__(self, name): print('__init__ ') self.__name = name # # def __del__(self): print("__del__ ") print("%s ..." % self.__name) # dog = Animal(" ") # del dog cat = Animal(" ") cat2 = cat cat3 = cat print("--- cat ") del cat print("--- cat2 ") del cat2 print("--- cat3 ") del cat3 print(" 2 ") time.sleep(2)

6-3 Python 9-4 (4 )

Root ax+bx+c=0 a b c 3 3 getDiscriminant() b-4ac getRoot1() getRoot2() getRoot1() getRoot2()

1

class Root: def __init__(self,a,b,c): ...

2

a=float(input()) # b=float(input()) # c=float(input()) # 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!")

3

2.1 10.2 3.0

4

-0.31 -4.54

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)

6-4 Python 9-6 (4 )

Stock 1 4 2 3 get ; 4 get ; 5 get set ; 6 get set ; 7 getChangePercent() 8). :"Stock Information Class"

1

class Stock: ...

2

# 4 sCode = input() # sName = input() # priceYesterday = float(input()) # priceToday = float(input()) # # Stock s = Stock(sCode,sName,priceYesterday,priceToday) # print(" :", s.getCode()) print(" :", s.getName()) print(" :%.2f\n :%.2f" % (s.getPriceYesterday(),s.getPriceToday())) s.setPriceYesterday(50.25) print(" :%.2f" % 50.25) print(" :%.2f%%" % (s.getChangePercent()*100)) print(Stock.__doc__)

3

601318 63.21 64.39

4

: 601318 : :63.21 :64.39 :50.25 :28.14% Stock Information Class

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

6-5 Shape Circle, Rectangle Python 9-7 (5 )

Shape

  1. sName

  2. sName

Shape Rectangle ,

  1. Shape

  2. getArea()

Shape Circle,

  1. Shape

  2. getArea()

1

class Shape: ... class Rectangle(Shape): ... class Circle(Shape): ...

2

s1 = Shape("shape0") s = input() # w = float(input()) # h = float(input()) # r1 = Rectangle(s,w,h) s = input() # r = float(input()) # c1 = Circle(s,r) print(s1.sName) print(" %s : %.2f" % (r1.sName,r1.getArea())) print(" %s : %.2f" % (c1.sName,c1.getArea()))

3

Jupyter 12.1 9.9 Moon 3.3

4

shape0 Jupyter : 119.79 Moon : 34.21

5 Coder

from math import pi # Shape class Shape: def __init__(self, sName=""): # sName # sName self.sName = sName # Shape Rectangle , class Rectangle(Shape): # # Shape def __init__(self, sName='', h=0.0, w=0.0): Shape.__init__(self, sName="") self.h = h self.w = h self.sName = sName # getArea() def getArea(self): return h * w # Shape Circle , class Circle(Rectangle): # # Shape def __init__(self, sName='', r=0.0): Shape.__init__(self, sName="") self.r = r self.sName = sName # getArea() def getArea(self): area = pi * r ** 2 return area

6-6

Student

  1. count Student

  2. count 1

  3. (del) count 1

1

class Student ....

2

n = int(input()) # 1 s = [] for i in range(n): s.append(Student("Code"+str(i),"Name"+str(i))) del s[0] # count 1 print(" :",Student.count) for x in s: print(x.code,x.name)

3

3

4

: 2 Code1 Name1 Code2 Name2

5 Coder

# Student class Student: # count Student count = 0 def __init__(self, scode, sname): # count 1 self.code = scode self.name = sname Student.count += 1 # (__del__) count 1 def __del__(self): Student.count = Student.count - 1

6-7

set CountedSet set CountedSet

1

class CountedSet(set): ...

2

s = CountedSet() while True: # q v = input() # if (v!="q"): s.add(v) else: break # t = sorted(list(s)) print(" ") for x in t: print(x,"-",s.getCount(x)) print(" :",len(s))

3

a b a q

4

a - 2 b - 1 : 2

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]