creating a reverse method for a python list from scratch
>> reverse([1,2,3,4,5]) [5, 4, 3, 2, 1]
>> reverse([1,2,3,4,5]) [5, 4, 3, 2, 1]
Your solution explained: If we reverse the empty list, we obtain the empty list. If we reverse the list [H|T] , we end up with the list obtained by reversing T and concatenating with [H] . To see that the recursive clause is correct, consider the list [a,b,c,d] . If we reverse the tail of … Read more
Just iterate over the elements. Like this: Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
C implementation of your bonus question, in three lines:
I am not clear about your Odd number. The way this code works is (it is not a Java specific algorithm) Eg. input =2345 first time in the while loop rev=5 input=234 second time rev=5*10+4=54 input=23 third time rev=54*10+3 input=2 fourth time rev=543*10+2 input=0 So the reversed number is 5432. If you just want only … Read more
Use the built-in reversed() function: To also access the original index, use enumerate() on your list before passing it to reversed(): Since enumerate() returns a generator and generators can’t be reversed, you need to convert it to a list first.
This would be my approach:
In one line, using a lambda: Passing a function to list.sort:
Im trying to figure out how to reverse the string temp when I have the string read in binary numbers
use reversed() function: It’s much more meaningful. Update: If you want it to be a list (as btk pointed out): Update: If you want to use only range to achieve the same result, you can use all its parameters. range(start, stop, step) For example, to generate a list [5,4,3,2,1,0], you can use the following: It may be less intuitive but as … Read more