Learn Python's D5 loop nesting and lists

Posted by jerbecca on Sun, 16 Jan 2022 21:18:40 +0100

Loop exercises and lists

I loop nesting

  • The execution principle of loop nesting: the outer loop is once and the inner loop is complete
for x in range(5):
    for y in range(2, 5):
        print(x, y)

II Recognition list

  • Basic characteristics of the container:

    • A container type of data can save multiple other data at the same time
  • Element:

    • Each independent data in the container is an element
  • 1. What is a list

    • What does a list look like: a list is a container data type (sequence); Take [] as the flag of the container, in which multiple elements are separated by commas: [element 1, element 2, element 3,...]
    • Characteristics of list: the list is variable (the number, value and order of elements are variable) - add, delete and change; The list is ordered - subscript operations are supported
    • List requirements for elements: no requirements (no matter what type of data can be used as list elements)
  • Empty list

  • len(list) - Gets the number of elements in the list
      list1 = []
      list2 = [ ]
      print(type(list1), type(list2))   # <class 'list'> <class 'list'>
      print(bool(list1), bool(list2))   # False False
      print(len(list1), len(list2))     # 0 0
    
  • The list can save multiple data at the same time
    list3 = [89, 90, 76, 99, 58]
    print(list3)
    
    list5 = [10, 12.5, True, 'abc', [1, 0], {'a': 10}, (20, 9), {20, 9}, lambda x: x*2]
    print(list5)
    
    list6 = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    
  • 2. Query: get elements

    • Query is divided into three cases: obtaining a single element, slicing, and traversal (one by one)

      Get a single element
      '''
      Syntax: Lists[subscript]       
      Function: get the element corresponding to the specified subscript in the list
       explain:
      list      -      Any expression that results in a list, such as a variable that saves the list, a specific list value, and so on
      []       -       Fixed writing
       subscript      -      Subscript, also known as index, is the position information of elements in an ordered sequence.
                      Python Each element in the ordered sequence in has two sets of subscript values, which are: the subscript value increasing from 0 from the front to the back; From back to front-1 Subscript value to begin decrement
       Note: the subscript cannot be out of bounds
      '''
      
    • ergodic

      '''
      Mode 1 - Get each element in the list directly
      for element in list:
          Circulatory body
          
      Mode 2 - First get the subscript value of each element, and then get the element through the subscript
      for subscript in range(len(list)):
          Circulatory body
          
      for subscript in range(-1, -len(list)-1, -1):
          Circulatory body
          
      range(len(list)) == range(Number of elements in the list)
      
      Mode 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
      '''
      

3, Add element

  • 1. Add: add element

    • Add a single element

      list.append(element)   -   Add an element at the end of the list
       list.insert(subscript, element)  - Inserts the specified element before the element corresponding to the specified subscript
      
  • 2. Batch increase

    • List 1.extend(List 2)  - Add all the elements of list 2 after list 1
      

First week assignment

1, Multiple choice questions

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

    A. abc

    B. Npc

    C. 1name

    D ab_cd

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

    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?

    A.

    print('100 - 50')
    

    B.

    print(100 - 50)
    
  5. For quotation marks, what is the correct D in 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 x in range(5)
    	print ('you see see ,one day day')
    
  3. Write code and print numbers 11, 12, 13,... 21

    for x in range(11, 22):
        print(x)
    
  4. Write code and print numbers 11, 13, 15, 17,... 99

    for x in range(11, 100):
        print(x)
    
  5. Write code and print numbers: 10, 9, 8, 7, 6, 5

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

    n = 0
    for x in range(1, 21):
        n += x
    print(n)
    
  7. Write code to calculate the sum of all even numbers within 100

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

    n = 0
    for x in range(103, 200, 10):
        n += 1
    print(n)
    
  9. Write code to calculate 2 * 3 * 4 * 5 ** 9 results

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

    while True:
        x = int(input('Please enter a number'))
        if x % 2 == 0:
            print('even numbers')
            continue
        else:
            print('Odd number')
            continue
    
  11. Count the number of numbers within 1000 that can be divided by 3 but cannot be divided by 5.

    n = 0
    for x in range(0, 1001, 3):
        n += 1
    print(n)
        
    
  12. Judge how many primes there are between 101-200, and output all primes.

    a = 0
    for n in range(100, 201):
        for x in range(2, n):
            if n % x == 0:
                break
        else:
            a += 1
            print(n)
    print('have', a, 'individual')
    
  13. Find the cumulative value of integers 1 ~ 100, but it is required to skip all numbers with 3 bits.

    a = 0
    for x in range(1, 101):
        if x % 10 != 3:
            a += x
    print(a)
    
  14. 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

    pre1 = 1
    pre2 = 1
    n = 20
    for x in range(n):
        pre1, pre2 = pre2, pre1 + pre2
    print(pre2, '/', pre1)
    
  15. Write a program to calculate the factorial n of n! Knot of

    n = 4
    for x in range(1, n):
        n *= x
        if n == 1:
            print('1')
            break
    print(n)
    
  16. Seek 1 + 2+ 3!+…+ 20! Sum of

    a = 1
    b = 0
    for x in range(1, 21):
        a *= x
        b += a
    print(b)
    
  17. 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)

    a, n, c, b, = 3, 5, 0, 0
    for n in range(1, n+1):
        b += ((a-1) * (10 ** (n-1))) + (10 ** (n-1))
        c += b
    print(c)
    
  18. 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
    
  19. 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 zao in range(50):
        for ya in range(20):
            for xi in range(100 // 15 + 1):
                if xi * 15 + ya * 5 + zao * 2 == 100:
                    print(xi, ya, zao)
    
  20. 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)?

    n = 0
    while True:
        n += 1
        if (0.08 * (2 ** n)) >= 8848130:
            print(n)
            break
    
  21. 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?

    pre1 = 2
    pre2 = 2
    n = 3
    if n == 1 or n == 2:
        print(2)
    else:
        for x in range(n-3):
            pre1, pre2 = pre2, pre1 + pre2
        print(pre1 + pre2)
    
  22. Decompose a positive integer into prime factors. For example, enter 90 and print out 90=2x3x3x5.

  23. 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

    n = 7890
    for a in range(1, 5):
        b = (((n % (10 ** a)) // (10 ** (a - 1))) + 5) % 10
        print(b, end='')
    
  24. 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.

    n = 5
    a = 10000
    for n in range(1, 6):
        a += 0.003 * a
        print(a)
    
  25. Enter an integer and calculate the sum of its digits. (Note: the entered integer can be any bit)

  26. 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)

Topics: Python