程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python container exercises

編輯:Python

One 、 Tuple exercise

fruits = ("apple","banana","strawberry","pear")
#a. 1 Calculates the length of the tuple and outputs 
a = len(fruits) # Global function len()
print(" The tuple length is :",a)
print("---------------------------------")
#a.2
num = 0
for i in fruits:
num += 1
print(num)
print("---------------------------------")
# b. Get tuple number 2 Elements and output 
fruit1 = fruits[2]
print(fruit1)
print("---------------------------------")
# c. Get element number 2-3 Elements and output 
fruit2 = fruits[1:3]
print(fruit2)
print("---------------------------------")
# d. Use for Loop through the output tuple 
for i in fruits: #i Is the element in the tuple 
print(i)
print("---------------------------------")
for i in range(len(fruits)): # Take out elements by subscript 
print(i,fruits[i])

Two 、 Dictionary exercises

dict = {
"k1":"v1","k2":"v2","k3":"v3"}
# 1、 Please loop through all key
for key in dict:
print(key)
print("---------------------------------")
# 2、 Please loop through all value
for value in dict.values():
print(value)
print("---------------------------------")
# 3、 Please loop through all key and value
for key,value in dict.items():
print(key,value)
for key in dict: # Take out elements by subscript 
print(key,dict[key])
print("---------------------------------")
# 4、 Please add a key value pair to the dictionary ,"k4":"v4", Output the added Dictionary 
dict["k4"] = "v4"
dict.update({
'k4':'v4'}) # Dictionary method , Both are OK 
print(dict)
print("---------------------------------")
# 5、 Please delete the key value pairs in the dictionary "k1":"v1", And output the deleted results 
del dict['k1']
print(dict)
print("---------------------------------")
# 6、 Please delete the key in the dictionary "k5" Corresponding key value pair , If there is no key in the dictionary "k5", No error , return None
re1 = 0
try:
del dict['k5']
print(' Delete successful ')
except:
print(None)
print("---------------------------------")
# 7、 Please get the information in the dictionary "k2" Corresponding value 
value2 = dict['k2']
# 8、 Please get the information in the dictionary "k6" Corresponding value , If it doesn't exist , No error , And let it go back None.
re2 = 0
try:
print(dict['k6'])
except:
print(None)
print("---------------------------------")
# 9、 existing dict2 = {"k1":"v1","a":"b"}, Make by one line operation dict2 = {"k1":"v1","k2":"v2","k3":"v3","a":"b"}
dict2 = {
"k1":"v1","a":"b"}
dict2.update(dict)
print(dict2)

3、 ... and 、 Set exercises :

#1、 Generated N individual 1~100 Random integer between (N<=1000),N It's user input ; For the repeated figures in the futures index , Keep only one , Take out the rest of the same figures ;
import random
numbers = []
num = int(input(" Number of randomly generated :"))
for i in range(num):
nums = random.randint(1,100)
numbers.append(nums)
for i in range(len(numbers)): # Remove duplicate elements 
for i in numbers:
if numbers.count(i) > 1:
numbers.remove(i)
print(numbers)
print("---------------------------------")
#2、 How to use the set to complete the de duplication operation of the list , And output the final list from large to small .
list1 = [1,1,4,5,8,7,4,5,6,7]
set1 = set(list1) # Automatically remove duplicate elements from the collection , But the set is out of order , Unable to complete the sort operation 
list2 = list(set1) # Set to list 
lenth = len(list2)
# Bubble sort 
for i in range(lenth):
for j in range(i,lenth-i):
if list2[i] > list2[j]:
list2[i] ,list2[j] = list2[j] ,list2[i]
print(list2)

Four 、 String exercises :

#1、 Calculate how many decimal digits are in the string content entered by the user ? A few letters ? # Such as :asduiaf878123jkjsfd-‐213928 The numbers are 12 individual . The letters have 13 individual 
str = input(" Please enter :")
num = 0
StrNumber = 0
for i in str:
if i.isdigit():
num += 1
elif i.isalpha():
StrNumber += 1
else:
pass
print(f" The numbers are {num} individual ---- The letters have {StrNumber} individual ")
print("---------------------------------")
#2、 Develop sensitive word filters , Prompt the user to enter content , If the user's input contains special characters : Replace the sensitive words with ***
a = ["hello" ,"people", "world"] # Suppose there are sensitive words 
b = ''
def filter(str):
for i in a:
if i in str:
b = str.replace(i,"***",len(a))
str = input(" Please enter :")
filter(str)
print(b)
print("---------------------------------")
#3、 Make random captcha , Case insensitive technological process : - Randomly generated 6 Bit verification code ( Alphanumeric composition ) - Show the user the input verification code - User entered value - The value entered by the user is the same as the value displayed, and the correct information is displayed , Otherwise, continue to generate a new verification code and wait for the user to enter 
import random
nums=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q','R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
while True:
Identifying_Code = ""
for i in range(6):
Identifying_Code += random.choice(nums)
print(' Verification Code :',Identifying_Code)
a = input(" Please enter the verification code :")
if a.lower() == Identifying_Code.lower(): #(a.lower(), String method , Change the letters to lowercase )
print(" The verification code is correct ")
break
else:
print(" Verification code error ")
print("---------------------------------")

5、 ... and . List exercises

# 1、 A set of achievements 67,90,-20,105,88,92, Please change the negative score to 0, exceed 100 Of is set to 100, Then the output .
arr = [67,90,-20,105,88,92]
for i in range(len(arr)):
if arr[i] > 100:
arr[i] = 100
elif arr[i] < 0:
arr[i] = 0
print(arr)
print("---------------------------------")
# 2、 Input 5 Results of students , Descending output , And find the average score 
arr2 = []
sum = 0
for i in range(5):
score = int(input(" Please enter the first "+str(i+1)+" Students' grades :"))
arr2.append(score)
arr2.sort(reverse=True) # Tabular method reverse( Optional parameters ,True For the descending order )
for i in arr2:
sum += i
print(arr2)
print(" The average score is :",sum/5)
print("---------------------------------")
# 3、 Determine whether a sequence is orderly 
arr3 = [12,71,2,5,4,14,6,13,1,16,18,19,9]
arr4 = [12,71,2,5,4,14,6,13,1,16,18,19,9]
a = 0
for i in range(len(arr3)-1):
for j in range(i,len(arr3)-1):
if arr3[i] < arr3[j + 1]:
a = arr3[i]
arr3[i] = arr3[j + 1]
arr3[j + 1] = a
for i in range(len(arr4)):
if arr3[i] != arr4[i]:
print(' disorder ')
break

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved