Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding specific characters within a list

The goal is to make a list from the user's paragraph and iterating so that I can count how many words contain special letters "j,x,q,z".

Example input:
In a hole in the ground, there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat; it was a hobbit-hole, and that means comfort.

Example output: 1 word with a rare character

I've started the code where I break the user's paragraph into a list but I'm having a hard time iterating through the list and finding each instance of the special letters.

This is what I have so far:

def rareChar(words):
    rareWords = 0
    rareChars = ['j', 'x', 'q', 'z']
    for astring in words:
        wds = words.split()
        for char in wds:
            if char in rareChars:
                rareWords = rareWords + 1
    return rareWords

def CoolPara(words):
    print(rareChar(words), 'word(s) with a rare character')

    # DO NOT CHANGE CODE BELOW

    print(CoolPara(input("Enter: ")))

If I run with the example input, I get an output of '0 word(s) with a rare character'. How could I fix this so that I can get the expected output. Any help would be greatly appreciated as I am still relatively new to coding

Also a quick note: I am only allowed to use the methods/functions of split() and Len()

like image 302
yariee Avatar asked Oct 29 '19 19:10

yariee


People also ask

How do you find a specific character in a list Python?

To find the index of a list element in Python, use the built-in index() method. To find the index of a character in a string, use the index() method on the string. This is the quick answer.

How do I find a particular string in a list?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.

Can you use LEN () on a list?

Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.


2 Answers

Maybe this could be an opportunity to introduce you to some python features:

from typing import List


def rare_char(sentence: str, rare_chars: List[str]=["j", "x", "q", "z"]) -> List[str]:
    return [word for word in sentence.split() if 
            any(char in word for char in rare_chars)]


def cool_para(sentence: str) -> str:
    return f"{len(rare_char(sentence))} word(s) with rare characters"

This answer uses:

  1. typing, which can be used by third party tools such as type checkers, IDEs, linters, but more importantly to make your intentions clear to other humans who might be reading your code.
  2. default arguments, instead of hardcoding them inside the function. It's very important to document your functions, so that an user would not be surprised by the result (see Principle of Least Astonishment). There are of course other ways of documenting your code (see docstrings) and other ways of designing that interface (could be a class for example), but this is just to demonstrate the point.
  3. List comprehensions, which can make your code more readable by making it more declarative instead of imperative. It can be hard to determine the intention behind imperative algorithms.
  4. string interpolation, which in my experience is less error prone than concatenating.
  5. I used the pep8 style guide to name the functions, which is the most common convention in the python world.
  6. Finally, instead of printing I returned a str in the cool_para function because the code below the # DO NOT CHANGE CODE BELOW comment is printing the result of the function call.
like image 81
Marcus Vinícius Monteiro Avatar answered Oct 13 '22 02:10

Marcus Vinícius Monteiro


Ideally you want to use list comprehension.

def CoolPara(letters):
  new = [i for i in text.split()]
  found = [i for i in new if letters in i]
  print(new) # Optional
  print('Word Count: ', len(new), '\nSpecial letter words: ', found, '\nOccurences: ', len(found))

CoolPara('f') # Pass your special characters through here

This gives you:

['In', 'a', 'hole', 'in', 'the', 'ground', 'there', 'lived', 'a', 'hobbit.', 'Not',
 'a', 'nasty,', 'dirty,', 'wet', 'hole,', 'filled', 'with', 'the', 'ends', 'of',
'worms', 'and', 'an', 'oozy', 'smell,', 'no', 'yet', 'a', 'dry,', 'bare,', 'sandy',
'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat;',
'it', 'was', 'a', 'hobbit-hole,', 'and', 'that', 'means', 'comfort']
Word Count:  52
Special letter words:  ['filled', 'of', 'comfort']
Occurences:  3
like image 40
Barb Avatar answered Oct 13 '22 00:10

Barb