Ruby的几道题目

来源:互联网 发布:国内网络推广 编辑:程序博客网 时间:2024/04/28 20:59

Ruby的几道题目

2016/1/22

一、回文

给定词典文档word.txt(在这里下载),找出词典中是回文的单词并输出。回文词是指字母顺序颠倒但同样是单词的词,例如:level。

编程要求:

      (1)设计函数,统一命名为palindromes.rb

      (2)输出格式

           执行结果根据字符串长度由大到小输出。

           例如:现有回文集合{non, dad, madam, mom, level,redivider},则输出顺序为{redivider,madam, level, non, dad, mom}

 

程序如下:palindromes.rb

#encoding:utf-8require 'benchmark'  #加入库文件def palindromes  words =Array.new#words=[]  #保存回文的单词  fin=File.new("words.txt","r")  while word = fin.gets    word = word.strip  #去除单词的空格    if word == word.reverse  #判断是否回文      words.push word#words+=[word]#存入数组中    end  end  fin.close  fout=File.new("result.txt","w")  words=words.sort_by{|x| x.length}.reverse #按长度排序  fout.puts words #写入文件中  fout.closeendBenchmark.bm(20) do |t|  t.report('palindromes运行时间'){palindromes}end


运行结果如下:


运行时间如下:


一些函数简单说明:

1.      str.strip → new_str :Returns a copy of strwith leading and trailing whitespace removed.

去掉字符串前面和后面的空格。

示例:

"    hello    ".strip   #=> "hello""\tgoodbye\r\n".strip   #=> "goodbye"

2.      str.reverse → new_str:Returns anew string with the characters from strin reverse order.

翻转字符串。

示例:

"stressed".reverse   #=> "desserts"


3.       ary.push(obj,... ) → ary:Append — Pushes the given object(s) on to the end of thisarray. This expression returns the array itself, so several appends may bechained together. 

在数组后面追加数组元素,返回值为增加后的数组。

示例:

a = [ "a", "b", "c" ]a.push("d", "e", "f")        #=> ["a", "b", "c", "d", "e", "f"][1, 2, 3,].push(4).push(5)        #=> [1, 2, 3, 4, 5]


4.      enum.sort_by { |obj| block } → array enum.sort_by→ an_enumerator:Sorts enumusing a set of keys generated by mapping thevalues in enumthrough the given block. If no block isgiven, an enumerator is returned instead.

将枚举的元素按照某种方式排序(整理),此处是按照单词的长度排序(整理)

示例:

%w{apple pear fig}.sort_by { |word| word.length}              #=> ["fig", "pear", "apple"]

1.      Benchmark可以测试代码运行的时间。可以使用bm或者bmbm方法进行测试。

其中,report 括号里面为相应测试的标签名, 用来区别测试结果,bm里面参数7用来调节标签在结果里的显示占位宽度, 不对结果产生影响。产生的时间有4个时间,分别是用户CPU时间(user CPU time),系统CPU时间( system CPUtime),用户CPU时间与系统CPU时间之和(the sum of the user and system CPU times),实际运行的真实时间(the elapsed real time)。

示例:

require 'benchmark'n = 5000000Benchmark.bm(7) do |x|  x.report("for:")   { for i in 1..n; a = "1"; end }  x.report("times:") { n.times do   ; a = "1"; end }  x.report("upto:")  { 1.upto(n) do ; a = "1"; end }end

结果:

              user     system      total        real
for:      1.010000   0.000000   1.010000 (  1.015688)
times:    1.000000   0.000000   1.000000 (  1.003611)
upto:     1.030000   0.000000   1.030000 (  1.028098)



二、单词统计

给定一篇文章word9count.txt,也可以自选。统计文章中每个单词的词频,例如:"Tobe or not to be" # => {"to"=>2, "be"=>2,"or"=>1, "not"=>1}

编程要求:

       (1)设计函数,统一命名为count_words.rb

       (2)输出格式

        a.结果返回一个hash键值对(key,value),key指words字符串,value指每个单词出现的词频;   

        b.单词根据词频的大小由大到小输出;

        c.定冠词(the)不计入其中。

程序如下:

#encoding:utf-8require 'benchmark'  #加入库文件def count_words  count = Hash.new(0)  file = 'wordcount.txt'  File.read(file).gsub(/[!"";(),?.-]/," ").split.each {|word| count[word.downcase] +=1}  count.delete("the") #去掉定冠词the  count = count.sort_by{|x,y| y}.reverse #排序/整理  #count=count.sort{|x,y| y[1]<=>x[1]}  #从大到小排序  result=Hash[count]  #将数组转换为哈希  #puts result   #输出单词以及词频  fout=File.new("result2.txt","w")  result.each{|x,y| fout.puts x+ " => "+ y.to_s}#输出到文件中  fout.closeendBenchmark.bm(20) do |t|  t.report('count_words运行时间'){count_words}end

运行结果如下:



运行时间如下:


一些函数简单说明:

1.      str.gsub(pattern, replacement) → new_str   Returns a copy of strwith the alloccurrences of patternsubstituted for the second argument. The pattern istypically a Regexp; if given as a String, any regular expression metacharacters itcontains will be interpreted literally, e.g. '\\d'will match a backlash followed by 'd', instead ofa digit.      

字符串替换功能。将左边的字符替换为右边的字符。

举例:

"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"


附:正则表达式



2.      str.split(pattern=$;, [limit]) → anArray Divides strinto substrings based on a delimiter, returning anarray of these substrings.

字符串分隔,默认分隔符为空格

例子:

" now's  the time".split        #=> ["now's", "the", "time"]" now's  the time".split(' ')   #=> ["now's", "the", "time"]"mellow yellow".split("ello")   #=> ["m", "w y", "w"]"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]

3.      str.downcase → new_str Returns a copy of strwith all uppercase letters replaced with theirlowercase counterparts. The operation is locale insensitive—only characters“A'' to “Z'' are affected.

将字符串中的大写字母都转换为小写字母。

示例:

"hEllO".downcase   #=> "hello"


4.      ary.delete(obj) → item or nil  Deletes allitems from selfthat are equal to obj.

删除数组中的obj元素。

示例:

a = [ "a", "b", "b", "b", "c" ]a.delete("b")                   #=> "b"a                               #=> ["a", "c"]a.delete("z")                   #=> nila.delete("z") { "not found" }   #=> "not found"

三、找出字典中,字母相同、组合方式不同的集合

   在英文词库中,有这样一些有趣的集合,例如:{"rats","tars" , "star"},在这个集合中四个字母通过组合的方式分别构成了三个单词。在给定的word.txt词库中找到并输出这样的集合,注意,不输出只有一个字母的单词。

编程要求:

  (1)设计函数,统一命名为anagrams.rb

  (2)输出格式

       a.每个集合输出一行;

       b.集合间的单词以空格区分。

程序如下:

#encoding:utf-8require 'benchmark'  #加入库文件def anagrams  #创建hash表,用于存放‘兄弟单词’  #键值为单词,值为数组,存储满足该键值的所有单词  words={}  aFile = File.new("words.txt","r")  aFile.each() do|line| #读取文件中的每一行,每一行即为一个单词    line=line.strip #去除单词前后空格    #创建键值,将单词按字符拆分并排序    word=line.split('').sort.join('')    if words.has_key?(word)      #如果该键值存在,则在对于数组中加入该单词      words[word]+=[line]    else      words[word] = [line]#如果没有该单词,则创建    end  end  aFile.close  fout=File.new("result3.txt","w")  words.each do |key,value|    if value.length>1      # puts "#{key}=>#{value}"      fout.puts value.join(' ')    end  end  fout.closeendBenchmark.bm(20) do |t|  t.report('anagrams运行时间'){anagrams}end

程序运行结果如下:



程序运行时间如下:



一些函数简单说明:

1.      ary.sort → new_ary Returns a new array created by sorting self.

自身字符排序,字符串同理。

例子:

a = [ "d", "a", "e", "c", "b" ]a.sort                    #=> ["a", "b", "c", "d", "e"]

2.      ary.join(separator=$,) → str  Returns astring created by converting each element of the array to a string, separatedby the given separator.

组合字符

示例:

[ "a", "b", "c" ].join        #=> "abc"[ "a", "b", "c" ].join("-")   #=> "a-b-c"

本文使用的Ruby编译器为RubyMine

 

参考文献:

Ruby2.1.0 API:http://doc.rubyfans.com/ruby/v2.1/

Ruby开发文档 :http://doc.rubyfans.com/




1 0