1) Define a function Pzc(n) to determine whether the integer n is divisible by 3 at the same time. 2) Define a function Lst(n) that generates a list of n random integers between 0 and 100. 3) Use the above function to generate A list A composed of 15 positive integers less than 100. Find out the elements in the list that can be divisible by 3 at the same time and place them in list B. Count them and display them in descending order. The display format is shown in the following example: image.png
The sort() function is used to sort the original list, using the comparison function specified by the comparison function if an argument is specified. Syntax: list.sort(CMP =None, key=None, reverse=False) argument CMP — Optional argument that will be sorted using its method if specified. Key is the element that is used for comparison, and has only one argument. The argument to the function is taken from the iterable object, and one of the elements of the iterable object is specified for sorting. Reverse — sort rule, reverse = True descending, and reverse = False ascending (default). Returns a value This method does not return a value, but sorts the objects in the list. Since every Python module (Python file) contains the built-in variable __name__, __name__ equals the filename (including the suffix.py) when the running module is executed. If import is to another module, __name__ equals the module name (without the suffix.py). And “main” is equal to the name of the currently executing file (including the suffix.py). So when the module is executed directly, name == ‘main ‘is true; When a module is imported into another module, the name == ‘main ‘result is false, i.e. the corresponding method is not called. In short: name is the current module name, and the module name is main when the module is run directly. The code is run when the module is run directly, but not when the module is imported.
import random
The integer n is divisible by 3
def Pzc(n):
if n%3==0:
return 1
else:
return 0
Generates a list of n random integers between 0 and 100.
def Lst(n):
Ss =[Random. RandInt (0,100) for I in range(n)] return ss=[Random. RandInt (0,100) for I in range(n)] return ss
def main():
B=[] A=Lst(15) print(" for m in A: if Pzc(m)==1: B. format(len(B),B) : list.append(erd),B) : list.append(erd),B)
The main () # can be switched by the following comments’ ‘ ‘if name = =’ __main__ ‘: the main ()’ ‘ ‘