Home > Blockchain >  Searching through list for words containing character
Searching through list for words containing character

Time:01-19

I am new to programming and am in an introductory course using python. I am trying to implement a function that takes a list of strings and a character as a parameter and prints to the screen, all the strings that have the given character in them. If the list is empty, the function returns 'List is empty'. So it should look like this:

Given:

wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')

Return:

Absolute Sense Test

Given:

wordsWithChar([],'r')

return:

'List is Empty'

EDIT: I have tried the following:

def wordsWithChar(lst,x):
    for word in lst:
        print(word,end=' ')
    print()
    if len(lst)<1:
       print('List is empty')

def wordsWithChar(lst,x):
    for word in lst:
       print (word)
          if x in word:
              print(word)

def wordsWithChar(lst,x):
    newlst=[]
        for word in lst:
            newlst.append(word)
        print(newlst)
        if len(lst)<1:
            print('List is empty')
        if x in word:
           newlst.append(x)
        print(newlst)        
 
def wordsWithChar(lst,x):
    newlst=[]
    for word in lst:
        if x in lst:
           newlst.append(word)
    return newlst

    print(' ',join(lst))
    newlst=wordsWithChar(lst,x)
    if len(newlst)<1:
        print('List is empty')
    else:
        print(newlst)

I have tried everything I know with for-loops and if/else statements and cannot figure this out. Thank you in advance for the help.

EDIT: While I appreciate all the help, with every solution presented, IDLE gets to the wordsWithChar test and just stops. It for some reason does not return any values. just skips to a new input line.

CodePudding user response:

You nearly nailed it:

  def wordsWithChar(lst,x):
    for word in lst:
       print (word)
    if x in word:
       print(word)

The indentation of the if statement makes it run after the loop. But you would want it to run inside the loop:

def wordsWithChar(lst,x):
  for word in lst:
    if x in word:
      print(word)

if __name__ == "__main__":
  wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')

This does not show the "not found" message. A more pythonic way would be to first create the list of words containing x using a list comprehension:

words_containing_x =  [ w for w in lst if x in w ]
# words_containing_x = ['Absolute', 'Sense', 'Test']

Broken down:

  1. words_containing_x = - the new list
  2. [ w for w in lst ...] the new list is all w in the lists - a copy
  3. [... if x in w] but only if the word w contains x

If this is a bit confusing, the the following will return the length of all words in lst that contain x:

len_of_words_containing_x =  [ len(w) for w in lst if x in w ]
# len_of_words_containing_x = [8, 5, 4]

Back to the question. The list can be tested:

def wordsWithChar(lst,x):
  words_containing_x =  [ w for w in lst if x in w ]
  if words_containing_x:
    print(words_containing_x)
  else:
    print("Oh noes!")

CodePudding user response:

I feel a nested for loop would be your best bet. I dont want to just straight up give you the answer especially since this is for a course but try this as a starting point

def words_with_character(lst, char):
    new_lst = []
    for word in lst:
        for x in word:

noticed char is unused. You should be able to figure out where it is meant to be implemented. Good luck coding!

Hmm actaully your solution is very close.

def wordsWithChar(lst,x):
newlst=[]
for word in lst:
    if x in lst:
        newlst.append(word)
return newlst

Would work but you have the indents all wrong. Indentation is every important in Python. Additonal you never use word within the loop

def wordsWithChar(lst,x):
    newlst=[]
    for word in lst:
        if x in word: # word is the wrong variable to use here
            newlst.append(word)
    return newlst

CodePudding user response:

Note this implementation is rudimentary and not by any means the only or ideal way to look for words containing a specific character.

Also note, this implementation only looks for the exact character match. So wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s') and wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'S') (note the upper and lowercase s) are not the same questions

def wordsWithChar(words, char):
    words_with_char = []
    
    for word in words:
        if char in word:
            words_with_char.append(word)
    
    if len(words_with_char)<1:
        print('List is empty')
    else:
        print(' '.join(words_with_char))

words = ['Absolute','IDE','Summary','Sense','Test']
char = 's'

words_with_char = wordsWithChar(words, char)
  •  Tags:  
  • Related