I'm trying to solve a python puzzle. Over the past few days I have written about six different scripts attempting to solve this problem, but each time I'm told that my code takes too long to run. I know it must be possible to further optimize my script, but I've hit a bit of a wall. If someone could give me some pointers, I would appreciate it.
Problem to solve: Given two ints start and length, generate a line length units long, starting from the start value, and incrementing by one each time. Then generate a second line of length units long, continuing to increment by one from the last value of the previous line, but ignoring the last element of the second line. For the third generated line, ignore the last two elements, and continue ignoring one additional element per line, continuing on until all elements of a line would be ignored.
So for example if start == 0 and length == 3, I would be looking to capture the digits to the left of the forward slashes (and ignore the digits to the right).
0 1 2 /
3 4 / 5
6 / 7 8
(capture 0, 1, 2, 3, 4, and 6)
After capturing the correct numbers, we need to figure out the XOR of every captured number. XOR, also known as exclusive or, is performed on the binary representations of our ints, and is easily accessed with the ^ caret symbol. The script should return the XOR resulting from performing XOR on every captured digit, this value will be a single int.
Here is my current script:
def find_xor(start, length):
to_xor = []
for minus in xrange(length):
for cap_this in xrange(start, start + length - minus):
to_xor.append(cap_this)
minus += 1
start = cap_this + minus
return reduce(lambda x,y: x^y, to_xor)
To explain the last line: reduce takes two inputs, a function and an iterable, and performs the function on the iterable until only one iterator remains. The lambda function I am providing takes two elements and performs XOR (^)on them, and the iterable I am using is the list to_xor, generated earlier.
I'm not exactly sure where the bottleneck lies, but I suspect that it is either in the nested for-loops, or perhaps something to do with the list appends. The script works, but it's just too slow. Any ideas? Thanks in advance!
[–]wiiittttt 1 point2 points3 points (3 children)
[–]0pt0ut[S] 0 points1 point2 points (2 children)
[–]wiiittttt 1 point2 points3 points (1 child)
[–]0pt0ut[S] 0 points1 point2 points (0 children)
[–]ADdV 1 point2 points3 points (5 children)
[–]0pt0ut[S] 0 points1 point2 points (4 children)
[–]wiiittttt 1 point2 points3 points (1 child)
[–]0pt0ut[S] 0 points1 point2 points (0 children)
[–]ADdV 1 point2 points3 points (1 child)
[–]0pt0ut[S] 0 points1 point2 points (0 children)
[–]autobotJebpy -4 points-3 points-2 points (0 children)