Python. Experiment 1 data type

Experimental purpose

1. Master the basic usage of lists and slices.
2. Master the basic usage of tuples.
3. Master the basic usage of the dictionary.
4. Master the basic usage of set and list expressions.

Experimental content

1. Write a program to generate a list of 20 random integers, and then arrange the elements with even subscripts in descending order, while the elements with odd subscripts remain unchanged. (tip: use slice.)

import random
list1 = []
list2 = []
for i in range(0, 20):
    a = random.randrange(1, 100)
    list1.append(a)
for i in list1[0:len(list1):2]:
    list2.append(i)
list2.sort(reverse=True)
for i in range(0, 10):
    list1[i*2] = list2[i]
print(list2)
print(list1)

2. Write a program, input two sets setA and setB, and output their intersection, union and difference setA setB respectively

setA = set(input("Please enter setA:"))
setB = set(input("Please enter setB:"))

# intersection
print("intersection:", setA.intersection(setB))
# Union
print("Union:", setA.union(setB))
# Difference set
print("Difference set:", setA.difference(setB))

3. First, a string containing 1000 random characters is generated, and then the number of occurrences of each character is counted. (use dictionary)

import random

base = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-"
str1 = []
dict1 = {}

for i in range(10000):
    str1.append(random.choice(base))
Str = ''.join(str1)
print(Str)
for i in Str:
    dict1[i] = dict1.get(i, 0)+1
print(dict1)

4. Avanti played chess with the king. The king said that if he lost, Avanti could take whatever he wanted. Avanti said that he would like some rice. The chessboard has a total of 64 small squares, with 1 grain of rice in the first lattice, 2 grains of rice in the second lattice, 4 grains of rice in the third lattice and 8 grains of rice in the fourth lattice. By analogy, the rice in each grid in the back is twice that in the previous grid, and 64 grids are always full. How many grains of rice do you need?

#Method 1
num = 0
a = 1
for i in range(0, 64):
    num = num + a
    a *= 2
print(num)

#Method 2
print(sum([2 ** i for i in range(64)]))

5. Write a program. The user inputs a list and two integers as subscripts, and then outputs a sub list composed of elements mediating between the two subscripts. For example, user input [1,2,3,4,5,6] and 2,5, program output [3,4,5].

list1 = list(input("Please enter the input list:"))
x = int(input("Please enter the first integer:"))
y = int(input("Please enter the second integer:"))

if x >= y:
    print("Integer output error!")
else:
    print(list1[x:y])

7. Design a dictionary and write a program. The user inputs the content as the key, and then outputs the corresponding value in the dictionary. If the key entered by the user does not exist, the output "the key you entered does not exist!"

dict1 = {"1": "a", "2": "b", "3": "c"}
print(f"Dictionary is:{dict1}")
key1 = input("Please enter key:")
if key1 in dict1.keys():
    print(dict1[key1])
else:
    print("The key you entered does not exist!")

8. Suppose there are three lists:
lst_who = ["pony", "lamb", "deer"],
lst_where = ["on the grass", "cinema", "home"],
lst_what = ["watching movies", "listening to stories", "having dinner"].
Try to write a program, randomly generate three integers in the range of 0-2, use them as indexes to access the corresponding elements in the three lists, and then make sentences. For example, if three integers are randomly generated, which are 1, 0 and 2 respectively, the sentence "Lamb has dinner on the grass" is output.

import random
lst_who = ["pony", "lamb", "fawn"]
lst_where = ["On the grass", "cinema", "of one's own unit"]
lst_what = ["watch movie", "Listen to the story", "sup on"]
print(f"{lst_who[random.randrange(3)]}{lst_where[random.randrange(3)]}{lst_what[random.randrange(3)]}")

9. Generate a list containing 20 two digit random integers, and arrange the first ten elements in ascending order and the last ten elements in descending order.

import random

list1 = []
for i in range(0, 20):
    a = random.randrange(1, 100)
    list1.append(a)
list1 = sorted(list1[:10], reverse=False) + sorted(list1[10:], reverse=True)
print(list1)

10. Generate tuples containing 20 random integers, and arrange the first ten numbers in ascending order and the last ten numbers in descending order.

import random

tuple1 = ()
list1 = []
for i in range(0, 20):
    a = random.randrange(1, 100)
    tuple1 = tuple1 + tuple({a})
tuple1 = tuple(sorted(list(tuple1[:10]), reverse=False) + sorted(list(tuple1[10:]), reverse=True))
print(tuple1)

11. Here are two lists:
List A: (1, 7, 9, 11, 13, 15, 17, 19)
List b: (2, 4, 6, 8, 10)
The two lists are combined into a list c, arranged in ascending order.

listA = [1, 7, 9, 11, 13, 15, 17, 19]
listB = [2, 4, 6, 8, 10]
listC = sorted(listA + listB)
print(listC)

12. Write a program to delete duplicate elements in a list.

list1 = [1, 1, 1, 2, 2, 3, 4, 5]
list1 = list(set(list1))
print(list1)

Tags: Python

Posted by marseille on Fri, 15 Apr 2022 21:10:47 +0930