+ 1
Find longest word in a text, fixed
I need to find the longest word in a text. This is the approach I went with and I can’t seem to figure it out. I am not getting any output, how can I approach the problem and get the desired output? FIXED https://code.sololearn.com/cIv1Uy9HL5k4/?ref=app
7 odpowiedzi
+ 1
First, pls edit your question description and substitute the wall of code for a link to your code in Code Playground. This way, we can test and debug your code. Also, it's hard to follow indentation levels in the question description.
So far, I can ser a couple issues:
1. The code never uses variable "txt"
2. The code never calls function "longestword"
3. The function parameter overwrites function "input"
4. The while loop end condition never happens - len(text) never changes
5. The text index "i" keep increasing, leading to a certain out of range error
6. The code doesn't store the longest word anywhere
7. The function returns itself
8. The return value uses a variable defined outside the function
I suggest you start over from scratch. But think the logic though before writing any code. When the logic is unclear in your head, the code will never make full sense.
+ 1
Yes. A good practice for iterations is to keep the iterable unchanged in the loop.
Take a good read on iterations in Python. It's easy. Spoiler: the loop lets you work one item at a time, so you don't have to touch the list.
Also, reread the lesson on functions. Understand how they are called and return values.
Plus, make sure your variable, function, etc. names don't overwrite Python function names. Things get quite dark when this happens.
+ 1
Normally you can use the built in max function as you have in your code.
If you want to build an algorithm you can also use your original idea with the while loop. Just a little adjustment is needed. Read my comment in code:
https://code.sololearn.com/cVYT5XhIclln/?ref=app
+ 1
Alex Madsen yes, pop(n) deletes the element at index n
0
I wanted to iterate through the list, and continuously delete any word shorter than the next, so that after enough iterations only the longest word remained.
And of course, if i am way off base, and there is a better way to do it, any hints would be appreciated.
0
I suppose I’ll start from scratch.
Would you say that the concept of iterating trough the list a deleting words is flawed? Should i start over with a different method?
0
So .pop() deletes the element whose index it is given as an argument?