3

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?

2
  • My personal opinion is that you should explicitly say that you want the output in the form of a list, rather than making readers scrutinize your actual and desired outputs to see what the difference is. I could just be unobservant, but it took me a few readings to see it. Commented Nov 13, 2017 at 15:40
  • Hope we were able to assist you. If so, please mark the answer used as correct :) Have a nice day! Commented Nov 13, 2017 at 15:58

5 Answers 5

2

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

print(list(walsh_transform(arr)))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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]

Comments

0

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

re.sub function should work too.

2 Comments

No, walsh_transform() does not return a string. Please check ;)
walsh_transform() is returning an numpy array, not a string.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.