问题
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:
- You can use partition to turn the string into a sequence of "words". Remember to provide a
stepargument of1, so you get all the possible overlapping subsequences. - frequencies counts how many times things (including sequences) appear in a collection.
- 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.
partitionwill 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