145 · 大小写转换
将一个字符由小写字母转换为大写字母
def lowercaseToUppercase(self, character):
return character.upper()
之前写的方法:
def lowercaseToUppercase(self, character):
return ord(character) + ord('A') - ord('a')
def lowercaseToUppercase(self, character):
# Write your code here
#ASCII码中小写字母与对应的大写字母相差32
return chr(ord(character) - 32)
23 · 判断数字与字母字符
给出一个字符c,如果它是一个数字或字母,返回true,否则返回false。
def isAlphanumeric(self, c: str) -> bool:
# write your code here
return c.isalnum()
之前写的:
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
1141 · 月份天数
给定年份和月份,返回这个月的天数。
def getTheMonthDays(self, year, month):
# write your code here
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month != 2:
return months[month - 1]
else:
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
return months[month - 1] + 1
else:
return months[month - 1]
768 · 杨辉三角
给一整数 n, 返回杨辉三角的前 n 行
def calcYangHuisTriangle(self, n):
# write your code here
res = [[1], [1, 1]]
if n == 1:
return [res[0]]
elif n == 2:
return res
elif n == 0:
return []
layer = 2
while n != layer:
tmp = [1]
for i in range(1, layer):
tmp.append(res[layer -1][i - 1] + res[layer -1][i])
tmp.append(1)
res.append(tmp)
layer += 1
return res
之前写的比这次写得好:
def calcYangHuisTriangle(self, n):
# write your code here
if n <= 0: return []
elif n == 1: return [[1]]
elif n == 2: return [[1], [1, 1]]
li = [[1], [1, 1]]
for i in range(2, n):
temp = [1]
for j in range(1, i):
temp.append(li[i-1][j-1] + li[i-1][j])
temp.append(1)
li.append(temp)
return li
485 · 生成给定大小的数组
给你一个大小size,生成一个元素从1 到 size的数组
def generate(self, size):
# write your code here
return list(range(1, size + 1))