views:

94

answers:

4

If i have this code

s = 'abcdefghi'
for grp in (s[:3],s[3:6],s[6:]):
    print "'%s'"%(grp)

    total = calc_total(grp)

    if (grp==s[:3]):
        # more code than this
        p = total + random_value
        x1 = my_function(p)

    if (grp==s[3:6]):
        # more code than this
        p = total + x1
        x2 = my_function(p)

    if (grp==s[6:]):
        # more code than this
        p = total + x2
        x3 = my_function(p)

If the group is the first group, perform code for this group, if the group is the second group, perform code using the a value generated from code performed for the first group, the same applies for the third group, using a generated value from code for the second group:

How can i tidy this up to use better looping?

Thanks

+3  A: 

I may have misunderstood what you're doing, but it appears that you want to do something to s[:3] on the first iteration, something different to s[3:6] on the second, and something else again to s[6:] on the third. In other words, that isn't a loop at all! Just write those three blocks of code out one after another, with s[:3] and so on in place of grp.

Peter Westlake
Sorry, i forgot to include my `total = calc_total(grp)` statement
joec
A: 
x = reduce(lambda x, grp: my_function(calc_total(list(grp)) + x),
        map(None, *[iter(s)] * 3), random_value)

At the end, you'll have the last x.

Or, if you want to keep the intermediary results around,

x = []
for grp in map(None, *[iter(s)] * 3):
    x.append(my_function(calc_total(list(grp)) + (x or [random_value])[-1]))

Then you have x[0], x[1], x[2].

ephemient
A: 

I'd code something like this as follows:

for i, grp in enumerate((s[:3],s[3:6],s[6:])):
    print "'%s'"%(grp)

    total = calc_total(grp)
    # more code that needs to happen every time

    if i == 0:
        # code that needs to happen only the first time
    elif i == 1:
        # code that needs to happen only the second time

etc. The == checks can be misleading if one of the groups "just happens" to be the same as another one, while the enumerate approach runs no such risk.

Alex Martelli
A: 

Get your data into the list you want, then try the following:

output = 0
seed = get_random_number()
for group in input_list:
    total = get_total(group)
    p = total + seed
    seed = my_function(p)

input_list will need to look like ['abc', 'def', 'ghi']. But if you want to extend it to ['abc','def','ghi','jkl','mno','pqr'], this should still work.

jcdyer