0
How do I sort words more efficiently?
The user writes the number of words to sort which is between 1 and 10 000. (The length of a word is between 1 and 100 letters) Then he writes all the words we need to sort one at a time, the program should take less than 1second on a 1GHz machine and take less than 8,000 KB However, it seems that my program, which uses the predefined sort function, exceeds the time limit. https://code.sololearn.com/cqDN6M3ZgG5r/?ref=app
11 odpowiedzi
+ 3
alice boulay , you may use this for output:
...
for word in tab:
print(word)
but this may not reduce the time you want to save. sort() is operating in place, so this could be a reason, but it does not use extra space.
Have you tested with sorted()?
+ 3
alice boulay , I did a try with checking the time that sort() and sorted() is consuming. It is about the same. But this is not the reason I come back. See the results down from the test I have done. it is 10_000 words each with 100 characters to use sort() and sorted(). see also the time consumption, which is 0.006533 seconds done on a midrange tablet with android. this will lead me to the assumption that the code you presented here is not identical with the code you have used and got problems.
so there may be an other reason for your post?
'''
ready creating list of words randomly
start sorting with inplace sort()
0:00:00.006533 sec
number of words: 10_000, word length: 100
start sorting with sorted()
0:00:00.006300 sec
number of words: 10_000, word length: 100
first word in sorted list:
'aabddvawmknruevlstaelvqyolrggkxqcccpoudyfbmvfhzekvbppygyygqkokphdhinukpyjnxvynibuvutgpmjvointewguoxx'
[Program finished]
'''
+ 1
alice boulay , how do you create the words as input?. Do you generate them randomly?
+ 1
Sorry for the late response...
Strange...I had a go using the method I suggested (although must smaller sample) and it took about a quarter of the time.
0
Thanks, I'll try with sorted(). I assumed sorted() would take more time since we would have to store the elements in a new var
0
"Then he writes all the words we need to sort one at a time" <== don't understand this bit?
Do you mean "output" the sorted words?
0
Lothar The user types them in
0
rodwynnejones the user inputs the words one at a time, the sorted need to '' output'' but this isn' t the main problem
0
I'll try and create my own sort function and see how it goes
0
what you could do is:
I assume your entering one word at a time and appending to a list rather than entering one sentence and splitting it...if so...after you enter each word...sort the list.... so the last "sort/sorted" is quicker (your bottleneck).
(sorted() is quicker than in-place sort().
0
rodwynnejones
Thanks, I tried your proposition, however it seems that the program takes longer by doing so