首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >搜索在单独函数中生成的值

搜索在单独函数中生成的值
EN

Stack Overflow用户
提问于 2018-09-27 08:49:18
回答 1查看 44关注 0票数 0

我有以下代码,随机生成大小的数字数量。

代码语言:javascript
复制
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“。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-09-27 10:05:59

使用类

一种方法是将这两个函数实现到一个类中,如下所示:

代码语言:javascript
复制
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字符串格式的详细信息

用法示例:

代码语言:javascript
复制
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)

输出

代码语言:javascript
复制
[False, 1]
[True, 42]

没有类

代码语言:javascript
复制
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“用法的示例:

代码语言:javascript
复制
db = createDatabase(6)
# Suppose that the database have the following numbers: 4, 8, 15, 16, 23, 42
searchDatabase(db, 1)
searchDatabase(db, 42)

给出与上面相同的输出

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52527885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档