tags:

views:

268

answers:

3

Why do you need to use the function 'str' in the following code?

I am trying to count the sum of digits in a number.

My code

for i in number:
    sum(map(int, str(i))

where number is the following array

[7,79,9]

I read my code as follows

  1. loop though the array such that
  2. count sum of the integer digits
  3. by getting given digits in a number by map increasingly
  4. such that each object (given number) is converted to String // This does not make sense

Manual says this for str

Type:           type
Base Class:     <type 'type'>
String Form:    <type 'str'>
Namespace:      Python builtin
Docstring:
    str(object) -> string

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

What happens when you try that code without using str()?

The str() is used to convert the integer into a sequence of characters, so that map() can iterate over the sequence. The key point here is that a "string" can be treated as a "sequence of characters".

Greg Hewgill
**How can you see that `map()` needs charaters as an input?** - It says in the manual that *map(function, sequence[, sequence, ...]) -> list*. - **What is the data type for sequence?** - It seems to be possible that a sequence may consists letters only, not numbers.
Masi
In more well-typed languages `map` has the type: `forall a. (a -> b), list(a) -> list(b)`. Sequence (in fact `Iterable` here) in Python is something that has the `__iter__` method returning another thing called `Iterator`. Iterators have the same `__iter__` and `next` that does the actual iteration.
Andrey Vlasovskikh
"It seems to be possible that a sequence may consists letters only, not numbers." No. Sequences of numbers are perfectly possible, like (1,2,3,4,5) for example.
Lennart Regebro
And, it's necessary to keep in mind the difference between numbers (integers, like the mathematical concept), and characters (which may be a letter or a digit or punctuation or other character).
Greg Hewgill
+7  A: 

Given 79 you need to get [7, 9] in order to sum up this list.

What does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base 10 in this case). E. g. 79 is 7 * 10**1 + 9 * 10**0.

And what is the simplest (well, at least in this context) way to get such a representation of a number? To convert it to a string of decimals!

Your code does exactly that:

>>> str(79)
'79'

# Another way to say this is [int(c) for c in str(79)]
>>> map(int, str(79))
[7, 9]

>>> sum(map(int, str(79)))
16
Andrey Vlasovskikh
I found out that "strings" are immutable sequences of characters in Python such that you need first a new string to have your edits. - However, it does not make sense to me why you need to use `str`for 79 when it is a new input in your example. - **I wonder when you do not need to use the function `str` in the given example.**
Masi
**Do you mean that conversion to a decimal number allows to count the sum?** - It makes sense to me, since integers are unique, while decimals are non-unique. This would allow easily to have many pointers for different decimal presentations which is not possible for integers.
Masi
Numbers are just numbers. You can add or subtract them. But there is no such thing as digit as far as you do not define digit as a coefficient in a representation of a number in some numeric system.You can write a function `num_to_digits`, that accepts an `int` and the numeric system base, and returns a `list` of `int`s. But you can just reuse `str` that does internally a) this thing, b) conversion from `int` digit to `str`.
Andrey Vlasovskikh
Immutability and uniqueness are not relevant here.
Andrey Vlasovskikh
Question: "I wonder when you do not need to use the function `str in the given example"Aswer: When i is a sequence.
Lennart Regebro
+2  A: 

Why do you need to use the function 'str' in the following code?

Because map takes an iterable, like a list or a tuple or a string.

The code in question adds upp all the numbers in an integer. And it does it by a little clever hack. It converts the number into a sequence of numbers by doing

map(int, str(i))

This will convert the integer 2009 to the list [2, 0, 0, 9]. The sum() then adds all this integers up, and you get 11.

A less hacky version would be:

>>> number = [7,79,9]
>>> for i in number:
...     result = 0
...     while i:
...         i, n = divmod(i, 10)
...         result +=n
...     print result
... 
7
16
9

But your version is admittedly more clever.

Lennart Regebro
Yes, but yuo should basically abstract such a code as, for example, function `digits(number, base) -> [int]` and `sum`.
Andrey Vlasovskikh
If you intend to use it more than once, yes.
Lennart Regebro
Your code seems to be buggy. It seems to need `i = 0; while i < something` to the beginning. However, I could not get it work with these changes.
Masi
It only needs i to be some sort of integer, as it is in your question. That's it. No bugs. I double checked again.
Lennart Regebro
@Lennart: I get `unsupported operand type(s) for divmod(): 'list' and 'int'` after running the code with the initial data in running the code with Ubuntu and with OS X Leopard. - **What is your output?**
Masi
Sigh. I used the exact same variable names as you did. I updated my post for extreme clarity.
Lennart Regebro