0

I created a function called readBinaryWatch and for some reason when my num=2, I get an answer 1.15. After debugging for a long time, I still can't figure out why there is a 1:15 in my solution instead of a 1:16

When I put in the print statements as you can tell my h,m prints

1.08

1.0 0.08 8.0

['3:00', '5:00', '9:00', '1:01', '1:02', '1:04', '1:08']

1.16

1.0 0.16 16.0

['3:00', '5:00', '9:00', '1:01', '1:02', '1:04', '1:08', '1:15'] The question is where is this 1:15 coming from!?!??! Please help.

Here's the code

def readBinaryWatch(num):
    """
    :type num: int
    :rtype: List[str]
    """
    time=[1,2,4,8,.01,.02,.04,.08,.16,.32]
    def dfs(i,n,path):
        if not n:
            print path
            h,m=divmod(path,1)
            print h,m,m*100
            ret.append('%d:%02d' % (h, m*100))
            print ret
        for j in xrange(i,len(time)):
            dfs(j+1,n-1,path+time[j])
    ret=[]
    dfs(0,num,0)
    return ret
Haxet
  • 73
  • 7
  • Floating point numbers are not precise, as discussed in the linked question. Convert to some precise type, such as ints (maybe integer numbers of seconds) or the `decimal` module instead. You may have other problems, that's just the first one I saw. – Peter DeGlopper Sep 12 '17 at 21:50
  • That can't be the issue, I'm not using any irrational numbers. A simple test would show me that '%d:%02d' % (h, m*100) using h=1.0 and m=.16 would give me the outcome 1:16. Also, as you can tell from my print commands, I do get h=1.0 and m=.16. So there is something going wrong with '%d:%02d' – Haxet Sep 12 '17 at 21:54
  • 1
    The problem is that many fractions that are finite, even nice and round, in decimal notation require an infinite number of figures in binary for accurate representation. Since precision isn't infinite, that means that your intuition for which values are "exact" is incorrect. – kindall Sep 12 '17 at 22:06
  • Got it that makes sense. Thanks – Haxet Sep 12 '17 at 22:07

0 Answers0