Programma Python per ordinare una stringa

Ordinamento è sempre stata un'utilità piuttosto popolare con molte applicazioni ovunque, dove il linguaggio Python opta. Python nel suo linguaggio offre una funzione di ordinamento per eseguire questo compito. Ma poiché non tutti i contenitori Python sono mutabili, come le stringhe, la funzione di ordinamento non funziona così com'è nel tentativo di ordinare e l'immutabilità lo impedisce. Parliamo dei modi specifici in cui è possibile ordinare una stringa.

Esempio

  Input:   geekforgeeks   Output:   eeeefggkkors   Explaination:  The Sorting the characters in ascending order gives us 'eeeefggkkors'. 

Programma per ordinare una stringa in Python

Di seguito sono riportati gli elenchi dei metodi che tratteremo:

Programma per ordinare una stringa usando join() e sorted()

La combinazione delle funzioni di cui sopra può potenzialmente risolvere questo particolare problema. Questa attività viene eseguita nella seconda fase in cui nel primo passaggio otteniamo l'elenco ordinato dei caratteri e poi uniamo il risultato per ottenere il risultante stringa ordinata.

Python3




test_string> => 'geekforgeeks'> # printing original string> print> (> 'The original string : '> +> str> (test_string))> # using join() + sorted()> # Sorting a string> res> => ''.join(> sorted> (test_string))> > # print result> print> (> 'String after sorting : '> +> str> (res))>

Produzione

The original string : geekforgeeks String after sorting : eeeefggkkors 

Complessità temporale: La complessità temporale del codice è O(n log n).
Complessità spaziale: La complessità spaziale del codice dato è O(n).

Ordina una stringa Python u cantare il metodo nativo

Per ordinare una determinata stringa con l'input dell'utente utilizzando il metodo di ordinamento Python integrato.

Python3




String> => 'geekforgeeks'> print> (> 'Original String: '> , String)> lst> => list> (String)> lst.sort()> print> (> 'Sorted String: '> )> for> i> in> lst:> > print> (i, end> => '')>

Produzione:

Original String: geekforgeeks Sorted String:  eeeefggkkors 

Complessità temporale: La complessità temporale del codice è O(n log n).
Complessità spaziale: La complessità spaziale del codice dato è O(n).

Ordina una stringa Python usando reduce() e lambda

Questa particolare attività può essere eseguita anche utilizzando una combinazione delle funzioni di cui sopra. Qui uniamo l'elenco ordinato di caratteri risultante utilizzando il comando funzione lambda uniti dalla funzione di riduzione. Funziona solo per Python2

Pitone




test_string> => 'geekforgeeks'> # printing original string> print> (> 'The original string : '> +> str> (test_string))> # using sorted() + reduce() + lambda> res> => reduce> (> lambda> x, y: x> +> y,> sorted> (test_string))> > # print result> print> (> 'String after sorting : '> +> str> (res))>

Produzione

The original string : geekforgeeks String after sorting : eeeefggkkors 

Complessità temporale: La complessità temporale del codice è O(n log n).
Complessità spaziale: La complessità spaziale del codice dato è O(n).

Ordina una stringa in Python utilizzando Bubble Sort

Converti la stringa in un elenco di caratteri, quindi utilizza il file ordinamento delle bolle l'algoritmo per ordinare l'elenco ora si unisce all'elenco ordinato per formare una stringa.

Python3




def> sort_string(s):> > chars> => list> (s)> > n> => len> (chars)> > for> i> in> range> (n):> > for> j> in> range> (> 0> , n> -> i> -> 1> ):> > if> chars[j]>carri armati[j> +> 1> ]:> > chars[j], chars[j> +> 1> ]> => chars[j> +> 1> ], chars[j]> > return> ''.join(chars)> s> => 'geekforgeeks'> print> (> 'Original string:'> , s)> print> (> 'String after sorting:'> , sort_string(s))>

Produzione

Original string: geekforgeeks String after sorting: eeeefggkkors 

Complessità temporale : O(n^2) perché utilizziamo l'algoritmo bubble sort che ha una complessità temporale di O(n^2).
Spazio ausiliario: O(n) perché creiamo un nuovo elenco di caratteri dalla stringa originale.

Programma per ordinare una stringa utilizzando Merge Sort

Questo approccio utilizza il unisci ordinamento algoritmo per ordinare i caratteri nella stringa. Innanzitutto converte la stringa in un elenco di caratteri, quindi divide ricorsivamente l'elenco a metà finché non viene raggiunto il caso base di un singolo elemento. Le due metà vengono quindi riunite nuovamente insieme in ordine ordinato utilizzando la funzione merge(). L'elenco ordinato viene quindi riconvertito in una stringa.

Python3




# Define a function called 'merge_sort'> def> merge_sort(s):> > if> len> (s) <> => 1> :> > return> s> > # find the middle index of the string 's'> > mid> => len> (s)> /> /> 2> > # split the string into two halves, left and right> > left> => merge_sort(s[:mid])> > right> => merge_sort(s[mid:])> > #Recursively apply the merge_sort function on the left and right halves.> > return> merge(left, right)> > # Merge the left and right halves using the merge function.> def> merge(left, right):> #Initialize an empty list called 'result' and two indices, 'i' and 'j', both set to 0.> > result> => []> > i> => j> => 0> > while> i <> len> (left)> and> j <> len> (right):> > if> left[i] result.append(left[i]) #Increment the index of the array i += 1 else: result.append(right[j]) #Increment the index of the array j += 1 result += left[i:] result += right[j:] return result s = 'geekforgeeks' #Convert the sorted list to a string and print the result. sorted_s = ''.join(merge_sort(list(s))) print('String after sorting:', sorted_s)>

Produzione

String after sorting: eeeefggkkors 

Complessità temporale: O(n log n) dove n è la lunghezza della stringa di input s.
Complessità spaziale: O(n) dove n è la lunghezza della stringa di input s.

Ordina una stringa in un programma Python usando un dizionario

Questo programma ordina una determinata stringa di input in ordine crescente in base ai caratteri presenti in essa. Utilizza un dizionario per contare la frequenza di ciascun carattere e quindi ordinarli in base al valore ASCII del carattere.

Python3




input_string> => 'geekforgeeks'> #Initialize an empty dictionary to store the count> char_count> => {}> #Loop through each character in the input string and update the count of that character> for> char> in> input_string:> > if> char> in> char_count:> > char_count[char]> +> => 1> > else> :> > char_count[char]> => 1> > #Create an empty string to store the sorted string.> sorted_string> => ''> #Loop through each character in the sorted list of keys of the dictionary> #Add that character multiplied by its count in the input string to the sorted string.> for> char> in> sorted> (char_count.keys()):> > sorted_string> +> => char> *> char_count[char]> #Print the original string and the sorted string.> print> (> 'Original string: {}'> .> format> (input_string))> print> (> 'String after sorting: {}'> .> format> (sorted_string))>

Produzione

Original string: geekforgeeks String after sorting: eeeefggkkors 

Complessità temporale: La complessità temporale di questo algoritmo è O(nlogn) a causa dell'uso della funzione sorted().
Complessità spaziale: La complessità spaziale di questo algoritmo è O(n) a causa dell'uso del dizionario per memorizzare il conteggio di ciascun carattere.