Help doing it the "python way"

Dave Angel d at davea.name
Thu May 24 17:12:16 EDT 2012


On 05/24/2012 04:22 PM, Scott Siegler wrote:
> Hello,
>
> I am an experienced programmer but a beginner to python.  As such, I can figure out a way to code most algorithms using more "C" style syntax.
>
> I am doing something now that I am sure is a more python way but i can't quite get it right.  I was hoping someone might help.
>
> So I have a list of grid coordinates (x, y).  From that list, I want to create a new list that for each coordinate, I add the coordinate just above and just below (x,y+1) and (x,y-1)
>
> right now I am using a for loop to go through all the coordinates and then separate append statements to add the top and bottom.
>
> is there a way to do something like: [(x,y-1), (x,y+1) for zzz in coord_list] or something along those lines?
>
> thanks!

So, where's the code that works?  That you want optimized, or
"pythonified" ?

Your algorithm description is sufficiently confusing that I'm going to
have make some wild guesses about what you're after.  Apparently you
have a list of tuples, and you want to create a second list that's
related to the first in the sense that each item (i) of list2 is the sum
of the items (i-1) and (i+1) of list1.  Presumably you mean sum as in
vector sum, where we add the x and y values, respectively.

Easiest way to handle edge conditions is to stick an extra (0,0) at both
the beginning and end of the list.

list1 = [ (3,7), (2,2), (944, -2), (12, 12) ]
def sumtuple(mytuple1, mytuple2):
    return ( mytuple1[0] + mytuple2[0] , mytuple1[1] + mytuple2[1])

def makesum(list1):
    list2 = []
    list1a = [(0, 0)] + list1 + [(0, 0)]
    for item1, item2 in zip(list1a, list1a[2:]):
        list2.append( sumtuple(item1, item2) )
    return list2

print makesum(list1)


output:
[(2, 2), (947, 5), (14, 14), (944, -2)]


Now, that undoubtedly isn't what you wanted, but perhaps you could
clarify the algorithm, so we could refine it.  No point in making it
more compact till it solves the problem you're actually interested in.





-- 

DaveA




More information about the Python-list mailing list