简体   繁体   中英

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. 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)). 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. For that pattern, use n == 0 or n == 1 or shorter 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM