Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list into string without loop and join() in Python

I am given a task to sort list like shown below:

Input:  "Sorting1234"
Output: "ginortS1324"

without using join(), for or while anywhere in the code. I succeeded after a lot of tries to sort in the required way, but I am unable to print it as a string

My Output is: ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']

Here is my algorithm to sort with sorted():

st=input()
def iseven(x):
if x.isdigit():
    return int(x)+9 if int(x)%2==0 else int(x)
res=sorted(st, key=lambda x: (x.isdigit(), x.isupper(), iseven(x), ord(x) ))
print(res)

Please help me on this

like image 588
Humoyun Ahmad Avatar asked Nov 25 '25 16:11

Humoyun Ahmad


2 Answers

but I am unable to print it as a string

Just unpack the arguments out of the list using the * operator when calling print() and use "" as a separator:

>>> L = ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
>>> print(*L, sep="")
ginortS1324
like image 157
Eugene Yarmash Avatar answered Nov 27 '25 04:11

Eugene Yarmash


You can use reduce, it is not in forbidden list. Append this line at the end of your code:

new_res=reduce( lambda x,y: x+y, res, "")
print(new_res)
like image 45
dani herrera Avatar answered Nov 27 '25 06:11

dani herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!