Dies mag trivial erscheinen, aber ich habe keine gute Lösung für das Problem gefunden. Ich habe sogar Folgendes gefunden: Erzeugen Sie alle nbit -binären Zahlen auf schnellstmögliche Weise. Aber ich habe kein genaues Duplikat gefunden. Längen. Der Algorithmus sollte vollständig in der binären Domäne arbeiten, denn wie ich alles verstehe (Text, Fotos, Musik, Videos ...) in Computern sind binäre Ziffern bis hin zum Umwandeln, so Domänen). < /p>
Ich habe ein einfaches Programm geschrieben, das genau das tut, was ich beschreibe:from typing import Generator, Tuple
def count_in_binary(n: int) -> Generator[Tuple[int], None, None]:
if not isinstance(n, int) or n < 1:
raise ValueError("The argument n must be a positive integer")
l = (n - 1).bit_length() if n > 1 else 1
numeral = [0] * l
maxi = l - 1
for _ in range(n):
yield tuple(numeral)
i = maxi
while True:
if not (d := numeral):
numeral = 1
break
else:
numeral = 0
i -= 1
< /code>
Aber ich bin mir nicht sicher, ob dies der effizienteste Weg ist, dies in Python zu tun. Ich habe nicht viele Bitoperationen verwendet und Computer repräsentieren bereits Zahlen als binär, daher sollte es schnellere Möglichkeiten geben.def count_in_binary1(n: int) -> Generator[Tuple[int], None, None]:
if not isinstance(n, int) or n < 1:
raise ValueError("The argument n must be a positive integer")
l = len(f'{n-1:b}')
for i in range(n):
yield tuple(map(int, f'{i:0{l}b}'))
< /code>
In [50]: %timeit list(count_in_binary(256))
59.9 μs ± 209 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
In [51]: %timeit list(count_in_binary1(256))
452 μs ± 3.68 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
< /code>
Edit
I didn't do much testing with the original function, I just thought it would work, now it's fixed.
And no, the scope of the scope is limited to pure Python, so NumPy isn't allowed.
Edit 2
Now I think there are no exceptions.
I have upvoted and accepted the second answer as it does answer the original question though the original question doesn't include all the relevant information, so the problem I was trying to solve by posting a question remains unsolved.
I have posted a new question without all relevant information, please answer it: Fastest way to find all permutations of 0, 1 of width n without itertools in pure Python?
Wie zähle ich die ersten n natürlichen Zahlen in binär? ⇐ Python
-
- Similar Topics
- Replies
- Views
- Last post