Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

ruby - How to detect wether or not a string is a pangram and return true or false

A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). I'm trying to make a method that takes a string and returns true or false for if it is a pangram. This is what I tried so far.

def pangram?(string)
  letters = string.chars.downcase.uniq
  letters.uniq.all? {|c| string.count(c)==26}
end

def pangram?(string)
  string.downcase
  ("a".."z").all?{|c| string.count(c) <= 1}
end

Any better suggestions? Thanks in advance!

question from:https://stackoverflow.com/questions/65831749/how-to-detect-wether-or-not-a-string-is-a-pangram-and-return-true-or-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could go with something like:

s.downcase.scan(/[a-z]/).uniq.size == 26 

This downcases the String scans for all characters "a" through "z" and checks that the uniq size of these characters equals 26.

Issues with your Current solutions

The first one will never work as is

  1. chars returns an Array and Array#downcase is not a method
  2. You are checking that each letter in the original string occurs 26 times (string.count(c)==26) so 'a' * 26 will pass this test but "The quick brown fox jumps over the lazy dog" will not.

The second has issues too:

  1. the first line serves no purpose. It downcases the string and disposes of the result
  2. String#count is going to be inefficient;
  3. '' will pass this test as each letter occurs 0 times. e.g. <= 1 times.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...