0
how can I make a ab aba ... numbers?
hi, I want to make numbers with a & b so that for exp: n=3 aba n=4 abab n=2 ab n=5 ababa without using for & while and str😊
14 Respuestas
+ 1
Flandre Scarlet I don't think the problem was about that. But even if it were, reduce would do it just fine
reduce(lambda x, k: 10*x+b if k%2 else 10*x+a, range(n), 0)
+ 5
Kishalaya Saha i think the question is like this:
supposed a=1, b=2, k=3, we should get 121, and not allowed to use int("121")🤔
+ 5
Kishalaya Saha seems it's exactly what he want😂
+ 4
I would do it with recursion🤔
aba = lambda a,b,k: k and [b,a][k%2] + 10*aba(a,b,k-1)
https://code.sololearn.com/c0Pkz7a6q49V
+ 3
Or,
"ab" * (n//2) + "a" * (n%2)
+ 3
The numbers are not converted to strings. The quotation marks are around ab (and also a in my case). The numbers remain numbers. "ab" * (n//2) concatenates the string "ab" with itself n//2 times. If n//2 were treated as a string, that wouldn't even make sense!
Regarding reduce, this should work:
from functools import reduce
n = 5
print(reduce(lambda x, k: x+"b" if k%2 else x+"a", range(n), ""))
But obviously it still uses strings, and is not better in any way than Bennet's method.
+ 1
thanks a lot ... I was searching for reduce solution 😊
0
thanks but I forget that I dont have permission to use str
0
But we're not using the str() function!
0
I wrote a code for it but it is realy prolix, can you solve it by using reduce func?
0
we are getting numbers as string by using " "
0
thanks for explaining this 👌👌
0
You're welcome, shima 😊
0
Flandre Scarlet , oh, okay then! 😂