import json
word2 = []
base = input("Enter word:- ")
base = base.lower()
with open('D:\Code\Python\words_dictionary.json') as data:
word = json.load(data)
for i in range(len(word)):
if(len(base)==len(word[i])):
if sorted(base) == sorted(word[i]):
word2.append(word[i])
print("Possible words:-")
print("\n".join(word2))
Counting the amount of each letters would be faster than sorting. Aka storing an array[26] for the input word, then for each word in dictionary with same length, make the same array[26] and compare.
You likely run more comparisons, it's 26 array indices which is likely considerably more comparisons than the comparisons needed to sort an average length word, in addition to still having to read and write a value to memory for each character in each word you test.
In fact, your "o(n)" method only outperforms the o(n*log(n)) of the sorting approach if the average word length is greater than 8 letters, and that's assuming a base 2 log. It's much worse for higher bases.
Your method will also not able to deal with any other characters than that alphabet! The shown method works with everything that can be input and loaded from JSON.
The whole thing: linear time looping on the number of words (n) and sorting each word’s characters (w) is at best wlog(w). Having to do this over millions of inputs makes this a very inefficient implementation.
Instead, preprocessing the dictionary into a nice data structure like a trie of letter counts before receiving inputs means you can take the algorithm down to O(w) with O(n) space in the worst case.
3
u/Gem2578 Aug 25 '21
At least it is more readable them https://www.reddit.com/r/badcode/comments/pa5gip/i_wrote_this_pile_of_shit_for_a_codewars/ha5go1s
2
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Aug 25 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
1
u/genericindividual69 Aug 25 '21
wordshould be nameddictionary_wordsandword2should bematchesbut other than that it's not terrible code.1
u/sodjanathan Aug 26 '21
So what ill be a better version of this?
1
u/Python_Lab2021 Aug 27 '21
It is not so bad)
0
u/legendoffjelda Aug 25 '21
Ah yes, O(n * w log w)