1

I'm having problems with a homework question.

"Write a function, to_str(a), that takes an array, a, converts each of its elements to a string (using str(a[i])) and appends all these strings together."

This is what I have

def to_str(a):
    for i in a: a.append([i])
    return str(a[i])

I have no idea how to use str(a[i]), I was wondering if someone can point me to the right direction

4 Answers 4

9

From the docs:

str(object) -> string

Return a nice string representation of the object. If the argument is a string, the return value is the same object.

So str(a[i]) will return a string representation of a[i], i.e. convert a[i] to a string. You will then need to concatenates the strings for all values of i.

As for your code, I have the following comments:

  • i is an element of a, not an index, as you might be thinking;
  • you are appending elements of a to a (endlessly, I'm afraid);
  • a[i] can cause an exception, because, like I said, i is an element, not an index;
  • you need to return a concatenation of strings, not a string from one element.

Also, if using str(a[i]) is not strictly mandatory, I'd suggest to skip it as unpythonic. You don't need indexes at all for this. Examples:

''.join(str(element) for element in a)

or

''.join(map(str, a))

will return what you need. In both cases str is applied to all elements of a.

The simplest-to-understand ("beginner") way without using indexes will be

s = ''
for element in a:
    s += str(element)
return s

It's a bit less efficient, though it does effectively the same thing.

Sign up to request clarification or add additional context in comments.

3 Comments

I think it's cleaner to loop over the elements of a itself rather than looping over the indices.
@DSM Me too, too bad it's a part of the assignment. I've added that to my answer, too.
@Tadeck I already took back my downvote; this doesn't change the fact that your answer contained incorrect code for quite a bit of the time when this question received most of the attention. As for reduce, I have nothing against it, but I wouldn't advice it to a newcomer without a verbose enough explanation. This question is, in old terms, a [homework] question, so the answer quality depends a lot on the verbosity, not elegance. Anyway, the right thing to use here is str.join, not reduce, I believe.
1

Converting each element into a string is easiest to use list comprehension:

[ str(i) for i in a ]
# equivalent to
[ str(a[i]) for i in range(len(a)) ]
# equivalent to
map(str, a) # most concise, use if you want to feel incredibly clever...

So you can write the function:

def to_str2(a):
    ''.join([str(i) for i in a]) # concatenates the list as a list of strings

.

Your code nearly does this:

def to_str(a):
    new_a = [] # rather than use the same a!
    for i in a:
        new_a.append(str(i)) #convert i to string before appending
    return new_a

Comments

0

The code meeting all the task criteria is rather something like:

def to_str(a):
    return reduce(lambda x, y: x + str(y), a, '')

Which does things exactly in the mentioned way: first converts them to strings, then adds to the string made from already processed elements (which at the beginning is just emty string).

EDIT: The clearer (and supported by Python 3) way is to use explicit looping through elements. It does exactly the same, clarifying at the same time how reduce() works:

def to_str(a):
    result = ''  # third argument of reduce()
    for item in a:
        result += str(item)  # does what reduce() lambda argument was doing
    return result

4 Comments

+1 (not sure why down voted, but perhaps reduce is confusing without explanation?) I however, like map/reduce solutions :)
Wasn't me -- I comment instead of downvoting -- but the (just-deleted) first one didn't work, and the second one (by comparison with something like ''.join(str(elem) for elem in a) uses the out-of-favour reduce, introduces a lambda function and two non-obviously-named variables, and shows quadratic behaviour. [Or maybe the downvoter was being really literal about using a[i] and looping over the indices, who knows?]
My downvote was due to the incorrect first snippet; undownvoted.
@hayden: I have added alternate solution doing the same as reduce(). Thanks for clarification :)
-1

the simplest way is:

[str(i) for i in a]

if you want a function:

def to_str(a):
    return [str(i) for i in a]

1 Comment

That solves the first part of the problem, not the "appends all these strings together" part.

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.