如果在函数返回的哈希值中找到子字符串,for 循环中的 if 语句将停止迭代

If statement in a for loop to stop iteration if a substring is found in a hash value returned by a function

出于教学目的,我正在寻找以下代码来执行以下操作:

  1. 函数散列,获取字符串(比方说“比特币”)和return一个散列值。
  2. for循环从0迭代到一个范围,不断添加“!”到字符串“bitcoin”,例如在迭代 1 = 比特币、迭代 2 = 比特币!、迭代 3 = 比特币!!、迭代 4 = 比特币!!!,等等。
  3. 在每种情况下,都会为字符串找到散列值(在每次迭代中,由于连接的“!”字符,会生成不同的散列值。
  4. 我在 for 循环中添加了一个 if 函数,如果该值以“00”开头,它应该停止并打印散列值。

不是。 4 我的代码中断。我尝试了各种方法,但认为我遗漏了一些非常基本的东西。

测试数据:请使用:"bitcoin"

预期结果:如果由函数 hash 编辑的哈希值 return 中有两个前导零,例如从00开始,for循环应该停止,它应该打印出for循环中的数字(i)和实际的哈希值。

import hashlib

def hash(mystring):
    hash_object=hashlib.md5(mystring.encode())
    print(hash_object.hexdigest())


mystring=input("Enter your transaction details (to hash:")


for i in range(100000000000):
    hash(mystring)
    mystring=mystring+"!"
    if "00" in hash(mystring):
        break
    print(hash(mystring))

hash(mystring)

我输入“bitcoin”得到的错误是:

Enter your transaction details (to hash:bitcoin
cd5b1e4947e304476c788cd474fb579a
520e54321f2e9de59aeb0e7ba69a628c
Traceback (most recent call last):
  File "C:/Users/testa/Desktop/bitcoin_mine_pythonexample.py", line 14, in <module>
    if "00" in hash(mystring):
TypeError: argument of type 'NoneType' is not iterable
>>> 

我也试过这个 - 尝试添加一个 return 语句并使用稍微不同的方法 - 这是否正确?

import hashlib

def hash(mystring):
    hash_object=hashlib.md5(mystring.encode())
    print(hash_object.hexdigest())
    if "00" in hash_object:
                return 1
        else:
                return 0

mystring=input("Enter your transaction details (to hash:")


for i in range(100):
    hash(mystring)
    mystring=mystring+"!"
    if hash(mystring)==1":
            print("Found")

hash(mystring)

几件事。首先,hash 没有返回任何东西,它只是打印结果然后返回 None。通过删除 print 并返回哈希值来更改它。

其次,使用 "00" in string 在字符串中的任何位置查找 "00",而不仅仅是开始。此外,主循环每次迭代调用 hash 三次。还有一个循环外对 hash 的最终调用毫无用处。

下面应该做你想做的:

def myhash(mystring):
    hash_object=hashlib.md5(mystring.encode())
    return hash_object.hexdigest()

mystring=input("Enter your transaction details (to hash:")

while True:
    hashval = myhash(mystring)
    print(hashval)
    if hashval.startswith("00"):
        break
    mystring += "!"

更新:我将 hash 重命名为 myhash 以避免覆盖 Python 中的内置 hash 函数。