![]() So this method would be suitable when you are counting a list that contains a collection of words that are repeated often without many other possible words that may only be counted once. The try / except pattern is faster when you have a low amount of exceptions that will be raised, in other words there are are a lot of duplicate words or keys that you are counting. Meaning that if less than 22% of all words being counted in the body of text are unique the try / except pattern will be faster. So when should you use a try / except pattern instead of an if / else pattern? Well, after running some tests it appears that the threshold is roughly 22% of all words in the body of text being unique. However, there are actually different situations where each pattern is superior. Some people have pointed out that a try / except pattern like the one below can yield better performance. While it may seem intuitive to use an if / else pattern like the following to count items: text = # a list of words Say for example you want to count the amount of words in a body of text. To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = Ī dictionary can be a convenient data structure for counting the occurrence of items.
0 Comments
Leave a Reply. |