0

I have some function FUN(a, b): on two characters. I want to define another function foo(s), such that

foo(s):
    FUN(a[0],a[1])
    FUN(a[2],a[3])
    FUN(a[4],a[5])
    ...

for all characters in s (assume s is even length). My thoughts are that we basically need to run FUN(a,b) (len(s)%2) times, but I'm not sure how to iterate a function in that way, while also making sure FUN has the right inputs. Any ideas?

3
  • 4
    for i in range(0, len(s), 2): FUN(s[i], s[i+1]) or for i in range(0, len(s), 2): FUN(*s[i:i+2]) Commented Oct 31, 2013 at 11:01
  • @falsetru I like my answer better :P Commented Oct 31, 2013 at 11:06
  • @GamesBrainiac well, your answer is less readable and probably worse performance-wise than falsetru's comment. I definitely wouldn't prefer it... Commented Oct 31, 2013 at 11:38

2 Answers 2

2

Well this would be easy to do with zip:

def fun(a, b):
    print a, b


def foo(s):
    for x, y in zip(s[::2], s[1::2]):
        fun(x, y)


foo("12345678")

Output:

1 2
3 4
5 6
7 8

A more efficient way, using generators, would be using izip (same output):

from itertools import izip


def fun(a, b):
    print a, b


def foo(s):
    for x, y in izip(s[::2], s[1::2]):
        fun(x, y)


foo("12345678")
Sign up to request clarification or add additional context in comments.

1 Comment

thanks this is similiar to what i wanted. what would the easiest way be to concatenate all the outputs into a single string?
1

When a question ist tagged with iteration there must be a way to do it with iter. :-)

values = range(10)

def do_work(x, y):
    print('{}_{}'.format(x, y))

it = iter(values)
try:
    while it:
        do_work(next(it), next(it))
except StopIteration:
    pass

Nice suggestion from l4mpi:

it = iter(values)
for value in it:
    do_work(value, next(it))

3 Comments

Erm, using exceptions for program flow is a bad idea. They're supposed to catch errors. Atleast, thats what I'm used to anyways.
This can be rewritten as a for loop: for x in it: do_work(x, next(it)) - avoids catching the StopIteration, but only works for input with an even number of elements. @GamesBrainiac you don't have any idea how a for loop is implemented in python, do you? It uses the same StopIteration exception to find out when the sequence it iterates over runs out of values - and that's required, as iterators in python by design only have a next method, but no has_more or is_empty method.
I knew that there had to be a simple solution. :-( A lot of years with Python and still learning. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.