前几年经历过python从入门到放弃,最近重拾python的体会是,如果熟悉或精通类C语言,整体上可以快速、轻松的掌握基本特性。因为既然是编程语言,很多特性都是举一反三、触类旁通的,上手成本较小。工作上有了用武之地,也可以用它来巩固数据结构。
链表 - 实现反转链表
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
import ListNode
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
def reverseN(head, cnt):
if cnt == 1:
return head
tail = head.next
_head = reverseN(tail, cnt - 1)
head.next = tail.next
tail.next = head
return _head
dummy_node = ListNode(-1, head)
pre = dummy_node
for _ in range(left - 1):
pre = pre.next
cur = pre.next
pre.next = reverseN(cur, right - left + 1)
return dummy_node.next
与java 用时和内存对比:
队列 - 实现循环队列
class MyCircularDeque:
def __init__(self, k: int):
self.size = 0
self.head = 0
self.tail = 0
self.elements = [0] * k
def insertLast(self, value):
if self.isFull():
return False
self.elements[self.tail] = value
self.tail = (self.tail + 1) % len(self.elements)
self.size += 1
return True
def insertFront(self, value: int) -> bool:
if self.isFull():
return False
self.head = (self.head - 1 + len(self.elements)) % len(self.elements)
self.elements[self.head] = value
self.size += 1
return True
def deleteFront(self) -> bool:
if self.isEmpty():
return False
self.head = (self.head + 1) % len(self.elements)
self.size -= 1
return True
def deleteLast(self) -> bool:
if self.isEmpty():
return False
self.tail = (self.tail - 1 + len(self.elements)) % len(self.elements)
self.size -= 1
return True
def getFront(self) -> int:
if self.isEmpty():
return -1
return self.elements[self.head]
def getRear(self) -> int:
if self.isEmpty():
return -1
return self.elements[(self.tail - 1 + len(self.elements)) % len(self.elements)]
def isEmpty(self) -> bool:
return self.size == 0
def isFull(self) -> bool:
return self.size == len(self.elements)
与java 用时及内存对比:
栈 - 实现基本计算器
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
def calculate(s: str) -> int:
def getPriority(opt) -> int:
if opt == '+':
return 1
if opt == '-':
return 1
if opt == '*':
return 2
if opt == '/':
return 2
return -1
def cal(num1, num2, opt) -> int:
if opt == '+':
return num1 + num2
if opt == '-':
return num1 - num2
if opt == '*':
return num1 * num2
if opt == '/':
return int(num1 / num2)
raise Exception()
s = s + '#'
length = len(s)
stack_num = []
stack_opt = []
num = 0
for i in range(length):
if s[i] != ' ' and s[i].isdigit():
num = num * 10 + (ord(s[i]) - ord('0'))
else:
stack_num.append(num)
num = 0
while len(stack_opt) > 0 and getPriority(s[i]) <= getPriority(stack_opt[-1]):
num2 = stack_num.pop()
num1 = stack_num.pop()
opt = stack_opt.pop()
ret = cal(num1, num2, opt)
stack_num.append(ret)
stack_opt.append(s[i])
return stack_num[-1]
与java 用时及内存对比: