Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Strings that can be converted to Int in a List

Tags:

scala

For example, my input is:

scala> val myList = List("7842", "abf45", "abd", "56")
myList: List[String] = List(7842, abf45, abd, 56)

7842 and 56 can be converted to Int; therefore, my expected output is 2. We can assume that negative integers don't happen, so -67 is not possible.

This is what I have so far:

scala> myList.map(x => Try(x.toInt).getOrElse(-1)).count(_ > -1)
res15: Int = 2

This should work correctly, but I feel like I am missing a more elegant and readable solution, because all I have to do is count number of successes.

like image 970
Akavall Avatar asked Feb 15 '17 01:02

Akavall


People also ask

How do you count the number of strings in a list in Python?

The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.

How do I convert a list of strings to a list of integers in Python?

To convert a list of strings to a list of integers: Pass the int() class and the list to the map() function. The map() function will pass each item of the list to the int() class. The new list will only contain integer values.

How do you count the number of specific elements in a list in Python?

We can use the len( ) function to return the number of elements present in the list.


2 Answers

I would caution against using exception handling (like Try) in control flow -- it's very slow.

Here's a solution that uses idiomatic Scala collection operations, performs well, and will not count negative numbers:

scala> val myList = List("7842", "abf45", "abd", "56")
myList: List[String] = List(7842, abf45, abd, 56)

scala> myList.count(_.forall(_.isDigit)) 
res8: Int = 2

EDIT: @immibis pointed out that this won't detect strings of numbers that exceed Integer.MaxValue. If this is a concern, I would recommend one of the following approaches:

import scala.util.Try
myList.count(x => Try(x.toInt).filter(_ >= 0).isSuccess)

or, if you want to keep the performance of my first answer while still handling this edge case:

import scala.util.Try
myList.count(x => x.forall(_.isDigit) && Try(x.toInt).filter(_ >= 0).isSuccess)
like image 153
Tim Avatar answered Sep 21 '22 01:09

Tim


This is a bit shorter:

myList.count(x => Try(x.toInt).isSuccess)

Note that this solution will handle any string that can be converted to integer via .toInt, including negative numbers.

like image 28
nmat Avatar answered Sep 22 '22 01:09

nmat