{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# a7q2 - CS 116 Ru Wang r46wang 20319247 Assignment 7...

This preview shows pages 1–2. Sign up to view the full content.

## CS 116 Ru Wang r46wang 20319247 ## Assignment 7 Question 2 ## word_frequency: String String -> float[0, 1] ## consumes a text in string and a target string and returns the float between 0 and 1 of the frequency the target appear in the text. (the number that the target appears divided by the total number of words in the text) ## examples: ## word_frequency ("i am an apple", "hi") -> 0.0 ## word_frequency ("hi hi hi hi hi", "hi") -> 1.0 ## word_frequency ("hi there", "hi") -> 0.5 ## word_frequency ("i am an apple", "an") -> 0.25 ## word_frequency ("", "") -> 0.0 ## word_frequency ("", "hi") -> 0.0 ## word_frequency ("i am an apple", "") -> 0.0 def word_frequency(text, target): listoftext = text.split() total = len (listoftext) pos = 0 num = 0 while (pos < total): if (listoftext[pos] == target): num = num + 1 pos = pos + 1 else: pos = pos + 1 if (total < 1): return 0.0 else: return (float(num) / float(total)) ## word_frequency ("", "hi") -> 0.0 print "Test 1" expected = 0.0 ans = word_frequency ("", "hi") print expected == ans assert expected == ans

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 2

a7q2 - CS 116 Ru Wang r46wang 20319247 Assignment 7...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online