[本文出自天外归云的博客园]
看到一个《剑指Offer》上的问题:“遇到奇数移至最前,遇到偶数移至最后。”
我做了两种解法。一种是利用python内置函数,移动过程用了插入法,很简单。另一种是自定义与数字相关的类与函数,移动的过程用了指针思想。
代码如下:
'''
解法1:利用python中与列表相关的内置函数
'''
from collections import deque def move_numbers(numbers: list, new_numbers=deque()):
numbers = deque(numbers)
while len(numbers) > 0:
if numbers[0] % 2 == 0:
number = numbers.popleft()
new_numbers.append(number)
else:
number = numbers.popleft()
new_numbers.appendleft(number)
print(list(new_numbers)) '''
解法2:自定义与数字相关的类与函数
''' class Numbers:
header = None
tail = None
numbers = None class Number:
def __init__(self, value):
self.value = value
self.next = None def __init__(self, *args):
self.numbers = tuple([Numbers.Number(arg) for arg in args])
self.install(self.numbers) def install(self, args: tuple):
for i in range(len(args)):
number = args[i]
if i == 0 and len(args) > 1:
number.next = args[i + 1]
self.header = number
if i > 0 and i < len(args) - 1:
number.next = args[i + 1]
if i == len(args) - 1 and len(args) > 1:
self.tail = number def show(self):
subs = []
index = self.header
while index:
subs.append(index.value)
index = index.next
print(subs) def move(self):
index = self.header
new_header = None
for i in range(len(self.numbers)):
_next = index.next
if index.value % 2 == 0:
index.next = None
self.tail.next = index
self.tail = index
if index.value % 2 != 0 and i != 0:
if new_header:
index.next = new_header
new_header = index
else:
new_header = index
new_header.next = self.header
self.header = new_header
index = _next
self.show() '''
题目:
遇到奇数移动到最前面
遇到偶数移动到最后面
'''
if __name__ == '__main__':
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # 解法1
move_numbers(numbers) # 解法2
Numbers(*numbers).move()
其中:
1. 内置数据类型collections.deque是python中的队列,在队头插入和弹出元素比list的insert和pop操作效率高
2. 在main函数中将list类型的numbers转化为*args进行Numbers类对象初始化