Count how many vowels and consonants occur in a string: Difference between revisions

No edit summary
Line 1,509:
contains 22 vowels (5 distinct), 31 consonants (13 distinct), and 16 other (2 distinct).
</pre>
 
=={{header|Picat}}==
===List comprehension===
Also using maps for counting individual characters.
<lang Picat>main =>
S = "Count how many vowels and consonants occur in a string",
vowels(Vowels),
consonants(Consonants),
CountVowels = [C : C in S, membchk(C,Vowels)].len,
CountConsonants = [C : C in S, membchk(C,Consonants)].len,
println([vowels=CountVowels,consonants=CountConsonants,rest=(S.len-CountVowels-CountConsonants)]),
nl,
 
% Occurrences of each character
println(all=count_chars(S)),
println(vowels=count_chars(S,Vowels)),
println(consonants=count_chars(S,Consonants)),
nl.
 
vowels("aeiouAEIOU").
consonants("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ").
 
count_chars(S) = count_chars(S,"").
count_chars(S,Cs) = Map =>
Map = new_map(),
foreach(C in S, (Cs != "" -> membchk(C,Cs) ; true))
Map.put(C,Map.get(C,0)+1)
end.</lang>
 
{{out}}
<pre>[vowels = 15,consonants = 30,rest = 9]
 
all = (map)[m = 1,s = 4,w = 2,C = 1,e = 1,c = 3,h = 1,n = 8,u = 2,t = 3,a = 4,d = 1,i = 2,l = 1,o = 6,r = 2,v = 1,y = 1, = 9,g = 1]
vowels = (map)[u = 2,i = 2,o = 6,a = 4,e = 1]
consonants = (map)[m = 1,s = 4,w = 2,C = 1,c = 3,h = 1,n = 8,t = 3,d = 1,l = 1,r = 2,v = 1,y = 1,g = 1]</pre>
 
===Recursion===
<lang Picat>main =>
S = "Count how many vowels and consonants occur in a string",
vowels(Vowels),
consonants(Consonants),
NumVowels = count_set(Vowels,S),
NumConsonants = count_set(Consonants,S),
NumRest = S.len - NumVowels - NumConsonants,
println([vowels=NumVowels,consontants=NumConsonants,rest=NumRest]),
nl.
vowels("aeiouAEIOU").
consonants("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ").
 
count_set(Set,S) = Vs =>
count_set(Set,S,0,Vs).
count_set(_Set,[],Vs,Vs).
count_set(Set,[C|Cs],Vs0,Vs) :-
(membchk(C,Set) ->
Vs1 = Vs0 + 1
;
Vs1 = Vs0
),
count_set(Set,Cs,Vs1,Vs).</lang>
 
{{out}}
<pre>[vowels = 15,consontants = 30,rest = 9]</pre>
 
 
=={{header|Python}}==
495

edits