16,002,236 members
1.00/5 (1 vote)
See more:
Using recursion, I need to display the consonant letters and the total number of consonant letters from the user's input. Thank you in advance.

What I have tried:

Python
```a = input("Enter your string:")

def isCons(ch):

ch = ch.upper()

return not (ch == 'A' or ch == 'E' or
ch == 'I' or ch == 'O' or
ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90

def totalCons(string, n):

if n == 1:
return isCons(string[0])

print(totalCons(a, len(a)))```
Posted
Updated 21-Apr-21 0:21am
v3

## Solution 1

Don't use recursion - it's not a suitable method for processing this kind of request, and it may cause your app to fail.

This is an iterative problem, that just requires a simple loop: nothing in the "structure" of s string of characters is recursive, unlike the definition of factorial for example:
`f(N) = N <= 1 ? 1 : N * f(N - 1)`
Where the function is defined in terms of the function.

Use a simple for loop instead. Remember, each time you call a function, you use stack space, and that is very limited. A long string will exhaust the stack space in a recursive solution, where the looping version needs almost no stack at all. When you stack runs out, your app crashes.

lil_mint 21-Apr-21 20:50pm
Thank you very much for the explanation. I did think for loop seems more ideal but my assignment was to use recursion. Again thank you.

## Solution 2

Python
```for letter in string:
if letter not in 'aeiouAEIOU':
print(letter, 'is a consonant')```

CPallini 21-Apr-21 3:56am
That would classify '%' as a consonant.
Richard MacCutchan 21-Apr-21 4:08am
It is an over simplification, and OP is expected to consider all cases. Unfortunately few people seem capable of independent though these days.

## Solution 3

If you have to use recursion then, recursively building the string of consonants should do the trick
Python
```a = input("Enter your string:")

def cons(ch):
uch = ch.upper()
if  ( ord(uch) >= 65 and ord(uch) <=90 and not ( uch in "AEIOU")):
return ch
return ''

def totalCons(string, n):
if n == 1:
return cons(string[0])

totcons = totalCons(a, len(a))
print( totcons, len(totcons))```

lil_mint 21-Apr-21 21:07pm
This gave me new knowledge. Again Thank you very much.
CPallini 22-Apr-21 1:56am
You are welcome.

## Solution 4

I would rather search for letters I want.
Python
`Consonant= "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"`

and check each char from input against this string.
Quote:
Using recursion

In this case, recursion complicate things. It is easier to use a loop.