Look for the Sys.getlocale function in the R documentation, here is a handy link, courtesy of the Zurich polytechnic.
For my case, to solve the problem I called:
Sys.setlocale("LC_ALL", "C")
Sys.setlocale("LC_ALL", "C")
def cv(data):
"""
:param data a list of numbers
:returns its coefficient of variation, or NaN.
:rtype float
"""
return 0.0
Now I can write a few test cases for it:class CV(unittest.TestCase):
def test_none(self):
coll = None
self.assertTrue(math.isnan(cv(coll)))
def test_empty(self):
self.assertTrue(math.isnan(cv([])))
def test_zero_mean(self):
coll = [1, 2, 0, -1, -2]
self.assertTrue(math.isnan(cv(coll)))
def test_std_var_0(self):
coll = [42, 42, 42]
self.assertEqual(cv(coll), 0)
def test_1(self):
coll = [0, 0, 6, 6]
self.assertEqual(cv(coll), 1)
def test_dot5(self):
coll = [10, 4, 12, 15, 20, 5]
self.assertAlmostEqual(cv(coll), 0.503, delta=0.001)
Following the line of the previous post, I have decided that my function should return NaN if the caller passes a None or an empty list in. I remarked this requisite with the first two test cases, test_none and test_empty.def cv(data):
"""
:param data a list of numbers
:returns its coefficient of variation, or NaN.
:rtype float
"""
#1
if not data:
return float('NaN')
#2
mean = sum(data) / float(len(data))
if mean == 0:
return float('NaN')
#3
sq_sum = 0.0
for d in data:
sq_sum += (d - mean) ** 2
stddev = math.sqrt(sq_sum / len(data))
#4
return stddev / mean
1. When the user passes a None or an empty list, NaN is returned.def cv_(data):
"""
:param data a list of numbers
:returns its coefficient of variation, or NaN.
:rtype float
"""
if not data:
return float('NaN')
mean = numpy.mean(data)
if mean == 0.0:
return float('NaN')
return numpy.std(data) / mean
Full code and test cases are on github.
def standard_deviation(strings):
"""
:param strings: a list of strings
:returns the standard deviation of the lengths of the strings, or NaN.
:rtype float
"""
return 0.0
The function docstring specifies what I expect as input parameter and what the caller should expect to get as output.class StdDevTest(unittest.TestCase):
def test_none(self):
self.assertTrue(math.isnan(standard_deviation(None)))
def test_empty(self):
strings = []
self.assertTrue(math.isnan(standard_deviation(strings)))
def test_1(self):
strings = ['a', 'z', 'p']
self.assertEqual(standard_deviation(strings), 0)
def test_2(self):
strings = ['apples', 'oranges', 'kiwis', 'pineapples']
self.assertAlmostEqual(standard_deviation(strings), 1.8708, delta=0.0001)
def test_3(self):
strings = ['mftbycwac', 'rhqbqawnfl', 'clgzh', 'ilqy', 'ckizvsgpnhlx', 'kziugguuzvqarw', 'xqewrmvu', 'ktojfqkailswnb']
self.assertEqual(standard_deviation(strings), 3.5355339059327378)
def test_4(self):
strings = ['zgbljwombl', 'slkpmjqmjaaw', 'nddl', 'irlzne', '', 'poieczhxoqom', 'waqyiipysskxk', 'dloxspi', 'sk']
self.assertEqual(standard_deviation(strings), 4.447221354708778)
def test_bad_data(self):
with self.assertRaises(TypeError):
standard_deviation([1, 2, 3])
test_none, test_empty: What the function should do in case of None passed as input parameter is not specified by the problem. I decided to let it behaves as it gets an empty list of strings in. Notice the use of the function isnan from the standard math library.lengths = [len(s) for s in strings] # 1
mean = math.fsum(lengths) / len(lengths) # 2
# 3
sq_sum = 0.0
for l in lengths:
sq_sum += (l - mean) ** 2
return math.sqrt(sq_sum / len(lengths)) # 4
1. Let's prepare the data in input, converting the strings to their sizes, that is what really matter to us.if not strings:
return float('NaN')
This would catch both the case of an empty list of strings and a None passed by mistake.def merge(line):
result = [] # 1
check = False # 2
for cur in line: # 3
if check and result[-1] == cur: # 4
result[-1] *= 2
check = False
elif cur != 0: # 5
result.append(cur)
check = True
while len(result) < len(line): # 6
result.append(0)
return result
1. The result list, initialized empty.txt = raw_input('your input: ')
print 'This is',
if not palindrome(txt):
print 'not',
print 'a palindrome'
Not much to say about it, I guess.def palindrome(text):
text = strip(text) # 1
return text == text[::-1] # 2
1. A strip() function removes all the uninteresting characters from the original input.def strip(text):
ignore = (',', '.', ' ') # 1
stripped = '' # 2
for c in text: # 3
if c not in ignore: # 4
stripped += c
return stripped
1. This is the suggested ignore tuple. Actually, I put in it just three characters. Question mark, colon, semicolon, are just a few of the many candidates to enter in this selection.import re # 1
def palindrome(text):
text = re.sub(r'\W+', '', text) # 2
return text == reverse(text)
1. I am using the python regular expression library.first if test else secondAnd it reads: check test, if it is true returns first, otherwise second. I found it sort of perlish, but I guess in a while I should get used to it. I reckoned it was sort of fun showing how to use it by a simple programming problem. Say that you have a file containing a bunch of integers, each one on a different line, do not worry about any error handling. You have to write a python script that read that file and output for each number in input a 0 for any odd number and 1 for the even ones. Here is how I solved it:
import sys
data = open(sys.argv[1], 'r')
for line in data:
print(1 if int(line) % 2 == 0 else 0)
As comparison, In C++ I would have written the same piece of code like this:
int value;
while(file >> value)
std::cout << (value % 2 == 0 ? 1 : 0) << std::endl;
import sys
def fib(n):
if n == 0:
return 0
prev, cur = 0, 1
for i in range(n - 1):
prev, cur = cur, prev + cur
return cur
if __name__ == '__main__':
for line in open(sys.argv[1]):
if len(line) > 0:
print fib(int(line) + 1)