简体   繁体   中英

Counting words containing certain letter

The task was to write a function with name count_letter that takes a list of words and certain letter and returns amount of words where this letter is found at least once. And, we have to use a for loop. So I did a list of some programming languages and letter "a", and tried to apply everything we learned so far plus some internet tutorials to understand how to translate human logic into lines of code, but obviously I am missing something, because it doesn't work:( That is how my code looks like at the moment:

mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
  count = 0
  for i in range(len(mylist)):
    if letter in i:
      count += 1
      a_list.append(i)
  return a_list
  print(len(a_list))

Result is - no result. Online-python compiler returns response ** process exited - return code: 0 ** My question is - what could I miss or positioned wrongly that loop doesn't work. I want to understand it for myself. In tutorials I have found one construction which returns correct answer (and looks very elegant and compact), but it has no function, so it is not really what we needed to write:

mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
res = len ([ele for ele in mylist if letter in ele])
print ('Amount of words containing a: ' +str(res))

Here system response: 3 , as expected.

Please tell me what should I check in code #1.

Few mistakes I found in your code:

  1. When you do for i in range(len(mylist)), you are actually looping through the numbers 1,2,... instead of elements of mylist. So you have to use "for i in mylist" to loop through elements of the array mylist.

  2. When you return from a function, the code that is after the return is not executed. So you have to print it first and then return from the function.

  3. Don't forget to call the function. Otherwise the function won't be executed.

  4. No need count variable as you can access the length using len method.

mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
  for i in mylist:
    if letter in i:
      a_list.append(i)
  print(len(a_list))
  return a_list
  
print(count_letter(mylist))

All the best in your journey!

Personally, I find Python source code easier to read when things are indented by four spaces. So, here is your function again with a wider indentation:

def count_letter(mylist):
    count = 0
    for i in range(len(mylist)):
        if letter in i:
            count += 1
            a_list.append(i)
    return a_list
    print(len(a_list))

for i in range(...) will iterate over a collection of integers. So, i will take on a new integer value for each iteration of the loop. First i will be 0 , then 1 on the next iteration, and so on.

You then ask if letter in i: . This can never be true. letter is a string, and i is an integer. A string can never be "in" an integer - so this if-statement will never execute. Rather, you want to check if letter is in the current word (the i th word in the list). The if-statement should read:

if letter in mylist[i]:
    ...

Where mylist[i] is the current word.

You then increment count and append i to a_list . You probably meant to append mylist[i] to a_list , but I don't see why you even need a_list . You just need count , since that keeps track of how many words you've encountered so far for which the condition is true. count is also the variable you should be returning in the end, since that is the purpose of the function: to return the number of words (not the words themselves) which contain a certain letter.

Also, the way your final print statement is indented makes it part of the function's body. It's after the return , though, which means it will never actually get a chance to print. When you use return inside a function, it ends the function, and flow of execution returns to the place from which the function was originally invoked.

One final change that needs to be applied, is that your function should accept a letter to look for as a parameter. Right now, your function only takes one parameter - the list of words through which to search.

Here are the changes I would apply to your code:

def count_letter(words, letter): # I find 'words' is a better name than 'mylist'.
    count = 0
    for i in range(len(words)):
        current_word = words[i]
        if letter in current_word:
            count += 1
    return count

Here is how you might use the function:

words = ["hello", "world", "apple", "sauce"]
letter = "e"
count = count_letter(words, letter)
print("The letter '{}' appeared in {} words.".format(letter, count))

Output:

The letter 'e' appeared in 3 words.

I think that 'takes' means that function must be defined with two parameters: words_list and letter:

def count_letter(words_list, letter):

Algorithm in natural language could be: give me sum of words where letter is present for every word in words list.

In Python it can be expressed as:

def count_letter(words_list, letter):
    return sum(letter in word for word in words_list)

Some explanation: letter in word returns boolean value (True or False) and in Python bools are subclass of integer (True is 1 and False is 0). If letter is in word the result would be 1 and if not it would be 0. Summing up of results gives number of words where letter is present

I have read all your answers, some important points I wrote down, sat today again with my code, and after some more tries it worked... So final version looks like:

words = ['fortran', 'basic', 'java', 'python', 'c++']
letter = "a"


def count_letter(words, letter):
    count = 0
    for word in words:
        if letter in word:
            count += 1
    return count
print(count_letter((words),letter))

System response: 3

What is not yet obvious for me: correct indents (they were also part of a problem), and additional pair of parentheses around words in print line. But it comes with learning.

Thank you once again!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM