MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / hamming

Function hamming

maths/special_numbers/hamming_numbers.py:8–46  ·  view source on GitHub ↗

This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param n_element: The number of elements on the list :return: The nth element of the list >>> hamming(-5) Traceback (most

(n_element: int)

Source from the content-addressed store, hash-verified

6
7
8def hamming(n_element: int) -> list:
9 """
10 This function creates an ordered list of n length as requested, and afterwards
11 returns the last value of the list. It must be given a positive integer.
12
13 :param n_element: The number of elements on the list
14 :return: The nth element of the list
15
16 >>> hamming(-5)
17 Traceback (most recent call last):
18 ...
19 ValueError: n_element should be a positive number
20 >>> hamming(5)
21 [1, 2, 3, 4, 5]
22 >>> hamming(10)
23 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12]
24 >>> hamming(15)
25 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
26 """
27 n_element = int(n_element)
28 if n_element < 1:
29 my_error = ValueError("n_element should be a positive number")
30 raise my_error
31
32 hamming_list = [1]
33 i, j, k = (0, 0, 0)
34 index = 1
35 while index < n_element:
36 while hamming_list[i] * 2 <= hamming_list[-1]:
37 i += 1
38 while hamming_list[j] * 3 <= hamming_list[-1]:
39 j += 1
40 while hamming_list[k] * 5 <= hamming_list[-1]:
41 k += 1
42 hamming_list.append(
43 min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5)
44 )
45 index += 1
46 return hamming_list
47
48
49if __name__ == "__main__":

Callers 1

hamming_numbers.pyFile · 0.85

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected