What are the classic basic cases of Python
This article mainly introduces the classic basic cases of Python, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand.
1. List sort def que6 (): # 6. Enter three integers x, y, z to form a list. Please output the n from small to large. # Program analysis: lists have sort methods, so just put them into lists. Li = np.random.randint (- 100,100, size=10) # Local conversion li = li.tolist () # use sort () result li_sort = sorted (li, reverse = False) print ('use sort method, rearrange result: {}' .format (li_sort)) # write sorting method without sort method # Bubble sort 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 [sorting _ L] > m [ranking _ R]: M [sorting _ L] M [inserted _ R] = m [inserted _ R], m [inserted _ 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 location # the number of loops should be at least greater than the list length + 1 None also occupies one place (empty list), that is, there is an 'empty card' at the end of the playing card for i in range (len (li) + 1): # modify the identifier and mark 'the next loop after traversing' That is, comparing if I = (len (li)): tab = True # before the comparison of li [- 1] is completed (including) and finding a position, that is, compare the poker from left to right.
< li[i]: li.insert(i, k) break # 如果遍历完成,多循环一次,即和'空牌'不需要比较,直接把牌替换掉'空牌' if tab: li.append(k) return li # 遍历列表 # result = result[:1] for length in range(len(m)): result = to_insert(result, m[length]) # print(result,m[length]) return result # 插入排序2(直接嵌套循环): def insertSort2(m): m = m.copy() result = m[:1] for index_choose in range(1, len(m)): # 手上已经有index_choose张牌,比较第index_choose+1张牌则append # 逐个比对手上的牌,如果都对比了一遍,则加到最后 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('插入排序:',insertSort3(li)) print('选择排序:',selectSort(li)) print('冒泡排序:',bubbleSort(li))que6()2.调换字典键值# 1. 调换元素.\def que1(): d={1:"one",2:"two"} # 方法1 --- 动态赋值 def method1(d): d = d.copy() result = {} for k,v in d.items(): result[v] = k return result # 方法2 --- 生成器 def method2(d): d = d.copy() result = {v:k for k,v in d.items()} return result # 方法3 --- 由值寻找键 def method3(d): d = d.copy() # 由键寻找值 def match(dic, b): return [k for k,v in dic.items() if v == b] # 先生成key-None,再赋值 result = {} result = result.fromkeys(d.values()) for k in result.keys(): result[k] = match(d, k)[0] return result # 方法4 --- 列表转字典 < 直接转换/动态赋值 >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)): result T1 [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 ('key search 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. Delete duplicate elements in the list
No one answers any questions? The editor created a Python learning communication group: 531509025
Looking for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
Delete the repeating element list = [1, 2, 5, 4, 1, 5, 6, 8, 0, and 5]
A = np.random.randint (- 100,100 Size=10) a = a.tolist () def method1 (a): a = a.copy () a = set (a) return adef method2 (a): B = a.copy () c = 0 for i in range (len (a)-1): if b [iTunc] in b [: iTunc] + b [i+c+1:]: b.pop (iTunc) c-= 1 return bprint ('aggregate method:' Method1 (a) print ('ergodic:', method2 (a)) 4. Output prime number def prime (end): prime_list = [] if end 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# 产生随机数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)# 参数初始化result = 1 # 判断结果i = 0 # 循环次数frequency = 3 # 循环限制次数# 提示总猜测次数、剩余次数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 the number num = int ('Please guess an int_number:\ n') result = judge_num (num, num_random) I + = 17. Binary conversion # arbitrary decimal to decimal def other_to_decimal (hex, num): # convert integers to lists Num_str = str (num) # map () converts elements in List objects (list type) to 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 digits digit = len (num_list) num_decimal = 0 # cumulative for i in range (digit): numi = num_ list [I] # print (numi, hex**i) num_decimal + = numi* (hex**i) # add return num_decimal# decimal to arbitrary def decimal_to_other (hex) for the power exponent of each digit Num): # get digits digit = len (str (num)) num_hex = [] quotient = 1 # divided The remainder is included in the list num_hex while quotient: # remainder and quotient quotient = num / / hex remainder = num% hex # print (quotient, remainder) # remainder is counted in the list num_hex.append (remainder) # quotient does the next cycle num = quotient # list reverse order Num_hex = num_hex [::-1] # num_hex.sort (reverse=True) # can be achieved through slicing and the sort () function if it exceeds the decimal system Convert the ASCII code to the letter for i in range (len (num_hex)): if num_ Hexi > 9: num_ Hexi [I] = chr (int (num_ Hexi]) + 87) # print (num_hex) # list into the string result = ('. Join ('% s'% m for m in num_hex)) return resultType = bool (input ("enter 1 for decimal to arbitrary) Enter 0\ n ") for any decimal conversion if Type: hex = int (input (" how many decimal systems need to be converted? Please enter a positive integer\ n) num = int (input ("the number to be converted is:") print ("the conversion result is:", decimal_to_other (hex, num)) else: hex = int ("how many digits need to be converted to decimal? Please enter a positive integer\ nyear) num = int (input ("the number to be converted is:") print ("conversion result is:", other_to_decimal (hex, num)) Thank you for reading this article carefully. I hope the article "what are the classic basic cases of Python" shared by the editor will be helpful to you. At the same time, I hope you will support me and pay attention to the industry information channel. More related knowledge is waiting for you to learn!