How to Sort a Single String Output in Ascii Descending Order Through a Function

How do I sort a single string output in ASCII descending order through a function?

map:

def count(i):
word2 = map(lambda x: map(str,x),Counter(i).items())
return " ".join(sorted(map(':'.join,word2),reverse=True))

Or comprehensions:

def count(i):
word2 = Counter(i).items()
return " ".join(sorted(['{0}:{1}'.format(*i) for i in word2],reverse=True))

Now:

print count(word1)

Both Reproduce:

v:1 t:1 s:1 o:1 i:1 e:1 a:1 L:1 C:1

How do I sort a bunch of letters and their corresponding frequencies from a string?

Using collections.Counter, string.ascii_lowercase and sorted

from collections import Counter
from string import ascii_lowercase
s = 'pooiiiuuuuyyyyyttttttrrrrrrrHow do I sort a single string output in ASCII descending order through a function?How do I sort a bunch of letters and their corresponding frequencies from a string?Sorwwwwwwwwwqqqqqqqqqq'
sorted([(i.upper(),Counter(s)[i]) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)

Or without using collections

sorted([(i.upper(), s.count(i)) for i in ascii_lowercase], key=lambda x:x[1], reverse=True)

Output:

[('Q', 10),
('W', 9),
('E', 8),
('R', 7),
('T', 6),
('Y', 5),
('U', 4),
('I', 3),
('O', 2),
('P', 1),
('A', 0),
('B', 0),
('C', 0),
('D', 0),
('F', 0),
('G', 0),
('H', 0),
('J', 0),
('K', 0),
('L', 0),
('M', 0),
('N', 0),
('S', 0),
('V', 0),
('X', 0),
('Z', 0)]

Sorting strings in descending order in Javascript (Most efficiently)?

If you consider

obj.sort().reverse();

VS

obj.sort((a, b) => (a > b ? -1 : 1))

VS

obj.sort((a, b) => b.localeCompare(a) )

The performance winner is : obj.sort().reverse().

Testing with an array of 10.000 elements, obj.sort().reverse() is faster than obj.sort( function ) (except on chrome), and obj.sort( function ) (using localCompare).

Performance test here :

var results = [[],[],[]]
for(let i = 0; i < 100; i++){ const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30)); const randomArray = randomArrayGen(); const copyArray = x => x.slice();
obj = copyArray(randomArray); let t0 = performance.now(); obj.sort().reverse(); let t1 = performance.now();
obj = copyArray(randomArray); let t2 = performance.now(); obj.sort((a, b) => (a > b ? -1 : 1)) let t3 = performance.now();
obj = copyArray(randomArray); let t4 = performance.now(); obj.sort((a, b) => b.localeCompare(a)) let t5 = performance.now();
results[0].push(t1 - t0); results[1].push(t3 - t2); results[2].push(t5 - t4); }
const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;
console.log("obj.sort().reverse(): " + calculateAverage(results[0]));console.log("obj.sort((a, b) => (a > b ? -1 : 1)): " + calculateAverage(results[1]));console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2]));

How to sort list based on it's corresponding ascii values?

You can just use your ascii conversion function as the sort key to sort by those values:

list1 = ['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

print(sorted(list1, key = lambda s: sum(map(ord, s)), reverse=True))

Output

['abcd', 'bcd', 'abc', 'cd', 'bc', 'ab', 'd', 'c', 'b', 'a']

Note that this will leave values in list1 which have the same ascii value sorted as they were in the original list (since python sort is stable). You may want to sort them in the same order as the rest of the list (so for example 'da' would sort before 'ad'), in which case you can just add the current value to the key function so that it sorts first by the ascii value and then the actual string:

sorted(list1, key = lambda s: (sum(map(ord, s)), s), reverse=True)

Thanks to @superbrain for the input to these edits.

sorting of strings with ascii and length of the strings

Easy enough.

qsort takes a user-defined comparison function. So compare lengths first. If they are equal, call strcmp to compare alphabetically.

If you need to implement qsort, write a bubblesort with the same interface first to get things working, then replace with a faster algorithm.

Converting string to char and sort in descending order (ascii)

You can try

String str = "AbCdEf";
char[] arr = str.toCharArray();

for(int i = 0; i < arr.length; i++) System.out.print(arr[i]);
System.out.println();

Arrays.sort(arr); // sorted in ascending order

// print them backwards i.e. descending order.
for(int i = arr.length - 1; i >= 0; i--) System.out.print(arr[i]);
System.out.println();

prints

AbCdEf
fdbECA

How to sort a list of strings in reverse order without using reverse=True parameter?

You'll have to sort twice. Python's sort algorithm is stable, which means that elements that are equal keep their relative order. Use this to first sort on the second element (sorting in ascending order), then sort that output again, on only the first element and in reverse order:

sorted(sorted(my_list2, key=lambda t: t[1]), key=lambda t: t[0], reverse=True)

Using operator.itemgetter() instead of lambdas can make this little bit faster (avoiding stepping back in to the Python interpreter for each element):

from operator import itemgetter

sorted(sorted(my_list2, key=itemgetter(1)), key=itemgetter(0), reverse=True)

Demo:

>>> from operator import itemgetter
>>> my_list2 = [('aaa', 'bbb'), ('aaa', 'ccc'), ('bbb', 'aaa'), ('bbb', 'ccc')]
>>> sorted(sorted(my_list2, key=lambda t: t[1]), key=lambda t: t[0], reverse=True)
[('bbb', 'aaa'), ('bbb', 'ccc'), ('aaa', 'bbb'), ('aaa', 'ccc')]
>>> sorted(sorted(my_list2, key=itemgetter(1)), key=itemgetter(0), reverse=True)
[('bbb', 'aaa'), ('bbb', 'ccc'), ('aaa', 'bbb'), ('aaa', 'ccc')]

The general rule is to sort from the innermost element to the outermost element. So for an arbitrary-element-count sort, with a key and a reverse boolean each, you can use the functools.reduce() function to apply these:

from functools import reduce
from operator import itemgetter

def sort_multiple(sequence, *sort_order):
"""Sort a sequence by multiple criteria.

Accepts a sequence and 0 or more (key, reverse) tuples, where
the key is a callable used to extract the value to sort on
from the input sequence, and reverse is a boolean dictating if
this value is sorted in ascending or descending order.

"""
return reduce(
lambda s, order: sorted(s, key=order[0], reverse=order[1]),
reversed(sort_order),
sequence
)

sort_multiple(my_list2, (itemgetter(0), True), (itemgetter(1), False))

How to sort a list by length of string followed by alphabetical order?

You can do it in two steps like this:

the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length

Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.

You can also do it like this:

the_list.sort(key=lambda item: (-len(item), item))

Generally you never need cmp, it was even removed in Python3. key is much easier to use.

Function is just reversing the order of the input instead of sorting it in descending order

You're very close to the solution.

It's impossible to sort the array of strings in sortString because it only has access to the one string you pass in. Move the array sorting code to a separate method, and then you can call it while passing it the entire array:

static String sortString(String str) {

char[] chArr = str.toCharArray();
String SortString = "";

// For sorting each individual strings character by character
for (int i = 0; i < chArr.length; i++) {
for (int j = 0; j < chArr.length; j++) {
if (chArr[i] > chArr[j]) {
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}

//converting all of the character into a single string
for (int k = 0; k < chArr.length; k++) {
SortString = SortString + chArr[k];
}

return SortString;
}

static void sortArray(String[] OldArray) {

//sorting all of the strings in descending order
for (int i = 0; i< OldArray.length;i++)
{
for (int j = i+1; j< OldArray.length;j++)
{
if(OldArray[i].compareTo(OldArray[j]) > 0)
{
String temp = OldArray[i];
OldArray[i] = OldArray[j];
OldArray[j] = temp;
}
}
}
}

The main method needs a small change too: the characters in the strings have to be sorted before you sort the array. Here, the characters are sorted while reading the input, and then the array is sorted with one call to sortArray:

public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);

String[] names = new String[5];

// will take a String user input from a user and store it in an arra
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = sortString(UserInput.next().toLowerCase());
}while(names[counter].length() > 25);
}

sortArray(names);

//will print the assorted array
for(int i = 4; i >= 0; i--)
{
System.out.println(names[i]);
}
}


Related Topics



Leave a reply



Submit