Hi I'm trying to find a way to find the first avogadro cipher whose digital sum exceeds 100,
I've come to:

#!/usr/bin/python

def dig_sum(n):
	lst = list(str(n))
	ln = len(lst)
	sm = 0
	while(i < ln):
		sm += int(lst[i])
	return sm

def avo(i,j,k,c):
	k = j
	j = i + j
	i = k
	arr.append(j)
	c += 1
	print arr
	if(dig_sum(i) > 100):
		print "solved:" + arr[c]
	else:
		avo(i,j,k,c)

i = 1 #num 1
j = 1 #num 2
k = 0 #reserve
c = 1 #turns
arr = [i,j]
avo(i,j,k,c)

but it just stops working after it has printed 21 :o
what have I done wrong?

You have a number of issues in your code revolving around scope.

Here are the first few that jumped out at me:

1) In your dig_sum function, you refer to i but never define it (in your while loop). Perhaps you're referring to the i from the avo function or from the global scope. If that is the case you should be passing it to the function specifically, not relying on the global value. Otherwise you need to define a starting point and somehow increment it inside the while loop.

2) Same as above but in the avo function you're referencing and modifying the list named arr. Again, if you really want to modify this list you should be passing it and not using globals.

Note: number 1 is the reason that your program hangs. You don't modify the value of i so that while loops simply runs forever.

EDIT: Here's a cleaner way of doing a digital sum using list comprehension:

>>> def dig_sum(n):
...     ''' Prints the digital sum of number n. '''
...     return sum([int(each_numeral) for each_numeral in str(n)])
...     
>>> dig_sum(52)
7
>>>

And to break that out:

>>> def dig_sum(n):
...     ''' Prints the digital sum of number n. '''
...     dsum = 0
...     for each_numeral in str(n):
...         dsum += int(each_numeral)
...     return dsum
...     
>>>

Edited 7 Years Ago by jlm699: n/a

Stupid I forgot to do i += 1 :f
but I didn't find a digital_sum method on the internet so I made my own one :D,
okay now it gives me a result with a dig_sum of 93 :(

#!/usr/bin/python

def dig_sum(n):
     ''' Prints the digital sum of number n. '''
     return sum([int(each_numeral) for each_numeral in str(n)])

def avo(i,j,k,c):
	k = j
	j = i + j
	i = k
	arr.append(j)
	c += 1
	if(dig_sum(i) > 100):
		print "solved:" + str(arr[c])
	else:
		avo(i,j,k,c)

i = 1 #num 1
j = 1 #num 2
k = 0 #res
c = 1
arr = [i,j]
avo(i,j,k,c)

Nevermind I found it,
I had to do: if(dig_sum(arr[c]) > 100): instead of if(dig_sum(i) > 100):

This question has already been answered. Start a new discussion instead.