0

I have an issue with the creation of lists.

I have a function that returns the roots of a polynomial (see below). What I obtain is a list of roots (R.keys()) and the times each one appears in the solution (R.values()).

When I obtain R.items() I am given a set of pairs of roots and their multiplicities: [(-2, 2), (-1, 1), (-3, 3)] as returned from the example below.

But what I want is to obtain a list with each root repeated by the number of times it appears, that is, [-2, -2, -1, -3, -3, -3].

I guess this is not difficult but I'm getting stuck with finding a solution.

pol=Lambda((y), y**6 + 14*y**5 + 80*y**4 + 238*y**3 + 387*y**2 + 324*y + 108)
poli=Poly(pol(y))
R=roots(poli)
R.keys()
R.values()
R.items()

def list_of_roots(poli):
    return(R.items())
list_of_roots(poli)
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
NS1
  • 3
  • 3

5 Answers5

0

If you can get the list of items in the form of an Array<Tuple>, then you can create a list like this:

items = [(-2, 2), (-1, 1), (-3, 3)]
listOfRoots = []
for x in items:
    for y in range(x[1]):
        listOfRoots.append(x[0])
print(listOfRoots)
A. Sokol
  • 336
  • 2
  • 13
0
roots = [(-2, 2), (-1, 1), (-3, 3)]
[ r for (root, mult) in roots for r in [root] * mult]

[-2, -2, -1, -3, -3, -3]
Rich L
  • 369
  • 3
  • 12
0
def get_list_of_roots(poli):
    # initialize an empty list 
    list_of_roots = []
    # process your poli object to get roots
    R = roots(poli)
    # we obtain the key value pairs using R.items()
    for root, multiplicity in R.items():
        # extend the list_of_roots with each root by multiplicity amount
        list_of_roots += [root] * multiplicity
    return list_of_roots

EDIT: Processed poli within function since you seem to want to pass poli to it.

EDIT: Added explanation of code.

ooknosi
  • 374
  • 1
  • 2
  • 8
0
items = [(-2, 2), (-1, 1), (-3, 3)]
result = []
for val, mult in items:
  result.extend(mult * [val])
gipsy
  • 3,859
  • 1
  • 13
  • 21
0

I'm assuming you mean [-2, -2, -1, -3, -3, -3].

roots1 = [(-2, 2), (-1, 1), (-3, 3)]
roots2 = [i for (r, m) in roots1 for i in [r] * m]

This might be of interest: Making a flat list out of list of lists in Python

Community
  • 1
  • 1
Spherical Cowboy
  • 565
  • 6
  • 14