Python test case

 Python operator, built-in functions

Experimental purposes :
  1, Python proficient operator.
  2, skilled use of Python built-in functions.
Experiment:
  1, programming, input arbitrarily large natural number, the sum of the digits of the output.
  2, programming, and set B input setA two sets, outputs their intersection, union, and difference setA-setB.
  3, programming, input a natural number, the output of its binary, octal, hexadecimal representation.

the INPUT = num ( " Please enter a natural number: " )
 Print (SUM (the Map (int, num)))
 # SUM () represents the summation 
# the Map (int, num) num of you said it would convert to an integer

setA = eval (the INPUT ( " Please enter a collection: " )) 
set B = eval (the INPUT ( " Please enter a collection: " ))
 Print ( " intersection: " , setA | set B)
 Print ( " union: " , setA & set B)
 Print ( " setA-set B: " , setA - set B)

int = NUM (the INPUT ( " Please enter a natural number: " ))
 Print ( " binary: " , bin (NUM))
 Print ( " decimal: " , the OCT (NUM))
 Print ( " hex: " , hex (num))

 

Pi is calculated using a Monte Carlo approximation method

Purpose:
  1, understand the principles of Monte Carlo method.
  2, understand the nature of the for loop works.
  3 for commonly used random function module.
Experiment:
  Monte Carlo method is a method to obtain an approximate solution of the problem by probability, in many areas have important applications, including the calculation of pi approximation. Suppose a square of a 2 wood, painted above a unit circle, then the board free to throwing a dart impact point coordinates (x, y) is bound in the wood (more often falls within the unit circle), If you throw enough number, then divided by the total number of times that fall within the unit circle multiplied by 4, that number will be infinitely close to the value of pi. This is the Monte Carlo method of the invention is used for approximation calculation of PI, as shown in FIG.

     

  Programming, Monte Carlo simulation method calculates the ratio of the circumference approximation, darts input frequency and the output pi approximation.

# Author: "Wang Jiawei" 
# DATE: 2019-06-26 
# File: 3.py 
# IDE: PyCharm 

from Random Import Random 

Times = int (the INPUT ( " Please enter the times you throw darts: " )) 
HIT = 0
 for I in Range (Times): 
    X = Random () 
    Y = Random ()
     IF x * x + y * Y <=. 1 : 
        HIT = HIT +. 1
 Print (4.0 * HIT / Times) 

# If x * x + y * y <= 1 then the generated random number (throwing darts) falls on a circle. 
#I.e., the center point distance throwing darts distance is less than 1

 

Xiao Ming stairs

The experiment:
  1, understand and unpacking sequence skilled use.
  2, understand the recursive function works.
  3, able to write code for a recursive function to solve practical problems.
  4, understand the use of Python dictionary.
Experiment:
  assuming a total of 15 steps of stairs, Xiaoming step up to the three steps. Write a program to calculate how many ways this staircase Total Xiaoming. Required to give two kinds of recursive method and the recursion method code.

# Author: "Wang Jiawei" 
# DATE: 2019-06-26 
# File: 7.py 
# the IDE: PyCharm 

'' ' 
Recursion: 
from the 15th step looking back, there are three ways to come up (from 14 be a step on the stepped up one step, 
from the 13th step be a step up two steps, 12 steps from the first step on the steps of a step 3),
the same token, the first 14, 13, 12 this step can be calculated, thereby obtaining the formula f (n) = f (n -1) + f (n-2) + f (n-3),
where n = 15,14,13, ..., 5, 4.
Then the end condition is determined in this recursion formula, the
first step only one kind of the method, the second method step the two species (one step two step up step, the step be a step in a two-step up),
the first there are four steps on the three methods.
'' ' DEF climbStairs1 (n-): # Recursion A. 1 = # a step is only a method B = 2 # two steps, there are two methods C =. 4 # of the three steps, there are four methods for Iin range(n - 3): c, b, a = a + b + c, c, b return c def climbStairs2(n): # 递归法 first3 = {1:1,2:2,3:4} if n in first3.keys(): return first3[n] else: return climbStairs2(n-1)+climbStairs2(n-2)+climbStairs2(n-3) print(climbStairs1(15)) print(climbStairs2(15))

 

Monty Hall Paradox game

Purpose:
  1, understand the Monty Hall paradox content.
  2, understand the rules of the game.
  3, and the skilled use of dictionary methods set operations.
  4, understand the assertion assert the usage statement.
  5, skilled use of the cyclic structure.
Experiment:
  Suppose you are participating in a game show with prizes, and there are three doors Optional: One is behind the car, the other two followed by a goat. You choose a door, say No. 1, the moderator of course, know what is behind each door and opened another door, say No. 3, followed by a goat. At this point, the moderator will ask you "Do you want to re-election No. 2 do?", And then determine the final you want to open the door of your choice, and make sure you get goats (lost) or car (to win).
  Write a program to simulate the above games.

# Author: "Wang Jiawei" 
# DATE: 2019-06-26 
# File: 9.py 
# the IDE: PyCharm 

from Random Import randrange 

DEF the init ():
     '' ' 
    initializes three doors and the rear door Item 
    : return: return three a corresponding rear door article 
    '' ' 
    Result = {I: ' Goat '  for I in Range (. 3)}   # {0: Goat,. 1: Goat, 2: Goat} 
    R & lt = randrange (. 3) # randomly generated 0 an integer between 2 
    Result [R & lt] = ' CAR '  # the goat random index position to CAR 
    return Result #Initialization door is complete, return to door collection 

DEF StartGame ():
     '' ' 
    to start the game 
    : return: returns the result of the game 
    ' '' 
    DOORS = the init () # initialize door 
    # acquisition player chooses door number 
    the while True:
         the try : 
            firstDoorNum = int (the INPUT ( " the Choose a Door Open to: " ))
             # the assert - Python assertion is to detect a condition, if the condition is true, it does not do anything; on the contrary it triggers an error message with optional AssertionError 
            the assert 0 < firstDoorNum = <= 2
             BREAK 
        the except :
             Print ( " Door Number MUST BE BETWEEN {} and {}: ".format (0,2 ))
     # Moderator View other two items behind the door case 
    # from all the door (three doors - Remove a player selected index 0,1,2) were in the lead 
    for Door in doors.keys () - {firstDoorNum}:
         # open a door to which the door of the sheep 
        IF dOORS [door] == ' goat ' :
             Print ( " goat the door behind " , door)
             # Get the third door No. , allowing the player to tangle 
            # S.pop () returns a random element in the set S, if S is empty, abnormal 
            thirDoor = (doors.keys () - . {Door, firstDoorNum}) POP () 
            Change = INPUT ( " to {Y} Switch / n-: ".format(thirDoor))
            # 如果change='y'则finalDoorNum = thirDoor,否则finalDoorNum = firstDoorNum
            finalDoorNum = thirDoor if change=='y' else firstDoorNum
            if doors[finalDoorNum] == 'goat':
                return "I Win !"
            else:
                return "You Win !"

while True:
    print("="*30)
    print(StartGame())
    r = input("Do you want to try once more (y/n) :")
    if r == n:
        break

 

Guessing game

Purpose:
  1, skilled use of the selection structure and loop structure to solve practical problems.
  2, when aligned with the indentation attention to the selection code nested structure.
  3, the structure of the execution flow with circulation appreciated else clause.
  4, understand the conditional expression value1 if condition else value2 usage.
  5, it is understood that use structured exception handling usage constraints input by the user.
  6, the implementation process is understood with exception handling structure else clause.
Experiment:
  Simulation prepared guessing game. The program is running, the system generates a random number, then prompts the user to guess and make necessary suggestions based on user input (guessed, too big, too small), if you guessed early termination of the program, run out if the number is still I do not guess right, suggesting that the game is over and give the correct answer.

# Author: "Wang Jiawei" 
# DATE: 2019-06-26 
# File: 10.py 
# the IDE: PyCharm 

from Random Import the randint 

DEF the guessNumber (maxValue = 10, = maxTimes. 3 ):
     '' ' 
    Guess 
    : param maxValue: Random generating the maximum number 
    : param maxTimes: Guess the times 
    : return: null 
    '' ' 
    # generate a random integer --1 to maxValue 
    value the randint = (. 1 , maxValue)
     for I in Range (maxTimes):
         # if i = 1 output Start to GUESS: tips, otherwise the output GUESS again: prompt. 
        = prompt ' the Start to GUESS: ' IF I == 0 the else  ' GUESS Again: ' 
        # use structured exception handling, the digital input is not prevented. 
        the try : 
            the X- = int (the INPUT (prompt)) # get the value of the player entered 
        the except :
             Print ( " Must the INPUT 1 and the BETWEEN AN Interger " , maxValue)
         the else :
             IF the X-== value:
                 # guessed 
                Print ( " Congratulations ! " )
                 BREAK 
            elif the X-> value:
                 Print (" Too Big " )
             the else :
                 Print ( " Too Litter " )
     the else :
         # the else and for conjunction, that after the end of the for loop to run the else 
        # the number of runs has not guessed, the game is over, give tips. 
        Print ( " Game over, FAIL. " )
         Print ( " at The Number The IS " , value) 

guessNumber ()

 

 

Guess you like

Origin www.cnblogs.com/wjw1014/p/11088393.html