【发布时间】:2021-03-18 15:49:50
【问题描述】:
我试图在不使用 for 循环或 while 循环的情况下遍历链表。
class VaccList:
class Appointment:
def __init__(self, name, age, city, date):
assert type(name) is str, 'name variable must be a string'
assert type(age) is int, 'age variable must be a integer'
assert type(city) is str, 'city variable must be a string'
assert type(date) is datetime, 'date variable must be a datetime object'
assert name != None, 'name variable cannot be empty'
assert age >= 18 and age <= 100, 'age must be between 18 and 100'
# ADD 6 asserts. 4 for the types and name cannot be empty,
# and age must be between 18 and 100
self.name = name
self.age = age
self.city = city
self.date = date
self.confirmed = False
self.next = None
def __str__(self):
s = "Appointment for " + self.name + " on " + str(self.date) + " age:" + str(self.age) + " city:" + self.city
if self.confirmed:
s += " (confirmed)"
else:
s += " (unconfirmed)"
return s
def __init__(self):
self.head = None
self.tail = None
def confirm(self, name):
'''
Find an appointment for a person with the given name and set confirmed to true.
Return a string message "not found", "confirmed", "already confirmed."
'''
# Note... no loop!
# assert, type of name and non-empty string
assert type(name) is str, 'name variable must be a string'
assert name != None
current = self.head
if current.name == name:
if current.confirmed == False:
current.confirmed = True
return 'confirmed'
else:
return 'already confirmed'
这是我创建的课程中的方法,我正在尝试确认约会,除非它们已经被确认。我可以确认第一次约会,但如果我正在搜索的姓名不是约会列表中的第一个名字,我将如何找到下一个要检查的名字?
【问题讨论】:
-
你可以尝试使用递归
-
为什么要尝试在没有循环的情况下执行此操作?你能使用另一种不需要线性搜索的数据结构吗?
-
@Samwise 只在没有循环的情况下这样做,因为它意味着学校项目。
-
为了回答这个问题,我们至少需要看一下链表中节点的结构。请edit您的问题并添加此内容。
-
问我如何得知 Python 缺乏 TCO(这是在现实世界中,哈哈)
标签: python recursion linked-list