iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 28
0

寫在開頭

今天選的這題是#Easy,要算日期對應的是星期幾

進入正題

題目如下:

Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the day, month and year respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Constraints:
The given dates are valid dates between the years 1971 and 2100.

針對這個我找到參考1的裡有日期對應星期的一個function,用date.weekday()會輸出0-6的數字,分別對應星期一到星期日。另外要使用日期型態的變數要先匯入date
所以我設計的程式碼如下:

from datetime import date
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        ddate = date(year,month,day)
        week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        return week[ddate.weekday()]

submit後結果如下:
https://ithelp.ithome.com.tw/upload/images/20190929/20113393UHUrmMXx8T.png

參考資料

參考1datetime --- 基本的日期和时间类型


上一篇
#804 Unique Morse Code Words
下一篇
#69 Sqrt(x)
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言