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?

Chin Huat
  • 357
  • 1
  • 3
  • 10

4 Answers4

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'
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
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.

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
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'
mshsayem
  • 17,557
  • 11
  • 61
  • 69
-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.

FELASNIPER
  • 327
  • 2
  • 9