[英]python3 recursive function of n * (b(a))
I'm trying to write a function that would recursively hash a key for n times, alternating between sha224 and sha256. 我正在尝试编写一个函数,该函数将对密钥进行递归哈希n次,在sha224和sha256之间交替。 Each iteration would be hash_256(hash_224)--a hash256 for the hash224 of the key--so that it would yield n * (hash_256(hash_224)).
每次迭代都将是hash_256(hash_224)-密钥的hash224的hash256-因此它将产生n *(hash_256(hash_224))。 However, I'm new to coding and can't figure out how to write a recursive function with these parameters.
但是,我是编码的新手,无法弄清楚如何使用这些参数编写递归函数。
import hashlib
def shasum(key, n):
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8'))
hash_b = hashlib.sha256(hash_a).hexdigest()
if n == 0 or 1:
return hash_b #one iteration of 256(224)
else:
return n-1
return hash_b #stuck here
Edited: now it behaves like a number generator. 编辑:现在它的行为就像一个数字生成器。 What's wrong?
怎么了?
import hashlib
n = 0
def sha480(seed):
hashed_224 = str(hashlib.sha224(seed)).encode('utf-8')
hashed_256 = hashlib.sha256(hashed_224).hexdigest()
hashed_480 = str(hashed_256)
print("hash: " + hashed_480)
def repeater(key, n):
if n == 0:
return key
seed = str(key).encode('utf-8')
while n > 0:
return sha480(repeater(seed, n-1))
repeater('what', 2)
You have no recursive calls at all. 您根本没有递归调用。 You could change it to:
您可以将其更改为:
def hash_a(key):
return hashlib.sha224(key).hexdigest().encode('utf-8')
def hash_b(key):
return hashlib.sha256(key).hexdigest()
def shasum(key, n):
if n == 0: # base case: 0 iterations -> return key itself
return key
key = str(key).encode('utf-8')
return hash_b(hash_a(shasum(key, n - 1))) # recursve call
A side note: n == 0 or 1
is equivalent to (n == 0) or 1
which is always true. 旁注:
n == 0 or 1
等于(n == 0) or 1
,始终为true。 For that pattern, use n == 0 or n == 1
or shorter n in (0, 1)
对于该模式,
n in (0, 1)
使用n == 0 or n == 1
或更短的n in (0, 1)
Your code is nearly correct. 您的代码几乎是正确的。 just some minor issues fixed as below
只是解决了一些小问题,如下所示
import hashlib
def shasum(key, n):
print ("n: " + str(n))
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8')
print ("hash_a: " + str(hash_a))
hash_b = hashlib.sha256(hash_a).hexdigest()
print ("hash_b: " + str(hash_b))
if n == 0:
return hash_b #one iteration of 256(224)
else:
return shasum(hash_b, n-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.