I want to sort words in a list based on length.
The test case is {'cat','jump','blue','balloon'}
When run through this method it will print something along the lines of:
{'balloon','jump','blue','balloon'}
Another problem I have run into, is that the type of python we were using worked fine, however when I try to run the .py in the Python 3.5.2 shell, it comes up with errors.
I mainly just need to know what I did wrong, and what I can do to fix it so that it works. Any help is appreciated!
The .py file can be found here:
def wordSort():
words = []
minimum = 'NaN'
index = 0
x = 0
y = 0
z = 1
#How many words to be entered
length = input('How many words would you like to enter? ')
#Put words in the number of times you entered previously
while not z >= length + 1:
words.append(raw_input('Enter word #' + str(z) + ': '))
z += 1
while x < length:
minimum = words[x]
#Goes through the list and finds a smaller word
while y < length:
if len(words[y]) < len(minimum):
minimum = words[y]
index = y
y += 1
words[index] = words[x]
words[x] = minimum
x += 1
print words
In today’s article, we will show you 2 smart ways to sort a column of texts by length in your Word.
There are several ways to sort a column of texts or numbers in a table. But, have you ever thought about sorting a column of texts by length? In such case, your document layout will be more clear and easy for reading.
However, there is no direct way in Word for us to sort in this rule. Therefore, we have to look for workarounds to solve the issue.
Method 1: Use Word VBA
For example, let’s say we have a table as bellow:
- First and foremost, in Word press “Alt+ F11” to trigger VBA editor.
- Go to create a new module by clicking “Normal” in the left column.
- Then click “Insert” tab and choose “Module” on the drop-down menu.
- Next double click on module to open it and paste the bellowing macro there:
Sub SortByWordLength() Dim objTable As Table Dim objColumnCell As Cell Dim objColumnCellRange As Range Dim objNewColumnCellRange As Range Dim nRowNumber As Integer Dim nColumnNumber As Integer Dim strWordLenth As String Dim nSortOrder As Integer Dim nCurrentTableIndex As Integer Dim nTableColumnsInCurrentTable As Integer nCurrentTableIndex = ActiveDocument.Range(0, Selection.Tables(1).Range.End).Tables.Count nTableColumns = ActiveDocument.Tables(nCurrentTableIndex).Columns.Count nColumnNumber = InputBox("Enter the column number you want to sort", "Column Number", "For example:2") If nColumnNumber > 0 And nColumnNumber <= nTableColumns Then nSortOrder = InputBox("Choose the sort order:" & vbNewLine & "If you want to sort by descending, click 1" & vbNewLine & "If you want to sort by ascending, click 0", "Sort Order", "For example:1") If nSortOrder = 1 Or nSortOrder = 0 Then ' Add a new column to put the word length of the specified column. Set objTable = ActiveDocument.Tables(nCurrentTableIndex) objTable.Columns.Add BeforeColumn:=objTable.Columns(nColumnNumber) nRowNumber = 1 For Each objColumnCell In objTable.Columns(nColumnNumber + 1).Cells Set objColumnCellRange = objColumnCell.Range objColumnCellRange.MoveEnd Unit:=wdCharacter, Count:=-1 Set objNewColumnCellRange = objTable.Cell(nRowNumber, nColumnNumber).Range objNewColumnCellRange.MoveEnd Unit:=wdCharacter, Count:=-1 strWordLenth = Len(objColumnCellRange.Text) objNewColumnCellRange.InsertAfter (strWordLenth) nRowNumber = nRowNumber + 1 Next objColumnCell objTable.Select ' Sort by the word length. Selection.Sort ExcludeHeader:=True, FieldNumber:="Column " & nColumnNumber, SortFieldType:= _ wdSortFieldNumeric, SortOrder:=nSortOrder, FieldNumber2:="", _ SortFieldType2:=wdSortFieldAlphanumeric, SortOrder2:=wdSortOrderAscending _ , FieldNumber3:="", SortFieldType3:=wdSortFieldAlphanumeric, SortOrder3:= _ wdSortOrderAscending, Separator:=wdSortSeparateByCommas, SortColumn:= _ False, CaseSensitive:=False, LanguageID:=wdEnglishUS, SubFieldNumber:= _ "Paragraphs", SubFieldNumber2:="Paragraphs", SubFieldNumber3:="Paragraphs" objTable.Columns(nColumnNumber).Delete Else MsgBox ("Invalid sort type, please try again") End If Else MsgBox ("Invalid column number, please try again") End If End Sub
Note:
If your table contains no header row, then you need to alter the following code line:
Selection.Sort ExcludeHeader:=True
Replace “True” with “False”.
- Next click “Run”.
- Then in the first box open, enter the column number of target column, such as “2” for the second column.
- Click “OK”.
- In the second box, enter a number to specify a sorting rule. “0” represents sorting by ascending, “1” by descending.
- Similarly, click “OK”.
Check the effect:
Method 2: Sort in Excel
- Firstly, select table in Word and press “Ctrl+ C” to copy it.
- Next open Excel and paste it by pressing “Ctrl+ V”. Now if your table has no header row, then paste the table in cell A2.
- Then click on the column letter of the column. For instance, let’s say column C is the target column. You will see the total column in selection.
- Next right click and choose “Insert”.
- There will be a new column before column C. Position cursor at the second cell of new column.
- Enter “=LEN(C2)” in cell B2. Remember to replace the “C” with an actual one.
- Next put cursor at the right-down corner of cell B2 until it changes to a cross.
- Now double click. You will see the new column filled with numbers. These are number of characters for the texts in column C.
- Enter anything you like in cell B1. Just don’t leave it blank.
- Put cursor in any cell in column B that has a number.
- Go to click “Home” tab and click “Sort & Filter”.
- On the drop-down menu, choose “Sort Smallest to Largest” or “Sort Largest to Smallest”.
- Finally, select the newly inserted column and right click to choose “Delete”. And paste the table back to Word document.
Repair Corrupt Documents
Do you believe your documents stored on computers are safe? Even you can protect your computer from attack. There is still the possibility of having documents lost. So keep in mind that your file might not be perfectly safe. Consequently, get a docx recovery tool in advance would be a good choice.
Author Introduction:
Vera Chen is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including damaged xls and pdf repair software products. For more information visit www.datanumen.com
World’s simplest online line sorter for web developers and programmers. Just paste your text in the form below, press the Sort Lines button, and you get back the same lines but sorted by their length. Press a button – get the text. No ads, nonsense, or garbage.
Announcement: We just launched TECHURLS – a simple and fun tech news aggregator. Check it out!
Using a String Length Sorter in Cross-browser Testing
A string length sorter can be useful if you’re doing cross-browser testing. For example, if you want to neatify the way your web application displays a list of data, then you may want to sort the items so that they go from the shortest item to the longest (or from the longest to the shortest). To make sure your sorting algorithm works correctly, you may also want to write unit tests for it. A unit test is a simple program that takes an algorithm, input data, and output data, then runs the algorithm on the input data, and compares the result with the given output data. This way you can easily catch mistakes in the algorithm. In this program, the algorithm finds lengths of all given strings (one per line) and then sorts them by their length. Another use case for this program is finding the longest (or shortest) string or the longest (or shortest) text line. When you sort lines in ascending order, then the longest line will be the last one at the bottom (and the shortest line will be the first one on top), and if you sort lines in descending order, then the longest line will be the first one on top (and the shortest line will be the last one at the bottom).
Pro tip: You can use ?input=text query argument to pass text to tools.
We are given an array of strings, we need to sort the array in increasing order of string lengths.
Examples:
Input : {“GeeksforGeeeks”, “I”, “from”, “am”}
Output : I am from GeeksforGeeksInput : {“You”, “are”, “beautiful”, “looking”}
Output : You are looking beautiful
A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation, that uses Insertion Sort to sort the array.
Algorithm:
- Initialize the string with the input words.
- Calculate the string length.
- Sort the string array according to the length of words in ascending order With the help of insertion sort.
- Print the sorted array.
Below is the implementation of the above approach:
C++
#include<iostream>
using
namespace
std;
void
printArraystring(string,
int
);
void
sort(string s[],
int
n)
{
for
(
int
i=1 ;i<n; i++)
{
string temp = s[i];
int
j = i - 1;
while
(j >= 0 && temp.length() < s[j].length())
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
void
printArraystring(string str[],
int
n)
{
for
(
int
i=0; i<n; i++)
cout << str[i] <<
" "
;
}
int
main()
{
string arr[] = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
int
n =
sizeof
(arr)/
sizeof
(arr[0]);
sort(arr, n);
printArraystring(arr, n);
return
0;
}
Java
import
java.util.*;
class
solution
{
static
void
sort(String []s,
int
n)
{
for
(
int
i=
1
;i<n; i++)
{
String temp = s[i];
int
j = i -
1
;
while
(j >=
0
&& temp.length() < s[j].length())
{
s[j+
1
] = s[j];
j--;
}
s[j+
1
] = temp;
}
}
static
void
printArraystring(String str[],
int
n)
{
for
(
int
i=
0
; i<n; i++)
System.out.print(str[i]+
" "
);
}
public
static
void
main(String args[])
{
String []arr = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
int
n = arr.length;
sort(arr,n);
printArraystring(arr, n);
}
}
Python3
def
printArraystring(string, n):
for
i
in
range
(n):
print
(string[i], end
=
" "
)
def
sort(s, n):
for
i
in
range
(
1
, n):
temp
=
s[i]
j
=
i
-
1
while
j >
=
0
and
len
(temp) <
len
(s[j]):
s[j
+
1
]
=
s[j]
j
-
=
1
s[j
+
1
]
=
temp
if
__name__
=
=
"__main__"
:
arr
=
[
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
]
n
=
len
(arr)
sort(arr, n)
printArraystring(arr, n)
C#
using
System;
public
class
solution{
static
void
sort(String []s,
int
n)
{
for
(
int
i=1 ;i<n; i++)
{
String temp = s[i];
int
j = i - 1;
while
(j >= 0 && temp.Length < s[j].Length)
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
static
void
printArraystring(String []str,
int
n)
{
for
(
int
i=0; i<n; i++)
Console.Write(str[i]+
" "
);
}
public
static
void
Main()
{
String []arr = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
int
n = arr.Length;
sort(arr,n);
printArraystring(arr, n);
}
}
Javascript
<script>
function
sort(s, n)
{
for
(let i = 1 ; i < n; i++)
{
let temp = s[i];
let j = i - 1;
while
(j >= 0 && temp.length < s[j].length)
{
s[j + 1] = s[j];
j--;
}
s[j + 1] = temp;
}
}
function
printArraystring(str, n)
{
for
(let i = 0; i < n; i++)
document.write(str[i]+
" "
);
}
let arr = [
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
];
let n = arr.length;
sort(arr,n);
printArraystring(arr, n);
</script>
Output
I am from GeeksforGeeks
Time Complexity: O(n*m), where m is the length of the string and n is the size of the input array.
Auxiliary Space: O(1)
A better solution is to use the sort function provided by programming languages like C++, and Java. These functions also allow us to write our own custom comparator. Below is C++ implementation that uses C++ STL Sort function.
Algorithm:
- Initialize the string with the input words.
- Calculate the string length.
- Compare the strings and return the smallest one.
- Sort the string array with the help of the built-in sort function.
- Print the sorted array.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using
namespace
std;
bool
compare(string &s1,string &s2)
{
return
s1.size() < s2.size();
}
void
printArraystring(string str[],
int
n)
{
for
(
int
i=0; i<n; i++)
cout << str[i] <<
" "
;
}
int
main()
{
string arr[] = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
int
n =
sizeof
(arr)/
sizeof
(arr[0]);
sort(arr, arr+n, compare);
printArraystring(arr, n);
return
0;
}
Java
import
java.util.Arrays;
import
java.util.Comparator;
class
GFG {
static
void
printArrayString(String str[],
int
n) {
for
(
int
i =
0
; i < n; i++)
System.out.print(str[i] +
" "
);
}
public
static
void
main(String[] args) {
String arr[] = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
int
n = arr.length;
Arrays.sort(arr, Comparator.comparing(s->s.length()));
printArrayString(arr, n);
}
}
Python3
from
functools
import
cmp_to_key
def
compare(s1,s2):
return
len
(s1)
-
len
(s2)
def
printArraystring(
str
,n):
for
i
in
range
(n):
print
(
str
[i],end
=
" "
)
arr
=
[
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
]
n
=
len
(arr)
arr.sort(key
=
cmp_to_key(compare))
printArraystring(arr, n)
C#
using
System;
using
System.Linq;
using
System.Collections;
public
class
GFG
{
public
static
void
printArrayString(
string
[] str,
int
n)
{
for
(
int
i = 0; i < n; i++)
{
Console.Write(str[i] +
" "
);
}
}
public
static
void
Main(String[] args)
{
string
[] arr = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
var
n = arr.Length;
Array.Sort(arr,(s1,s2)=>s1.Length-s2.Length);
GFG.printArrayString(arr, n);
}
}
Javascript
<script>
function
compare(s1, s2) {
return
s1.length - s2.length;
}
function
printArraystring(str, n) {
for
(let i = 0; i < n; i++)
document.write(str[i] +
" "
);
}
let arr = [
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
]
let n = arr.length
arr.sort(compare);
printArraystring(arr, n);
</script>
Output
I am from GeeksforGeeks
Time Complexity: O(nlogn), where n is the size of the array.
Auxiliary Space: O(1)
Method 2: Simplified solution using sort function in python and javascript
- Take string as a list.
- Use the sort function in python and javascript, providing the key as len, in the python code.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using
namespace
std;
void
printsorted(vector<string>& arr)
{
sort(arr.begin(), arr.end(), [](
const
string& a,
const
string& b) {
return
a.length() < b.length();
});
for
(
const
auto
& str : arr) {
cout << str <<
" "
;
}
cout << endl;
}
int
main()
{
vector<string> arr = {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
printsorted(arr);
return
0;
}
Java
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
public
class
Main {
public
static
void
printSorted(ArrayList<String> arr) {
Collections.sort(arr, Comparator.comparingInt(String::length));
for
(String str : arr) {
System.out.print(str +
" "
);
}
System.out.println();
}
public
static
void
main(String[] args) {
ArrayList<String> arr =
new
ArrayList<String>();
arr.add(
"GeeksforGeeks"
);
arr.add(
"I"
);
arr.add(
"from"
);
arr.add(
"am"
);
printSorted(arr);
}
}
Python3
def
printsorted(arr):
print
(
*
sorted
(arr, key
=
len
))
arr
=
[
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
]
printsorted(arr)
C#
using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
Program {
static
void
printsorted(List<
string
> arr) {
arr = arr.OrderBy(s => s.Length).ToList();
foreach
(
var
str
in
arr) {
Console.Write(str +
" "
);
}
Console.WriteLine();
}
static
void
Main() {
List<
string
> arr =
new
List<
string
> {
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
};
printsorted(arr);
}
}
Javascript
function
printsorted(arr) {
arr.sort((a, b) => a.length - b.length);
console.log(...arr);
}
let arr = [
"GeeksforGeeks"
,
"I"
,
"from"
,
"am"
];
printsorted(arr);
Output
I am from GeeksforGeeks
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
This article is contributed by Rishabh jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
There is a wordlist look like this;
123
b
1
4rr
f
k3j3
gg
Then I needed to sort these words by string length (doesn’t matter which start with numeric or string both are okay)
The output should be this:
b
1
f
gg
123
4rr
4rr
Is there a sort command that allows me to do this?
Braiam
66.5k30 gold badges175 silver badges264 bronze badges
asked Jul 19, 2012 at 12:00
Smile.HunterSmile.Hunter
8,03510 gold badges32 silver badges35 bronze badges
I assume you want to do this on the command-line.
Most command line tools work in a line-based manner, so it is straightforward with awk
, sort
and cut
, see for example this other question:
awk '{ print length, $0 }' testfile | sort -n | cut -d" " -f2-
Breakdown:
# Print line-length and the line
awk '{ print length, $0 }' testfile |
# Sort numerically by line-length
sort -n |
# Remove line-length number
cut -d' ' -f2-
Output:
1
b
f
gg
123
4rr
k3j3
See man awk
, info sort
and info cut
for more.
answered Jul 19, 2012 at 12:24
1