Python code for digit-to-digit invariants
I wrote code that determines which natural numbers less than or equal to 1,000,000 are perfect digit-to-digit invariants (they can be written as the sum of their digits, each of which is raised to a degree equal to the value of a digit; https: / /en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant ) and expresses them as in this form.
def f(n):
y = str(n)
l = len(y)
list = []
for i in range(0,l):
list.append(int(y[i]))
list2 = []
for i in list:
list2.append(i**i)
return sum(list2)
N = 10**6
n = np.linspace(1,N,N,dtype=int)
list = []
for i in n:
if i == f(i):
list.append(i)
list = np.array(list)
list2 = []
for i in list:
list2.append(str(i))
for i in list2:
for j in range(0,len(i)-1):
print(i[j],'^',i[j],'+')
print(i[-1],'^',i[-1],'=',int(i))
print('----------')
The output that this code runs:
1 ^ 1 = 1
----------
3 ^ 3 +
4 ^ 4 +
3 ^ 3 +
5 ^ 5 = 3435
----------
The code gives the correct answer, but I want the expression 3 ^ 3 + 4 ^ 4 + 3 ^ 3 + 5 ^ 5 = 3435 to appear on one line. Is there a way to do this?
source to share
print()
Operators print a new line by default. To suppress this behavior and continue printing on the same line, add a parameter end=''
as follows:
for i in list2:
for j in range(0, len(i)-1):
print(i[j],'^',i[j],'+', end='')
print(i[-1],'^',i[-1],'=',int(i))
print('----------')
Alternatively, and more pythonically, you can replace the inner loop with join()
with string components and format the output like this:
for i in list2:
print(' + '.join(['{0:}^{0:}'.format(x) for x in i]) + ' = {}'.format(i))
print('----------')
source to share