Python Language Basics - 2.5 functions

Off 1: parameter usage of function

  • The function plus is defined to accumulate the numerical elements in the parameter (a list), and the number of elements in the list is uncertain;
  • Function returns the cumulative result.
#Create an empty list numbers
numbers = []

#str is used to store the input numeric string. lst1 is used to divide the input string with spaces and store it as a list
str = input()
lst1 = str.split(' ')

#Converts the input numeric string to an integer and assigns it to the numbers list
for i in range(len(lst1)):
   numbers.append(int(lst1.pop()))

# Please add the code of function plus here. The function parameter is a list, and the numerical elements in the list are accumulated and summed
#********** Begin *********#
def plus(numbers):
   a=0
   for i in numbers:
      a+=i
   return(a)
#********** End **********#

#Call the plus function and store the returned result in variable d
d = plus(numbers)
print(d)

Level 2: return of function

Define a function gcd, whose function is to find the maximum common divisor of two positive integers

#Enter two positive integers a,b
a = int(input())
b = int(input())

# Please add the function gcd code here to find the maximum common divisor of two positive integers
#********** Begin *********#
def gcd(a,b):
    if a<b:
        a,b=b,a
    y=a*b
    y=a%b
    while y!=0:
        a=b
        b=y
        y=a%b
    return(b)
#********** End **********#

#Call the function and output the maximum common divisor
print(gcd(a,b))

Level 3: function scope: Python scope

  • Write a program to find the least common multiple of two positive integers;
  • Required implementation method: first define a private function_ GCD () finds the maximum common divisor of two positive integers, and then defines the call of public function lcm()_ gcd() function finds the least common multiple of two positive integers.
#Enter two positive integers a,b
a = int(input())
b = int(input())

# Please add a private function here_ gcd() finds the greatest common divisor of two positive integers
#********** Begin *********#
def _gcd(a,b):
    if a<b:
        a,b=b,a
    y=a*b
    y=a%b
    while y!=0:
        a=b
        b=y
        y=a%b
    return(b)
#********** End **********#

#Please add a public function lcm() here and call it in lcm() function. gcd() function, find the least common multiple of two positive integers
#********** Begin *********#
def lcm(a,b):
    return (a*b//_gcd(a,b))
#********** End **********#

#Call the function and output the least common multiple of a and B
print(lcm(a,b))

Level 4: function comprehensive training ※

First question

If the three sides of the triangle are a, B and C respectively, so that p=(a+b+c)/2, the area of the triangle is:

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

This problem will use the triArea function to calculate the area of the shadow part as shown in the figure below, and print the result. Your task is to program the function triArea(a,b,c) and use the above formula to calculate the area of the triangle.

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt     #Import matplotlib.pyplot
import matplotlib.image as imgplt

# Question 1: find the area of the shadow part of the triangle
# Please write the function triarea (a, B, c) to return the area of the triangle
from math import *
def triArea(a ,b , c):
    #Write the code below
    ######## begin ###########
    p=(a+b+c)/2
    Area=sqrt(p*(p-a)*(p-b)*(p-c))
    ######## end #############
   #Please do not modify the following code
    return Area 
   
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))
print('\n***********************\n')

Second question

This problem verifies Goldbach's conjecture through programming, 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 tasks: 1) program a function isPrime(x) to judge whether the integer x is prime; 2) The program will use the function Goldbach(N) to decompose the integer N into the sum of two primes to verify Goldbach's conjecture. You need to supplement the complete function code.

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt     #Import matplotlib.pyplot
import matplotlib.image as imgplt

# Question 2: Goldbach conjecture
# Write the function isPrime(x). Judge whether x is a prime number. If it is a prime number, return True; otherwise, return False
def isPrime(x):
    #Write the code below
    ######## begin ###########
    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):  # Decompose N into the sum of two prime numbers
    if N < 6 or N % 2 == 1:  # If N is less than 6 or N is odd
        print('N Should be an even number greater than or equal to 6')
    else:
        # Loop judgment, get two prime numbers less than N that meet the requirements, and print them
        for x in range(2, N //2) : # think about why it's from 2 to N/2
              # Call isPrime function to get two prime numbers less than N that meet the requirements
          ######## begin ###########
            if isPrime(x)=='True' and isPrime(N-x)=='True':
                print(N, '=', x, '+', N - x)
                break
for num in [88, 68, 50, 1000]:
    Goldbach(num) 
print('\n***********************\n')

Question 3

The rule to judge whether the credit card number is legal is: a) for a given 8-digit credit card number, such as 43589795, start from the rightmost digit and add one digit apart, such as 5 + 7 + 8 + 3 = 23. b) Multiply each number in the card number that does not appear in the first step by 2, and then add each number of the multiplied result. For example, for the above example, if the numbers that do not appear in the first step are multiplied by 2 (from right to left) 18, 18, 10 and 8 respectively, then all the numbers are added to 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27. c) Add the numbers obtained in the above two steps. If the number of digits is 0, the entered credit card number is valid.

Please complete the function at the specified position to judge whether the 8-digit credit card number entered by the user is legal.

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt     #Import matplotlib.pyplot
import matplotlib.image as imgplt

# Question 3: credit card verification procedures
def validCreditCard(num):
    #Write the code below
    # ********** Begin ********** #
    s=0
    z=0
    for i in list(str(num)):
        i=eval(i)
        z+=1
        if z%2==0:
            s+=i
        else:
            i*=2
            a=list(str(i))
            w=0
            for n in a:
                w+=eval(n)
            s+=w
    valid=s%10==0
    # ********** End ********** #    
    #Please do not modify the following code
    return valid
for num in [1234567, 43589795, 87539319, 123456789]:
    valid = validCreditCard(num)
    print(valid)
print('\n***********************\n') 

Question 4

Write the function at the specified location, and print the calendar of the month according to the year and month. (for the formula for calculating the day of the week on a certain day, see [Chapter 2 - Fundamentals of Python language - 2.1 solution of simple calculation problems] Three functions have been defined in the code test question. Please complete these three functions. The function day is used to calculate and return the day of the week of a certain month in a certain year; the function isLeapYear is used to judge whether a certain year is a leap year; the function calendar prints the calendar of the given month and year. Pay attention to the output format requirements and the alignment of spaces, as shown in the figure below. For the specific number of spaces, see this question.

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt     #Import matplotlib.pyplot
import matplotlib.image as imgplt

#Question 4: print calendar

def day(y, m, d):#Calculate the day of the week on m / d, y
    # Write the code below
    # ********** Begin ********** #
    y0=y-(14-m)//12
    x=y0+y0//4-y0//100+y0//400
    m0=m+12*((14-m)//12)-2
    d0=(d+x+31*m0//12)%7
    # ********** End ********** #    
    # Please do not modify the following code
    return d0

def isLeapYear(year): #Judge whether year is a leap year
    # Write the code below
    # ********** Begin ********** #
    if y%4==0 and y%100!=0 or y%400==0:
        return(0)
    else:
        return(1)
    # ********** End ********** #    
    # Please do not modify the following code
def calendar(y, m): #Print y year m month calendar
    print('       {}year{}month'.format(y,m))
    print('Su\tM\tTu\tW\tTh\tF\tSa')
    # Please write the code below to call the function to calculate the day of the week on m / 1, y, and save it in the variable date
    # ********** Begin ********** #
    date=day(y,m,1)
    # ********** End ********** #

    days = 0
    # Please write the code below to calculate the number of days in y year and m month
    # ********** Begin ********** #
    if m==2:
        if isLeapYear(y)==0:
            days=29
        else:
            days=28
    elif m in [1,3,5,7,8,10,12]:
        days=31
    else:
        days=30
    # ********** End ********** # 
    count = date  # What day of the week is January 1st, y
    for i in range(date):
        print('\t', end='')
    for d in range(1, days + 1):
        print(str(d) + '\t', end="")
        count = (count + 1) % 7
        if count == 0:
            print()
    print()
   
    # Please do not modify the following code 
for (y,m) in [(2017,8), (2017,10),(2015,8), (2017,2), (2016,2)]:
        calendar(y, m)
        print('---------------------------')

print('\n***********************\n') 

Ask for three..

Tags: Python Anaconda Back-end

Posted on Mon, 22 Nov 2021 13:51:06 -0500 by puckeye