zoukankan      html  css  js  c++  java
  • 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)))

  • 相关阅读:
    webpack
    线程和同步
    C#高性能TCP服务
    平台架构实践
    异步
    net MVC 的八个扩展点
    Python计算&绘图——曲线拟合问题(转)
    最小二乘法多项式曲线拟合原理与实现(转)
    Apache Commons Math3学习笔记(2)
    最小二乘法拟合java实现源程序(转)
  • 原文地址:https://www.cnblogs.com/bernard-shen/p/13342136.html
Copyright © 2011-2022 走看看