0
点赞
收藏
分享

微信扫一扫

Tortoise racing---codewar刷题总结

西红柿上校 2022-04-13 阅读 44
pythondjango

Description:

Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage.

When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A?

More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A?

The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages.

If v1 >= v2 then return nilnothingnullNone or {-1, -1, -1} for C++, C, Go, Nim, Pascal, COBOL, [-1, -1, -1] for Perl,[] for Kotlin or "-1 -1 -1".

Examples:

(form of the result depends on the language)

race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37)   => [3, 21, 49] or "3 21 49"

Note:

  • See other examples in "Your test cases".

  • In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.

** Hints for people who don't know how to convert to hours, minutes, seconds:

  • Tortoises don't care about fractions of seconds
  • Think of calculation by hand using only integers (in your code use or simulate integer division)
  • or Google: "convert decimal time to hours minutes seconds"

 我的解决方案:

def race(v1, v2, g):
    print(v1,v2,g)
    if v1>=v2:
        return None
    speed=v2-v1#这等于是速度为speed,距离为g,算什么时间走完全程
    full_time=str(g/(v2-v1)).split('.')#是一个浮点数
    hours=int(full_time[0])#将整数部分取出来,这就是小时
    float_min=float('0.'+full_time[1])##小数部分取出来,是个浮点数,分钟的占比,*60就可算出实际值
    minutes=int(str(float_min*60).split('.')[0])  #算出分钟,第二位是浮点数,是秒数的占比
    
    float_sec=float('0.'+str(float_min*60).split('.')[1])  #取出算出分钟后的浮点数,这是秒数的占比
    seconds=int(round(float_sec*60,3))#算出有多少秒,round取出小数点后三位,我测了一下,round取的是近似值,如果小数点后是0.9999,它就会自动前一位加1
    #下面的函数是写一个60进制的时间进位代码,如果秒数是60,则它自己清零,分钟加1,分钟是60,它自己清零,小时加1
    if seconds==60:   
        seconds=0
        print(seconds)
        minutes+=1
    if minutes==60:
        minutes=0
        hours+=1
    return [hours,minutes,seconds]

 再看一下大佬写的:

def race(v1, v2, g):
    t = 3600 * g/(v2-v1)
    return [int(t/3600), int(t//60%60), int(t%60)] if v2 > v1 else None

 第二个:

def race(v1, v2, g):
    if v1 >= v2: return None
    t = float(g)/(v2-v1)*3600
    mn, s = divmod(t, 60)
    h, mn = divmod(mn, 60)
    return [int(h), int(mn), int(s)]

 其他的就不贴了,大致思路都跟第一个一样。

举报

相关推荐

0 条评论