• python练习001-实现hashcode


      卧槽居然有人看,罪过罪过。。。

      简单说下原理:

      hash是一种常用的算法,像md5.sha,常用在安全加密等方面;

      java中hashcode是用于快速查找对象物理存储区使用的,hashcode值不存在,则可以快速存储入集合;

      java官方给出的计算hashcode的算法:

      1. Integer.hashCode()实现:

        public int hashCode(){

        return value;

         }

      就是(10进制)整数的hashcode还是它本身;

      2. String.hashCode()实现为其ACII字符码:

      public int hashCode() {
        int h = hash;
        if (h == 0) {
          int off = offset;
          char val[] = value;
          int len = count;
          for (int i = 0; i < len; i++) {
          h = 31*h + val[off++];
            }
          hash = h;
          }
        return h;
      }

      就是字符串转换成ASCII码的值:

      比如:abc, ascii表中字母对应的ASCII码分别为:97、98、99

      那么,“abc”.hashcode() = 99+98*31+97*31*31=96354

      那么知道了怎么求它,就可以在python中来计算它:

      java中str的hashcode是按照32位算的,那么在64位的python我们要考虑处理内存溢出的问题,代码如下:

      def convert_n_bytes(n, b):

          bits = b * 8

          return (n + 2 ** (bits - 1)) % 2 ** bits - 2 ** (bits - 1)

      def convert_4_bytes(n):

          return convert_n_bytes(n, 4)

      def getHashCode(str):

          h = 0

          n = len(str)

          for i, c in enumerate(str):

              h = h + ord(c) * 31 ** (n - 1 - i)

          return convert_4_bytes(h)

      print(getHashCode(input(str)))

  • 相关阅读:
    Java实现蓝桥杯正则切分
    VS2013 预定义的宏
    VS2015编译boost1.62
    linux 下Qt WebEngine 程序打包简单记录
    Visual Studio 默认保存为UTF8编码
    微型Http服务器Tiny Http Server
    Bootstrap Paginator分页插件
    Web前端框架与类库
    开发与常用工具清单
    程序员修炼之道
  • 原文地址:https://www.cnblogs.com/bernard-shen/p/13342136.html
Copyright © 2020-2023  润新知