Skip to content
DeepForgeby svx
All problems
EasyML Fundamentalsml-089

Hashing Trick Bucket

Problem

Compute a deterministic hash bucket for a string key using h = (h * 31 + ord(ch)) mod num_buckets over the characters.

Return the bucket index; a non-positive num_buckets returns 0.

Hint

Fold each character code into the running hash with multiplication by 31.

Test cases

case 1
in: ["cat",10]
expected: 2
case 2
in: ["dog",10]
expected: 4
case 3
in: ["",5]
expected: 0
case 4
in: ["apple",7]
expected: 1
Starter codePython
def hash_bucket(key, num_buckets):
    # Your code here
    pass

4 test cases · run your code against them in the editor