找了一些题目,想用Python解决一下。

反向迭代一个序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 如果是一个list,最快的方法使用reverse
>>> tempList = [1, 2, 3, 4]
>>> tempList.reverse()
>>> t
[4, 3, 2, 1]

# 如果不是list,需要手动重排
>>> temp = (1, 2, 3, 4)
>>> for i in range(len(temp) - 1, -1, -1):
>>> print(temp[i])
4
3
2
1

查询替换文本中的字符串

1
2
3
4
5
6
7
8
9
10
11
# 最简单的方法使用replace()
>>> tempstr = "hello you hello python are you ok"
>>> tempstr = tempstr.replace("you", "python") # 把所有的you替换成python
'hello python hello python are python ok'

# 还可以使用正则
>>> tempstr = "hello you hello python are you ok"
>>> import re
>>> rex = r'(hello|Use)'
>>> print(re.sub(rex, "Bye", tempstr)) # 把所有hello替换成Bye
'Bye you Bye python are you ok'

python实现单例模式

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
# 方法一:可以使用__new__方法。
# 在__new__方法中把类实例绑定到类变量_instance上,如果cls._instance为None表示该类没有实例化过,实例化该类并返回。反之直接返回。

>>> class SingleTon(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args, *kwargs)
return cls._instance

# 测试
>>> class TestClass(SingleTon):
a = 1

>>> test1 = TestClass()
>>> test2 = TestClass()
>>> print(test1.a, test2.a)
1 1
>>> test1.a = 2
>>> print(test1.a, test2.a)
2 2
>>> print(id(test1), id(test2))
140666831839864 140666831839864

# 方法二:使用装饰器,建立过实例就放到instances里面,下次建立的时候先检查此里面是否有实例

>>> def SingleTon(cls, *args, **kwargs):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton

>>> @SingleTon
class LastClass(object):
a = 1

>>> test1 = LastClass()
>>> test2 = LastClass()
>>> print(test1.a, test2.a)
1 1
>>> print(id(test1), id(test2))
140666831841376 140666831841376

# 方法三:共享属性

>>> class SignalTon(object):
_state = {}
def __new__(cls, *args, **kwargs):
obj = object.__new__(cls, *args, **kwargs)
obj.__dict__ = cls._state
return obj

>>> class TestClass(SignalTon):
a = 1
>>> test1 = TestClass()
>>> test2 = TestClass()
>>> test1.a = 2
>>> print(test1.a, test2.a)
2 2

重新实现str.strip()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> def rightStrip(tempStr, splitStr):
endindex = tempStr.rfind(splitStr)
while endindex != -1 and endindex == len(tempStr)-1:
tempStr = tempStr[:endindex]
endindex = tempStr.rfind(splitStr)
return tempStr

>>> def leftStrip(tempStr, splitStr):
startindex = tempStr.find(splitStr)
while startindex == 0:
tempStr = tempStr[startindex+1:]
startindex = tempStr.find(splitStr)
return tempStr

>>> str = " H "
>>> print(str)
H
>>> print(leftStrip(str, " "))
H
>>> print(rightStrip(str, " "))
H

给列表中字典排序

1
2
3
4
5
6
7
>>> alist = [{"name": "a", "age": 20},
{"name": "b", "age": 30},
{"name": "c", "age": 25}]

>>> alist.sort(key=lambda x:x.get("age"))
>>> print(alist)
[{'name': 'a', 'age': 20}, {'name': 'c', 'age': 25}, {'name': 'b', 'age': 30}]

打乱一个排序好的列表

1
2
3
4
5
6
>>> from random import shuffle
>>> alist = range(10)
>>> v = list(alist)
>>> shuffle(v)
>>> print(v)
[6, 3, 4, 5, 1, 9, 7, 8, 2, 0]

获取最大公约数

1
2
3
4
5
6
>>> a = 25
>>> b = 15
>>> def max_common(a, b):
while b:
a, b = b, a%b
return a

获取两个数的最小公倍数

1
2
3
4
5
6
7
a = 25
b = 15
def min_common(a, b):
c = a * b
while b:
a, b = b, a%b
return c//a

实现一个简单的栈结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Stack(object):
def __init__(self):
self.value = []
def push(self, x):
self.value.append(x)
def pop(self):
s = self.value.pop()
return s

st = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.value)
stack.pop()
print(stack.value)

合并两个列表,排除重复元素

1
2
3
4
5
6
7
8
9
10
11
>>> a = ['x', 'y', 'z', 'e', 'f']
>>> b = ['a', 'b', 'c', 'd', 'e', 'f']

>>> def merge_list(*args):
s = set()
for i in args:
s = s.union(i)
return s

>>> merge_list(a, b)
{'d', 'y', 'b', 'c', 'e', 'a', 'z', 'x', 'f'}