Hi all, hopefully someone may be able to help me out here. Is there anyway I can take a sequence of numbers and add them together? For example say i have this sequence [1,0,2], what i want to do is basically add each number so in this case the final result would be 3.

Any help or suggestions on which methods i could use to achieve such a result would be greatly apreciated :cool:

CelestialDog

4
Contributors
15
Replies
16
Views
10 Years
Discussion Span
Last Post by ffao

>>> sum([1,0,2])
3

sum() works on lists, tuples, numeric dictionary keys, but not strings.

Jeff

P.S. The old-fashioned way would be

counter = 0
for item in [1,0,2]:
counter += item
print counter

Thanks for the reply. I tried using sum() within a seperate function and for some reason it would result in an answer that was one bigger than the actual value should be. Although i'm trying to convert an integer result to a list to work with, which may be the cause of the problem.

Post the code. Debugging is our hobby. :)

Ok I finally figured out how to get my results. Below is the code I've came up with. Its certainly not the shortest or most elegant way to get what I was looking for but it does work :)

def Numero(name):
'A function which converts a string to a numerical value(integer)'
alpha = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,
'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 1,
'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6,
'p': 7, 'q': 8, 'r': 9, 's': 1, 't': 2,
'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7,
'z': 8, ' ': 0}

counter1 = 0
counter2 = []

while counter1 != len(name):
for key, value in alpha.items():
if key in name[counter1]:
counter2.append(value)
counter1 += 1

tester = sum(counter2)
if tester > 9:
tester1 = list(str(tester))
return RoundOne(tester1)
else:
return tester

return

def RoundOne(numb):
numbers = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '0': 0}

stringcount1 = 0
stringcount2 = []
stringcount3 = 0
while stringcount1 != len(numb):
for key, value in numbers.items():
if key in numb[stringcount1]:
stringcount2.append(value)
stringcount1 += 1

stringcount3 = sum(stringcount2)
if stringcount3 > 9:
stringcount3a = list(str(stringcount3))
return RoundTwo(stringcount3a)
else:
return stringcount3

return

def RoundTwo(numb1):
numbers = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '0': 0}

stringcounta = 0
stringcountb = []

while stringcounta != len(numb1):
for key, value in numbers.items():
if key in numb1[stringcounta]:
stringcountb.append(value)
stringcounta += 1

return sum(stringcountb)

Hi,
1. You can use dictionary.has_key(key) function to check whether the key(a character, in your case) exists in a dictionary.
2. You can define numbers as global, because you require that more than once in your functions.
3. There is one return which is obsolete. Because in the if check > 9: you have return and you also defined else part a, return . So why is the last or third??

i have included the points which i mentioned above in following code.

numbers = { '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '0': 0}

def Numero(name):
'A function which converts a string to a numerical value(integer)'
alpha = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,
'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 1,
'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6,
'p': 7, 'q': 8, 'r': 9, 's': 1, 't': 2,
'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7,
'z': 8, ' ': 0}

counter1 = 0
counter2 = []

while counter1 != len(name):
if alpha.has_key(name[counter1]):
counter2.append(value)
counter1 += 1

tester = sum(counter2)
if tester > 9:
tester1 = list(str(tester))
return RoundOne(tester1)
else:
return tester

#    return  # why is this return ??
def RoundOne(numb):

stringcount1 = 0
stringcount2 = []
stringcount3 = 0
while stringcount1 != len(numb):
if numbers.has_key(numb[stringcount1]):
stringcount2.append(value)
stringcount1 += 1

stringcount3 = sum(stringcount2)
if stringcount3 > 9:
stringcount3a = list(str(stringcount3))
return RoundTwo(stringcount3a)
else:
return stringcount3

#    return     # Again why is this??

def RoundTwo(numb1):

stringcounta = 0
stringcountb = []

while stringcounta != len(numb1):
if numbers.has_key(numb1[stringcounta]):
stringcountb.append(value)
stringcounta += 1

return sum(stringcountb)

kath.

Thanks for the reply Kath. I knew there would have been a more elegant way of dealing with the dictionaries but i'm still finding my way around the language. My next task is to turn this in to a class which should be fun.

ok, good luck...

kath.

There is a lot of bad style / redundancies in your code, which is perfectly acceptable since you're a beginner. Your use of while loops when for loops would do is a clear sign of that. Something also leads me to believe that you have already programmed in a language that required declarations -- the statement "stringcount3 = 0" can be removed.

#we don't need the numbers dict!

def Numero(name):
'A function which converts a string to a numerical value(integer)'
alpha = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,
'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 1,
'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6,
'p': 7, 'q': 8, 'r': 9, 's': 1, 't': 2,
'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7,
'z': 8, ' ': 0}

#we don't need counters! a for loop dispenses their use...
tester = sum( [alpha[char] for char in name if char in alpha] ) # do you get what this line does?

if tester > 9:
return RoundOne(tester)
else:
return tester
#as a side-note, it's possible to do
#return (RoundOne(tester) if tester > 9 else tester)
#but that's unclear.

#ever considered passing RoundOne an integer and doing the list stuff here?
#it's considerably simpler to use externally, and also more bug-prone.
def RoundOne(numb):

#convert numb into a string (strings are iterable, so you don't need the extra conversion to list)
numb = str(numb)

#no counters here too!
stringcount = sum( int(char) for char in numb )

if stringcount3 > 9:
return RoundOne(stringcount) # RoundOne can handle it very well, you don't need two functions
else:
return stringcount

def Numero(name):
'A function which converts a string to a numerical value(integer)'
alpha = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,
'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 1,
'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6,
'p': 7, 'q': 8, 'r': 9, 's': 1, 't': 2,
'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7,
'z': 8, ' ': 0}

tester = sum( [alpha[char] for char in name if char in alpha] )

if tester > 9:
return RoundOne(tester)
else:
return tester

def RoundOne(numb):

numb = str(numb)

stringcount = sum( int(char) for char in numb )

if stringcount3 > 9:
return RoundOne(stringcount)
else:
return stringcount

And, for fun, a short version of RoundOne():

def RoundOne(numb):
while numb > 9:
numb = sum( int(char) for char in str(numb) )
return numb

Mathematically, the easiest way to do RoundOne is this:

def RoundOne(numb):
return numb % 9

Here's why: The final sum of digits computed by RoundOne must mathematically be equal to the original numb % 9.

Here's why that's true:

Take a number like 125. You learned way back when that this means 1 * 100 + 2 * 10 + 5 * 1. Now for a little cleverness:

125 = 1*100 + 2*10 + 5*1
= (1 + 1*99) + (2 + 2*9) + 5.

I just broke 100 as 1 + 99 and 10 as 1 + 9.

Rearranging,

125 = (1+2+5) + (1*99 + 2*9).

The first term, 1+2+5, is the sum of the digits. The second term is a bunch of numbers added all divisible by 9. So:

125 % 9 = (1+2+5) % 9 + (1*99 + 2*9) % 9
= (1+2+5) % 9 + 0.
= (1+2+5)%9

In other words, any number % 9 = the sum of its digits % 9.

(Formal proof below)

Now, all that RoundOne does is repeatedly add the digits together until the sum is less than 9. But if you think about it, the final sum of digits, which is less than 9, is its own remainder % 9. Therefore, the final answer is the same as the previous sum % 9, which will be the same as the sum before it % 9, which will be the same as ... all the way back to the original number % 9.

So the new improved RoundOne just cuts to the chase. :)

In case this all seems too weird, I ran a couple of tests:

>>> def RoundOne(numb):  # This is ffao's final version
while numb > 9:
numb = sum( int(char) for char in str(numb) )
return numb

>>> RoundOne(125)
8
>>> def RoundOneBeta(numb): # This is the suggested optimization.
return numb % 9

>>> RoundOneBeta(125)
8
>>> RoundOne(123897243)
3
>>> RoundOneBeta(123897243)
3
>>>

Jeff

Claim:

numb % 9 = (sum of digits of numb) % 9

Proof:

Write $numb = \sum_{i=0}^n a_i10^i$.
$= \sum_{i=0}^n a_i + \sum_{i=0}^n a_i(10^i-1)$
So,
$numb % 9 = (\sum_{i=0}^n a_i + \sum_{i=0}^n a_i(10^i-1)) % 9$
$= \sum_{i=0}^n a_i % 9 + \sum_{i=0}^n a_i(10^i-1) % 9$
$= \sum_{i=0}^n a_i % 9 + 0$
$= \sum_{i=0}^n a_i % 9$
Done.

You probably learned some version of this trick back in grade school when your teacher told you that any number divisible by 9 will have digits that add to 9.

Hi Jeff,

thanks for the explanation... well done...

i wonder where do we use these rounding in practical application.. for eg. with a given string or a number we arrive at single number at the end, which will be always less than 9. And it is very clear that we have that number for variety strings or numbers. Say if i want to go find the actual one, then?

I dont know, can we do that or how this rounding helps in practice.. im confused.

cheers,
kath.

The code I've writen was to be part of a Numerology program a friend asked me to create for her. Basically Numerology takes a person full birth name and converts each letter to a number ranging from 0 to 9...each number is then added to arrive at the final number(hearts desire number for example), which should only be a single digit unless its a power number such as 22, 33, 44 or 55 depending on the system used.

I thought i would start with the hardest part, as i saw it in regards to creating the software, and thats to convert the characters to numbers.

The each final number ranging from 0-9 has a special meaning in numerology.

Here's why: The final sum of digits computed by RoundOne must mathematically be equal to the original numb % 9.

Of course I knew that :P But somehow my brain didn't make the connection. Thanks for the trick!

lol no problem, the code i've been posting has purely been me trying to work it out in my mind, i used to be able to do a little C programming but that was a while back and i was never that good at that neither lol

i wonder where do we use these rounding in practical application.. for eg. with a given string or a number we arrive at single number at the end, which will be always less than 9. And it is very clear that we have that number for variety strings or numbers. Say if i want to go find the actual one, then?

So the rounding is really a hash, yes? We're mapping string s --> range(10).

Reversing the process (find the string based on the hash) is impossible, unless you have a small set of strings to choose from.

It might be useful, though, if you wanted to assign people to pseudo-random groups based on their names.

Jeff

It might be useful, though, if you wanted to assign people to pseudo-random groups based on their names.

Which is exactly what numerology does. (just completing your post).

I just realized now that the modulus trick demands the OP to treat 0 as 9 -- don't forget about that!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.