给定两个仅含数字的字符串,你需要返回一个由各个位之和拼接的字符串
def SumofTwoStrings(self, A, B):
# write your code here
min_length = min(len(A), len(B))
res = ""
for i in range(-1, -min_length - 1, -1):
res = str(int(A[i]) + int(B[i])) + res
if min_length == len(A):
res = B[0: len(B) - len(A)] + res
else:
res = A[0: len(A) - len(B)] + res
return res
比之前的代码写的简单,下面是之前的:
def SumofTwoStrings(self, A, B):
# write your code here
if not A and not B: return 0
res = ""
cur_a, cur_b = -1, -1
while (cur_a >= -len(A)) or (cur_b >= -len(B)):
if cur_a == -len(A) - 1 and B[cur_b]:
res = B[:cur_b + 1] + res
break
elif cur_b == -len(B) - 1 and A[cur_a]:
res = A[:cur_a + 1] + res
break
elif A[cur_a] and B[cur_b]:
if cur_a == -len(A) and cur_b == -len(B):
res = str(int(A[cur_a]) + int(B[cur_b])) + res
break
else:
res = str(int(A[cur_a]) + int(B[cur_b])) + res
cur_a -= 1
cur_b -= 1
return res
看了一个答案,虽然代码简单了,但是修改了A和B的值,不推荐。
def SumofTwoStrings(self, A, B):
# write your code here
if len(A) < len(B):
A, B = B, A
#Assume A is of larger length
res = ""
for i in range(-1, -len(B)-1, -1):
res = str(int(A[i]) + int(B[i])) + res
return A[ : (len(A)-len(B))] + res
def capitalizesFirst(self, s):
# Write your code here
li = s.split(' ')
res = []
for i in li:
if i.isalpha():
res.append(i[0].upper()+i[1:])
else:
res.append(i)
return " ".join(res)
用了一些方法的答案:
def capitalizesFirst(self, s):
# Write your code here
return s.title()
def capitalizesFirst(self, s):
# Write your code here
array = s.split(" ")
ans = " "
return ans.join(string.capitalize() for string in array)
判断一个正整数是不是回文数。
回文数的定义是,将这个数反转之后,得到的数仍然是同一个数。
def isPalindrome(self, num):
# write your code here
return str(num) == str(num)[::-1]
下面是之前写的:
def isPalindrome(self, num):
# write your code here
if num <= 0: return False
s = str(num)
left, right = 0, len(s) - 1
while left <= right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
给一个词典,找出其中所有最长的单词。
def longestWords(self, dictionary):
# write your code here
max_length = max([len(i) for i in dictionary])
res = []
for i in dictionary:
if len(i) == max_length:
res.append(i)
return res
看到一个用lambda和filter的
def longestWords(self, dictionary):
# write your code here
max_len = max([len(i) for i in dictionary])
return list(filter(lambda x:len(x)>=max_len,dictionary))
给定一个字符串, 包含大小写字母、空格 ’ ',请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
def lengthOfLastWord(self, s):
# write your code here
li = s.strip().split(' ')
if li[-1]:
return len(li[-1])
else:
return 0