+ 4
Oneliner question (Recurring Character)
I have recently made a code that gets the first recurring character in a string: https://code.sololearn.com/c65Q3VDt07Hl/?ref=app It raises an exception due to the method I used (using list indices), though I want it to display "None". While I can easy fix this using a try-except block, I want to keep it a oneliner. Any suggestions?
21 Answers
+ 2
HonFu How about this to reduce character count?
print((lambda x=input(): ([i for i in x if x.count(i)>1] or [None])[0])())
+ 4
Short and simple:
x=input();print(next((i for i in x if x.count(i)>1),None))
+ 3
Sorry, my version didn't work exactly as you wanted.
This one works:
print((lambda x=input(): ([i for i in x if x.count(i)>1] or [None, None])[0])())
+ 3
Cbr✔[ Exams ] Thomas Williams
It's a oneliner to me. Most of the times anything that isn't a function is not added to the lines/characters count.
At least that's the way golf challenges work on SL.
+ 3
Roneel thats actually a very good solution👍🏼 Thanks😁
+ 2
HonFu I get the 'or [None, None]' now! If list is empty, then it is replaced by [None]... Smart.
+ 2
HonFu Nice👍🏼 Thanks man, really appreciate it!
Cbr✔[ Exams ] Nice code, but just checked it out and it didnt do the "None" thing. Thanks for the reply, though
Thank you, guys👍🏼 Ill keep this thread for a day and then delete it
+ 2
Why delete? It's a programming-related question!
+ 2
Yeah, absolutely!
Other people may want to learn from it as well.
And it would be a pity if the very people who actually ask something programming-related, edit themselves out of here. 😂
+ 2
Lol that's True HonFu
+ 2
Ha - obviously! 🤦♂️
Thanks for pointing that out, Roneel !
+ 1
print((lambda x=input(): [i for i in x if x.count(i)>1][0] if len([i for i in x if x.count(i)>1]) > 0 else None)())
Here is my answer, with ternary operator!
+ 1
Théophile oh. I was hoping there would be a simpler way to do it. Yeah, I used that one in a beta-version. Was hoping someone would have a better solution
Thanks man👍🏼
+ 1
I don't know if a simpler way exists too. I'll see!
+ 1
print((lambda x: x[0] if len(x) > 0 else None)((lambda x=input(): [i for i in x if x.count(i)>1])()))
+ 1
Cbr✔[ Exams ] he wants a one liner code. In yours, you can't replace string by input.
But nice code, btw!
+ 1
HonFu I was going to delete it since its been answered. Jn retrospect, I should probably keep it around
+ 1
Oh. Cool👍🏼 Diego. Not oneliner, but good code anyway