2017-11-21 1 views
0

나는이 질문을하기 전에 물었습니다. 내 질문. 세션을 계속 전환 할 때 좌절감이 생겨서 몇 주일이 지났습니다. 과제물 자체는 내가 읽은 모든 게시물에서 실제로 질문에 답변하지 않았기 때문에 Coursera의 모든 사람들에게 수수께끼처럼 보입니다.
은 행 전체에서 가장 높은 단어 수를 계산할 것입니다. ruby ​​rspec

require_relative "../module2_assignment" 
require 'rspec' 

describe Solution do 
    subject(:solution) { Solution.new } 

    it { is_expected.to respond_to(:analyze_file) } 
    it { is_expected.to respond_to(:calculate_line_with_highest_frequency) } 
    it { is_expected.to respond_to(:print_highest_word_frequency_across_lines) } 

    context "#analyze_file" do 
    it "creates 3 line analyzers" do 
     expect(solution.analyzers.length).to eq 0 
     solution.analyze_file 
     expect(solution.analyzers.length).to eq 3 
    end 
    end 

    context "#calculate_line_with_highest_frequency" do 


    it "calculates highest count across lines to be 4" do 
     solution.analyze_file 

     expect(solution.highest_count_across_lines).to be nil 

     solution.calculate_line_with_highest_frequency 

     expect(solution.highest_count_across_lines).to be 4 
    end 
    it "calculates highest count words across lines to be will, it, really" do 
     solution.analyze_file 

     expect(solution.highest_count_words_across_lines).to be nil 

     solution.calculate_line_with_highest_frequency 

     words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten 
     expect(words_found).to match_array ["will", "it", "really"] 
    end 
    end 

end 


test.txt 파일 :

class = solution의 RSpec에 파일

#Implement all parts of this assignment within (this) module2_assignment2.rb file 

#Implement a class called LineAnalyzer. 
class LineAnalyzer 
    #Implement the following read-only attributes in the LineAnalyzer class. 
    #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated) 
    #* highest_wf_words - an array of words with the maximum number of occurrences (calculated) 
    #* content   - the string analyzed (provided) 
    #* line_number  - the line number analyzed (provided) 

    #Add the following methods in the LineAnalyzer class. 
    #* initialize() - taking a line of text (content) and a line number 
    #* calculate_word_frequency() - calculates result 

    #Implement the initialize() method to: 
    #* take in a line of text and line number 
    #* initialize the content and line_number attributes 
    #* call the calculate_word_frequency() method. 

    #Implement the calculate_word_frequency() method to: 
    #* calculate the maximum number of times a single word appears within 
    # provided content and store that in the highest_wf_count attribute. 
    #* identify the words that were used the maximum number of times and 
    # store that in the highest_wf_words attribute. 

    attr_accessor :highest_wf_count, :highest_wf_words, :content, :line_number 


    def initialize(content, line) 
    @content = content 
    @line_number = line 
    @highest_wf_count=0 
    calculate_word_frequency() 
    end 

    def calculate_word_frequency() 
    @highest_wf_words = Hash.new 
    words = @content.split 
    words.each { |w| 
     if @highest_wf_words.has_key?(w) 
     @highest_wf_words[w] += 1 
     else 
     @highest_wf_words[w] = 1 
     end 
    } 
    @highest_wf_words.sort_by { |word, count| count } 
    @highest_wf_words.each do |key, value| 
     if value > @highest_wf_count 
     @highest_wf_count = value 
     end 
    end 
    end 

    def highest_wf_count= (number) 
    @highest_wf_count = number 
    end 

end 


# Implement a class called Solution. 
class Solution 

    # Implement the following read-only attributes in the Solution class. 
    #* analyzers - an array of LineAnalyzer objects for each line in the file 
    #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array. 
    #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute 
    # equal to the highest_count_across_lines determined previously. 

    # Implement the following methods in the Solution class. 
    #* analyze_file() - processes 'test.txt' into an array of LineAnalyzers and stores them in analyzers. 
    #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and 
    # highest_count_words_across_lines attribute values 
    #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in 
    # highest_count_words_across_lines in the specified format 


    # Implement the analyze_file() method() to: 
    #* Read the 'test.txt' file in lines 
    #* Create an array of LineAnalyzers for each line in the file 

    # Implement the calculate_line_with_highest_frequency() method to: 
    #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array 
    # and stores this result in the highest_count_across_lines attribute. 
    #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines 
    # attribute value determined previously and stores them in highest_count_words_across_lines. 

    #Implement the print_highest_word_frequency_across_lines() method to 
    #* print the values of objects in highest_count_words_across_lines in the specified format 
    attr_reader :analyzers, :highest_count_across_lines, :highest_count_words_across_lines 

    def initialize() 
    @analyzers = Array.new 
    @highest_count_across_lines = nil 
    @highest_count_words_across_lines = nil 
    end 

    def analyze_file() 
    File.foreach('test.txt').with_index(1) do |content, line| 
     line_analyzer = LineAnalyzer.new(content, line) 
     @analyzers << line_analyzer 
    end 
    end 

    def calculate_line_with_highest_frequency() 
    @highest_count_across_lines = 0 
    @highest_count_words_across_lines = Array.new 
    @analyzers.each do |analyzer| 
     if analyzer.highest_wf_count > @highest_count_across_lines 
     @highest_count_across_lines = analyzer.highest_wf_count 
     end 
    end 
    end 

    def print_highest_word_frequency_across_lines() 
    @highest_count_words_across_lines = Array.new 
    puts "The following words have the highest word frequency per line:" 

    end 
end 

:

Here are the assignment questions

한편이 내 코드입니다

This is a really really really cool experiment really 
Cute little experiment 
Will it work maybe it will work do you think it will it will 


그리고 이것은 내가 지금까지 먹어 본 RSpec에 결과입니다 : 어디에 문제가

LineAnalyzer 
    has accessor for highest_wf_count 
    has accessor for highest_wf_words 
    has accessor for content 
    has accessor for line_number 
    has method calculate_word_frequency 
    calls calculate_word_frequency when created 
    attributes and values 
    has attributes content and line_number 
    content attribute should have value "test" 
    line_number attribute should have value 1 
    #calculate_word_frequency 
    highest_wf_count value is 3 
    highest_wf_words will include "really" and "you" 
    content attribute will have value "This is a really really really cool cool you you you" 
    line_number attribute will have value 2 

Solution 
    should respond to #analyze_file 
    should respond to #calculate_line_with_highest_frequency 
    should respond to #print_highest_word_frequency_across_lines 
    #analyze_file 
    creates 3 line analyzers 
    #calculate_line_with_highest_frequency 
    calculates highest count across lines to be 4 
    calculates highest count words across lines to be will, it, really (FAILED - 1) 

Failures: 

    1) Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really 
    Failure/Error: expect(words_found).to match_array ["will", "it", "really"] 

     expected collection contained: ["it", "really", "will"] 
     actual collection contained: [] 
     the missing elements were:  ["it", "really", "will"] 
    # ./spec/solution_spec.rb:39:in `block (3 levels) in <top (required)>' 

Finished in 0.13939 seconds (files took 0.39711 seconds to load) 
19 examples, 1 failure 

Failed examples: 

rspec ./spec/solution_spec.rb:31 # Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really 


정말 알아낼 수 없습니다.
오타가되었거나 어딘가 잘못 처리하고 있습니까?
누군가가 도와 준다면 아주 좋을 것입니다.
미리 감사드립니다.
Brice

+0

방금 ​​코드를 살펴 보았습니다 ... 실제로 시도하고있는 것을 파고 들지 않고 바로 ** @ highest_count_words_across_lines' 배열에 아무 것도 넣지 않았 음을 알게되었습니다 ** !! 'nil'으로 초기화 한 다음,'Array.new'로 설정하면 절대 값을 입력하지 않습니다. 그래서 당신의 최종 결과는 비어 있습니다. –

+0

'[] .map (& : highest_wf_words) == []','[] .flatten == []'.따라서 실제로 배열에 데이터를 채우지 않으므로 나머지 코드는 제대로 실행되지만 여전히 최종 결과는 비어 있습니다. –

+0

나는 이것을 시도했다 : @highest_count_words_across_lines = analyzer.highest_wf_words, 아무 소용이 없다. –

답변

0

앞서 말했듯이 즉각적인 문제는 @highest_count_words_across_lines이 빈 배열로만 설정된다는 것입니다. 따라서 최종 결과는 필연적으로 비어있게됩니다.

다음과 같이 반복의 최대 수를 포함하는 모든 단어의 목록을 만들 수 :

@highest_count_words_across_lines = analyzers.map do |analyzer| 
    analyzer.highest_wf_words.select do |word, count| 
    count == highest_count_across_lines 
    end 
end.flat_map(&:keys) 

당신은 LineAnalyzer 클래스, 예를 들어,로 그 논리의 일부를 이동하실 수 있습니다 LineAnalyzer#words_of_length(length) 방법.

두 개의["really", "it"] 만 반환한다는 점에 유의하십시오. 이것은 귀하의 코드가 현재 첫 번째 "Will"이 대문자로 쓰이는 다른 단어라고 생각하기 때문입니다. 이것이 원하지 않으면 파일을 분석 할 때 downcase 모든 단어를 사용해야합니다.

0

대단히 감사합니다. @Tom. 약간의 노력 후 아래 코드는 통과하지만 당신이 제안으로 LineAnalyser 클래스 수준에서와 downcase을 적용하기 전에 :

@highest_count_across_lines = analyzers.sort_by { |analyzer| analyzer.highest_wf_count }.reverse.first.highest_wf_count 
    @highest_count_words_across_lines = analyzers.select { |analyzer| @highest_count_across_lines == analyzer.highest_wf_count } 


많은 감사를 다시.

+0

죄송합니다 ... 명확히하기 위해, 내 데모 코드는'solution.highest_count_words_across_lines'을 ** 응답 **으로 만드는 것입니다. 추가 메서드를 호출 할 필요는 없습니다. 물론, 그런 식으로 일하도록 코드를 재 설계하고 싶다면, 그걸로 가십시오. –

+0

또한 * 답변 *으로 제출하면 안됩니다. 이와 같은 추가 정보는 원래 게시물에 [편집] (https://stackoverflow.com/posts/47410424/edit)으로 추가하거나 내 코멘트로 추가해야합니다. –

+0

추가 정보를 추가하려면 질문에 편집 링크를 사용하십시오. 답변 게시 버튼은 질문에 대한 완전한 대답을 위해서만 사용되어야합니다. - [From Review] (리뷰/저품절 게시물/18018585) – Isma

관련 문제