How To Do Clojure Program? [closed]

点点圈 提交于 2019-12-13 11:25:33

问题


I am learner, just now started learning regarding this..

Can anyone help me out???

Write a clojure program a function, most-frequent-word, which has two arguments. The first argument is a string, the second argument is an integer, call it n. most-frequent-word returns a sequence word(s) of length n that occurs most in the string. For example (most-frequent-word “TCGAAGCTAGACGCTAGTAGCTAGTGTGCA” 4) returns (“CTAG” “GCTA”)


回答1:


Tips to start:

Some tips to try and get you started:

  1. You can use partition to turn the string into a sequence of "words". Remember to provide a step argument of 1, so you get all the possible overlapping subsequences.
  2. frequencies counts how many times things (including sequences) appear in a collection.
  3. max or max-key search for the highest values among their inputs. Use apply to plumb the contents of a collection into them as individual inputs.
  4. partition will output sequences of characters, not strings. You can turn those back into strings with clojure.string/join.

I can get more explicit if you like, but for a beginner there's also a lot of value in experimenting with these at the REPL and trying to work it out for yourself.

Edit: My solution:

Right, this particular step was a bit obscure. Since you want all the strings that have maximal frequency you need to do something a bit more than just max-key. The way I did it was to first find the max of the frequency values, then filter out any key/frequency pairs with a different frequency than that.

(defn most-frequent-word [string n]
  (let[freqs (->> string
                  (partition n 1)
                  frequencies)
       biggest-value (apply max (vals freqs))
       maximal-pairs (filter #(= biggest-value (val %)) freqs)]
    (map #(clojure.string/join (key %)) maximal-pairs )))

This isn't quite ideal from a performance standpoint, but seemed to have a cleaner separation of concerns (and hopefully be easier to understand) than trying to do both jobs in one iteration.



来源:https://stackoverflow.com/questions/32817366/how-to-do-clojure-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!