0
n = 1
for n in range(3):         
    p = Poly(a[n+1][0:3])
    print p 
    n=n+1

this is my coding. basically, I have a 3 times 3 matrix, I want to assign each row to a polynomial function and then assign each polynomial function to a new array. however, i do not know how to assign the value of p each time executed from the poly function to the array I want.

some body please help me.

the output of p executed looks like

  • (749.55*x**2) + (6.95*x**1) + (9.68*(10^-4)*x**0)
  • (1285*x**2) + (7.051*x**1) + (7.375*(10^-4)*x**0)
  • (1531*x**2) + (6.531*x**1) + (1.04*(10^-3)*x**0)

basically, it will be good enough to build a 3*1 array from the executed p output.

for imformation , my matrix of a looks like this

[['A', 'B', 'C', 'PMIN', 'PMAX'], ['749.55', '6.95', '9.68*(10^-4)', '320', '800'], ['1285', '7.051', '7.375*(10^-4)', '300', '1200'], ['1531', '6.531', '1.04*(10^-3)', '275', '1100']]
[['A' 'B' 'C' 'PMIN' 'PMAX']
Volatility
  • 31,232
  • 10
  • 80
  • 89
һ 刘
  • 25
  • 1
  • 4
  • 1
    Welcome to [SO]! If you edit your question, select all your code, and click the button with `{}` and it will format it nicely as code. – askewchan Mar 10 '13 at 04:34

3 Answers3

1

List comprehensions describe this quite simply:

def Poly(a):
  return "{}x^2 + {}x + {}".format(a[0],a[1],a[2])
a = [['A', 'B', 'C', 'PMIN', 'PMAX'],[1,2,3,99,99],[4,5,6,42,42],[7,8,9,3.14,2.72]]
result = [Poly(a[n]) for n in range(1,4)]
print result

The output is:

['1x^2 + 2x + 3', '4x^2 + 5x + 6', '7x^2 + 8x + 9']
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Try this:

p = []
for n in range(3):
    p.append(Poly(a[n+1][0:3]))
print p

I don't have access to your Poly function or a array, but we can test it like this:

p = []
for n in range(3):
    p.append([n,n+1,n+2])
print p
#output:
#[[0, 1, 2],
# [1, 2, 3],
# [2, 3, 4]]

I also removed your lines with n+1 and n=n+1 because both of those are done automatically by using n in range(3) which does the following:

for n in range(3):
    print n
#output:
# 0
# 1
# 2

(note that it starts at 0 and ends with 2, this is so that it runs exactly 3 times)

askewchan
  • 45,161
  • 17
  • 118
  • 134
  • thanks, it solves my problem. can I ask one more question. of the value inside the output is in term of x. how could I differentiate the output against x for each term in the output? – һ 刘 Mar 10 '13 at 13:09
  • That's different enough from the current question that you'd be better off posting a new question, asking how to take a derivative. You'd need to post more details of that `Poly` function. – askewchan Mar 11 '13 at 00:31
0

however, i do not know how to assign the value of p each time executed from the poly function to the array I want.

results = []
for x in range(3):
   p = Poly(something)
   results.append(p) # adding it to the list `results`

By the way, in Python, there are no arrays, just lists (0-index collections) and dictionaries, which are more like hashes.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284