1

new to the python programming, havin some difficulties figuring this out. I'm trying to convert tuples into strings, for example ('h','e',4) into 'he4'. i've submitted a version using the .join function, and i'm required to come up with another ver. i'm given the following:

def filter(pred, seq): # keeps elements that satisfy predicate
    if seq == ():
        return ()
    elif pred(seq[0]):
        return (seq[0],) + filter(pred, seq[1:])
    else:
        return filter(pred, seq[1:])

def accumulate(fn, initial, seq):
    if seq == ():
        return initial
    else:
        return fn(seq[0],  accumulate(fn, initial, seq[1:]))

hints on how to use the following to come up with conversion of tuples to strings?

3
  • Possible duplicate of Python convert tuple to string Commented Sep 21, 2017 at 2:13
  • @BrandonKheang Nothing there uses the above two functions. Commented Sep 21, 2017 at 2:14
  • "the following"? Commented Sep 21, 2017 at 2:17

4 Answers 4

1

The given filter is useless for this but the given accumulate can be used easily:

>>> t = ('h','e',4)
>>> accumulate(lambda x, s: str(x) + s, '', t)
'he4'
Sign up to request clarification or add additional context in comments.

1 Comment

may i know what does str(x) + s means?
0

Just loop through the tuple.

#tup stores your tuple
string = ''
for s in tuple :
    string+=s

Here you are going through the tuple and adding each element of it into a new string.

4 Comments

I think the OP is required to use those funny looking functions, otherwise you're right this would be a very simple solution
Hmmm. Might be. Why complicate it when you can keep it simple I say. But yes, if that's the requirement, will looking into it.
Though @Davy M , the function the OP provides seems weird. Can you make out what that looks like?
I really can't haha
0

1) Use reduce function:

>>> t = ('h','e',4)
>>> reduce(lambda x,y: str(x)+str(y), t, '')
'he4'

2) Use foolish recursion:

>>> def str_by_recursion(t,s=''):
        if not t: return ''
        return str(t[0]) + str_by_recursion(t[1:])

>>> str_by_recursion(t)
'he4'

Comments

-1

You can use map to and join.

tup = ('h','e',4)
map_str = map(str, tup)
print(''.join(map_str))

Map takes two arguments. First argument is the function which has to be used for each element of the list. Second argument is the iterable.

Comments

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.