Day005 - loop exercises and list Basics

List basis

Premise concept

  • Container - a container type data can store multiple other data at the same time;
  • Element - each independent data in the container;

List - List

  • Container data type (sequence) in list, [] is used as the flag of the container, and multiple elements in it are separated by commas;
  • Representation: [element 1, element 2,..., element n]

List features

  • The list is variable (the number of elements, value and order are variable) - add, delete, modify and query;
  • **The list is ordered * * - subscript operation is supported;
  • The list has no requirements for elements, and any type of data can be used as the elements of the list;

List type

  • Empty list - list = []

  • List - you can save different types of data at the same time

    list3 = ['God', 777, 66.66, [], (2,), None, False]
    

View type

print(type(list1), type(list2))  # <class 'list'> <class 'list'>

Check whether it is null

  • Boolean value judgment and element number judgment
print(bool(list1), bool(list2))  # False False
print(len(list1), len(list2))  # 0 0

List query

  • The purpose of list query is to obtain the elements in the list;
  • Method of obtaining elements - obtaining a single element, slicing and traversal (one by one);

Get a single element

grammar

list[subscript]

function

  • Gets the element corresponding to the specified subscript in the list

explain

  • List - any expression whose result is a list (save the variables of the list, specific list values);
  • [] - Fixed writing method;
  • Subscript - subscript, also known as index, is the position information of elements in the list in an ordered sequence;
  • In Python, each element in an ordered sequence has two sets of subscript values; Front to back positive index (0n), back to front * * negative index * * (- 1-(n+1)); Note: the subscript cannot be out of bounds
names = ['Zhen Ji', 'army officer's hat ornaments', 'Han Xin', 'Lv Bu', 'Zhao Yun', 'Hou Yi', 'Luban', 'Di Renjie']
print(names[1])

ergodic

traversal method

  1. Directly obtain each element in the list;

    for variable in list:
        Circulatory body
    
    names = ['Zhen Ji', 'army officer's hat ornaments', 'Han Xin', 'Lv Bu', 'Zhao Yun', 'Hou Yi', 'Luban', 'Di Renjie']
    for i in names:
        print(i)
    
  2. First obtain the subscript value of each element, and then obtain the element through the subscript;

    for subscript in range(len(list)):
        Circulatory body
    
    names = ['Zhen Ji', 'army officer's hat ornaments', 'Han Xin', 'Lv Bu', 'Zhao Yun', 'Hou Yi', 'Luban', 'Di Renjie']
    for index in range(len(names)):
        print(index, names[index])
    
  3. At the same time, obtain the subscript corresponding to each element and element in the list;

    for subscript, element in enumerate(list):
        Circulatory body
    
    names = ['Zhen Ji', 'army officer's hat ornaments', 'Han Xin', 'Lv Bu', 'Zhao Yun', 'Hou Yi', 'Luban', 'Di Renjie']
    for index, item in enumerate(names):
        print(index, item)
    

practice

  1. Count the number of failed students

    scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
    fail_count = 0
    for i in scores:
        if i < 60:
            fail_count += 1
    print('The number of failed students is:', fail_count)
    
  2. Count the number of integers in the list

    list7 = [89, 9.9, 'abc', True, 'abc', '10', 81, 90, 23]
    num = 0
    for i in list7:
        if isinstance(i, int):
        # if type(i) == int:
            print(i)
            num += 1
    print('The number of integers is:', num)
    
  3. Find the sum of all even numbers in nums

    nums = [89, 67, 56, 90, 98, 30, 78, 51, 99]
    sum1 = 0
    for i in nums:
        if i % 2 == 0:
            sum1 += i
    print('The sum of even numbers is:', sum1)
    

Add element to list

Add a single element

grammar

  • List Append - adds a specified element at the end of the list;

  • **List Insert (subscript, element) * * - insert the specified element before the corresponding element of the specified subscript;

    movies = ['Fifty Shades of Grey', 'Circum Atlantic', 'Fuchun Mountain Residence']
    print(movies)
    movies.append('Jin Gangchuan')
    print(movies)
    movies.insert(2, 'Silent lamb')
    print(movies)
    

Batch add

grammar

  • List 1 Extend (list 2) - add all the elements in list 2 to the end of list 1;

    movies.extend(['Let the bullet fly', 'Out of reach', 'Léon'])
    print(movies)
    

practice

  1. Extract all passing scores from the list

    scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
    pass_scores = []
    for i in scores:
        if i >= 60:
            pass_scores.append(i)
    print(pass_scores)
    

Weekend exercises

Basic questions

First week assignment

1, Multiple choice questions

  1. Which of the following variable names is illegal? (C)

    A. abc

    B. Npc

    C. 1name

    D ab_cd

  2. Which of the following options is not a keyword? (B)

    A. and

    B. print

    C. True

    D. in

  3. Which of the following options corresponds to the correct code? (C)

    A.

    print('Python')
      print('Novice Village')
    

    B.

    print('Python') print('Novice Village')
    

    C.

    print('Python')
    print('Novice Village')
    

    D.

    print('Python''Novice Village')
    
  4. Which of the following options can print 50? B

    A.

    print('100 - 50')
    

    B.

    print(100 - 50)
    
  5. For quotation marks, what is the correct use of the following options? D

    A.

    print('hello)
    

    B.

    print("hello')
    

    C.

    print("hello")
    

    D.

    print("hello")
    

2, Programming problem

  1. Write code and print good study, day, day up on the console!

    print('good good study, day day up!')
    
  2. Write code and print 5 times on the console you see, one day!

    for _ in range(5):
        print('you see see, one day day!')
    
  3. Write code and print numbers 11, 12, 13,... 21

    num = 10
    while True:
        num += 1
        print(num, end=' ')
        if num == 21:
            break
    
  4. Write code and print numbers 11, 13, 15, 17,... 99

    for i in range(11, 100, 2):
        print(i, end=' ')
    
  5. Write code and print numbers: 10, 9, 8, 7, 6, 5

    for i in range(10, 4, -1):
        print(i, end=' ')
    
  6. Write code to calculate the sum of 1 + 2 + 3 + 4 +... + 20

    num = 0
    for i in range(20):
        num += i
    print(num)
    
  7. Write code to calculate the sum of all even numbers within 100

    num = 0
    for i in range(0, 100, 2):
        num += i
    print(num)
    
  8. Write code to count the number of 3 in 100 ~ 200

    for i in range(103, 200, 10):
        print(i, end=' ')
    
  9. Write code to calculate 2 * 3 * 4 * 5 ** 9 results

    num = 1
    for i in range(2, 10):
        num *= i
    print(num)
    
  10. Enter a number. If the number entered is an even number, print an even number. Otherwise, print an odd number

    num = int(input('Please enter a number:'))
    if num % 2 == 0:
        print('This number is even')
    else:
        print('This number is odd')
    
  11. Count the number of numbers within 1000 that can be divided by 3 but cannot be divided by 5.

    count = 0
    for i in range(3, 1000, 3):
        if i % 5 != 0:
            count += 1
    print(count)
    

Advanced questions

  1. Judge how many primes there are between 101-200, and output all primes.

    prime_num = []
    for i in range(101, 200):
        for j in range(2, i + 1):
            if i % j == 0:
                if i == j:
                    prime_num.append(i)
                else:
                    break
    print(len(prime_num), prime_num)
    
    # result
    21 [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
    
  2. Find the cumulative value of integers 1 ~ 100, but it is required to skip all numbers with 3 bits.

    sum1 = 0
    for i in range(1, 101):
        if i % 10 != 3:
            sum1 += i
    print(sum1)
    # result
    # 4570
    
  3. There is a sequence of fractions: 2 / 1, 3 / 2, 5 / 3, 8 / 5, 13 / 8, 21 / 13... Find the 20th fraction of this sequence

    # It can be seen from the examination that the denominator is the peibonacci sequence starting from the second term, and the numerator is the peibonacci sequence starting from the third term
    n1, n2 = 1, 1
    n = 20
    Denominator = 0
    molecular = 0
    for i in range(3, n + 3):
        n1, n2 = n2, (n2 + n1)
        if i == n - 1:
            Denominator = n2
        if i == n:
            molecular = n2
    print('20th score:', molecular, '/', Denominator)
    # result
    # 20th score: 6765 / 4181
    
  4. Write a program to calculate the factorial n of n! Results

    num = int(input('Please enter a number:'))
    factorial = 1
    for i in range(1, num + 1):
        factorial *= i
    print(num, 'factorial  n! Results:', factorial)
    
  5. Seek 1 + 2+ 3!+…+ 20! Sum of

    num = 20
    factorial_sum = 0
    factorial = 1
    for j in range(1, num + 1):
        # Calculate the product of each term
        for i in range(1, j + 1):
            factorial *= i
        # Calculates the product of all items
        factorial_sum += factorial
        factorial = 1
    print('1+2!+3!+...+20!The sum of is:', factorial_sum)
    # result
    # 1+2!+ 3!+...+ 20! The sum of: 256132749411820313
    
  6. Write a program to find the result of the expression a + aa + aaa + aaaa +... Where a is a number from 1 to 9, and the number of summation items is controlled by n. (A and N can be expressed as variables)

    For example, when a is 3 and n is 5, 3 + 33 + 333 + 3333 + 33333

    a = 3
    n = 5
    num, num1 = 0, 0
    for i in range(0, n):
        # Calculate the number of each item
        num += a * 10 ** i
        # Sum of items
        num1 += num
    print(num1)
    # result
    # 370368
    
  7. Console output triangle

    a.according to n The corresponding shape is output according to the different values of
    n = 5 Time             n = 4
    *****               ****
    ****                ***
    ***                 **
    **                  *
    *
    
    b.according to n The corresponding shape is output according to the different values of(n Odd number)
    n = 5               n = 7
      *                    *
     ***                  ***
    *****                *****
                        *******
    
    c. according to n The corresponding shape is output according to the different values of
    n = 4
       1
      121
     12321
    1234321
    
    n = 5
        1
       121
      12321
     1234321
    123454321
    
    # a
    n = 4
    for i in range(5,0,-1):
        print('*'*i)
    # b
    n = 7
    for i in range(1, n + 1):
        if i % 2 != 0:
            print(' ' * (n - i), ' *' * i)
    # c
    # Square of 1 per row
    n = 5
    num = 1
    num1 = 0
    for i in range(n):
        num *= num * 10 ** i
        num1 += num
        num = 1
        print(' ' * (n - i), num1 ** 2)
    
  8. Xiaoming's unit issued a 100 yuan shopping card. Xiaoming went to the supermarket to buy three kinds of washing products, shampoo (15 yuan), soap (2 yuan) and toothbrush (5 yuan). If you want to spend 100 yuan, what combination can you buy?

    for shampoo in range(0, 7):
        for soap in range(0, 50):
            for toothbrush in range(0, 21):
                if shampoo * 15 + soap * 2 + toothbrush * 5 == 100:
                    print('shampoo:', shampoo, 'Soap:', soap, 'Toothbrush:', toothbrush)
    
  9. The thickness of a piece of paper is about 0.08mm. How many times can it be folded in half to reach the height of Mount Everest (8848.13m)?

    count = 0
    paper_thickness = 0.08
    Everest_height = 884813
    while True:
        count += 1  # Statistics of fold times
        paper_thickness *= 2  # Calculate the thickness after each fold
        if paper_thickness >= Everest_height:
            break
    print('Half discount:', count, 'second')
    # result 
    # Half discount: 24 times
    
  10. Classical question: a pair of rabbits give birth to a pair of rabbits every month from the third month after birth. The little rabbit grows to another pair of rabbits every month after the third month. If the rabbits don't die, what is the total number of rabbits every month?

    # Through the listing of rabbit logarithms in the past few months, we can know that it is a problem to find the specified item of peibonacci sequence
    month_n = 7
    m1, m2 = 1, 1
    for i in range(2, month_n):
        m1, m2 = m2, m1 + m2
    print('The first', month_n, 'Yue you', m2 * 2, 'Rabbit')
    # result
    # There were 26 rabbits in July
    
    
  11. Decompose a positive integer into prime factors. For example, enter 90 and print out 90=2x3x3x5.

    num = 987654321
    lst1 = []
    print(num, '= ', end='')
    for i in range(2, int(num**0.5) + 1):  # Set to traverse all numbers greater than 2 and less than this number
        if num % i == 0:  # If the remainder of the traversed number is 0, it indicates that this is a prime factor
            # Take out all the prime factors of i through the cycle, and then find the next prime factor
            while True:
                num /= i
                lst1.append(i)
                if num % i != 0:
                    break
    # If the last remaining number is not equal to 1 and cannot be divided by any number after the change sign, this number is the maximum prime factor of the number
    if num != 1:
        lst1.append(int(num))
    # Print the list of stored quality factors in control format
    for i in range(len(lst1)):
        if i == len(lst1) - 1:
            print(lst1[i], end='')
        else:
            print(lst1[i], 'x ', end='')
    # result
    # 987654321 = 3 x 3 x 17 x 17 x 379721
    
  12. A company uses a public telephone to transmit data. The data is a four digit integer and is encrypted in the transmission process. The encryption rules are as follows: add 5 to each number, then replace the number with the remainder of sum divided by 10, and then exchange the first and fourth bits, and the second and third bits. Find the encrypted value of the input four bit integer

    num = 5678
    a, b = 0, 0
    for i in range(len(str(num))):  # Set the number of cycles according to the digital length
        a = num % 10  # Get low digits
        num //=10 # lower the high-order number
        b = (a + 5) % 10  # Calculate according to the requirements of the question stem
        print(b, end='')
    # result
    # 3210
    
  13. The principal of 10000 yuan is deposited in the bank with an annual interest rate of 3%. Every one year, add the principal and interest as the new principal. Calculate the principal obtained after 5 years.

    year = 5
    principal = 10000
    APR = 3/1000
    for i in range(year):  # Annual cycle
        # The principal plus interest of the previous year is equal to the principal of the following year
        principal = principal + principal*APR
    print(principal)
    
    # result
    # 10150.90270405243
    
  14. Enter an integer and calculate the sum of its digits. (Note: the entered integer can be any bit)

    num = int(input('Please enter a number:'))
    sum1, tmp = 0, 0
    for i in str(num):  # The number is cycled as many times as there are digits
        tmp = num % 10  # Take the number of digits of the number
        num //=10 # erase one digit of the number
        sum1 += tmp  # Add the bits of each cycle in turn
    print('The sum of the figures on your list:', sum1)
    
    num = int(input('Please enter a number:'))
    sum1 = 0
    for i in str(num):  # Fetch numbers as strings one by one
        sum1 += int(i)  # Add each digit directly
    print('The sum of the figures on your list:', sum1)
    
  15. Find the maximum common divisor and minimum common multiple of two numbers. (Note: the common divisor must be less than or equal to the smaller of the two numbers, and can be divided by the two numbers at the same time; the common multiple must be greater than or equal to the larger of the two numbers, and the multiple of the larger number can be divided by the decimals of the two numbers)

    num1, num2 = 27, 48
    # num1 = int(input('Please enter the first number: ')
    # num2 = int(input('Please enter the second number: ')
    GCD, LCM = 0, 0
    for i in range(1, min(num1, num2) + 1):
        # If two numbers can be divided by the same number, this number is less than the smaller one
        if num1 % i == 0 and num2 % i == 0:
            GCD = i
    # Multiplying two numbers by their common divisor is the least common multiple
    LCM = int(num1 * num2 / GCD)
    print('The maximum common divisor is:', GCD, '|The minimum common multiple is:', LCM)
    # result
    # The maximum common divisor is: 3 | the minimum common multiple is: 432
    

Keywords: Python

Added by phat_hip_prog on Sun, 16 Jan 2022 09:03:02 +0200