简体   繁体   中英

Python: can I use the lambda argument n to repeat lambda operation (n+n) n times?

I am trying to code-golf a Python function that takes a parameter n and squares it without pow, * or **. I am at this stage:

square = lambda n: n+n

Can I iterate n+nn times using about 10 more characters?

You can use recursion with lambda:

x = lambda y, c:y+y + x(y, c+1) if c< 10 else 0
print(x(10, 0))

Output:

200

You can do it with recursion, a conditional expression and a default argument:

square = lambda n, i=0: n + square(n, i + 1) if n > i else 0
square(10)  # 100

I suppose this probably only works for positive numbers ... but could be made to work with negative numbers with some judicious absolute values:

square = lambda n, i=0: abs(n) + square(n, i + 1) if abs(n) > i else 0

as @mgilson said, you can do it with recursion and lambdas:

square = lambda n, m=0: 0 if n==m else n+square(n,m+1)

the important thing is to carry the result with you in each step

square = lambda n : sum([n]*n)编辑:(不使用*或**) square = lambda n : n+sum(range(2,n+n,2))

You can try this:

sqr = lambda n : sum(n for i in range(n))

OUTPUT

>>> sqr(9)
81
>>> sqr(12)
144

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM