【问题标题】:Using binary search and recursion to search a text file使用二进制搜索和递归搜索文本文件
【发布时间】:2021-04-20 17:52:11
【问题描述】:

我想使用递归和二进制搜索在文本文件中搜索用户名和密码。每个帐户(用户名和密码)都保存在一行中,两者之间用空格隔开。

这是我目前拥有的(确实有效),只是想使用更多技术:

def validation(username1, password1):
    file = open("Accounts.txt", "r")
    for line in file:
        line = line.split("\n")
        line = line[0].split(" ")

        if username1 == line[0] and password1 == line[1]:
            main_menu()     #main_menu() will allow the user to enter the game
        else:
            valid = Label(root, text="Account not found try again or sign up")
            valid.place(x=215, y=130)
            login()        #will recall the login window and ask them to renter details 
    file.close()

我想使用以下代码:

def validation(username1, password1):
    file = open("Accounts.txt", "r")

userame1 和 passwrod1 是用户输入的详细信息。我现在想检查是否已经使用二进制搜索和递归创建了一个帐户。

Amy 关于如何做到这一点的想法?我还在学习如何编码。

【问题讨论】:

  • 你的需求还是不清楚,你提到了二进制、递归和冒泡排序?
  • @AbhinavMathur 很抱歉我已经改变了问题 x
  • 读取所有行,对该列表进行排序,然后使用二进制搜索?这里有什么问题
  • @AbhinavMathur 你能给我一个例子吗
  • @Katie010203 二分查找和递归似乎都与此任务无关。如果您想使用另一种方法,我建议创建一个以用户名作为键、密码作为值的字典。然后,如果用户名不在结果字典中,您的程序将提示创建一个新帐户;但如果是,程序会检查密码,如果错误,提示用户(使用 while 循环)输入正确的密码。

标签: python file sorting search


【解决方案1】:

您可以尝试查看特定单词是否在文本文件中:

def validation(username1, password1):
    file = open("Accounts.txt", "r")
    content = file.read()

    if str(username1) and str(password1) in content:
        return True

    else:
        return False

然后根据validation()的结果调用main_menu()或者login()

【讨论】:

  • 这是否使用递归和二分搜索? x
  • 我不会撒谎,我完全不知道。但我会说是的
  • @persephone 不,它没有。请先阅读术语
【解决方案2】:

最简单的方法是读取所有行并对其进行排序,以便可以应用二进制搜索。

def validation(username1, password1):
    file = open("Accounts.txt", "r")
    lines = [i.strip().split() for i in file.readlines()]
    # lines is a list of [username, password] sublists
    lines.sort()
    if binary_search(lines, [username1, password1]):
        login()
    else:
        print(“User Not Found”)

【讨论】:

  • “binary_search”是某种功能吗? x
  • @Katie010203 请参阅 python 标准库中的 bisect module
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多