0

I am an absolutely beginner in Python and trying to create algorithm which is looking a word in a list and if it finds one return an index accordingly. I know that it can be done in “more professional” way, but I am trying to create own code (efficient or not). The problem is the code runs out form range.

Thanks in advance!



lst = ['caT.', 'Cat', '.cat', 'NONE', 'caty']

word_to_find = 'cat'

i = 0
j = 0

while i <= len(lst):
    if j+len(word_to_find) <= len(lst[i]):
        if lst[i][j] == 'C' or 'c':
            if lst[i][j+1] == 'a'or'A':
                if lst[i][j+2] == 't'or'T':
                    print(i)
        j+=1
    i+=1
NIk
  • 123
  • 5
  • What exception are you getting when you run your code? – bit Aug 21 '20 at 19:11
  • 1
    All of your `if` statements [have bugs](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value). That is not how you compare a value to multiple candidate values. – Cory Kramer Aug 21 '20 at 19:13
  • you could try a switch statement instead of using multiple conditional statements. – bit Aug 21 '20 at 19:15
  • @MyWrathAcademia Python doesn't have a `switch` statement. You can use a [dictionary lookup](https://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement) but that does not compile to the equivalent of a C-like switch statement – Cory Kramer Aug 21 '20 at 19:16
  • 0 2 Traceback (most recent call last): File "D:/Pythone Practice/Kaggel/1213.py", line 9, in if j+len(word_to_find) <= len(lst[i]): IndexError: list index out of range – NIk Aug 21 '20 at 19:20
  • That's useful information. Which line in your code is line 9? – bit Aug 21 '20 at 19:38
  • What should the result be for the given input? – Karl Knechtel Aug 21 '20 at 19:42

5 Answers5

1

A more compact way to do this is using a list comprehension. You can use enumerate to iterate over a sequence by tuples of (index, value). Then you can compare your search word as a substring of each element using in, and you can use .lower for case-insensitive comparison.

>>> [idx for idx, value in enumerate(lst) if word_to_find.lower() in value.lower()]
[0, 1, 2, 4]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

If you want just to correct your code, you can start by using the .lower() method in Python. Using it prevents from your code to get too repetitive (using 'c' or 'C' to get the same string) and from bugs as well. As for the bugs, your code had three of it. The first one, is that if you still don't want to use .lower(), you must write the or statement like this:

example = 's'
if example == 's' or example == 'S':
    print(example)

This is the correct way to use the or statement. The second bug is at your while loop:

while i <= len(lst):
    if j+len(word_to_find) <= len(lst[i]):
        if lst[i][j] == 'C' or 'c':
            if lst[i][j+1] == 'a'or'A':
                if lst[i][j+2] == 't'or'T':
                    print(i)
        j+=1
    i+=1

You must remember that the len() function returns the number of elements inside the list or string. As we start counting the position of values at 0 in a object, the last index will be len(lst)-1. For example:

testList = ['a', 'b', 'c']
len(testList) # returns 3
testList[2] # returns 'c'

As you can see, even if I type testList[2], it returns the last value of the list. Your while try to access the lst[5], since it has the less than or equal sign [while <= len(lst)]. Changing it to the less than (<) sign solves the problem.

The last bug I found is your variable j. In your code, it just get added by 1 everytime the loop starts over. The problem is, your next word may not have that specific letter. For example:

lst = ['lion', 'cat']

In your while loop, Python will return a bug for the second word. Cat doesn't have a fourth letter as lion does. To prevent this, you must set the variable j to 0 everytime the loop starts again. You can do this by adding a j = 0 right after your while statement, as below.

lst = ['caT.', 'Cat', '.cat', 'NONE', 'caty']

word_to_find = 'cat'

i = 0

while i < len(lst):
    j = 0
    if j+len(word_to_find) <= len(lst[i]):
        if lst[i][j].lower() == 'c':
            if lst[i][j+1].lower() == 'a':
                if lst[i][j+2].lower() == 't':
                    print(i)
        j+=1
    i+=1

The code above is the final and working form, it will find any string that starts with 'cat'. There is more efficent ways to code a search algorithm like that, but I think you just want help with the bugs in your code. I hope that this help you. Keep coding!

leodsc
  • 111
  • 4
0

When you right the while loop make sure that you have while i<= len(lst)-1. Becuase then it would go out of range by one.

DedS3t
  • 183
  • 1
  • 7
0

you can do it using a function like that :

list_of_strings = ["London", "Paris", "Madrid", "Rome", "Berlin"]
target_string = "MADRID"
target_string_lower = target_string.lower()

is_target_in_list = target_string_lower in (string.lower() for string in list_of_strings)

print(is_target_in_list)
Jasar Orion
  • 626
  • 7
  • 26
-1

Try this:

lst = ['caT.', 'Cat', '.cat', 'NONE', 'caty']

word_to_find = 'cat'

i = 0
j = 0

while i <= len(lst) - 1:
    if j+len(word_to_find) <= len(lst[i]):
        if lst[i][j] == 'C' or 'c':
            if lst[i][j+1] == 'a'or'A':
                if lst[i][j+2] == 't'or'T':
                    print(i)
        j+=1
    i+=1
bit
  • 443
  • 1
  • 7
  • 19
  • `lst[i][j] == 'C' or 'c'` is a [very common bug](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Cory Kramer Aug 21 '20 at 19:12