Go अभ्यास
Word Frequency Counter in Go
Count how often each word appears with a map and print the most common ones.
आप क्या सीखेंगे
- strings.Fields
- counts[word]++
- Sorting by count
counts
"the"3"brown"1"dog"1The word is the key, the count is the value
Counting words is a typical job for a map: the word is the key and the number of times it appears is the value.
counts[word]++ works even for a new word, because a missing key reads as 0. The words are then sorted by count, highest first, and alphabetically when the counts are equal, so the output is always the same.
मुख्य बातें
- A missing key reads as 0, so ++ just works.
- Sort by count, then by word.
words[:3]keeps the top three.
चलने योग्य Go उदाहरण
main.go
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
text := "the quick brown fox jumps over the lazy dog the end"
counts := map[string]int{}
for _, word := range strings.Fields(text) {
counts[word]++
}
words := make([]string, 0, len(counts))
for word := range counts {
words = append(words, word)
}
sort.Slice(words, func(i, j int) bool {
if counts[words[i]] != counts[words[j]] {
return counts[words[i]] > counts[words[j]]
}
return words[i] < words[j]
})
for _, word := range words[:3] {
fmt.Printf("%s: %d\n", word, counts[word])
}
}
the: 3
brown: 1
dog: 1अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- शब्दों की गिनती करें एक वाक्य में शब्दों की गिनती करें। आसान
- अक्षर आवृत्ति हर अक्षर कितनी बार आता है, गिनें। आसान