educoder: Python function (2)※

Level 1: Parameters of Functions - Bricks to Build Function Houses

mission details

When we need to perform the same type of task multiple times in the program, we don't need to repeatedly write code segments to complete the task, but can use function tools to greatly facilitate our programming work. Functions are reusable pieces of code used to implement associated functionality.

The goal of this training is to let readers understand and master the relevant knowledge of the function structure, and the small goal of this level is to let the readers first understand and master the relevant knowledge of function parameters.

related information

Before we use a function, we must first define a function that meets our own requirements. The basic structure for defining a function is:

  1. def functionname( parameters ):
  2. "函数_文档字符串"
  3. function_suite
  4. return [expression]
  • The definition function defstarts with a keyword, followed by the function name, parentheses (), parameters in parentheses, and a colon;
  • Then, write the function body in the indented block. The first line of the function is usually written as a document string, which is used to store the function description, or you can choose not to write it;
  • Return[expression]Indicates the end function and returns a value. Without an expression returnis equivalent to returning a null value.

The focus of this level is to study the parameters of the function parameters. When defining a function, the names and positions of the parameters are determined, and the interface definition of the function is also completed. When we call a function, we only need to know what parameters to pass. The internal operation of the function has been encapsulated, and the user does not need to understand it.

PythonThe function parameters mainly include the following:

  • Required parameters;
  • Default parameters;
  • variable parameter;
  • keyword arguments.

required parameter

Mandatory parameters are also called positional parameters, which are the most commonly used parameters in functions. Mandatory parameters are parameters that must be specified when calling a function, for example:

  1. #定义加法函数plus,参数a,b就是必选参数
  2. def plus(a,b):
  3. c=a+b
  4. return(c)
  5. #调用函数plus时,必须给参数a,b传递值
  6. d=plus(1,2)
  7. #输出结果d
  8. print(d)

Output result:

3

If plusthe parameters passed in do not meet the requirements when calling the function, for example:

>>d = plus() TypeError: plus() missing 2 required positional arguments: 'a' and 'b'

>>d = plus(1) TypeError: plus() missing 1 required positional argument: 'b'

default parameters

A default parameter refers to providing a default value for a function parameter. If no value is passed to the parameter when the function is called, the parameter uses the default value. For example:

  1. #定义加法函数plus,参数a是必选参数,参数b是默认值2的参数
  2. def plus(a,b=2):
  3. c=a+b
  4. return(c)
  5. #调用函数plus时,必须给参数a传递值,若不给b传递值,则b默认为2
  6. d=plus(1)
  7. #输出结果d
  8. print(d)

As can be seen from the above example, there is no need to pass parameter values ​​to default parameters during function calls. But when using default parameters, there are two points to note:

  • Default parameters should be placed after all required parameters;
  • Default arguments must point to immutable objects.

variable parameter

In some cases, when we define a function, we cannot determine how many parameters the function should contain. At this time, we can use variable parameters, which means that the number of parameters passed in is variable. For example:

  1. #定义plus函数,完成的功能是返回输入的整数之和。
  2. # 参数numbers是可变参数,表示输入的参数个数可以为任意值
  3. def plus(*numbers):
  4. add = 0
  5. for i in numbers:
  6. add += i
  7. return(add)
  8. #调用3次plus函数,每次的参数个数都不相同
  9. d1 = plus(1,2,3)
  10. d2 = plus(1,2,3,4)
  11. d3 = plus(1,3,5,7,9)
  12. #向函数中可以传递任意参数,包括0个参数
  13. d4 = plus()
  14. #输出结果
  15. print(d1)
  16. print(d2)
  17. print(d3)
  18. print(d4)

Output result:

6 10 25 0

In the above example, numbersit is a variable parameter, and an identifier is added in front of the variable parameter *. Inside the function, numbersthe value received by the variable parameter is one tuple.

When we call a function whose parameters are variable parameters, we can pass any number of parameters to the function, including 0parameters.

keyword arguments

Variable parameters allow us to pass in any number of parameters when calling a function, and these variable parameters are automatically assembled into one when the function is called tuple.

The keyword parameters allow us to pass in any number of parameters with parameter names, and these keyword parameters are automatically assembled into one when the function is called dict. That is, keyword arguments pass key-value pairs of any length, as arguments, to functions.

  1. #定义一个包含关键字参数的函数,返回值为参数值
  2. def plus(**kw):
  3. return kw
  4. #调用plus函数,参数值为空
  5. d1 = plus()
  6. #调用plus函数,参数值为x=1
  7. d2 = plus(x=1)
  8. #调用plus函数,参数值为x=1,y=2
  9. d3 = plus(x=1, y=2)
  10. #输出d1,d2,d3
  11. print(d1)
  12. print(d2)
  13. print(d3)

Output result:

{} {'x': 1} {'x': 1, 'y': 2}

In the above example, kwit is a keyword parameter, and two *words are added in front of the keyword parameter. The keyword parameter can expand the function of the function and make the process of passing parameters easier, for example:

  1. #定义一个plus函数,有3个参数,返回值是3个参数之和
  2. def plus(x,y,z):
  3. return x+y+z
  4. #有一个dict列表,当中3个键的值分别为1,2,3
  5. dict = {'x':1, 'y':2, 'z':3}
  6. #将dict列表中的3个值传入plus函数中,得到返回值d
  7. d = plus(dict['x'],dict['y'],dict['z'])
  8. #输出d
  9. print(d)

Output result:

6

But in the above example, plusthe method of passing parameters from the value in the dictionary to the function is too cumbersome, and the method of keyword parameters can be adopted. For example:

  1. #定义一个plus函数,有3个参数,返回值是3个参数之和
  2. def plus(x,y,z):
  3. return x+y+z
  4. #有一个dict列表,当中3个键的值分别为1,2,3
  5. dict = {'x':1, 'y':2, 'z':3}
  6. #用关键字参数的方法将dict列表中的3个值传入plus函数中,得到返回值d
  7. d = plus(**dict)
  8. #输出d
  9. print(d)

Output result:

6

The method of using keyword parameters **dictcan greatly improve the efficiency of parameter passing.

parameter combination

In the process of function definition, we can use one or more of mandatory parameters, default parameters, variable parameters, and keyword parameters at the same time. However, it is important to note that these four parameters are in order during use, and the order should be mandatory parameters, default parameters, variable parameters, and keyword parameters.

For example:

  1. #定义一个包含必选参数、默认参数、可变参数和关键字参数的函数plus
  2. def plus(x, y, z=0, *args, **kw):
  3. print('x=',x)
  4. print('y=',y)
  5. print('z=',z)
  6. print('args=',args)
  7. print('kw=',kw)
  8. #调用函数plus,输入两个参数1,2
  9. plus(1,2)

Output result:

  1. x= 1
  2. y= 2
  3. z= 0
  4. args= ()
  5. kw= {}

In the above example , plustwo mandatory parameters 1and are passed into the function 2. The mandatory parameters must provide values, but the default parameters, variable parameters and keyword parameters do not need to provide values.

We can also pass values ​​to default parameters, variadic parameters and keyword parameters, for example:

  1. 定义一个包含必选参数、默认参数、可变参数和关键字参数的函数plus
  2. def plus(x, y, z=0, *args, **kw):
  3. print('x=',x)
  4. print('y=',y)
  5. print('z=',z)
  6. print('args=',args)
  7. print('kw=',kw)
  8. #调用函数plus,输入参数x=1,y=2,z=3,args=(4,5,6),kw={}
  9. plus(1,2,3,4,5,6)
  10. print('\n')
  11. #调用函数plus,输入参数x=1,y=2,z=3,args=(4,5,6),kw={'k':7, 'm':8}
  12. plus(1,2,3,4,5,6,k=7,m=8)

Output result:

  1. x= 1
  2. y= 2
  3. z= 3
  4. args= (4, 5, 6)
  5. kw= {}
  6. x= 1
  7. y= 2
  8. z= 3
  9. args= (4, 5, 6)
  10. kw= {'k': 7, 'm': 8}

summary

  • Different types of parameters are ordered, followed by mandatory parameters, default parameters, variable parameters and keyword parameters;
  • Default parameters must use immutable objects, and using variable objects is prone to logic errors;
  • *argsRepresents variable parameters and *argsreceives a tuple;
  • **kwRepresents keyword arguments and **kwreceives a dictionary.

programming requirements

The programming task of this level is to complete src/Step1/plus.pythe code of the file and realize the corresponding function. Specific requirements are as follows:

  • Define a function plus, the function is to accumulate the numerical elements in the parameter (a list), and the number of elements in the list is uncertain;
  • The function returns the accumulated result.

The code framework of the code files involved in this level src/Step1/plus.pyis as follows:

  1. #coding=uft-8
  2. #创建一个空列表numbers
  3. numbers = []
  4. #str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表
  5. str = input()
  6. lst1 = str.split(' ')
  7. #将输入的数字字符串转换为整型并赋值给numbers列表
  8. for i in range(len(lst1)):
  9. numbers.append(int(lst1.pop()))
  10. # 请在此添加函数plus的代码,函数参数为一个列表
  11. #********** Begin *********#
  12. #********** End **********#
  13. d = plus(numbers)
  14. print(d)

Test instruction

The test file of this level is src/Step1/plus.py, the test process is as follows:

  1. The platform automatically compiles and generates plus.exe;
  2. The platform runs plus.exeand provides test input as standard input;
  3. The platform takes plus.exethe output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.

The following is src/Step1/plus.pya sample test set for a platform pair:

Test Input: 1 2 3 4 5Expected Output:15

Test Input: 1 3 5 7 9 11Expected Output:36

Test Input: 2 4 6 8 10 12 14 16Expected Output:72


Let's start your mission, I wish you success!

Even though I have nothing to do every day, I don't feel a little bit relaxed. Why don't you go exercise

If you think the content of this level is helpful to you, please like it below.

code:

#coding=utf-8

#创建一个空列表numbers
numbers = []

#str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表
str = input()
lst1 = str.split(' ')

#将输入的数字字符串转换为整型并赋值给numbers列表
for i in range(len(lst1)):
   numbers.append(int(lst1.pop()))

# 请在此添加函数plus的代码,函数参数为一个列表,对列表中的数值元素进行累加求和
#********** Begin *********#
def plus(numbers):
   add=0
   for i in numbers:
      add+=i
   return add
#********** End **********#

#调用plus函数,并将返回结果存储到变量d中
d = plus(numbers)
print(d)








Level 2: The return value of the function - dispensable return

mission details

After the function performs operation processing, the value returned is called the return value. The value returned by the function is returnexecuted through the statement. The return value allows us to directly get the result of the function processing without having to care about the complex and heavy calculation process inside the function, which greatly improves the programming efficiency.

The main goal of this level is to let readers understand and master the relevant knowledge of function return values.

related information

returnThe statement returns the value to the exit of the calling function, and the function must have returna return value to be a complete function. If we don't define the function return value in the function, then the program will automatically let the function return a result, which is Nonean object, and Nonethe object means that there is no value.

return value as

There is only one return value of a function, but sometimes we find that some functions seem to have multiple return values. In fact, the "multiple" here does not mean multiple return values. For example, a function returns a list containing many element values. This is similar to: only one box can be taken away from the supermarket, but we are allowed to put some things in the box as one thing to take away. For example:

  1. def f():
  2. return 1,'abc','1234'
  3. print(f())

Output result:

(1, 'abc', '1234')

When the function is called f(), the output of the program is a tuple, so the return value of the function is a value on the surface 3, but in fact it returns a tuple, which contains three different elements (the tuple syntax does not need to be enclosed in parentheses).

function as return value

In addition to using various types of values ​​as return values, we can also use functions as return values.

For example, we want to define a function to calculate the sum of the numerical elements in the list. Generally, we define it like this:

  1. def plus(*args):
  2. s = 0
  3. for n in args:
  4. s = s + n
  5. return s

However, what if we don't need to sum immediately, but calculate according to the needs in the later program? At this time, the function we define may not return the result of the summation, but return the function of calculating the summation!

So we can also define functions as follows:

  1. def lazy_plus(*args):
  2. def plus():
  3. s = 0
  4. for n in args:
  5. s = s + n
  6. return s
  7. return plus

When we call lazy_plus(), what is returned is not the result of the sum, but a function that calculates the sum:

  1. #定义求和函数,返回的并不是求和结果,而是计算求和的函数
  2. def lazy_plus(*args):
  3. def plus():
  4. s = 0
  5. for n in args:
  6. s = s + n
  7. return s
  8. return plus
  9. #调用lazy_plus()时,返回的并不是求和结果,而是求和函数
  10. f = lazy_plus(1,2,3,4,5)
  11. print(f)

Output result:

<function lazy_plus.<locals>.plus at 0x000001DAC97F9950>

fThe result of the summation is actually calculated when the function is called :

  1. #定义求和函数,返回的并不是求和结果,而是计算求和的函数
  2. def lazy_plus(*args):
  3. def plus():
  4. s = 0
  5. for n in args:
  6. s = s + n
  7. return s
  8. return plus
  9. #调用函数f时,得到真正求和的结果
  10. f = lazy_plus(1,2,3,4,5)
  11. print(f())

Output result:

15

In the above example, we lazy_plusdefined the function in the function plus, and the internal function pluscan refer to lazy_plusthe parameters and local variables of the external function. When the function lazy_plusreturns to the function plus, the relevant parameters and variables will also be saved in the returned function. This method is also called “闭包(Closure)”.

Summary: In addition to the value calculated by the function as the return value, we can also use the function as the return value.

If you want to know more about list operations, please refer to: 【美】Eric Matthes著《Python编程——从入门到实践》第八章.

programming requirements

The programming task of this level is to complete src/step2/return.pythe code of the file and realize the corresponding function. Specific requirements are as follows:

  • Define a function gcd, the function is to find the greatest common divisor of two positive integers;

The code framework of the code files involved in this level src/step2/return.pyis as follows:

  1. #coding=utf-8
  2. #输入两个正整数a,b
  3. a = int(input())
  4. b = int(input())
  5. # 请在此添加函数gcd代码,求两个正整数的最大公约数
  6. #********** Begin *********#
  7. #********** End **********#
  8. #调用函数,并输出最大公约数
  9. print(gcd(a,b))

Test instruction

The test file of this level is src/step2/return.py, the test process is as follows:

  1. The platform automatically compiles and generates return.exe;
  2. The platform runs return.exeand provides test input as standard input;
  3. The platform takes return.exethe output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.

The following is src/step2/return.pya sample test set for a platform pair:

Test Input: 1 8Expected Output:1

Test Input: 9 3Expected Output:3

Test Input: 9 21Expected Output:3

Test Input: 126 36Expected Output:18


Let's start your mission, I wish you success!

There is always someone who is better, more handsome, and more self-satisfied than yourself. Accept this reality, but you still want to be the king in your heart.

If you think the content of this level is helpful to you, please like it below.

code:

#coding=utf-8

#输入两个正整数a,b
a = int(input())
b = int(input())

# 请在此添加函数gcd代码,求两个正整数的最大公约数
#********** Begin *********#
def gcd(a,b):
    if a<b:
        t=a
        a=b
        b=t
    while b:
        maxs=a%b
        a=b
        b=maxs
    return a

#********** End **********#

#调用函数,并输出最大公约数
print(gcd(a,b))


Level 3: Scope of use of functions: Python scope

mission details

Functions have a scope of use. In a module, we can define many functions and variables, but we hope that some functions and variables can be used by others, and some functions and variables can only be used inside the module. That's Pythonthe problem with scope.

The goal of this chapter is to let readers understand and master the scope of use of functions, that is, the Pythonrelevant knowledge of scope.

related information

In Python, normal function and variable names are public ( public) and can be directly referenced, such as: abs(), abc, dir()and so on.

Variables like __xxx__this format are special variables that are allowed to be referenced directly, but will be used for special purposes, for example __author__, __name__are special variables. helloThe documentation comments defined by the module can also be accessed with special variables __doc__, and the variables defined by our own programming generally do not use such variable names.

Functions and variables similar _xxxto __xxxthis format are non-public ( private) and should not be referenced directly.

Supplement: _xxxThe functions and variables are protectedthat we directly access from the outside will not generate exceptions. __xxxFor functions and variables private, we will report an exception when we directly access them from the outside. We should pay attention to the difference in prefix symbols.

We should pay attention to the difference in terms, we say that privatefunctions and variables "should not" be directly referenced, not "cannot" be directly referenced, this is because there is no Pythonway to really completely restrict access to privatefunctions or variables. variable. But in order to develop good programming habits, we should not refer to privatefunctions or variables.

privateThe function of the function is to hide the internal logic of the function, so that the function has better encapsulation.

For example:

  1. def _private_1(name):
  2. return 'Hello, %s' % name
  3. def _private_2(name):
  4. return 'Hi, %s' % name
  5. def greeting(name):
  6. if len(name) > 3:
  7. return _private_1(name)
  8. else:
  9. return _private_2(name)

We expose greeting()the function in the above program block, greeting()the function needs to use _private_1()and _private_2()the function, and the reader does not need to know greeting()the internal implementation details of the function. So we can privatehide the internal logic with functions. This is a very common method of code encapsulation.

Summary: In order to make the encapsulation of the program better, we generally limit the scope of use of functions. Generally, we define functions that need to be used externally as functions, publicand define functions that are only used internally and do not need to be referenced externally as functions private.

programming requirements

The programming task of this level is to complete src/step3/scope.pythe code of the file and realize the corresponding function. Specific requirements are as follows:

  • Write a program whose function is to find the least common multiple of two positive integers;
  • Required implementation method: first define a privatefunction  _gcd()to find the greatest common divisor of two positive integers, and then define publica function lcm()call  _gcd()function to find the least common multiple of two positive integers.

The code framework of the code files involved in this level src/step3/scope.pyis as follows:

  1. #coding=utf-8
  2. #输入两个正整数a,b
  3. a = int(input())
  4. b = int(input())
  5. # 请在此添加一个private函数_gcd()求两个正整数的最大公约数
  6. #********** Begin *********#
  7. #********** End **********#
  8. # 请在此添加一个public函数lcm(),通过调用_gcd()求两个正整数的最小公倍数
  9. #********** Begin *********#
  10. #********** End **********#
  11. #调用函数,并输出a,b的最小公倍数
  12. print(lcm(a,b))

Test instruction

The test file of this level is src/step3/scope.py, the test process is as follows:

  1. The platform automatically compiles and generates scope.exe;
  2. The platform runs scope.exeand provides test input as standard input;
  3. The platform takes scope.exethe output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.

The following is src/step3/scope.pya sample test set for a platform pair:

Test Input: 5 6Expected Output:30

Test Input: 8 10Expected Output:40

Test Input: 16 24Expected Output:48

Test Input: 132 214Expected Output:14124


Let's start your mission, I wish you success!

There will be a lot of troubles and difficulties in the journey, we need to endure, but also to solve, Yu Minhong once said: Persevere, not because we are strong enough, but because we have no choice.

If you think the content of this level is helpful to you, please like it below.

code:

#coding=utf-8

#输入两个正整数a,b
a = int(input())
b = int(input())

# 请在此添加一个private函数_gcd()求两个正整数的最大公约数
#********** Begin *********#
def gcd(a,b):
    if a<b:
        t=a
        a=b
        b=t
    while b:
        maxs=a%b
        a=b
        b=maxs
    return a

#********** End **********#

#请在此添加一个public函数lcm(),在lcm()函数中调用_gcd()函数,求两个正整数的最小公倍数
#********** Begin *********#

def lcm(a,b):
    return int(a*b/gcd(a,b))


#********** End **********#


#调用函数,并输出a,b的最小公倍数
print(lcm(a,b))

Level 4: Function Comprehensive Training※

mission details

The task of this level: use the knowledge of functions to complete the following exercises.

Relevant knowledge (omitted)

programming requirements

Begin-EndAccording to the prompt, supplement the code in the editor on the right to complete the following requirements:

first question

If the three sides of a triangle are a, b, c, respectively p=(a+b+c)/2, then the area of ​​the triangle is:

S=p(p−a)(p−b)(p−c)​

In this question, we will use triAreathe function to calculate the area of ​​the shaded part in the figure below, and print out the result. Your task is to program a function triArea(a,b,c)to calculate the area of ​​a triangle using the above formula.

second question

This question uses programming to verify Goldbach's conjecture, that is, any even number greater than or equal to 6 can be expressed as the sum of two prime numbers. For example: 11111112 = 11 + 11111101. Your task: 1) Implement a program isPrime(x)to determine xwhether an integer is a prime number; 2) The program will use the function Goldbach(N)to Ndecompose an integer into the sum of two prime numbers to verify Goldbach's conjecture. You need to complete the function code.

third question

It is known that the initial launch velocity of a certain type of mortar is 300m/s, the projectile has no power during flight, and the air resistance is not considered, and the acceleration due to gravity is taken as 9.8m2/s. Under different angles, the landing time and flying position of the shell are different. This question uses programming to draw [30, 45, 60, 75]the trajectory of the bomb when the angles are degrees. The function calculates position coordinates calBombT\frace(theta)during the flight of the shell , and the time samples are evenly distributed. nYour task is to complete the program code.

The calculation logic example is as follows (rounding is not required when programming):

When the angle is 30degrees, the flight time of the bomb in the air is about 30.6s,

If 5a uniform time sample is taken, they are approximately[ 0, 7.6, 15.3, 22.9, 30.6 ]

Then the corresponding xcoordinates are[0,1988, 3976, 5964, 7953]

The corresponding ycoordinates are then[ 0, 860,1147, 860, 0 ]

fourth question

As shown, the equation of the uniform function is

f(x)=exsin(x)

Find [0,pi]the length of the function curve in the interval. Your task: 1) Write a function f(x)to calculate the value of the above function; 2) Write a function pt(a, b)to calculate the length of the hypotenuse of a right triangle using the Pythagorean theorem.

Tip: Divide the interval into nsmall intervals, and the curve can be approximated as a line segment. When the number of intervals in the small interval is large enough, the approximate length is close to the real value.

Test instruction

The platform will test the code you write: Test input:

60

30

Expected output:

  1. 24.201994
  2. 60 = 7 + 53
  3. [0.0, 158.339198, 316.678395, 475.017593, 633.356791, 791.695989, 950.035186, 1108.374384, 1266.713582, 1425.05278, 1583.391977, 1741.731175, 1900.070373, 2058.409571, 2216.748768, 2375.087966, 2533.427164, 2691.766362, 2850.105559, 3008.444757, 3166.783955, 3325.123153, 3483.46235, 3641.801548, 3800.140746, 3958.479944, 4116.819141, 4275.158339, 4433.497537, 4591.836735]
  4. [0.0, 570.553037, 1100.352285, 1589.397745, 2037.689417, 2445.2273, 2812.011395, 3138.041702, 3423.31822, 3667.84095, 3871.609892, 4034.625045, 4156.88641, 4238.393987, 4279.147775, 4279.147775, 4238.393987, 4156.88641, 4034.625045, 3871.609892, 3667.84095, 3423.31822, 3138.041702, 2812.011395, 2445.2273, 2037.689417, 1589.397745, 1100.352285, 570.553037, 0.0]
  5. l = 15.476558

Let's start your mission, I wish you success!

code:

import numpy as np

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt     #导入matplotlib.pyplot
# 第一题
######## begin ###########
# 请编写函数triArea(a ,b , c),返回三角形的面积
def triArea(a,b,c):
    p=((a+b+c)/2)
    S=pow(p*(p-a)*(p-b)*(p-c),1/2)
    return(S)
######## end #########
S1 = triArea(9.8, 9.3, 6.4)
S2 = triArea(2.9, 4.1, 4.7)
S3 = triArea(2.0, 1.4, 2.3)
print('%.6f' %(S1-S2+S3))
# 第二题
######## begin ###########
# 请编写函数isPrime(x)。判断x是否是素数,返回True或者False
def isPrime(x):
    n=0
    for i in range(2,x//2):
         if x%i==0:
            n+=1
    if n==0:
        return("True")
    else:
        return("False")
#######  end    ############
def Goldbach(N):  # 将N分解成两素数之和
    if N < 6 or N % 2 == 1:  # 若N小于6或N为奇数
        print('N应该是大于等于6的偶数')
    else:
        # 循环判断,得到符合要求的小于N的两个素数,并打印
        for x in range(2, N // 2):  # 想想为什么是从2到N/2
            # 调用isPrime函数,得到符合要求的小于N的两个素数
            ######## begin ###########
            if isPrime(x)=="True" and isPrime(N-x)=="True":
            ######## end ###########
                print(N, '=', x, '+', N - x)
                break
N = int(input())
Goldbach(N)
# 第三题
# calBombTrace 函数
def calBombTrace(theta):
    v0, g, n = 300, 9.8, 30
    theta_d = np.radians(theta)     #因numpy中cos、sin的输入为弧度值,故先将theta从度转换为弧度
    v0_x = v0*np.cos(theta_d)       #炮弹水平初速度
    v0_y = v0*np.sin(theta_d)       #炮弹垂直初速度
    tmax = 2*v0_y/g                 #落地时间,即v0_y*t-0.5gtt=0的解
    t = np.linspace(0, tmax, n)     #n个时刻
    xt = v0_x*t                     #n个时刻的横坐标
    yt = v0_y*t-1/2*g*t**2          #n个时刻的纵坐标
    return xt, yt
for theta in [30, 45, 60, 75]:
    ############ begin #########
    # 调用函数,得到theta返回的值,并存储到xt与yt变量
    xt,yt=calBombTrace(theta)
    ########### end #############
    plt.plot(xt, yt)
plt.grid('on')
plt.axis([0, 10000, 0, 5000])
plt.savefig('./src/step4/res/轨迹.png')
plt.close()
print([round(x,6) for x in xt])
print([round(x,6) for x in yt])
# 第四题
# 在此添加代码,编写函数f(x),计算f(x)的值
from math import * 
########### begin #############
def f(x):
    a=((np.e)**x)*(np.sin(x))
    return(a)
########### end #############
# 在此添加代码,编写函数pt(a, b),利用勾股定理计算直角三角形的斜边长
########### begin #############
def pt(a, b):
    c=pow(a**2+b**2,1/2)
    return(c)
########### end ############
n = 1000  # 细分成n个子区间
x = np.linspace(0, np.pi, n + 1)  # n个子区间的n+1个端点
l, h = 0, np.pi / n  # l为曲线长度、h为子区间宽度
for i in range(n):  # 对每个子区间
    li = pt(f(x[i + 1]) - f(x[i]), h)  # 曲线在第i个子区间的近似长度
    l += li  # 将航渡累加到l中
print('l = %.6f' %l)

Guess you like

Origin blog.csdn.net/weixin_62174595/article/details/127532865