if语句,用于在函数返回的哈希值中找到子字符串时停止迭代

j7dteeu8  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(231)

我有以下代码,出于教学目的,正在寻求执行以下操作:
函数hash,获取字符串(比如说“比特币”)并返回哈希值。
for循环从0迭代到一个范围,并不断添加“!”到字符串“比特币”,例如在迭代1=比特币,迭代2=比特币!,迭代3=比特币!!,迭代4=比特币!!!,等等
在每种情况下,都会找到字符串的哈希值(在每次迭代中,由于连接的“!”而生成不同的哈希值)性格
我在for循环中添加了一个if函数,如果值以“00”开头,该函数应该停止并打印哈希值。
我的代码在第四位中断。我尝试过各种方法,但我觉得我缺少一些基本的东西。
测试数据:请使用“比特币”
预期结果:如果函数hash返回的哈希值中有两个前导零,例如以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)

我在输入“比特币”时遇到的错误是:

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)
b91juud3

b91juud31#

有几件事。第一, 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 += "!"

更新:我重新命名了 hashmyhash 为了避免覆盖内置的 hash 函数。

相关问题