7 classic basic cases about Python
- 2021-12-12 09:00:28
- OfStack
Directory 1. List sorting 2. Exchange dictionary key values 3. Delete duplicate elements in the list 4. Output prime number 5. Judge the day of the year 6. Guess the number 7. Binary conversion
1. Sort the list
def que6():
# 6. Input 3 Integer x, y, z , forming 1 List, please put this n The number is output from small to large.
# Program analysis: The list has sort Method, so just make them a list.
li = np.random.randint(-100, 100, size=10)
# In-situ transformation
li = li.tolist()
# Use sort() Results
li_sort = sorted(li, reverse = False)
print(' Use sort Method to rearrange the results: {}'.format(li_sort))
# No need sort Method, write your own sorting method,
# Bubble sorting
def bubbleSort(m):
m = m.copy()
for time in range(1, len(m)):
for index in range(len(m) - time):
if m[index] > m[index+1]:
m[index], m[index+1] = m[index+1] , m[index]
return m
# Select sort
def selectSort(m):
m = m.copy()
for seat_L in range(len(m)-1):
for seat_R in range(seat_L+1, len(m)):
if m[seat_L] > m[seat_R]:
m[seat_L], m[seat_R] = m[seat_R], m[seat_L]
return m
# Insert sort 1 (Internally written as a function):
def insertSort_1(m):
result = []
# Single element k Insert list li
def to_insert(li, k):
# Identifier
tab = False
# Find the insertion position
# The number of cycles should be at least greater than the length of the list +1 , None Also account for 1 Bits (empty list), that is, it is considered that there are still at the end of playing cards 1 An empty card '
for i in range(len(li) + 1):
# Modify the identifier and flag 'After traversal, the following 1 Cycle ' That is, in and'empty cards ' Comparison
if i == (len(li)):
tab = True
# If you are in the right li[-1] Before the comparison is completed (included), and the position is found, that is, the poker is compared from left to right 1 Pass
if not tab and k < li[i]:
li.insert(i, k)
break
# If the traversal is complete, multiple loops 1 Second, that is, and'empty cards ' No need to compare, directly replace the cards' empty cards '
if tab:
li.append(k)
return li
# Traverse the list
# result = result[:1]
for length in range(len(m)):
result = to_insert(result, m[length])
# print(result,m[length])
return result
# Insert sort 2( Direct nested loop ) :
def insertSort2(m):
m = m.copy()
result = m[:1]
for index_choose in range(1, len(m)):
# I already have it on my hand index_choose Card, compare the first index_choose+1 A card rule append
# Compare your opponent's cards one by one, if they are all compared 1 If it is repeated, it will be added to the end
for index_insert in range(len(result) + 1):
print(result, index_insert,'\n',m, index_choose,'\n\n')
if index_insert != index_choose and m[index_choose] < result[index_insert] :
result.insert(index_insert, m[index_choose])
break
if index_insert == index_choose:
result.append(m[index_choose])
# print(result, m[index_choose])
return result
# print(li)
print(' Insert sort: ',insertSort3(li))
print(' Select sort: ',selectSort(li))
print(' Bubble sorting: ',bubbleSort(li))
que6()
2. Switch dictionary key values
# 1. Interchange element .\
def que1():
d={1:"one",2:"two"}
# Method 1 --- Dynamic assignment
def method1(d):
d = d.copy()
result = {}
for k,v in d.items():
result[v] = k
return result
# Method 2 --- Generator
def method2(d):
d = d.copy()
result = {v:k for k,v in d.items()}
return result
# Method 3 --- Find keys by value
def method3(d):
d = d.copy()
# Find values by keys
def match(dic, b):
return [k for k,v in dic.items() if v == b]
# Mr. Cheng key-None, Re-assignment
result = {}
result = result.fromkeys(d.values())
for k in result.keys():
result[k] = match(d, k)[0]
return result
# Method 4 --- List-to-dictionary < Direct conversion / Dynamic assignment >
def method4(d):
d = d.copy()
key = d.keys()
val = d.values()
data = list(zip(key, val))
# Method 4-1
result1 = {}
for i in range(len(data)):
result1[data[i][1]] = data[i][0]
# Method 4-2
result2 = dict(zip(val, key))
return result1, result2
print(' New list dynamic assignment method: {}'.format(method1(d)))
print(' Generator method: {}'.format(method2(d)))
print(' Find value by key method: {}'.format(method3(d)))
print(' Dynamic assignment list to dictionary method: {}'.format(method4(d)[0]))
print(' Direct list to dictionary method: {}'.format(method4(d)[1]))
# que1()
3. Remove duplicate elements from the list
No one answers the questions? This site has created an Python Learning Exchange Group: 531509025
Looking for like-minded friends to help each other. There are also good video learning tutorials and PDF e-books in the group!
Delete repeating element list = [1, 2, 5, 4, 1, 5, 6, 8, 0, 2, 5]
a = np.random.randint(-100, 100, size=10)
a = a.tolist()
def method1(a):
a = a.copy()
a = set(a)
return a
def method2(a):
b = a.copy()
c = 0
for i in range(len(a)-1):
if b[i+c] in b[:i+c]+b[i+c+1:]:
b.pop(i+c)
c -= 1
return b
print(' Set method: ',method1(a))
print(' Traversal method: ',method2(a))
4. Output prime numbers
def prime(end):
prime_list = []
if end <= 1:
print(' Must be greater than 1')
else:
# prime_list.append(2)
for i in range(2, end+1, 1):
count = 0
if i == 2:
if i%2 != 0:
prime_list.append(2)
else:
for m in range(2, i):
# If you can divide exactly, you will jump out of the loop
if (i % m) == 0:
# print(i, m)
break
# Otherwise count +1
else:
count += 1
# Judge whether the division is completed (0/n)
if count == i - 2:
prime_list.append(i)
print(count, i, m)
return (prime_list)
num = int(input(' Want to output 2 To how much? '))
print(prime(num))
5. Judge the day of the year
def que3():
# 3. Enter a certain year, month and day to judge this 1 God is this 1 What day is the year? :
# Leap year judgment function
def judge_leap(num):
date = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# (4 Year 1 Leap and not Centennial ) or 4 Hundred-year leap
if (num % 4 == 0 and num % 100 != 0) or num % 400 ==0:
date[1] =29
return date
# Format conversion
date = (input(' Please enter 1 Date, formatted as: " 2018.02.12 ": '))
date_list = (list(map(int, (date.split('.')))))
# Traversal calculation days
day = date_list[2]
for i in range(date_list[1]):
day += judge_leap(date_list[0])[i]
print('{} Month {} Day is {} The first part of the year {} Days \n'.format(date_list[1], date_list[2], date_list[0], day))
# que3()
Step 6 Guess the numbers
# Re-guess the numbers
import random
def judge_num(num, num_random):
if num > num_random:
print('It\'s too big')
return 1
elif num < num_random:
print('It\'s too small')
return 1
else:
print("Congratulation!! That\' right!")
return 0
# Generate random numbers
num_start = int(input('Digital lower limit of guess number:\n'))
num_end = int(input('Digital upper limit of guess number:\n'))
num_random = random.randint(num_start, num_end)
# Parameter initialization
result = 1 # Judgment result
i = 0 # Number of cycles
frequency = 3 # Loop limit number
# Prompt total guess times, remaining times
print('WARNING: You have " {} " chances you guess '.format(frequency), end = '--&&>>--')
print(' " {} " chances left now:\n'.format(frequency - i +1))
while result and i != frequency:
# Guess numbers
num = int(input('Please guess a int_number:\n'))
result = judge_num(num, num_random)
i += 1
7. Binary conversion
# Arbitrary binary conversion 10 Binary system
def other_to_decimal(hex, num):
# Integer to list,
num_str = str(num)
# map () will List Elements in the object ( list Type to a collection ( set ) Type
num_list = list(map(int, num_str))
# List reverse order
num_list = num_list[::-1]
print(list(map(int, num_str)))
# Get the number of digits
digit = len(num_list)
num_decimal = 0
# Accumulation
for i in range(digit):
numi = num_list[i]
# print(numi, hex**i)
num_decimal += numi*(hex**i) # To each 1 Power exponential accumulation of digits
return num_decimal
# 10 Binary to arbitrary binary
def decimal_to_other(hex, num):
# Get the number of digits
digit = len(str(num))
num_hex = []
quotient = 1
# Divide, and the remainder is included in the list num_hex
while quotient:
# Remainder and quotient
quotient = num // hex
remainder = num % hex
# print(quotient, remainder)
# The remainder is included in the list
num_hex.append(remainder)
# Do business 1 Sub-cycle
num = quotient
# List reverse order , By slicing and sort() Function can be implemented
num_hex = num_hex[::-1]
# num_hex.sort(reverse=True)
# If it exceeds 10 Binary system, using ASCII Code is converted into letters
for i in range(len(num_hex)):
if num_hex[i] > 9:
num_hex[i] = chr(int(num_hex[i])+87)
# print(num_hex)
# List to string
result = (''.join('%s' %m for m in num_hex))
return result
Type = bool(input("10 Please enter the binary system to any binary system 1 , arbitrary binary conversion 10 Please enter the binary system 0\n"))
if Type:
hex = int(input(" Need to put 10 How many binary systems are converted to? Please enter a positive integer \n"))
num = int(input(" The number that needs to be converted is :"))
print(" The conversion result is: ", decimal_to_other(hex, num))
else:
hex = int(input(" How many binary systems need to be converted to 10 Binary system? Please enter a positive integer \n Year "))
num = int(input(" The number that needs to be converted is :"))
print(" The conversion result is: ", other_to_decimal(hex, num))