![]() You can use a generator comprehension instead of a list comprehension, but as pointed out by in the comments, in CPython str.join turns arbitrary iterables into lists as the very first step, negating any potential benefits. """Converts integer to a string of base-2 bits, What I would end up with looks like this: def integer_to_binary_string2(int_value): Instead, use str.join, as it will do better from a memory allocation perspective Repeatedly appending to strings/lists/things is generally not the best from a performance perspective (this has to do with how memory is allocated).Creating a function called reverse_string is unnecessary - the idiomatic/Pythonic way to do this is using the slice notation you mentioned - hiding it behind a method is just going to confuse experienced Python users.Generally, I prefer list comprehensions over an explicit loop they're often faster.Now to actually review your code (the reinventing-the-wheel tag was added after I started writing this): Way faster ( timeit with 1,000,000 iterations clocks at 0.23s for my method, 1.82s for yours).Doesn't require someone to understand the math behind it.Obvious what is happening & idiomatic Python.Your function would then become: def integer_to_binary_string(int_value): Your implementation seems fine at a glance, but Python actually provides two really easy ways to do this: Print(integer_to_binary_string(user_input)) ![]() Rev_str = integer_to_reverse_binary(int_value)ĭef integer_to_reverse_binary(int_value): '''Converts integer to a string of base-2 bits, ![]() I chose the log2 function and the for loop to calculate how long to run, rather than trying to guess if the calc is over on each pass of the loop, but I assume there is a cleaner/simpler way to do that. My experience level is I've been using Python for about 7 years, hobbyist, haven't collaborated with other programmers ever, and I'm now in a Comp Sci degree program. My goals are correctness and that it is obvious what the code is doing. Please review it for good style and organization, and I'm especially looking for a critique of the algorithm and level of documentation. For example, input 2 outputs '10' and input 25 outputs '11001'. This code takes a user input number which is a positive integer, and outputs a string representation of the number in binary.
0 Comments
Leave a Reply. |