Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

hash() python

# Using the built in hash() function in Python, which will return an integer.
my_int = 65244
my_string = "Hello World!"

print(hash(my_int)) # Returns 65244, because it was an int originally.

print(hash(my_string)) # Returns a long integer, such as -8213909634957577290

"""
PLEASE NOTE:
The hash() function will return the same result each time it is
executed with the same string, until you stop the code. Each time you run the
script, the results will differ. 

For example, the following would return True:
"""
hash("Hello") == hash("Hello")
"""
However, the exact value will change each time you rerun the program. 
The only way to stop it is to ctreate an environment variable called
PYTHONHASHSEED, and set it to an integer.
That way, it will not generate a new random seed every time you run the script.
"""
Comment

hash with python

import hashlib

name = "grepper"
hashed_name = hashlib.sha256(hashed_name.encode('utf-8')).hexdigest())
print(hashed_name)
# result: 82475175ad97f60d1e2c57ef5fd8ae45629d555e1644d6f2a37b69b550a96e95
Comment

hash function in Python

# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))
Comment

python hash

from hashlib import blake2b
import time
k = str(time.time()).encode('utf-8')
h = blake2b(key=k, digest_size=16)
h.hexdigest()
Comment

how to do hashing in python

string = "Countries"
print(hash(string))
Comment

Hash Table python

"""Hash Table
THIS HASH TABLE ASSUMES THAT YOU ARE PUTTING UNIQUE KEYS WHEN YOU...
...CALL put FUNCTION, 
MAKE AN UPDATE FUNCTION IF YOU ARE PUTTING REPEATED KEYS

Included:
	- hash / rehash (using linear probe)
	- load factor
    - put
	- get

Not included:
	- Get prime/ Check prime
    - Resize
    - Update
    and more...
"""
import fractions
class HashTable:
    def __init__(self, size):
        self._size = size
        self._used = 0
        self._keys = [None]*size
        self._values = [None]*size
        
    def hash_function(self, key):
        return (key % self._size)
    
    def rehash(self, old_key):
        return self.hash_function(old_key + 1) # Linear Probe
    
    def load_factor(self):
        return fractions.Fraction(self._used, self._size)
    
    def full(self):
        return self.load_factor() == 1
    
    def put(self, key, value):
        if self.full():
            return "Full"
        
        # There is empty space
        # Get digest
        digest = self.hash_function(key)
        
        # Resolve collisions
        # Rehash if not empty or key does not exist
        while self._keys[digest] is not None and self._keys[digest] != key:
            digest = self.rehash(digest)
            
        # Don't put if key already exists
        if self._keys[digest] == key:
            return "Exists"
        
        # Finally can put in empty space
        else:
            self._keys[digest] = key
            self._values[digest] = value
            self._used += 1 # update used space counter
            return "Entered"
            
    def get(self, key):
        # Get digest
        digest = self.hash_function(key)
        
        # Within the range of the total space
        for _ in range(self._size):
            if self._keys[digest] != key:
                digest = self.rehash(digest)
            else:
                return self._values[digest]
        
        # Not found
        return "Not found"
        
# Test
from randstr import randstr
from random import randint
def HT_Test(HT):
    print(f">>> HashTable:")
    # Make keys and values
    r = randint(8, 15)
    keys = [randint(10, 100) for _ in range(r)]
    vals = list(randstr(len(keys)))
    print(f"Keys to enter: {keys}",
          f"Vals to enter: {vals}",
          f"Key-value pair: {list(zip(keys, vals))}",   # display one list with key-value pair
          sep = "
", end = "

")
    
    # Initiate Hash Table
    H = HT(len(keys) - 2)
    
    # Put the key-value pair into Hash Table
    print("Put:")
    for i in range(len(keys)):
        key, val = keys[i], vals[i]
        print(f"Key: {key}",
              f"Status: {H.put(key, val)}",
              f"Load factor: {H.load_factor()}", 
              sep = " | ")
    print()
    print(f"Keys entered: {H._keys}",
          f"Values entered: {H._vals}", 
          sep = "
", end = "

")
    
    # Get the values in Hash Table for each corresponding key
    print("Get:")
    for key in keys:
        print(f"Key: {key}",
              f"({H.get(key)})",
              sep = " | ")
Comment

hash table python

A hash table is a dictionary in python

has_table = {'key_name': key_value}
Comment

PREVIOUS NEXT
Code Example
Python :: how to input n space separated integers in python 
Python :: creating an apis with python and flask 
Python :: vscode python workding directory 
Python :: download image from url 
Python :: mapping with geopandas 
Python :: 2d arrays using python numpy 
Python :: code folding vim python 
Python :: argmax implementation 
Python :: load static 
Python :: celery timezone setting django 
Python :: Create chatbot in Python - Source: NAYCode.com 
Python :: python swap numbers 
Python :: Filter Pandas rows by specific string elements 
Python :: get file parent directory python 
Python :: add list to end of list python 
Python :: create pandas dataframe 
Python :: why to use self in python 
Python :: pydub play audio 
Python :: python replace n with actual new line 
Python :: list reverse method in python 
Python :: how to set numerecal index in pandas 
Python :: python - count number of occurence in a column 
Python :: slice in python 
Python :: read an excel file 
Python :: create a virtual environment in python3 
Python :: python code for extracting data from pdf 
Python :: python is space 
Python :: python check variable size in memory 
Python :: Change Python interpreter in pycharm 
Python :: check if number is prime python 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =