randomhopeful randomhopeful - 4 months ago 7
Python Question

.join() elements of a user generated list using range in Python

In my program user enters a number (input_n) that will go through :

0+1+2+ ... + n = n*(n+1)/2 axiom.

My desired output for an input_n <= 10 (in this case : 5)

[0, 1, 2, 3, 4, 5]
0 + 1 + 2 + 3 + 4 + 5 = 15
5*(5+1)/2 = 15


My desired output for an input_n > 10 (in this case : 999)

[0, 1, 2, 3, 4, 5, ... , 995 , 996, 997, 998, 999]
0 + 1 + 2 + 3 + 4 + 5 + ... + 995 + 996 + 997 + 998 + 999 = 499500
999*(999+1)/2 = 499500


I thought I could use two range functions with a " + ... + " string between them in a print statement.
But what I'm typing must be nonsensical since I get a syntax error :

SyntaxError: Generator expression must be parenthesized if not sole argument


What does that error mean ? I get that the expression in question must be parenthesized. I tried to correct the error with my beginner's logic but my attempts failed.

Here's my code :

input_n = int(input("Choisissez un nombre : "))

input_list = list()
for i in range(0,input_n+1):
input_list.append(i)

if input_n <= 10:
print ("+".join(str(i) for i in input_list) + " = ", sum(input_list))
print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2))
elif input_n > 10:
print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,input_n+1), sum(input_list)))
print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2))





For noobs, like me :
I already got answers for previous encountered problems in this topic, you should definetly check the answers given.

Answer

You forgot to close the bracket of the join built-in method, so I guess this is what you want:

>>> input_list = list(range(21))
>>> 
>>> input_n = 20
>>> print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,input_n+1)) + ' = ', sum(input_list))
0+1+2+3+4 + ... +15+16+17+18+19+20 =  210
Comments