Lists and dictionaries —> one-dimensional lists

The content of this issue can be combined with the first issue https://guidm.blog.csdn.net/article/details/130900129?spm=1001.2014.3001.5502
insert image description here

Let's start with a topic:

1. Input an integer n and request to output all the complete numbers in the range of [1,n].

A perfect number is a positive integer that is exactly equal to the sum of all its distinct proper factors.

a = [6, 28, 496, 8128] 
try:
    while True:
        cnt = 0
        n = int(input())
        print(n, end=':')
        for i in a:
            if i <= n:
                cnt += 1
                print('',i,end='' )
            else:
                break
        if cnt == 0:
            print('NULL')
        else:
            print()
except EOFError:
    pass

one-dimensional list

1. Basic concepts

Definition of one-dimensional list: list name = [list value table]

The list name should be a legal user identifier, and the list value table can be empty or have one or more elements, and each element is separated by a comma. Each element in the list can be accessed by subscript, and the following table starts from 0.

Some list usages:

a = []
b = [1]
c = [1, 2, 3, 4, 5]
d = [0]*5 复制五个0创建列表
e = [1, 2, 3] + [4, 5, 6]#用+ 合并两个列表成为一个新的列表

An empty list can be created with the built-in function list( ), and the length of the list can be found with the built-in function len( ).

built-in function sorted(iterable object, key, reverse)

When sorting, sort according to the return value of the function corresponding to the keyword key. The default value of key is None, indicating ascending order; the reverse order flag reverse defaults to False, indicating that no reverse order processing is performed. If reverse is specified as True, the sorting result will be sorted Process in reverse order.

The difference between sorted() and listname.sort is that the former will not change the list, while the latter will.

2. Application of one-dimensional list

2.1 Reverse order output

Output a number of integers, and then display the data in reverse order of input.

Option 1: Except for the first data, output a space before outputting each data.

Solution 2: Except for the last data, output a space after outputting each data.

#方案一:
a = list(map(int, input().split()))
n = len(a)
for i in range(n-1, -1, -1):
    if i != n-1:
        print('', end = ' ')
    print(a[i], end='')
print()

#方案二:
a = list(map(int, input().split()))
n = len(a)
cnt = 0
for i in range(n-1, -1, -1):
   cnt += 1
   if cnt > 1:
        print('', end='')
   print(a[i], end='')
print()

In fact, you can directly use reverse to reverse the list. If you require a space before the data, you can directly add a * before these iterable objects, and output it as the parameter data of the built-in function print().

a = list(map(int, input().split()))
a.reverse()
print(*a)

Using *a as the parameter of the print() function is actually to take out each element in the list a one by one as the parameter of the print() function.

2.2 Digital Separation

Input an integer n, ask to output its digits, and output the digits in forward and reverse order respectively. Separate each pair of data with a comma.

n = int(input())
a = [0]*10
i = 0
while n > 0:
    a[i] = n % 10
    n = n // 10
    i += 1
print(i, end='')
for j in range(i-1, -1, -1):
    print(',', a[j], sep='', end='')
for j in range(i):
    print(',', end='')
    print(a[j], end='')
print()

Interpretation: To separate the digits of each digit in n, you can continuously use the remainder operator % to obtain the ones digit and store it in the list, and use n=n//10 to remove the ones digit until n is 0.

2.3 Joseph Ring

There are n people in a circle, counting 1, 2, and 3 from No. 1, and those who report 3 will quit, and the next one will start counting from 1...until there is only one person left. Enter an integer n, what is the original position of the last remaining person.

n = int(input())
a = [True]*n   #定义长度为n的逻辑型列表,所有元素为True
j = -1         #下标变量j赋初值
cnt = 0        #报数计数器赋初值
m = n          #剩余人数计数器赋初值
while m>1:
    j = (j+1)%n
    if a[j] == False:
        continue
    cnt += 1
    if cnt %3 == 0:
        a[j] = False
        m -= 1
for i in range(n):
    if a[i] == True:
        print(i + 1)
        break

Interpretation: At the beginning, set the values ​​of all elements of a logical list to True to indicate that the corresponding person is in the circle. When the remaining number exceeds 1 person, use the subscript j to scan the list elements one by one to check the person corresponding to the current table below. Whether it has been out of the circle, if it has been out of the circle, it will be skipped, otherwise the counter cnt will increase by one, if the counter is a multiple of three, the corresponding person will be out of the circle, set it to False.

2.4 Cyclic shift

First input two-digit numbers n and m on a line, and then input n integers to form a sequence, requiring the first m numbers to be cyclically shifted to the right of the sequence.

a = list(map(int, input().split()))
n = a[0]
m = a[1]
a = a[2:]
for i in range(m):
    x = a[0]
    for j in range(1,n):
        a[j-1] = a[j]
    a[n-1] = x
print(*a)
2.5 Smaller first

The first line inputs an integer n, and the second line inputs n integers into a list, so that the smallest number among them becomes the first element (the first element) of the list. If there are multiple minimum numbers, the first element is only exchanged with the smallest number that appears first.

n = int(input())
a = list(map(int, input().split()))
k = 0
for i in range(1, n):
    if a[i]<a[k]:
        k = i
a[0],a[k] = a[k],a[0]
print(*a)
2.6 Selection sort

The number n of data is input in the first line, and n integers are input in the second line to form an integer sequence, and the integers are required to be sorted in ascending order.

n = int(input())
a = list(map(int, input().split()))
for i in range(0, n-1):
    k = i
    for j in range(i+1, n):
        if a[k] > a[j]:
            k = j
    if k!=i:
        a[i], a[k] = a[k], a[i]
print(*a)

For the sorting of n numbers in ascending order, a total of n-1 sortings are performed, each time the smallest number is selected from the sequence to be sorted, and placed in the current front position through the exchange operation.

2.7 Bubble sort

The number n of data is input in the first line, and n integers are input in the second line to form an integer sequence, and the integers are required to be sorted in ascending order. ,

n = int(input())
a = list(map(int, input().split()))
for i in range(0, n-1):
    for j in range(n-1-i):
        if a[j]>a[j+1]:
            a[j],a[j+1] = a[j+1],a[j]
print(*a)

Arrange n numbers in ascending order, and perform n-1 sorting in total. Each time compares two adjacent numbers in turn. If the position is reversed, exchange them. Put the smaller one in front and the larger one in the back. Each time At the end of sorting, put the current maximum number in the current last position.

Guess you like

Origin blog.csdn.net/m0_61901625/article/details/131066711