Apu Gharami You have given a string. Now your task is to sort this string in descending order. Implement this using function. Sample Input 1 abddccss Sample Output 1 ssddccba

 

Apu Gharami
You have given a string. Now your task is to sort this string in descending order. Implement this using function. Sample Input 1 abddccss Sample Output 1 ssddccba



answer :


To sort a string in descending order, you can use the following function:

def sort_string(string): # Convert the string to a list of characters char_list = list(string) # Sort the list in descending order char_list.sort(reverse=True) # Join the list of characters back into a string sorted_string = ''.join(char_list) return sorted_string

This function first converts the input string to a list of characters. It then sorts the list in descending order using the sort method and the reverse parameter. Finally, it joins the list of characters back into a string using the join method.

For example, if you call sort_string('abddccss'), the function will return 'ssddccba'.

Note that this function is not case-sensitive, so if you call sort_string('AbddcCSS'), it will still return 'ssddccba'. If you want to preserve the case of the original string, you can modify the function to sort the list of characters using the key parameter and a custom function that returns the lowercase version of a character.

For example:

def sort_string(string): # Convert the string to a list of characters char_list = list(string) # Sort the list in descending order, preserving the case of each character char_list.sort(key=lambda x: x.lower(), reverse=True) # Join the list of characters back into a string sorted_string = ''.join(char_list) return sorted_string

This modified function will sort the string in descending order, preserving the case of each character. For example, if you call sort_string('AbddcCSS'), it will return 'SSddcCBA'.



Post a Comment

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();