1

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]-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.

2
  • Why change_num(7,'forward',5) -> 4? Commented May 19, 2011 at 20:28
  • ya it was typo, should be '2', fixed it Commented May 19, 2011 at 20:29

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

2
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.

2 Comments

I take it nums is defined as nums = range(10)
there is no nums. i mistyped before
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.