0

I have a function which takes 2 arguments - an input string, and a list of words. For every word in the list which is present in the string, the function returns "True", else "False".

My code is given below:

#!/usr/bin/python


# inputStr is a string, inputList is  list of strings

def keyword_usage(inputStr, inputList):

    splitStr = inputStr.split();
    L = [];
    k = 0;
    bool = 0;

    for i in range(0,len(inputList)):

        for  j in range(0, len(inputStr)):

            if inputList[i]==splitStr[j]:
                bool = 1;
            else:
                bool = 0;
        if bool==1:
            L[k] = "True";
        else:
            L[k] = "False";
        k+=1;
    return tuple(L);

I am running it in the interpreter as shown below:

>>> from keyword_usage import keyword_usage
>>> res = keyword_usage('Dive  Into  Python',  ['Python',  'python', 'scala'])

When I press enter, I get this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "keyword_usage.py", line 17, in keyword_usage
    if inputList[i]==splitStr[j]:
IndexError: list index out of range

I am new to Python coding and am very confused. It seems a basic question, but I could not get any answer on any forum. Can someone spot the error? Thanks in advance!!

5 Answers 5

2

I would suggest a more pythonic solution:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = []
    for i in inputList:
        L.append(i in splitStr)
    return tuple(L)

That's it!

Use the in operator. It checks if an element is present in a list and returns True or False.

'Dive' in ['Python', 'python', 'scala']
>>> False
'Python' in ['Python', 'python', 'scala']
>>> True
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you too for this information, I didn't know it could be that simple!
Now you know. Python is that simple and elegant, but it takes time to get enlightened with the wisdom :)
1

Use this:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split();
    L = []
    b = False
    for i in range(0,len(inputList)):
        for  j in range(0, len(inputStr)):
            b = inputList[i]==splitStr[j]
        L.append(b)
    return tuple(L)

print keyword_usage('Dive  Into  Python',  ['Python',  'python', 'scala'])

You made a lot of mistakes:

  • Python doesn't use ';'
  • Don't use 0 or 1 as boolean but use True and False instead.
  • Now you can save True or False in that boolean
  • In the seccond loop, I think you ment splitStr instead of inputList

And the error was caused by:

L[k] = "True";

Since L has no items yet, you can't add items that way. Use append instead:

L.append("True")

Ouput now:

(True, False, False)

1 Comment

Thank you so much for the help and information! Actually I had added the ";" because of the errors I kept getting, and yes, I meant splitStr.
1

And let's take it one step beyond. Learn to know the comprehension lists:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = [i in splitStr for i in inputList]
    return tuple(L)

Now you can run the function:

keyword_usage('Dive Into Python', ['Python', 'python', 'scala'])
>>> (True, False, False)

But I would extend the function even on step further:

def keyword_usage(inputStr, inputList):
    splitStr = inputStr.split()
    L = [i in splitStr for i in inputList]
    return dict(zip(inputList, L))

Now you have this result:

keyword_usage('Dive Into Python', ['Python', 'python', 'scala'])
>>> {'Python': True, 'python': False, 'scala': False}

So you know immediately which list element was found in the string.

You can rewrite the list comprehension like this:

L = [(i in splitStr) for i in inputList]

for better readability, if you like it more.

The built-in function zip combines two lists together, first element of list A with the first element of list B, second element of list A with the second element of list B, and so on. The built-in function dict then makes a nice dictionary of these values.

Enjoy!

Comments

0

It looks like just a typo.

This:

for  j in range(0, len(inputStr)):

Should be this:

for j in range(0, len(splitStr)):

Comments

0

print len(splitStr)

gives :- 3

print len(inputList), len(inputStr)

gives:- 3, 18

when you check

if inputList[i]==splitStr[j] #for i = 1 and j = 12

while splitStr just have three values ['Dive', 'Into', 'Python']

when you run for j in range(0, len(inputStr)) it will loop for 18 times anf every time j takes values from (0,18) so it checks for splitStr[j] let's say 10 then splitStr[10] which is actually (['Dive', 'Into', 'Python']) out of range.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.