Python算法笔试题目,破解Hash值,回溯法

本文介绍了一种使用回溯法解决特定字符串哈希问题的方法。通过枚举指定字符集内的所有可能组合来找到匹配特定哈希值的8位字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Find the string which has this hash: 25267566250558

The string has length8.

Characters can befrom: c,e,i,a,r,w,u,s,p


The hash functionworks like this:

hash(str):

    1.LETTERS = c, e, i, a, r, w, u, s, p

    2. h =7

    3. forc in str:

        1.i = index of c in LETTERS

        2.h = 37 * h + i

    4.return h


Please send us thestring you found, and the code you used to find it.


上边是题目。

下边是使用回溯法的枚举解法,运行代码几分钟后出现结果:

# calculate the hash number of the str_hash
str_hash_length = 8
hash_result = 25267566250558
LETTERS = ['c', 'e', 'i', 'a', 'r', 'w', 'u', 's', 'p']


def calculate_hash(str_hash):     
    h = 7
    for c in str_hash:
        # print c
        i = LETTERS.index(c) #+ 1 ###
        # print i,
        h = 37*h + i
    return h

## for test of calculate_hash()
# str_hash = 'ec'
# print calculate_hash(str_hash)


## calculate the str_hash using n-nary and recursive
# instialize a list to store the characters
str_hash_list = ['' for i in xrange(str_hash_length)]
# print 'the type is ',type(str_hash_list)
def find_str(k):    
    if str_hash_length == k:        
        # this conversion can move to just before it needs to print
        str_hash = ''.join(str_hash_list)
        str_hash_value = calculate_hash(str_hash)        
        # print str_hash_value
        if str_hash_value == hash_result:
            print "yes! the string '%s' is found ,its hash is %d" %(str_hash,str_hash_value)
        #return   ##!neglected, will it be ok when negelected?, ans: yes

        ## can add

    else:
        for c in LETTERS:
            #if str_hash_list[len(str_hash_list)-1] is not '':
            #print str_hash_list               
            str_hash_list[k] = c
            find_str(k+1)

def main():
    find_str(0)

if __name__ == '__main__':
    main()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值