文章目录
478 · 简单计算器
def calculate(self, a, operator, b):
# write your code here
if operator == '+': return a + b
elif operator == '-': return a - b
elif operator == '*': return a * b
elif operator == '/': return a // b
283 · 三数之中的最大值
给三个整数,求他们中的最大值。
def maxOfThreeNumbers(self, num1, num2, num3):
# write your code here
if num1 > num2: temp = num1
else: temp = num2
if temp > num3: return temp
else: return num3
145 · 大小写转换
将一个字符由小写字母转换为大写字母
def lowercaseToUppercase(self, character):
# write your code here
return ord(character) + ord('A') - ord('a')
官方题解:
def lowercaseToUppercase(self, character):
# Write your code here
#ASCII码中小写字母与对应的大写字母相差32
return chr(ord(character) - 32)
def lowercaseToUppercase(self, character):
return character.upper()
23 · 判断数字与字母字符
def isAlphanumeric(self, c: str) -> bool:
# write your code here
if ord(c) >= ord('0') and ord(c) <= ord('9'): return True
elif ord(c) >= ord('a') and ord(c) <= ord('z'): return True
elif ord(c) >= ord('A') and ord(c) <= ord('Z'): return True
else: return False
官方答案:
def isAlphanumeric(self, c):
if c.isalnum():
return True
else:
return False
Python isalnum() 方法检测字符串是否由字母和数字组成。
其他一些优秀答案:
def isAlphanumeric(self, c: str) -> bool:
# write your code here
a = ord(c)
if a >= 48 and a <= 57:
return True
elif a >= 65 and a <= 90:
return True
elif a >= 97 and a <= 122:
return True
else:
return False```
1141 · 月份天数
给定年份和月份,返回这个月的天数。
def getTheMonthDays(self, year, month):
# write your code here
days31_month = [1, 3, 5, 7, 8, 10, 12]
days30_month = [4, 6, 9, 11]
if month in days31_month: return 31
elif month in days30_month: return 30
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
return 29
else: return 28
闰年定义:
766 · 闰年
判断给出的年份 n 是否为闰年. 如果 n 为闰年则返回 true
def isLeapYear(self, n):
# write your code here
if (n % 100 != 0 and n % 4 == 0) or (n % 400 == 0): return True
else: return False
看了一个答案,直接return,改了下代码:
def isLeapYear(self, n):
# write your code here
return (n % 400 == 0) or (n % 100 != 0 and n % 4 == 0)
省去了条件语句。让结果自己说话。妙啊