Go अभ्यास
Palindrome Check in Go
Does the text read the same in both directions? Ignore spaces, punctuation and case.
आप क्या सीखेंगे
- Filtering letters
- Lower case
- Comparing from both ends
level
l0
e1
v2
e3
l4
The same forwards and backwards
A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.
The first loop keeps only letters and digits in lower case. The second compares the first character with the last, the second with the second to last, and so on, and stops at the first difference. %q prints the text with quotes.
मुख्य बातें
- Keep only letters and digits.
- Compare in lower case.
- Stop at the first difference.
चलने योग्य Go उदाहरण
main.go
package main
import (
"fmt"
"strings"
"unicode"
)
func isPalindrome(text string) bool {
letters := []rune{}
for _, r := range strings.ToLower(text) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
letters = append(letters, r)
}
}
for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 {
if letters[i] != letters[j] {
return false
}
}
return true
}
func main() {
for _, text := range []string{"level", "A man, a plan, a canal: Panama", "Go"} {
fmt.Printf("%q -> %t\n", text, isPalindrome(text))
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Go" -> falseअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Palindrome String जांचें कि कोई टेक्स्ट आगे और पीछे से एक जैसा पढ़ा जाता है या नहीं। आसान
- Palindrome संख्या जांचें कि कोई संख्या उल्टा पढ़ने पर भी वैसी ही रहती है या नहीं। आसान