3

I have written 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 raised to a power equal to the digit; see 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 running this code gives is:

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?

1123581321
  • 209
  • 2
  • 4
  • 9

2 Answers2

2

print() statements by default print a newline as well. To suppress that behavior and continue printing on the same line, add the end='' parameter like so:

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 could replace the inner loop by join()ing the string componets and formatting the output as follows:

for i in list2:
    print(' + '.join(['{0:}^{0:}'.format(x) for x in i]) + ' = {}'.format(i))
    print('----------')
Ma0
  • 15,057
  • 4
  • 35
  • 65
0

Try the end=" " option in print

for j in range(0,len(i)-1):
    print(i[j],'^',i[j],'+', end=" ")
voidpro
  • 1,652
  • 13
  • 27