Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String manipulation based on lists

Hello I need to write a function that will automatically make a specific string

For example I have a List of elements:

tab = [12, 23, 13, 4, 2]

I want the function to take each element and add it to a string like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string:

12 + 23x + 13x^2 + 4x^3 + 2x^4

Basically, rewrite 1st element then add 'x' to the 2nd and every other but every element after 2nd must be raised to the power (starting with 2 on the third element and increasing by 1 for each next element)

The list can be infinitely long and it can contain floats so the function has to be universal

I tried this:

tab = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

string = ""
num = 0
for x in tab:

    if num < 1:
        string = string + str(x) + ' ' + '+' + ' '
    elif num < 2:
        string = string + str(x) + 'x' + ' ' + '+' + ' '
    else:
        string = string + str(x) + 'x' + f'^{num}' + '+' + ' '
    num = num + 1

print(string)

output:

'1 + 2x + 3x^2+ 4x^3+ 5x^4+ 6x^5+ 7x^6+ 8x^7+ 9x^8+ 10x^9+' 

>Solution :

I think this is the simplest code to do this. Initiate the output_string with the first number that is cast to be a string. Then, iterate on other elements of the list and do concatenation of +x^index to the output_string:

tab = [12, 23, 13, 4, 2]
output_string = str(tab[0])
for each_index in range(1, len(tab)):
    output_string += " + " + str(tab[each_index]) + "x^" + str(each_index)
print(output_string)

The output:

12 + 23x^1 + 13x^2 + 4x^3 + 2x^4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading