Making an efficient merge function for the game 2048 in python
<p>I know there a bunch of other posts regarding this topic however I'm taking a slightly different approach. </p>

<pre><code>def merge(line):
    """
    Function that merges a single row or column in 2048.
    """
    #remove all non zeros
    no_zeros = [ num for num in line if num != 0 ] 

    #make a pair of all adjacent numbers 
    pairs = zip(no_zeros[:-1] , no_zeros[1:])
    #create a boolean value for each pair depending whether elements are equal  
    is_pair = map( lambda (x,y): x == y , pairs ) 

    merged = []
    count = 0
    last = False #if elements in the last pair are euqal this is true 
    #merging algo 
    for i,pair in enumerate(is_pair):
        if last == False and pair == True :
            merged.append(pairs[i][0]*2)
            last = True #As this is a valid pair the next pair will not need to be 
                        #checked as the first number is the last number from this pair
        # The following two statements allows the pair to be checked it's
        # numbers have not been checked in any previous pair 
        if last == True: 
            count += 1
        if count == 2:
            last = False
            count = 0 

    return merged

print merge([2, 0, 2, 4, 0])
print 'should return [4, 4, 0, 0]'
print '-------------------------------'
print merge([0, 0, 2, 2])
print 'should return [4, 0, 0, 0]'
print '-------------------------------'
print merge([2, 2, 0, 0])
print 'should return [4, 0, 0, 0]'
print 'to merge [2, 2, 2, 2, 2]'
print '-------------------------------'
print merge([2, 2, 2, 2, 2])
print 'should return [4, 4, 2, 0, 0]'
print '-------------------------------'
print merge([8, 16, 16, 8])
print 'should return [8, 32, 8, 0]'
</code></pre>

<p>So far my code merges all pairs. However if a number is not does not have a pair this needs to also be amended to the 'merged list'. I can't figure out for the life of me how to do this in a simplistic way, other that giving every number a unique stamp then if that stamp hasn't been merged it's added to 'merged'. I tried to implement this and it got very convoluted. </p>

<p>Any help would be appreciated </p>

<p>Any suggestions would</p>

<p>EDIT</p>

<p>I have solved my problem with 2 additional statements :</p>

<pre><code># This allows 'un-paired' numbers to be added to 'merged' 
if not last and not pair: 
    merged.append(pairs[i][0])
# The above doesn't take into account the last digit, if 'pairs' has len=1 which is solved by:
if i == len(is_pair)-1 and i&gt;1 and (last or not pair) :
    merged.append(pairs[i][1])
</code></pre>