Challenge: Creating Hash Function
Uppgift
Swipe to start coding
Now you will create a simple hash function:
- Specify
input_string
andhash_size
as arguments of thesimple_mod_hash()
function. - Use the modulo (
%
) operation to create a hash value inside the function.
Note
hash_size
argument determines the number of possible hash values the function can generate, which is used to keep the hash value within a specific range.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def simple_mod_hash(input_string, hash_size):
hash_value = 0
# Sum the ASCII values of each character in the input string
for char in input_string:
hash_value += ord(char)
# Apply the modulo operation to get the hash within the specified range
hash_value = hash_value % hash_size
return hash_value
# Example usage:
input_data = "password"
hash_size = 10
result = simple_mod_hash(input_data, hash_size)
print(f"The hash value for '{input_data}' is {result}")
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 6
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def simple_mod_hash(___, ___):
hash_value = 0
# Sum the ASCII values of each character in the input string
for char in input_string:
hash_value += ord(char)
# Apply the modulo operation to get the hash within the specified range
hash_value = hash_value ___ hash_size
return hash_value
# Example usage:
input_data = "password"
hash_size = 11
result = simple_mod_hash(input_data, hash_size)
print(f"The hash value for '{input_data}' is {result}")
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal