Posts: 33 Threads: 11 Joined: Jul 2020 (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 Posts: 33 Threads: 11 Joined: Jul 2020 (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 Posts: 33 Threads: 11 Joined: Jul 2020 (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 Posts: 1,953 Threads: 8 Joined: Jun 2018 Feb-18-2021, 10:22 AM (This post was last modified: Feb-18-2021, 10:22 AM by perfringo.) 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  . 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. Posts: 1 Threads: 0 Joined: Sep 2023 Sep-07-2023, 06:39 AM (This post was last modified: Sep-09-2023, 02:17 AM by Larz60+.) # 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 Posts: 1,210 Threads: 146 Joined: Jul 2017 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) |