Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of unique characters in string

Tags:

scala

I need to write a function that returns a List of (Char, Int) pairs given an input String.

My solution produces the correct result but I'm wondering if there is a better way:

def countChars(s: String): List[(Char, Int)] = {
    s.groupBy(c => c.toLower).flatMap(e => List((e._1, e._2.length))).toList
  }                                              

This produces a result like this in a worksheet:

countChars("Green Grass")
// res0: List[(Char, Int)] = List(('e', 2), ('s', 2), ('n', 1), ('a', 1), (' ', 1), ('g', 2), ('r', 2))
like image 352
Dmitri Avatar asked May 24 '14 16:05

Dmitri


People also ask

How do you count unique characters in a string in Python?

To count the number of unique characters in a string:Use the set() class to convert the string to a set of unique characters. Use the len() function to get the number of unique characters in the string.

How do you find unique strings?

A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.


1 Answers

Making a singleton List just to flatten it is redundant.

"Green Grass".groupBy(c => c.toLower).map(e => (e._1, e._2.length)).toList
like image 180
dhg Avatar answered Oct 21 '22 11:10

dhg