class Vehicle:
def __init__(self, brand):
self._brand = brand # 私有属性用下划线表示
def set_brand(self, brand):
self._brand = brand
def get_brand(self):
return self._brand
def move(self):
print(f"{self._brand} is moving...")
class Car(Vehicle):
def __init__(self, brand, seat_count):
super().__init__(brand)
self._seat_count = seat_count
def show_info(self):
print(f"This car is a {self.get_brand()} with {self._seat_count} seats.")
def move(self):
print(f"{self.get_brand()} car is driving on the road!")
class Bike(Vehicle):
def __init__(self, brand):
super().__init__(brand)
def move(self):
print(f"{self.get_brand()} bike is cycling on the path!")
def main():
v1 = Car("Toyota", 5)
v2 = Bike("Giant")
v1.move() # 输出: Toyota car is driving on the road!
v2.move() # 输出: Giant bike is cycling on the path!
if __name__ == "__main__":
main()
def gray_code(n):
if n == 0:
return ["0"]
if n == 1:
return ["0", "1"]
prev = gray_code(n-1)
result = []
for s in prev:
____________________________
for i in range(len(prev)-1, -1, -1):
result.append("1" + prev[i])
return result
2分
登录后查看选项
11
请将下列树的深度优先遍历代码补充完整,横线处应填入( )。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def dfs(root):
if not root:
return
_________________________
stack.append(root)
while stack:
node = stack.pop()
print(node.val, end=" ")
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
2分
登录后查看选项
12
令 n 是树的节点数目,下列代码实现了树的广度优先遍历,其时间复杂度是( )。
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def bfs(root):
if not root:
return
q = deque()
q.append(root)
while q:
node = q.popleft()
print(node.val, end=" ")
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
def find_selected_bananas(bananas, dp):
selected = []
i = len(bananas) - 1
while i >= 0:
if i == 0:
selected.append(0)
break
if dp[i] == dp[i-1]:
i -= 1
else:
selected.append(i)
i -= 2
selected.reverse()
print("小猴子吃了第: ", end="")
for idx in selected:
print(idx + 1, end=" ")
print("个香蕉")
def main():
bananas = [1, 2, 3, 1] # 每个香蕉的甜度
if not bananas:
return
n = len(bananas)
dp = [0] * n
dp[0] = bananas[0]
if n > 1:
dp[1] = max(bananas[0], bananas[1])
for i in range(2, n):
dp[i] = max(bananas[i] + dp[i-2], dp[i-1])
find_selected_bananas(bananas, dp)
if __name__ == "__main__":
main()
2分
登录后查看选项
编程题 共2道
26
试题名称:划分字符串
时间限制:1.0 s
内存限制:512.0 MB
题目描述
小A有一个由 n 个小写字母组成的字符串 s。他希望将 s 划分为若干个子串,使得子串中每个字母至多出现一次。
例如,对于字符串 street 来说,str + e + e + t 是满足条件的划分;而 s + tree + t 不是,因为子串 tree 中 e 出现了两次。