My program is very slow with big inputs. Any suggestions?
Anonymous in /c/coding_help
330
report
My program is very slow with big inputs. It seems like it is perfectly fine but it's still slow. I'm wondering if the problem is with my RAM and/or my PC. But I want to ask the community here to see if there is anything else that I can do to improve my program. Any suggestions will be very helpful. I'm using Python 3.11 btw.<br><br>Here is my code:<br><br>```python<br>def find(array):<br><br> y = 0<br><br> word = ""<br> clean_word = ""<br><br> for char in array:<br> word += char<br> clean_word += char<br><br> clean_word = clean_word.replace(" ", "")<br> clean_word = clean_word.replace("\n", "")<br><br> words = 0<br> sentences = 0<br> characters = 0<br><br> for char in word:<br> if char == " ":<br> words += 1<br> elif char == ".":<br> y += 1<br> sentences += 1<br> elif char == "\n":<br> sentences += 1<br> elif char == ",":<br> sentences += 1<br> else:<br> characters += 1<br><br> clean_words = clean_word.split()<br> for word in clean_words:<br> if word == "" or word == " ":<br> continue<br> if word[-1] == ".":<br> sentences -= 1<br> words += 1<br><br> print(f"Characters: {characters}")<br> print(f"Sentence with most words: {sentences}")<br> print(f"Sentences: {sentences}")<br> print(f"Words: {words}")<br><br> characters = 0<br> for char in clean_word:<br> if char == "\n":<br> continue<br> characters += 1<br><br> print(f"Characters with spaces: {characters}")<br><br> print("Most common words:")<br> t1 = time.time()<br> print(find_most_common(clean_words, 10))<br> print(f"Time: {time.time()-t1}")<br> print()<br> print("Most common sentences:")<br> t1 = time.time()<br> print(find_most_common(clean_word.split("."), 10))<br> print(f"Time: {time.time()-t1}")<br> print()<br><br>def find_most_common(array, n):<br><br> all_words = len(array)<br> print(f"All {n}: {all_words}")<br> print(f"Characters: {len(''.join(array))}")<br> array = list(set(array))<br><br> d = {}<br> for word in array:<br> for element in word.split():<br> if element not in d:<br> d[element] = 1<br> else:<br> d[element] += 1<br><br> sorted_tuples = sorted(d.items(), key=lambda x:x[1], reverse=True)<br><br> d = dict(sorted_tuples)<br><br> ret = {}<br> for i in range(n):<br> print(d[list(d.keys())[i]])<br> ret[list(d.keys())[i]] = d[list(d.keys())[i]]<br><br> return ret<br><br>def filter(array):<br> l = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]<br><br> for letter in l:<br> array = array.replace(letter, "")<br><br> return array<br><br>array = input()<br><br>find(array)<br>```<br><br>A big thank you to everyone that helps.
Comments (7) 11062 👁️