Fourth, the common data structure exercises and integrated case

Exercises and integrated case:

Exercise 1: Marquee display text on the screen

Exercise 2: Design of a generating function specified length codes, capitalization codes consists of letters and numbers.

Exercise 3: Design a function to return to the given filename extension.

Exercise 4: Design a function return values ​​passed in the list of the largest and second largest element.

Exercise 5: Calculate the date specified in the first few days of the year

Exercise 6: print Pascal's Triangle .

Exercise 7: Enter the calculated average student test scores

Exercise 8: the number of columns generated Feibolaqie

Exercise 9: Find the list of the largest or smallest element

Exercise 10: student test scores table

Case 1: Pick color ball

Integrated Case 2: Josephus problem

Integrated Case 3: Tic-tac-toe game

 

answer:

Exercise 1:

"" " 
Marquee 
" "" 
Import os 
Import Time 


DEF main (): 
    Content = 'Beijing welcomes you for your visit ............' 
    the while True: 
        the output on the screen # cleanup 
        os.system ( 'cls') # os .system ( 'Clear') 
        Print (Content) 
        # 200 ms sleep 
        the time.sleep (0.2) 
        Content Content = [. 1:] + Content [0] 


IF the __name__ == '__main__': 
    main ()

  

"""
成绩页面跑马灯
"""

import os
import time

def main():
    str = 'Welcome to 1000 Phone Chengdu Campus      '
    while True:
        print(str)
        time.sleep(0.2)
        str = str[1:] + str[0:1]
        # for Windows use os.system('cls') instead
        os.system('clear')


if __name__ == '__main__':
    main()

  

Exercise 2:

"" " 
Produce a specified length codes, codes composed of uppercase and lowercase letters and numbers 
" "" 
Import Random 


DEF generate_code (= code_len. 4): 
    "" " 
    generate the specified length codes 

    : param code_len: length codes of ( default 4 characters) 

    : return: a case letters and a numeral random codes 
    "" " 
    all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 
    the last_pos = len (all_chars) -. 1 
    code = '' 
    for _ in Range (code_len): 
        index = the random.randint (0, the last_pos) 
        code all_chars + = [index] 
    return code

  

Exercise 3:

"" " 
Return to the extension given filename 
" "" 
DEF get_suffix (filename, has_dot = False): 
    "" " 
    get the file name extension 

    : param filename: File name 
    : param has_dot: Returns the suffix with the need for point 
    : return: the file extension 
    "" " 
    POS = filename.rfind ( '.') 
    IF 0 <POS <len (filename) -. 1: 
        index = + POS POS. 1 IF has_dot the else 
        return filename [index:] 
    the else: 
        return ''

  

Exercise 4:

"" " 
Returns a list passed the maximum value and the second largest element 
" "" 
DEF MAX2 (X): 
    M1, M2 = (X [0], X [. 1]) IF X [0]> X [ . 1] the else (X [. 1], X [0]) 
    for index in Range (2, len (X)): 
        IF X [index]> M1: 
            M2 = M1 
            M1 = X [index] 
        elif X [index]> M2: 
            M2 = X [index] 
    return M1, M2

I wrote it myself, I feel more simple

def maxnum(x):
    list1 = x
    maxfirst = max(list1)
    list1.pop()
    maxsecond = max(list1)
    return maxfirst,maxsecond

list =[1,2,3,4,5,6]
num = maxnum(list)
print(num)

  

 

 

Exercise 5:

"" " 
Calculates the date is the first few days of the year 
." "" 
DEF is_leap_year (year): 
    "" " 
    Year of the designated judge is not a leap year 

    : param year: Year 
    : return: leap year leap year returns True and False 
    "" " 
    return year and year% 4 == 0 = 0% 100% 400 == 0 or year! 


DEF which_day (year, month the, dATE): 
    " "" 
    calculation date is passed in the first few days of the year 

    : param year: Year 
    : param month: January 
    : param date: May 
    : return: the first few days 
    "" " 
    DAYS_OF_MONTH = [ 
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30,31]
    ][is_leap_year(year)]
    total = 0
    for index in range(month - 1):
        total += days_of_month[index]
    return total + date


def main():
    print(which_day(1980, 11, 28))
    print(which_day(1981, 12, 31))
    print(which_day(2018, 1, 1))
    print(which_day(2016, 3, 1))


if __name__ == '__main__':
    main()

  

Exercise 6:

"" " 
Output line 10 Pascal's triangle - Binomial expansion coefficient of n-th power 
. 1 
. 1. 1 
. 1 2. 1 
. 1. 3. 3. 1 
. 1. 1. 4. 4. 6 
... ... ... 
" "" 


DEF main () : 
    NUM = int (INPUT ( 'Number The of rows:')) 
    YH = [[]] * NUM 
    for Row in Range (len (YH)): 
        YH [Row] = [None] * (Row +. 1) 
        for COL Range in (len (YH [Row])): 
            IF or COL 0 COL == == Row: 
                YH [Row] [COL]. 1 = 
            the else: 
                YH [Row] [COL] = YH [Row -. 1] [COL ] + YH [Row -. 1] [COL -. 1] 
            Print (YH [Row] [COL], End = '\ T') 
        Print () 


IF the __name__ == '__main__': 
    main ()

  

Exercise 7:

"" " 
Enter student test scores to calculate average 
" "" 

DEF main (): 
    Number The = int (the INPUT ( 'Please enter the number of students:')) 
    names = [None] * Number The 
    Scores = [None] * Number The 
    for index in Range (len (names)): 
        names [index] = iNPUT ( 'Please enter% d student name:'% (index +. 1)) 
        Scores [index] = a float (iNPUT ( 'enter.% d student performance: '% (+ index. 1))) 
    Total = 0 
    for index in Range (len (names)): 
        Print ('% S:% .1f minutes'% (names [index], scores [index]) ) 
        Total scores + = [index] 
    Print ( 'average score is:% .1f minutes'% (Total / Number)) 


IF the __name__ == '__main__': 
    main ()

 

Exercise 8:

"""
生成斐波拉切数列
"""


def main():
    f = [1 , 1]
    for i in range(2, 20):
        f += [f[i - 1] + f[i - 2]]
        # f.append(f[i - 1] + f[i - 2])
    for val in f:
        print(val, end=' ')


if __name__ == '__main__':
    main()

  

Exercise 9:

"" " 
Find the maximum or minimum of the list elements 
" "" 


DEF main (): 
    Fruits = [ 'Grape', 'Apple', 'Strawberry', 'at Waxberry', 'Pitaya'] 
    # max built and used directly min function finds the maximum and minimum of the list elements 
    # Print (max (Fruits)) 
    # Print (min (Fruits)) 
    MAX_VALUE = MIN_VALUE = Fruits [0] 
    for index in Range (. 1, len (Fruits)): 
        IF Fruits [ index]> MAX_VALUE: 
            MAX_VALUE = Fruits [index] 
        elif Fruits [index] <MIN_VALUE: 
            MIN_VALUE Fruits = [index] 
    Print ( 'Max:', MAX_VALUE) 
    Print ( 'Min:', MIN_VALUE) 


IF the __name__ == '__main__' :
    main () 
# If you think the biggest element has two to find out how to do should the second-largest

 

Practice 10:

"" " 
Student test scores table 
." "" 


DEF main (): 
    names = [ 'Guan', 'Zhang', 'Zhao', 'Ma Chao', 'Huang'] 
    subjs = [ 'language', 'mathematical' 'English'] 
    scores = [[0] *. 3] *. 5 
    for Row, name in the enumerate (names): 
        Print ( 'enter% s score'% name) 
        for COL, of subj in the enumerate (subjs): 
            scores [Row] [COL] = a float (iNPUT (of subj + ':')) 
    Print (scores) 
# for Row, name in the enumerate (names): 
# Print ( 'enter% s score'% name) 
# scores [ Row] = [None] * len (subjs) 
# for COL, of subj in the enumerate (subjs): 
# Score = a float (INPUT (of subj + ':'))
#           scores[row][col] = score
#   print(scores)

if __name__ == '__main__':
    main()

  

Case 1:

"" " 
Color ball Pick a random program 
." "" 

From Random Import randrange, randint, the Sample 


DEF Run the display (Balls): 
    "" " 
    output list in two color numbers 
    ." "" 
    For index, Ball in the enumerate (Balls): 
        IF index == len (Balls) -. 1: 
            Print ( '|', End = '') 
        Print ( '% 02d'% Ball, End = '') 
    Print () 


DEF random_select (): 
    ' "" 
    randomly select a group of numbers 
    "" " 
    red_balls = [X for X in Range (. 1, 34 is)] 
    selected_balls = [] 
    for _ in Range (. 6): 
        index = randrange (len (red_balls)) 
        selected_balls.append(red_balls[index])
        del red_balls[index]the append (red_balls [index]) 
    # for loop above this line of code can be written as
    # Sample of the random function is a function module 
    # selected_balls = Sample (red_balls,. 6) 
    selected_balls.sort () 
    selected_balls.append (the randint (. 1, 16)) 
    return selected_balls 


DEF main (): 
    n-int = (INPUT ( 'unit selected from several Note: ')) 
    for _ in Range (n-): 
        the display (random_select ()) 


IF the __name__ ==' __main__ ': 
    main ()

  

Case 2:

"" " 
" Lucky Christians " 
There are 15 Christians and 15 non-Christians in distress at sea, in order to allow some people had to survive among 15 people into the sea to go inside, someone thought of a way that is we formed a circle, started by someone from a number of newspaper, report of 9 people into the sea inside, behind him who then reported that the number starting with 1, 9 people continue to report into the sea inside, throw until 15 personal Because God forbid, 15 Christians have survived, most of these people began to ask how the station, which position is the position which a Christian non-Christians. 
"" " 


DEF main (): 
    persons = [True] 30 * 
    counter, index, Number = 0, 0, 0 
    the while counter <15: 
        IF persons [index]: 
            Number + =. 1 
            IF == Number. 9: 
                persons [index] = False 
                counter +. 1 = 
                Number 0 = 
        index + = . 1 
        index = 30% 
    for persons in Person: 
        Print ( 'base' if person else 'non', end = '')

)
if __name__ == '__main__':
    main()

  

Case 3:

"""
井字棋游戏
"""

import os



def print_board(board):
    print(board['TL'] + '|' + board['TM'] + '|' + board['TR'])
    print('-+-+-')
    print(board['ML'] + '|' + board['MM'] + '|' + board['MR'])
    print('-+-+-')
    print(board['BL'] + '|' + board['BM'] + '|' + board['BR'])


def main():
    init_board = {
        'TL': ' ', 'TM': ' ', 'TR': ' ',
        'ML': ' ', 'MM': ' ', 'MR': ' ',
        'BL': ' ', 'BM': ' ', 'BR': ' '
    }
    begin = True
    while begin:
        curr_board = init_board.copy()
        begin = False
        turn = 'x'
        counter = 0
        os.system('clear')
        print_board(curr_board)
        while counter < 9:
            move = input('轮到%s走棋, 请输入位置: ' % turn)
            if curr_board[move] == ' ':
                counter += 1
                curr_board[move] = turn
                if turn == 'x':
                    turn = 'o'
                else:
                    turn = 'x'
            os.system('clear')
            print_board(curr_board)
        choice = input('再玩一局?(yes|no)')
        begin = choice == 'yes'


if __name__ == '__main__':
    main()

  

Guess you like

Origin www.cnblogs.com/jieperhaps/p/11429440.html