1. Bubble sorting
lis = [56,12,1,8,354,10,100,34,56,7,23,456,234,-58] def sortport(): for i in range(len(lis)-1): for j in range(len(lis)-1-i): if lis[j]>lis[j+1]: lis[j],lis[j+1] = lis[j+1],lis[j] return lis if __name__ == '__main__': sortport() print(lis)
2. Method to calculate the n th power of x
def power(x,n): s = 1 while n > 0: n=n-1 s=s*x return s print(power(2,4))
3. Calculate a*a + b*b + c*c +
def calc(*numbers): sum=0 for n in numbers: sum=sum+n*n return sum print(calc(2,4,5))
4. Calculate factorial n!
#Method 1 def fac(): num = int(input("Please enter a number:")) factorial = 1 #See if the number is negative, 0 or positive if num<0: print("Sorry, negative numbers don't have factorials") elif num == 0: print("0 The factorial of is 1") else: for i in range(1,num+1): factorial = factorial*i print("%d The factorial is%d"%(num,factorial)) if __name__ == '__main__': fac()
#Method two def fac(): num = int(input("Please enter a number:")) #See if the number is negative, 0 or positive if num<0: print("Sorry, negative numbers don't have factorials") elif num == 0: print("0 The factorial of is 1") else: print("%d The factorial is%d"%(num,factorial(num))) def factorial(n): result = n for i in range(1,n): result=result*i return result if __name__ == '__main__': fac()
#Method three def fac(): num = int(input("Please enter a number:")) #See if the number is negative, 0 or positive if num<0: print("Sorry, negative numbers don't have factorials") elif num == 0: print("0 The factorial of is 1") else: print("%d The factorial is%d"%(num,fact(num))) def fact(n): if n == 1: return 1 return n * fact(n - 1) if __name__ == '__main__': fac()
5. List all files and directory names under the current directory
import os for d in os.listdir('.'): print(d)
6. Change all strings in a list to lowercase:
L = ['Hello','World','IBM','Apple'] print([s.lower()for s in L])#All strings in the whole list become lowercase, and a list is returned for s in L: s=s.lower() print(s) #Change each string in the list to lowercase and return each string
7. Output the paths of all files and folders under a certain path
import os def print_dir(): filepath = input("Please enter a path") if filepath == "": print("please enter a correct path") else: for i in os.listdir(filepath): #Get the list of files and subdirectories in the directory print(os.path.join(filepath,i)) #Combine paths print(print_dir())
8. Output a path and all file paths under its subdirectories
import os def show_dir(filepath): for i in os.listdir(filepath): path = (os.path.join(filepath,i)) print(path) if os.path.isdir(path): #isdir() to determine whether it is a directory show_dir(path) #If directory, use recursive method filepath = "E:\BaiduYunDownload" show_dir(filepath)
9. Output a path and all files with. html suffix under its subdirectory
import os def print_dir(filepath): for i in os.listdir(filepath): path = os.path.join(filepath,i) if os.path.isdir(path): #isdir() to determine whether it is a directory print_dir(path) #If directory, use recursive method if path.endswith(".html"): print(path) filepath = "E:\BaiduYunDownload" print_dir(filepath)
10. Reverse the key value of the original dictionary and produce a new dictionary
dict1 = {"A":"a","B":"b","C":"c"} dict2 = {y:x for x,y in dict1.items()} print(dict2) #The output result is {'a': 'a', 'B':'b ',' C ':'c'}
11. Print multiplication table
for i in range(1,10): for j in range(1,i+1): print('%d x %d = %d \t'%(j,i,i*j),end='') #By specifying the value of the end parameter, you can cancel the output of carriage return at the end to achieve no line wrapping. print()
12. Replace all 3 in the list as 3a
num = ["harden","lampard",3,34,45,56,76,87,78,45,3,3,3,87686,98,76] print(num.count(3)) print(num.index(3)) for i in range(num.count(3)): #Get 3 occurrences ele_index = num.index(3) #Get the coordinates of the first 3 occurrences num[ele_index]="3a" #Amendment 3 is 3a print(num)
13. Print each name
L = ["James","Meng","Xin"] for i in range(len(L)): print("Hello.%s"%L[i])
14. Merger and de duplication
list1 = [2,3,8,4,9,5,6] list2 = [5,6,10,17,11,2] list3 = list1 + list2 print(list3) #Do not duplicate, only combine two lists print(set(list3)) #De duplication, type set needs to be converted to list print(list(set(list3)))
15. Two ways of randomly generating verification code (alphanumeric)
import random list1=[] for i in range(65,91): list1.append(chr(i)) #Append asii to the empty list through for loop traversal for j in range (97,123): list1.append(chr(j)) for k in range(48,58): list1.append(chr(k)) ma = random.sample(list1,6) print(ma) #List obtained ma = ''.join(ma) #Convert list to string print(ma)
16. Calculation of square root
num = float(input('Please enter a number:')) num_sqrt = num ** 0.5 print('%0.2f The square root of is%0.2f'%(num,num_sqrt))
17. Judge whether the string is only composed of numbers
#Method 1 def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except(TypeError,ValueError): pass return False t="a12d3" print(is_number(t))
#Method two t = "q123" print(t.isdigit()) #Check whether the string is composed of numbers only
#Method three t = "123" print(t.isnumeric()) #This method is only for unicode objects
18. Judge odd and even numbers
#Method 1 num = int(input('Please enter a number:')) if (num % 2) == 0: print("{0}Even numbers".format(num)) else: print("{0}It's odd.".format(num))
#Method two while True: try: num = int(input('Please enter an integer:')) #Judge whether the input is an integer, not a pure number, and need to be re entered except ValueError: print("The input is not an integer!") continue if (num % 2) == 0: print("{0}Even numbers".format(num)) else: print("{0}It's odd.".format(num)) break
19. Determine leap year
#Method 1 year = int(input("Please enter a year:")) if (year % 4) == 0: if (year % 100) == 0: if(year % 400) ==0: print("{0}It is a leap year.".format(year)) #Leap years are the ones that can be divided by 400 else: print("{0}Not a leap year.".format(year)) else: print("{0}It is a leap year.".format(year)) #Leap years are those that can be divided by four else: print("{0}Not a leap year.".format(year))
#Method two year = int(input("Please enter a year:")) if (year % 4) == 0 and (year % 100)!=0 or (year % 400) == 0: print("{0}It is a leap year.".format(year)) else: print("{0}Not a leap year.".format(year))
#Method three import calendar year = int(input("Please enter the year:")) check_year=calendar.isleap(year) if check_year == True: print("%d It is a leap year."%year) else: print("%d It's the year of peace."%year)
20. Get the maximum value
N = int(input('Enter the number of numbers to compare:')) print("Please enter the number to compare:") num = [] for i in range(1,N+1): temp = int(input('Please input number 1.%d Number:'%i)) num.append(temp) print('The number you entered is:',num) print('The maximum value is:',max(num))
N = int(input('Enter the number of numbers to compare:\n')) num = [int(input('Please input number 1.%d Number:\n'%i))for i in range(1,N+1)] print('The number you entered is:',num) print('The maximum value is:',max(num))