我有以下代码,它们会随机生成数字大小的数量。
def createDatabase(size):
Database=[]
for j in range(0, size):
Database.append(randomNumberGenerator(100,Database))
#randomNumberGenerator is a separate function in my program
def searchDatabase(Database, guess):
if(guess in Database):
print('[True,'+str(guess)+']')
else:
print('[False,'+str(guess)+']')
我希望searchDatabase搜索以前创建的数据库。如果数据库中有猜测,它将打印[True,guess]。它不是在搜索创建的数据库。如何使其搜索数据库?我假设我想用其他东西代替“数据库”。谢谢。
答案 0 :(得分:3)
一种方法是将这两个函数实现到一个类中,如下所示:
class Database():
def __init__(self):
self.database = []
def createDatabase(self, size):
for j in range(0, size):
# I did'nt get why you pass database here, but I leaved as it is in your code
self.database.append(randomNumberGenerator(100,self.database))
def searchDatabase(self, guess):
# here I'm taking advantage of the test redundancy to shorten the code
print('[{}, {}]'.format(guess in self.database, guess))
如果您对python面向对象编程感兴趣,请参阅this question right here in Stack Overflow的答案以获取对该主题的基本介绍。
有关打印here中使用的python字符串格式的更多信息
用法示例:
db = Database()
db.createDatabase(6)
# Suppose that the database have the following numbers: 4, 8, 15, 16, 23, 42
db.searchDatabase(1)
db.searchDatabase(42)
输出
[False, 1]
[True, 42]
def createDatabase(size):
databse = []
for j in range(0, size):
# I did'nt get why you pass database here, but I leaved as it is in your code
database.append(randomNumberGenerator(100,self.database))
return database
def searchDatabase(database, guess):
# here I'm taking advantage of the test redundancy to shorten the code
print('[{}, {}]'.format(guess in database, guess))
相当于“经典”的用法示例:
db = createDatabase(6)
# Suppose that the database have the following numbers: 4, 8, 15, 16, 23, 42
searchDatabase(db, 1)
searchDatabase(db, 42)
提供与上述相同的输出