如何做Clojure计划?
我是学习者,刚刚开始学习关于这个..
I am learner, just now started learning regarding this..
任何人都可以帮助我?
编写一个clojure程序一个函数,most-frequent-word,它有两个参数。第一个参数是一个字符串,第二个参数是一个整数,调用它n。最频繁字返回长度为n的在字符串中最多出现的序列字。例如(最常用字词TCGAAGCTAGACGCTAGTAGCTAGTGTGCA4)返回(CTAGGCTA)
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")
:
有些提示可供您尝试:
Tips to start:
Some tips to try and get you started:
-
分区
将字符串转换为字词序列。请记住提供1
的步骤
参数,以便得到所有可能的重叠子序列。 -
frequencies
计算集合中出现的事物(包括序列)的次数。 -
max
或max-key
搜索其输入中的最高值。使用apply / code>
将集合的内容作为单独的输入插入到它们中。 -
分区
的字符,而不是字符串。您可以使用将它们转换为字符串clojure.string / join
。
- You can use
partition
to turn the string into a sequence of "words". Remember to provide astep
argument of1
, so you get all the possible overlapping subsequences. -
frequencies
counts how many times things (including sequences) appear in a collection. -
max
ormax-key
search for the highest values among their inputs. Useapply
to plumb the contents of a collection into them as individual inputs. -
partition
will output sequences of characters, not strings. You can turn those back into strings withclojure.string/join
.
我可以得到更明确的,如果你喜欢,但对于初学者,还有很多的价值,在实验这些在REPL和试图为自己工作。
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.
对,这个特定的步骤有点模糊。因为你想要全部有最大频率的字符串,你需要做一些事情,而不仅仅是 max-key
。我这样做是首先找到 max
的频率值,然后过滤掉不同频率的任何键/频率对 。
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.