Manipulate a number algorithm
How can I fix this algo?
def change_num(n, direc, numMove):
if direc == 'back':
nums = range(10)
return nums[n-numMove]
elif direc == 'forward':
nums = range(10)
nums.reverse()
return nums[n-numMove]-开发者_JS百科1
This doesn't work for direc == 'back' here are some sample expected returns:
0 1 2 3 4 5 6 7 8 9
change_num(1,'back', 5) -> 6
change_num(5,'back', 1) -> 4
change_num(7,'forward',5) -> 2
change_num(0,'forward',5) -> 5
Do you understand how the algo works? I'm just not implementing it right.
Instead of 'back'
and 'forward'
, it will be easier to pass +1
for forward and -1
for back. Then your function simplifies to
def change_num(n, direc, num_move):
return (n + direc * num_move) % 10
def change_num(n, direc, numMove):
d = {'back' : -1, 'forward' : 1}
return (n + d[direc]*numMove) % 10
Have you given thought to what this function does? this num
list is pointless bc num[x]
=== x
. You don't need if statements for 'back' and 'forward', they really just correspond to -1
and 1
respectively.
Your function is over-complicated and won't work in Python 3.
% cat ./test.py
#!/usr/bin/env python
import unittest
def change_num(n, direc, numMove):
directions = {
'back': -1,
'forward': +1,
}
steps = n + directions[direc] * numMove
wrapped = steps % 10
return wrapped
class TestChangeNum(unittest.TestCase):
def test_back_no_wrap(self):
self.assertEquals(6, change_num(1, 'back', 5))
def test_back_with_wrap(self):
self.assertEquals(4, change_num(5, 'back', 1))
def test_forward_with_wrap(self):
self.assertEquals(2, change_num(7, 'forward', 5))
def test_forward_no_wrap(self):
self.assertEquals(5, change_num(0, 'forward', 5))
if __name__ == '__main__':
unittest.main()
% python test.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OK
精彩评论