Reputation: 282
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:
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+'
Upvotes: 1
Views: 202
Reputation: 1087
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
Upvotes: 0
Reputation: 1826
in a compact way to create the list
, you could use enumerate
:
tab = [12, 23, 13, 4, 2]
result = []
for index,element in enumerate(tab):
result.append(str(element)+(f"x^{index}" if index != 0 else ''))
print("list: ",result)
output:
['12', '23x^1', '13x^2', '4x^3', '2x^4']
and then join with the ' + '
string:
result = ' + '.join(result)
print("actual string:",result.__repr__())
output:
list: ['12', '23x^1', '13x^2', '4x^3', '2x^4']
actual string: '12 + 23x^1 + 13x^2 + 4x^3 + 2x^4'
Upvotes: 1