Skip to content

Commit

Permalink
Merge pull request #1 from GoodNotes/khoi/flash
Browse files Browse the repository at this point in the history
Speed up buildGraph by removing redundant error checking
  • Loading branch information
khoi authored Apr 22, 2024
2 parents 6ba963a + daafc71 commit bd4aa73
Show file tree
Hide file tree
Showing 3 changed files with 2,496 additions and 13 deletions.
16 changes: 9 additions & 7 deletions Sources/TextRank/TextGraph.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,19 @@ public class TextGraph {
/// - a: First node.
/// - b: Second node.
/// - weight: Weight of the edge (default is 1). The edge weight must be greater than 0, else neither the nodes nor edge are added.
public func addEdge(from a: Sentence, to b: Sentence, withWeight weight: Float = 1.0) throws {
public func addEdge(
from a: Sentence,
to b: Sentence,
withWeight weight: Float = 1.0
) throws {
if weight <= 0 {
throw TextGraphError.NonpositiveEdgeWeight(value: weight)
}
if weight > 0 {
for n in [a, b] {
setValue(of: n)
}
setEdge(from: a, to: b, withWeight: weight)
setEdge(from: b, to: a, withWeight: weight)
for n in [a, b] {
setValue(of: n)
}
setEdge(from: a, to: b, withWeight: weight)
setEdge(from: b, to: a, withWeight: weight)
}

/// Add a node.
Expand Down
11 changes: 5 additions & 6 deletions Sources/TextRank/TextRank.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,17 @@ extension TextRank {
/// Build the TextGraph using the sentences as nodes.
func buildGraph() {
graph.clearGraph()
var numberOfErrors = 0

for (i, s1) in sentences.enumerated() {
for s2 in sentences[(i + 1) ..< sentences.count] {
do {
try graph.addEdge(from: s1, to: s2, withWeight: similarity(s1, s2))
} catch {
numberOfErrors += 1
let similarity = similarity(s1, s2)
if similarity > 0 {
try? graph.addEdge(from: s1, to: s2, withWeight: similarity)
}
}
}
}

/// Calculate the similarity of two senntences.
/// - Parameters:
/// - a: First sentence.
Expand Down
Loading

0 comments on commit bd4aa73

Please sign in to comment.