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😊

29th Nov 2018, 11:11 AM
shima
shima - avatar
14 ответов
+ 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)
29th Nov 2018, 7:41 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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")🤔
29th Nov 2018, 7:14 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 5
Kishalaya Saha seems it's exactly what he want😂
29th Nov 2018, 7:49 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 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
29th Nov 2018, 7:18 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 3
Or, "ab" * (n//2) + "a" * (n%2)
29th Nov 2018, 11:45 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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.
29th Nov 2018, 12:13 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
thanks a lot ... I was searching for reduce solution 😊
29th Nov 2018, 7:48 PM
shima
shima - avatar
0
thanks but I forget that I dont have permission to use str
29th Nov 2018, 11:59 AM
shima
shima - avatar
0
But we're not using the str() function!
29th Nov 2018, 12:00 PM
Kishalaya Saha
Kishalaya Saha - avatar
0
I wrote a code for it but it is realy prolix, can you solve it by using reduce func?
29th Nov 2018, 12:01 PM
shima
shima - avatar
0
we are getting numbers as string by using " "
29th Nov 2018, 12:03 PM
shima
shima - avatar
0
thanks for explaining this 👌👌
29th Nov 2018, 12:34 PM
shima
shima - avatar
0
You're welcome, shima 😊
29th Nov 2018, 12:37 PM
Kishalaya Saha
Kishalaya Saha - avatar
0
Flandre Scarlet , oh, okay then! 😂
29th Nov 2018, 7:50 PM
Kishalaya Saha
Kishalaya Saha - avatar