Format output in python

Viewed 71

I have the following function which transforms list of numbers:

import numpy as np
from math import *


def walsh_transform(x):
    if len(x) > 3:
        n = len(x)
        m = trunc(log(n, 2))
        x = x[0:2 ** m]
        h2 = [[1, 1], [1, -1]]
        for i in range(m - 1):
            if i == 0:
                h = np.kron(h2, h2)
            else:
                h = np.kron(h, h2)

        return np.dot(h, x) / 2. ** m

arr = [1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0]

print(walsh_transform(arr))

It returns output [ 0.625 -0.125 -0.125 0.125 0.625 -0.125 -0.125 0.125]

How can I make it return output [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125] ? I.e. comma-separated values?

5 Answers

Just cast the end result to a list, since lists print out in the format you want.

print(list(walsh_transform(arr)))

You could use return [z for z in np.dot(h, x) / 2. ** m] instead of return np.dot(h, x) / 2. ** m

You can convert the resultant array to list to get a output as you wanted.

w = walsh_transform(arr) # w = [ 0.625 -0.125 -0.125  0.125  0.625 -0.125 -0.125  0.125]

print(list(w)) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

Try using repr

print(repr(walsh_transform(arr))) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

Alternatively, you can cast it to a list:

print(list(walsh_transform(arr))) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

All you have to do is replace the whitespace with commas.

re.sub function should work too.

Related