11

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()

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
yariee
  • 111
  • 4

6 Answers6

4

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.
  • 1
    One of the best implementations I've seen so far. Couldn't be more Pythonic. :-) I would just rename ```rare_chars()``` to ```find_rare_words()``` instead. – accdias Oct 29 '19 at 21:05
1

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
Barb
  • 427
  • 3
  • 14
0
def rareChar(words):
rareWords = 0
rareChars = ['j', 'x', 'q', 'z']

#Split paragraph into words
words.split()
for word in words:
    #Split words into characters
    chars = word.split()
    for char in chars:
        if char in rareChars:
            rareWords = rareWords + 1
return rareWords

def CoolPara(words):
    #return value rather than printing
    return '{} word(s) with a rare character'.format(rareChar(words))


# DO NOT CHANGE CODE BELOW

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

Input: Hello this is a sentence about zoos

Output: 1 word(s) with a rare character

KILLtheWEEZEL
  • 268
  • 1
  • 7
0

The following code is an edit of yours which results in the proper answer of 1

def main():

    def rareChar(words):
        rareWords = 0
        rareChars = ['j', 'x', 'q', 'z']

        all_words = list(words.split())

        for a_word in all_words:
            for char in a_word:
                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: ")))

main()

Answer:

C:\Users\Jerry\Desktop>python Scraper.py
Enter: 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.

1 word(s) with a rare character
artemis
  • 6,857
  • 11
  • 46
  • 99
0

This code will work for you. Unremark the words input and remark out the words string statement that I used to test the code.

The para method is not needed.

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

words = 'john xray quebec zulu'
# words = (input("Enter: "))

x = rareChar(words)
print(f"There are {x} word(s) with a rare character")
VC Healy
  • 84
  • 9
0

The solution provided by Barb works for a single letter:

CoolPara('f')

But it does not work with mulitple characters as asked by the original poster. For e.g. this does not return the correct results:

CoolPara("jxqz")

Here is slightly improved version of Barb's solution:

def CoolPara(letters):
    new = [i for i in text.split()]
    found = list()
    for i in new:
        for x in i:
            for l in letters:
                if x == l:
                    found.append(i)
    print("Special letter words: ", found)
    print("word(s) with rare characters ", len(found))
shantanuo
  • 31,689
  • 78
  • 245
  • 403