使用Scala

时间:2015-09-29 22:56:01

标签: scala

我是编程新手。而且我被要求通过在scala中使用子字符串和递归来计算字符串中特定字符的出现次数。我完全迷失了,我不知道如何检查该字符串中第二个字符的相等性。我不应该使用tailrecursion和map。非常感谢!

到目前为止我的代码看起来像这样:

def countChars(str:String, chr:Char):Int = {
    if (str.length == 0)  0
    else {
    if (chr == str.substring(0,1)) 1
    else 0}   + countChars()
}
println(countChars())

4 个答案:

答案 0 :(得分:2)

首先,这是一个工作版本(没有使用最短的版本,使其更容易阅读):

1

你有两个问题。首先,您没有使用正确的参数调用countChars。更重要的是,也许不是很明显:你将Char与String进行了比较。这永远不会成真:

1
9 9
5 1
1 2
1 4
1 3
3 8
4 9
3 9
4 6
6 7
8

因为import copy from collections import defaultdict class Node: def __init__(self, i): self.index = i self.neighbors = [] self.currentPath = [] def createNeighbor(self, neighbor): self.neighbors.append(neighbor) def __str__(self): neighbors = [str(n.index) for n in self.neighbors] return "(i = %d, neighbors: %s)"%(self.index, " ".join(neighbors)) def __repr__(self): return str(self) class Graph: def __init__(self): self.nodes = defaultdict(lambda: False) def neighborNodes(self, node, neighbor): if not self.nodes[node.index]: self.nodes[node.index] = node if not self.nodes[neighbor.index]: self.nodes[neighbor.index] = neighbor self.nodes[node.index].createNeighbor(neighbor) self.nodes[neighbor.index].createNeighbor(node) def printNeighborsNeighbors(self, start_num): node = self.nodes[start_num] print(node.neighbors) #for n in node.neighbors: # print(n.neighbors) def listNodes(self): for node in self.nodes.values(): print(node) f = open('input.txt', 'r') t = int(f.readline()) for _ in range(t): graph = Graph() n, m = f.readline().split() n = int(n) m = int(m) for _ in range(m): x, y = f.readline().split() x = int(x) y = int(y) nodeX = Node(x) nodeY = Node(y) graph.neighborNodes(nodeX, nodeY) s = int(f.readline()) print("running graph.listNodes") graph.listNodes() print("running print neighbors neighbors") graph.printNeighborsNeighbors(4) def countChars(str: String, chr: Char): Int = { if (str.length == 0) { 0 } else { (if (chr.toString() == str.substring(0, 1)) { 1 } else { 0 }) + countChars(str.substring(1), chr) } } println(countChars("Hello World", 'l')) //> 3 都是先检查类型,所以这是不同的。只需使用类型转换,或者在这种情况下使用简单的chr == str.substring(0,1) ,就像我一样。

希望这会对你有所帮助。

修改抱歉,只是意外按下了帖子按钮。

答案 1 :(得分:2)

这是一个使用每次迭代时第一个字符的存在/值匹配的解决方案:

def countChars(str: String, chr: Char): Int = str.headOption match {
    case None => 0
    case Some(ch) if ch == chr => 1 + countChars(str.substring(1), chr)
    case _ => countChars(str.substring(1), chr) 
}

答案 2 :(得分:1)

惯用的scala解决方案将是:

map

我不知道您为什么要使用filter,但您的问题并未说明不使用{{1}}

答案 3 :(得分:1)

来自@cokeSchlumpf和@Shadowlands的答案,

def countChars(s: String, c: Char): Int = {
  if (s.isEmpty) 0
  else if (s.substring(0,1).head == c) 1 + countChars(s.substring(1),c)
  else countChars(s.substring(1),c)
}
相关问题