Python Forum
Function to count words in a list up to and including Sam
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function to count words in a list up to and including Sam
#1
Good Morning
I am running Python 3.8.5 and trying to develop a function that counts the number of words in a list up to and including the word Sam. Here is what I have developed so far:
lst = ["able", "been", "state", "Sam", "beer"]
length = len(lst)
def test(lst):
    length = len(lst)
for w in lst:
    if w == "Sam":
        break
    print(w)
print(test(lst))
The out put I get is:
able
been
state
None

I would appreciate input to:
1. Help me understand why I cannot get the answer as a number (4)
2. Understand why I have to state 'length = len(lst) as a variable outside of the function, then repeat it as the first line of the function

Thanks in advance
Reply
#2
Where do you count anything?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
(Feb-15-2021, 09:20 AM)Oldman45 Wrote: Good Morning
I am running Python 3.8.5 and trying to develop a function that counts the number of words in a list up to and including the word Sam. Here is what I have developed so far:
lst = ["able", "been", "state", "Sam", "beer"]
length = len(lst)
def test(lst):
    length = len(lst)
for w in lst:
    if w == "Sam":
        break
    print(w)
print(test(lst))
The out put I get is:
able
been
state
None

I would appreciate input to:
1. Help me understand why I cannot get the answer as a number (4)
2. Understand why I have to state 'length = len(lst) as a variable outside of the function, then repeat it as the first line of the function

Thanks in advance

1. You don't get the answer as a number because that's not what you ask for.
2. You set the variable length in two places but you never use it.

Did you put this code together yourself? It seems odd when someone presents code that they don't understand.

In the first line you declare the list "lst". No problem...

In the next line you set length (but you never use it)

Then there are the two lines (3 and 4) where you delcare the function "test":
def test(lst):
    length = len(lst)
The function calculates the length of the list but never returns any value, meaning that the function, when called, will return the default value "None".

The next lines (5 - 8), are not part of the function as they are not indented to be part of it. So, these lines are called first, giving the output:
Output:
able been state
Then you call the function "test" and print its return value, which, as mentioned above, is "None".

You need to study some basic python tutorial. This is too messy to be corrected. A function to give you the number of elements in a list up to a certain element can be done in many ways. The most obvious is to create a counter and then scan through the list, adding 1 to the counter for each element in the list and break after encountering the searched-for element, returning the value of the counter as the result unless you went trough the whole list without finding the element in question. Then you return 0 or whatever is stipulated as a "did not find"-value.

Another approach is to find the index for the element in question and return that index + 1 but that requires catching an error if the element is not in the list so you would need a little more than the most basic knowledge of python. You don't need the length of the list unless you decide to use it as a stop value when going through the list.
Reply
#4
Lots of issues. Here is yours with comments:
lst = ["able", "been", "state", "Sam", "beer"]
length = len(lst) # you don't use this
def test(lst): #needs a better name, like maybe count_to_sam
    length = len(lst)# this is the end of the function. It does not return anything
for w in lst: #starting the only part of the program that does anything you use
    if w == "Sam":
        break
    print(w)# this loop prints the items up to "Sam" but does not count them. And, by assignment, should be in the function
print(test(lst)) #Since test() does not return anything, this prints "None"
Here is your project better organized. Look closely, kept to pretty elementary Python
lst = ["able","been","state","Sam","beer"]
def count_to_sam(samlist): #better name for function
    return_count = 0 #this will be the count of words
    for element in samlist: #loop is in the function
        if element == "Sam":
            break
        return_count = return_count+1 #or use return_count += 1
    return return_count #function returns the count
print(count_to_sam(lst))
Reply
#5
(Feb-15-2021, 01:39 PM)jefsummers Wrote: Lots of issues. Here is yours with comments:
lst = ["able", "been", "state", "Sam", "beer"]
length = len(lst) # you don't use this
def test(lst): #needs a better name, like maybe count_to_sam
    length = len(lst)# this is the end of the function. It does not return anything
for w in lst: #starting the only part of the program that does anything you use
    if w == "Sam":
        break
    print(w)# this loop prints the items up to "Sam" but does not count them. And, by assignment, should be in the function
print(test(lst)) #Since test() does not return anything, this prints "None"
Here is your project better organized. Look closely, kept to pretty elementary Python
lst = ["able","been","state","Sam","beer"]
def count_to_sam(samlist): #better name for function
    return_count = 0 #this will be the count of words
    for element in samlist: #loop is in the function
        if element == "Sam":
            break
        return_count = return_count+1 #or use return_count += 1
    return return_count #function returns the count
print(count_to_sam(lst))
Hello jefsummers
Thank you for your very helpful reply and the time you have spent upon it. Your annotation is extremely helpful as I am a complete tyro in Python and have learned a lot from your answer. However, when I run the function it returns three so it is not including the word Sam: how would you modify the function to include Sam?
I have tried by changing return_count +1 to return_count +2 but that returns 6!
Could you please recommend a learning source as I am really struggling to learn functions? I am currently trying to teach myself from How To Think Like A Computer Scientist.
Thanks again for all you time and input
Reply
#6
lst = ["able","been","state","Sam","beer"]
def count_to_sam(samlist): #better name for function
    return_count = 0 #this will be the count of words
    for element in samlist: #loop is in the function
        return_count = return_count+1 #or use return_count += 1
        if element == "Sam":
            break
    return return_count #function returns the count
print(count_to_sam(lst))
Reply
#7
(Feb-15-2021, 12:27 PM)Serafim Wrote:
(Feb-15-2021, 09:20 AM)Oldman45 Wrote: Good Morning
I am running Python 3.8.5 and trying to develop a function that counts the number of words in a list up to and including the word Sam. Here is what I have developed so far:
lst = ["able", "been", "state", "Sam", "beer"]
length = len(lst)
def test(lst):
    length = len(lst)
for w in lst:
    if w == "Sam":
        break
    print(w)
print(test(lst))
The out put I get is:
able
been
state
None

I would appreciate input to:
1. Help me understand why I cannot get the answer as a number (4)
2. Understand why I have to state 'length = len(lst) as a variable outside of the function, then repeat it as the first line of the function

Thanks in advance

1. You don't get the answer as a number because that's not what you ask for.
2. You set the variable length in two places but you never use it.

Did you put this code together yourself? It seems odd when someone presents code that they don't understand.

In the first line you declare the list "lst". No problem...

In the next line you set length (but you never use it)

Then there are the two lines (3 and 4) where you delcare the function "test":
def test(lst):
    length = len(lst)
The function calculates the length of the list but never returns any value, meaning that the function, when called, will return the default value "None".

The next lines (5 - 8), are not part of the function as they are not indented to be part of it. So, these lines are called first, giving the output:
Output:
able been state
Then you call the function "test" and print its return value, which, as mentioned above, is "None".

You need to study some basic python tutorial. This is too messy to be corrected. A function to give you the number of elements in a list up to a certain element can be done in many ways. The most obvious is to create a counter and then scan through the list, adding 1 to the counter for each element in the list and break after encountering the searched-for element, returning the value of the counter as the result unless you went trough the whole list without finding the element in question. Then you return 0 or whatever is stipulated as a "did not find"-value.

Another approach is to find the index for the element in question and return that index + 1 but that requires catching an error if the element is not in the list so you would need a little more than the most basic knowledge of python. You don't need the length of the list unless you decide to use it as a stop value when going through the list.

Hello Serafim
Thanks for your reply and input, I am learning a lot. Yes I did put the code together myself and as you can tell I am a complete tyro in Python. You mention the need for a basic Python tutorial: could you please recommend one?
I am trying to teach myself using How To Think Like A Computer Scientist and as can be ssen not very successfully. I am really struggling to learn functions.
Thanks again for all your time and advice
Reply
#8
Note that, if "Sam" is not in the list, you get the length of the list as result.
This, however, gives "None" if "Sam" is missing:
def count_to_sam(samlist):
    if "Sam" not in samlist:
        return None
    else:
        return samlist.index("Sam") + 1

lst = ["able","been","state","Sam","beer"]
print(count_to_sam(lst))
another_list = ["able","been","state","Tom","beer"]
print(count_to_sam(another_list))
Output:
4 None
Reply
#9
Is Sam🦄 so special that he need a function that only work for him.
So to give a example of what i mean.
def count_to_name(lst, name):
    count = 0
    for element in lst:
        count += 1
        if element == name:
            break
    return count

if __name__ == '__main__':
    lst = ["able", "been", "state", "Sam", "beer"]
    name = 'been'
    if name not in lst:
        print(f'<{name}> not in list')
    else:
        result = count_to_name(lst, name)
        print(f'<{name}> appear at number <{result}> in list')
Output:
<been> appear at number <2> in list
You may see the point now and that is more flexible.
Change only name and will get result number or that element is not in list.
name = 'car'
Output:
<car> not in list

Oldman45 Wrote:You mention the need for a basic Python tutorial: could you please recommend one?
Here something you can look at.
List of Free Python Resources here
Training sites most start with basic task,as eg Elementary in CheckiO.
CheckiO
exercism.io
Python Exercises, Practice, Solution
Reply
#10
(Feb-16-2021, 03:55 PM)Oldman45 Wrote: Could you please recommend a learning source as I am really struggling to learn functions? I am currently trying to teach myself from How To Think Like A Computer Scientist.

The Python series from Socratica on Youtube fit my sense of humor. I would also recommend any Youtube video from Ned Batchelder, once you get the basic syntax down, to get a better understanding of name spaces and how it all works.

Here is the Socratica video on functions https://www.youtube.com/watch?v=NE97ylAnrz4
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list.count does not appear to function Oldman45 7 644 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  how to create pythonic codes including for loop and if statement? aupres 1 350 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  How to use the count function from an Excel file using Python? jpy 2 387 Dec-21-2020, 12:30 AM
Last Post: jpy
  List of error codes to find (and count) in all files in a directory tester_V 8 598 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Count number of occurrences of list items in list of tuples t4keheart 1 356 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Including modules in Python using sys.path.append JoeDainton123 1 600 Aug-24-2020, 04:51 AM
Last Post: millpond
  Trying to find first 2 letter word in a list of words Oldman45 7 881 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  Including a Variable In the HTML Tags When Sending An Email JoeDainton123 0 398 Aug-08-2020, 03:11 AM
Last Post: JoeDainton123
  how to check if string contains ALL words from the list? zarize 6 888 Jul-22-2020, 07:04 PM
Last Post: zarize
  How to get unique entries in a list and the count of occurrence james2009 3 639 Jun-22-2020, 01:31 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020