# List of python algorithms

Posted by wildncrazyath3rt on Fri, 04 Mar 2022 19:34:38 +0100

# List of python algorithms

### Basic Usage

```car = ['audi','bmw','benchi','lingzhi']
```
• Create a list of numbers

```numbers = list(range(1,4))
>>> print(numbers)
[1, 2, 3]
```
• Access values in the list

```car = ['audi','bmw','benchi','lingzhi']
>>> print(car[0].title())
Audi
>>> print(car[2].title())
Benchi
```

#The title() method takes any list element and capitalizes the first letter

```list1 = ['Google','baidu','1997','2000']
list2 = [1,2,3,4,5,6,7]
>>> print("list1[0]:",list1[0])
>>> print("list2[0]:",list2[1:5])
list2[0]: [2, 3, 4, 5]
```

#The index starts from 0. For example, if the index is 0, it means the first one, and if the index is 1, it means the second one; Index intervals are generally left closed and right open. For example, [1,5] indicates from index 1 to index 4, that is, the second to fifth.

### Delete duplicate elements and leave the order unchanged

If the elements saved in the sequence are hashable, the function of de duplication can be realized by collection and generator. Examples are as follows:

```def dedupe(items):
seen = set()        #Create an empty collection
for item in items:
if item not in seen:
yield item

if __name__ == '__main__':
a = [5,5,2,1,9,1,5,10]
print(a)
print(list(dedupe(a)))
#output
'''
[5, 5, 2, 1, 9, 1, 5, 10]
[5, 2, 1, 9, 10]
'''
```

Yield is actually equivalent to return, but the existence of yield is a generator rather than a function. Please refer to the article for details Portal

About collections: the elements in a collection are not repeated and have no order. The basic purposes of collections are member testing and de duplication of entries. Set objects also support mathematical operations such as union, intersection, difference and symmetric difference. Curly braces or the set() function can be used to create a collection. Note: to create an empty set, you must use set (), not {}; The latter will create an empty dictionary.

About hashing: if an object is hashable, its lifetime must be immutable. In python, integers, floating-point numbers, strings and tuples are immutable, that is, hashable.

• If in a sequence of non hashable objects

In the following list a, the element is a dictionary and is not hashable.

Idea: convert non hashable to hashable, and then operate.

```def buha(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item

if __name__ == '__main__':
a = [
{'x':2, 'y':3},
{'x':1, 'y':4},
{'x':2, 'y':3},
{'x':2, 'y':3},
{'x':10, 'y':15}
]
print(a)
print(list(buha(a, key=lambda a: (a['x'],a['y']))))
#The lambda function converts {X ': 2,' y ': 3} into a (2,3) hashable object
#output
'''
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 2, 'y': 3}, {'x': 2, 'y': 3}, {'x': 10, 'y': 15}]
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 10, 'y': 15}]
'''
```

### Find the most frequent element in the list

Use most in the Counter class in the collections module_ The common () method can be implemented

```from collections import Counter
words = [
'look','into','my','AAA','look','my','AAA','the','look','AAA','my','into',
'the'
]
word_counts = Counter(words)  #The Counter class counts the number of occurrences of each element
top_three = word_counts.most_common(3)  #most_ The method of common returns up to three elements
print(word_counts)
print(top_three)
#output
'''
Counter({'look': 3, 'my': 3, 'AAA': 3, 'into': 2, 'the': 2})
[('look', 3), ('my', 3), ('AAA', 3)]
'''
```

### Example of sorting class definition

```from operator import attrgetter
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
#Original order
users = [User(19), User(17), User(18)]
print(users)

#According to user_id order
print(sorted(users, key=lambda u:u.user_id))  #Using lambda functions
print(sorted(users, key=attrgetter('user_id'))) #Use operator Attrgetter() built in function

#output
'''
[User(19), User(17), User(18)]
[User(17), User(18), User(19)]
[User(17), User(18), User(19)]
'''
```

```sorted(iterable, key=None, reverse=False)
'''
iterable -- Iteratable object.
key -- It is mainly used to compare the elements. There is only one parameter. The parameters of the specific function are taken from the iteratable object. Specify an element in the iteratable object to sort.
reverse -- Collation, reverse = True In descending order, reverse = False Ascending (default).
'''
```

### Use list derivation

List derivation is a beautiful method to simplify the code. It can construct a new list very concisely. The obtained elements can be transformed and deformed with a simple expression.

The syntax format is as follows:

```variable = [out_exp_res for out_exp in input_list if out_exp==2]
'''
out_exp_res: List generated element expression, which can be a function with return value
for out_exp in input_list: iteration input_list, take out_exp afferent out_exp_res In expression
if out_exp==2: Judge which values can be filtered according to the conditions
'''
```

Example: create a square list from 1 to 10

```#tradition
squares = []
for x in range(10):
squares.append(x**2)
print(squares)

#concise
exmple = [i**2 for i in range(1,11)]
print(exmple)
'''
output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
'''
```

Example: output an integer that can be divided by 3 within 30

```#tradition
squares = []
for x in range(30):
if x%3==0:
squares.append(x)
print(squares)

#concise
exmple = [i for i in range(30) if i%3==0]  #Or i%3 is 0
print(exmple)
'''
output
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
'''
```

Example: output the square of an integer that can be divided by 3 within 30

```#Functions can be used
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i%3 is 0]
print(multiples)

#Of course, it can also be more concise
exmple = [i**2 for i in range(30) if i%3 is 0]
print(exmple)
'''
output
[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
'''
```
• Filter data in list

```mylist = [1,4,-5,10,-7,2,3,-1]
#All positive values
zheng = [n for n in mylist if n>0]
print(zheng)

#All negative values
fu = [n for n in mylist if n<0]
print(fu)

'''
output
[1, 4, 10, 2, 3]
[-5, -7, -1]
'''
```
• If exception handling or other complex details are involved in the filtering process, you can consider putting the code in a single function.

```values = ['1','2','-3','-','4','N/A','5']
def is_int(val):
try:
x = int(val)
return True
except ValueError:
return False
ivals = list(filter(is_int, values))
print(ivals)
'''
output
['1', '2', '-3', '4', '5']
'''
```

#The filter function is used to filter the sequence. The receives two parameters. The first is a function and the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment, and then returns True or False. Finally, the element that returns True is placed in the new list.

### Named slice

slice() function can be used to realize slicing object and parameter transfer function in slicing operation function. It can be used in any place where slicing operation is allowed.

```class slice(stop)
class slice(start, stop[,step])
'''
star Starting position
stop End position
step step
'''
```

Example:

```items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2,4)
print(items[2:4])  #[2,3]
print(items[a])      #[2,3]
items[a] = [10, 11]
print(items)  #[0, 1, 10, 11, 4, 5, 6]
print(a.start)  #2
print(a.stop)  #3
print(a.step)   #None
s = 'HelloWorld'
print(a.indices(len(s)))  #(2, 4, 1)
for i in range(*a.indices(len(s))):
# *The function of number is to disassemble the iteratable sequence as the argument of the function
#Here is to split the tuple (2, 4, 1) into 2, 4, 1
print(s[i])   #l  #l
```

Indexes (len) function, whose return value is a tuple composed of three integer numbers; These numbers are the start and stop index numbers and step step values of the slice, respectively. Return when len is greater than or equal to stop (start, stop, step), and return when len is less than stop (start, len, step)

For * in python, refer to the article Portal

Topics: Python Algorithm list