50 lines of code, Python from getting started to getting into the ground

In the process of learning python, you will always find that Python can easily solve many problems. Some complex tasks can even be done with a line of Python code. Next, little F introduces 50 very practical Python lines of code. I hope you can find helpful skills

1. Letter ectopic words

If two words contain the same letters in different order, they are called anagram. For example, "silent" and "listen" are letter translocations, while "apple" and "aplee" are not translocations.

from collections import Counter

s1 = 'below'
s2 = 'elbow'

print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')

You can tell by using a line of Python code.

2. Binary to decimal

decimal = int('1010', 2)
print(decimal) #10

3. Convert string to lowercase

print("Hi my name is XiaoF".lower())
# 'hi my name is xiaof'

print("Hi my name is XiaoF".casefold())
# 'hi my name is xiaof'

4. Convert string to uppercase

print("hi my name is XiaoF".upper())
# 'HI MY NAME IS XIAOF'

5. Convert string to bytes

print("convert string to bytes using encode method".encode())
# b'convert string to bytes using encode method'

6. Copy file

import shutil

shutil.copyfile('source.txt', 'dest.txt')

7. Quick sort

qsort = lambda l: l if len(l) <= 1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])

print(qsort([17, 29, 11, 97, 103, 5]))
# [5, 11, 17, 29, 97, 103]

8. Sum of n consecutive numbers

n = 10

print(sum(range(0, n+1)))
# 55

9. Exchange the values of two variables

a,b = b,a

10. Fibonacci sequence

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)

print(fib(20))
# 6765

11. Merge nested lists into one list

main_list = [[0, 1, 2], [11, 12, 13], [52, 53, 54]]

result = [item for sublist in main_list for item in sublist]
print(result)

>
[0, 1, 2, 11, 12, 13, 52, 53, 54]

12. Run an HTTP server

python3 -m http.server 8000
python2 -m SimpleHTTPServer

13. Reverse list

numbers = [0, 1, 2, 11, 12, 13, 52, 53, 54]

print(numbers[::-1])
# [54, 53, 52, 13, 12, 11, 2, 1, 0]

14. Factorial

import math

fact_5 = math.factorial(5)
print(fact_5)
# 120

15. Use for and if in list derivation

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]

print(even_list)
# [2, 4]

16. The longest string in the list

words = ['This', 'is', 'a', 'list', 'of', 'words']

result = max(words, key=len)
print(result)
# 'words'

17. List derivation

li = [num for num in range(0, 10)]

print(li)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

18. Set derivation

num_set = {num for num in range(0, 10)}

print(num_set)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

19. Dictionary derivation

dict_numbers = {x: x*x for x in range(1, 5)}

print(dict_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16}

20,if-else

print("even") if 4 % 2==0 else print("odd")

21. Infinite cycle

while 1:0

22. Check data type

print(isinstance(2, int))
# True

print(isinstance("allwin", str))
# True

print(isinstance([3, 4, 1997], list))
# True

23. While cycle

a = 5

while a > 0:
    a = a - 1

print(a)
# 0

24. Write the file with print statement

print("Hello, World!", file=open('file.txt', 'w'))

The information can be printed out and saved as a file.

25. Calculate the frequency of a character in the string

print("umbrella".count('l'))
# 2

26. Consolidated list

list1 = [1, 2, 4]
list2 = ['XiaoF']
list1.extend(list2)

print(list1)
# [1, 2, 4, 'XiaoF']

27. Merge dictionary

dict1 = {'name': 'weiwei', 'age': 23}
dict2 = {'city': 'Beijing'}
dict1.update(dict2)

print(dict1)
# {'name': 'weiwei', 'age': 23, 'city': 'Beijing'}

28. Merge sets

set1 = {0, 1, 2}
set2 = {11, 12, 13}
set1.update(set2)

print(set1)
# {0, 1, 2, 11, 12, 13}

29. Time stamp

import time

print(time.time())

30. The most frequent element in the list

test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)

print(most_frequent_element)
# 4

31. Nested list

numbers = [[num] for num in range(10)]

print(numbers)
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

32. Octal to decimal

print(int('30', 8)) 
# 24

33. Convert key value pairs to dictionaries

result = dict(name='XiaoF', age=23)

print(result)
# {'name': 'XiaoF', 'age': 23}

34. Quotient and remainder

quotient, remainder = divmod(4, 5)

print(quotient, remainder)
# 0 4

The divmod() function returns a tuple containing quotient and remainder when parameter 1 is divided by parameter 2.

35. Delete duplicate items in the list

print(list(set([4, 4, 5, 5, 6])))
# [4, 5, 6]

36. Sort the list in ascending order

print(sorted([5, 2, 9, 1]))
# [1, 2, 5, 9]

37. Sort the list in descending order

print(sorted([5, 2, 9, 1], reverse=True))
# [9, 5, 2, 1]

38. Get lowercase alphabet

import string

print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz

39. Get the capital alphabet

import string

print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ

40. Get 0 to 9 strings

import string

print(string.digits)
# 0123456789

41. Hexadecimal to decimal

print(int('da9', 16))
# 3497

42. Date and time

import time

print(time.ctime())
# Thu Aug 13 20:00:00 2021

43. Convert the string in the list to an integer

print(list(map(int, ['1', '2', '3'])))
# [1, 2, 3]

44. Sort the dictionary with the key

d = {'one': 1, 'four': 4, 'eight': 8}
result = {key: d[key] for key in sorted(d.keys())}

print(result)
# {'eight': 8, 'four': 4, 'one': 1}

45. Sort dictionaries with key values

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
result = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

46. List rotation

li = [1, 2, 3, 4, 5]

# li[n:] + li[:n], right to left
print(li[2:] + li[:2])
# [3, 4, 5, 1, 2]

# li[-n:] + li[:-n], left to right
print(li[-1:] + li[:-1])
# [5, 1, 2, 3, 4]

47. Remove the number from the string

message = ''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))

print(message)
# abcdeffgvcg

48. Matrix transformation

old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
result = list(list(x) for x in zip(*old_list))

print(result)
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]

49. List filtering

result = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))

print(result)
# [2, 4, 6]

50. Unpacking

a, *b, c = [1, 2, 3, 4, 5]

print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5

Python is a very diverse and well-developed language, so there must be many functions I didn't consider. If you know, you can tell me in the comment area

Added by csj16 on Tue, 14 Dec 2021 11:03:34 +0200