Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a char array to a number for sorting?

Let’s say I have three words I want to sort:

  • hello
  • goodbye
  • alex

And alphabetically it’d be sorted ascendingly as ["alex", "goodbye", "hello"]. Is there a way to convert the string (limited to 100 characters)? For example, if I have:

['a', 'l', 'e', 'x']

And I use ord to get the code for each list-element:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1, 12, 5, 24]

How would I create a number from that, that would also be smaller than, say, goodbye ?

>Solution :

Use:

from operator import mul, pow
from itertools import repeat

LIMIT = 100
char_vals = [1, 12, 5, 24]
sum(map(mul, char_vals, map(pow, repeat(27), range(LIMIT, 0, -1))))

Since you’ve bounded the length of the strings, you can think of each word as a base-27 number. 0 represents that the letter doesn’t exist, 1 represents a, 2 represents b, etc.

Then, the numerical value of each word can be computed using the following polynomial:

i_1 * 27**100 + i_2 * 27**99 + ...

where char_vals = [i_1, i_2, ...] (i.e. each i is the integer value of the corresponding letter).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading