0

Pls someone should volunteer to explain the line three code for me

def f(x): j = range(x) e = eval("+".join([str(i * i) for i in j])) return e print(f(3))

27th Jun 2021, 8:17 PM
Muhammad Abdulmalik
Muhammad Abdulmalik - avatar
2 ответов
+ 3
j=range(3) creates a range object with following values (0, 1,2) [str(i*i) for i in j] returns ["0", "1", "4"] join method of string concatenates the values in list with a "+" sign in between each value , i.e. "0+1+4" eval("0+1+4") evaluates the following expression which returns value 5. A stackoverflow discussion on how eval works, https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do#:~:text=10%20Answers&text=The%20eval%20function%20lets%20a%20Python%20program%20run%20Python%20code%20within%20itself.&text=eval()%20interprets%20a%20string%20as%20code.
27th Jun 2021, 9:10 PM
Abhay
Abhay - avatar
+ 2
I don't really see the point of the code unless it's a demonstration of the use of eval(). The square brackets are superfluous and just create more work. Simpler is def f(x): return sum(i**2 for i in range(x)) print(f(3)) https://code.sololearn.com/c7g2P1k404nB
28th Jun 2021, 5:05 AM
David Ashton
David Ashton - avatar