我有以下代码,随机生成大小的数字数量。
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搜索之前创建的数据库。如果guess在数据库中,它将打印True,guess。它没有搜索创建的数据库。我如何让它搜索数据库?我假设我想用其他东西替换"Database“。谢谢。
发布于 2018-09-27 10:05:59
使用类
一种方法是将这两个函数实现到一个类中,如下所示:
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的答案以获得该主题的基本介绍。
有关print 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))等同于"classy“用法的示例:
db = createDatabase(6)
# Suppose that the database have the following numbers: 4, 8, 15, 16, 23, 42
searchDatabase(db, 1)
searchDatabase(db, 42)给出与上面相同的输出
https://stackoverflow.com/questions/52527885
复制相似问题