1. 程式人生 > >入坑codewars第11天-Clock in Mirror

入坑codewars第11天-Clock in Mirror

題目一:

Peter can see a clock in the mirror from the place he sits in the office. When he saw the clock shows 12:22

He knows that the time is 11:38

in the same manner:

05:25 --> 06:35

01:50 --> 10:10

11:58 --> 12:02

12:01 --> 11:59

Please complete the function WhatIsTheTime(timeInMirror)

, where timeInMirror is the mirrored time (what Peter sees) as string.

Return the real time as a string.

Consider hours to be between 1 <= hour < 13.

So there is no 00:20, instead it is 12:20.

There is no 13:20, instead it is 01:20.

題意:

題目意思是:
已知在鏡子裡看到的時間,求真實的時間。

解題思路:

我的思路是:
因為我們知道鏡子裡的時針、分針是關於y軸對稱;
因此設x是鏡子裡的時鐘數,y是分針數
則:實際時鐘數a=11-(x%12),b=60-y
但是有幾種特殊情況:比如12:00和08:00這樣的情況要特殊處理,具體看程式碼:

程式碼如下:

import re
def what_is_the_time(time_in_mirror):
    y=re.findall(r":(.+)",time_in_mirror)
    x=re.findall(r"(.+?):",time_in_mirror)
    a=11-(int(x[0])%12)
    b=60-int(y[0])
    hour=str(a)
    minute=str(b)
    if a==0:hour='12' #處理小時為12但是計算結果計算出是0
    if a<10 and a!=0: #處理<10的情況,要前面加0
        hour='0'+str(a)
    if b==60: #處理計算結果分鐘是60的情況,要考慮12:00的特殊情況
        minute='00'
        a=a+1
        hour=str(a)
        if a<10:
            hour='0'+str(a)
        
    if b<10 and b!=0: #同理處理分針小於10的情況
        minute='0'+str(b)
    c=hour+':'+minute
    return c

看看大神的精簡程式碼:

def what_is_the_time(time_in_mirror):
    h, m = map(int, time_in_mirror.split(':'))
    return '{:02}:{:02}'.format(-(h + (m != 0)) % 12 or 12, -m % 60)

(1)大神程式碼運用map()函式:

map函式怎麼用?

>>>def square(x) :            # 計算平方數
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 計算列表各個元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函式
[1, 4, 9, 16, 25]
 
# 提供了兩個列表,對相同位置的列表資料進行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

(2)還用到了python中取餘的特殊性

 

以-3 % 4為例:

q = ⌊-3/4⌋ = ⌊-0.75⌋ = -1

因此,餘數r = a - nq = -3 - (-1 * 4) = 1

此實現有如下特點:

1. 餘數的符號與除數相同

2. 這種實現在某些地方被稱之為求餘

(3)還用到了or的特性:

如果前面為真則不執行or後的,如果前面為假才執行or後面的,真的巧妙!!!