-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path001. List Sorting(Add elements amd control flow)
More file actions
77 lines (67 loc) · 2.35 KB
/
001. List Sorting(Add elements amd control flow)
File metadata and controls
77 lines (67 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# List sorting (choose different algorithms according to the situation)
# A: Bubble Sort
def order():
record = input()
record_list = record.split()
record_list = list(map(float, record_list))
record_len = len(record_list)
for i in range(record_len):
swapped=False
for j in range(0, record_len - 1):
if record_list[j] > record_list[j + 1]:
record_list[j], record_list[j + 1] = record_list[j + 1], record_list[j]
swapped=True
if not swapped:
break
return record_list
order()
# B: Timsort sorting:
Sorting using the sorted() function
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list)
Sort using list.sort() method
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list)
# C: leetcode algorithm question 21. Merge two ordered linked lists
def order_list(*lists):
ordered_lists = []
for i in lists:
ordered_lists.extend(i)
ordered_lists.sort()
return ordered_lists
list1 = [1, 2, 3]
list2 = [2, 3, 4]
list3 = [19, 92, 39]
list4 = [2, -3, 48]
order_list(list1, list2, list3, list4)
# Add elements to the list
# Summarize:
# append is used to add an element to the end of the list, which is added as a whole.
# extend is used to add elements of an iterable object to a list one by one, rather than as a whole.
# Which method you choose to use depends on your needs. If you want to add a whole element to a list, use append. If you want to add elements of an iterable object to a list one by one, you can use extend.
# Python control flow
# A.Conditional Statements
if condition:
# Code to be executed when the condition is true
else:
# Code to be executed when the condition is false
## B. Looping Structures
for element in iterable:
# Loop body, code executed for each element
while condition:
# Loop body, code that is executed repeatedly when the condition is true
# C. Loop Control Statements
for element in iterable:
if condition:
break #Exit the loop
if another_condition:
continue # Skip the current iteration and continue with the next one
# D.Exception Handling
try:
# Code that may cause exceptions
exceptExceptionType:
# Code to handle exceptions
finally:
# Code that is executed regardless of whether an exception occurs