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
#11
(Feb-16-2021, 04:25 PM)Serafim Wrote: 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

Hello Serafim
Thanks for the update, much appreciated and I will study this along with other information that I have received. Thanks again
Reply
#12
(Feb-16-2021, 08:02 PM)snippsat Wrote: 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

Hello Snippsat
That is really helpful, I will certainly study your code and then investigate the links you have kindly provided. Thanks again
Reply
#13
(Feb-17-2021, 01:52 AM)jefsummers Wrote:
(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
Hello jeffsummers
Thanks for your continued support - I think I will enjoy Socratica. Thanks again
Reply
#14
One alternative approach (assumes that if name not in the list then number of words in list should be returned): if the case is to count consecutive items then there is possibility to do that without setting counter outside for loop. Just using built-in function enumerate will suffice:

def countwhile_inclusive(iterable, predicate):
    for queue_no, item in enumerate(iterable, start=1):
        if item == predicate:
            break
    return queue_no
However, we test all our code, right Wink. By doing so we will find that if iterable is empty we get error (queu_no will be never assigned). So we probably have to deal with it. For that we need to decide what should we return if empty list is passed as argument. There are many possibilities but I point out two of them: raise error or return 0 (in human language it can be described as: 'how many blue marbles do you have?'; 'I don't know what blue marble is (return error); 'I don't have blue marbles (return 0)')

So we can write:

def countwhile_inclusive(iterable, predicate):
    if len(iterable) == 0:        # if list is empty
        return 0                  # or raise ValueError?
    for queue_no, item in enumerate(iterable, start=1):
        if item == predicate:
            break
    return queue_no
According to Python wiki getting list length is pretty cheap O(1)

There is also built-in module itertools which have takewhile which can be used to solve this type of problems as well.

EDIT: this can also be solved using else branch of for loop:

def countwhile_inclusive(iterable, predicate):
    for queue_no, item in enumerate(iterable, start=1):
        if item == predicate:
            return queue_no
    else:                      # no break
        return len(iterable)
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
#15
# In the name of GOD
# Hamed Hajavi
# [email protected]
# @cs_hamed

#%% Exercise 7.27.6: 
# Count how many words occur in a list up to and including the 1st occurrence of the word “sam”.
# (Write your unit tests for this case too. What if “sam” does not occur?)

# test(count_words_occur_in_01(['ali', 'sam', 'sam', 'sam'], 'sam') == 2)
# test(count_words_occur_in_01(['sam', 'sam', 'sam', 'sam'], 'sam') == 1)
# test(count_words_occur_in_01(['hamed', 'ali', 'hemmat'], 'sam') == 3)
# test(count_words_occur_in_01(['Sam', 'SAM', 'spam', 'sam'], 'sam') == 4)

#%% Unit Testing
import inspect

def test(did_pass):
    line_number = inspect.stack()[1].lineno
    msg = ''
    if did_pass:
        msg = f'Test at line {line_number} passed.'
    else:
        msg = f'Test at line {line_number} failed.'
        
    print (msg)
    
def count_words_occur_in_00(words:list, target:str) -> int:
    '''
        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.
        
    '''
    counter = 0 # will count the occurrence of words
    for word in words:
        counter += 1 # update counter value
        
        # note that, we must update counter before ending the loop.
        # because we want to count words occur in a list up to
        # and including the 1st occurrence of the word “target”.
        if word == target:
            break
            
    return counter

#===============================================================================
def count_words_occur_in_01(words:list, target:str) -> int:
    '''
        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. 
        
    '''
    # catching an error if the target is not in the list
    if target not in words: 
        return len(words)
    
    # target occur in the words
    return len(words[0:words.index(target)+1])

#===============================================================================
def count_words_occur_in_02(words:list, target:str) -> int:
    
    # target does not in the words
    if target not in words:
        return sum(1 for word in words)
    
    # target occur in the words
    return sum(1 for word in words[0:words.index(target)+1])

def count_words_occur_in_03(words:list, target:str) -> int:
    for idx,word in enumerate(words):
        
        # target occur in the words
        if word == target: 
            return idx+1
    
    # target does not in the words
    return len(words)

#===============================================================================
def count_words_occur_in_04(words:list, target:str) -> int:
    for idx,word in enumerate(words, start=1):
        
        # target occur in the words
        if word == target: 
            return idx
    
    # target does not in the words
    return len(words)

# test(count_words_occur_in_01(['ali', 'sam', 'sam', 'sam'], 'sam') == 2)
# test(count_words_occur_in_01(['sam', 'sam', 'sam', 'sam'], 'sam') == 1)
# test(count_words_occur_in_01(['hamed', 'ali', 'hemmat'], 'sam') == 3)
# test(count_words_occur_in_01(['Sam', 'SAM', 'spam', 'sam'], 'sam') == 4)
# test(count_words_occur_in_02(['ali', 'sam', 'sam', 'sam'], 'sam') == 2)
# test(count_words_occur_in_02(['sam', 'sam', 'sam', 'sam'], 'sam') == 1)
# test(count_words_occur_in_02(['hamed', 'ali', 'hemmat'], 'sam') == 3)
# test(count_words_occur_in_02(['Sam', 'SAM', 'spam', 'sam'], 'sam') == 4)
# test(count_words_occur_in_03(['ali', 'sam', 'sam', 'sam'], 'sam') == 2)
# test(count_words_occur_in_03(['sam', 'sam', 'sam', 'sam'], 'sam') == 1)
# test(count_words_occur_in_03(['hamed', 'ali', 'hemmat'], 'sam') == 3)
# test(count_words_occur_in_03(['Sam', 'SAM', 'spam', 'sam'], 'sam') == 4)
# test(count_words_occur_in_04(['ali', 'sam', 'sam', 'sam'], 'sam') == 2)
# test(count_words_occur_in_04(['sam', 'sam', 'sam', 'sam'], 'sam') == 1)
# test(count_words_occur_in_04(['hamed', 'ali', 'hemmat'], 'sam') == 3)
# test(count_words_occur_in_04(['Sam', 'SAM', 'spam', 'sam'], 'sam') == 4)
Larz60+ write Sep-09-2023, 02:17 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
I have added bbcode tags for you this time. please use BBCode tags on future posts

Attached Files

.py   Exercise_7_27_6.py (Size: 4.46 KB / Downloads: 24)
Reply
#16
Maybe pass a list and a word to the function??

def test(lst, word):
    if not isinstance(lst, list):
       raise TypeError(f"the list variable {lst} you chose is not a list but a {type(lst)}.")
    print('The list is', lst)
    print('The word is', word)
    if not word in lst:
        print(f'{word} is not in this list of words.')
        return
    count = 0
    for w in lst:
        count +=1
        print('word is', w, 'count is', count)
        if w == word:
            print(f'Found the word: {word} at position {count}.')
            return
        
if __name__ == '__main__':
    # maybe you have more than 1 list
    # then you need an input to choose which list and which word
    lst2 = ["able", "been", "state", "Sam", "beer", "tea", "coffee", "Susan", "King Charles"]
    myword = input('Enter a word to look for ... ')
    # would be more difficult to enter a list
    # probably choose a number from a list of lists
    test(lst2, myword)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,268 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,497 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get unique entries in a list and the count of occurrence james2009 5 2,910 May-08-2022, 04:34 AM
Last Post: ndc85430
  Including data files in a package ChrisOfBristol 4 2,463 Oct-27-2021, 04:14 PM
Last Post: ChrisOfBristol
  Not including a constructor __init__ in the class definition... bytecrunch 3 11,516 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  count item in list korenron 8 3,372 Aug-18-2021, 06:40 AM
Last Post: naughtyCat
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,756 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  list.count does not appear to function Oldman45 7 3,836 Mar-16-2021, 04:25 PM
Last Post: Oldman45
  how to create pythonic codes including for loop and if statement? aupres 1 1,886 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  How to use the count function from an Excel file using Python? jpy 2 4,361 Dec-21-2020, 12:30 AM
Last Post: jpy

Forum Jump:

User Panel Messages

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