Codewars笔记

时间:2023-03-08 22:18:30
说明:以下内容均来自codewars网站,列举的试题我都做过且通过,并以此记录来学习python。
1,需求:将大小写互相转换,非字母的字符保留
我的代码:
 def to_alternating_case(string):
#your code here
result = ''
for i in range(len(string)):
if string[i].isupper():
result += string[i].lower()
elif string[i].islower():
result += string[i].upper()
else:
result += string[i]
return result
示例代码1:
 def to_alternating_case(string):
return ''.join([c.upper() if c.islower() else c.lower() for c in string])
示例代码2:
 def to_alternating_case(string):
return string.swapcase()
测试代码:
 Test.assert_equals(to_alternating_case("hello world"), "HELLO WORLD")
Test.assert_equals(to_alternating_case("HeLLo WoRLD1234"), "hEllO wOrld1234")
Test.assert_equals(to_alternating_case("String.prototype.toAlternatingCase"), "sTRING.PROTOTYPE.TOaLTERNATINGcASE")
Test.assert_equals(to_alternating_case(to_alternating_case("Hello World")), "Hello World")
Test.it("should work for the title of this Kata")
title = "altERnaTIng cAsE"
title = to_alternating_case(title)
Test.assert_equals(title, "ALTerNAtiNG CaSe")
title = "altERnaTIng cAsE <=> ALTerNAtiNG CaSe"
总结:对基础仍不熟练,缺少主动性练习
2、需求:识别字符串中数字化的字符,并将其改正。
例如,处理一下错误
  • S is misinterpreted as 5
  • O is misinterpreted as 0
  • I is misinterpreted as 1
测试方法:
Test.assert_equals(correct("L0ND0N"),"LONDON");
Test.assert_equals(correct("DUBL1N"),"DUBLIN");
Test.assert_equals(correct("51NGAP0RE"),"SINGAPORE");
Test.assert_equals(correct("BUDAPE5T"),"BUDAPEST");
Test.assert_equals(correct("PAR15"),"PARIS");
我的代码:
 def correct(string):
for i in range(len(string)):
if "" in string:
string = string.replace('','S')
elif "" in string:
string = string.replace('','O')
elif "" in string:
string = string.replace('','I')
return string
示例代码1:
def correct(string):
return string.translate(str.maketrans("", "SOI"))
解析:
maketrans 和 translate 函数是进行字符串字符编码的常用方法
maketrans用法
string.maketrans(from, to) #制作翻译表
translate 用法
string.translate(s, table[, deletechars]) str.translate(table[, deletechars]) unicode.translate(table)
参数
  • table -- 翻译表,翻译表是通过 maketrans() 方法转换而来。
  • deletechars -- 字符串中要过滤的字符列表。
返回值
返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射 
实例:
 import string
map = string.maketrans('', 'abc')
s = ""
string.translate(s,map) #'abcc45'
s.translate(string.maketrans('', 'aaa'), '') #'aaaa4'
s.translate(map) #'abcc45'
s.translate(string.maketrans('', 'aaa')) #'aaaa45'
示例代码2:
 def correct(string):
return string.replace('','I').replace('','O').replace('','S')
3、需求:得到一组数字,返回所有正数的总和。
Example [1,-4,7,12] => 1 + 7 + 12 = 20
提示:如果数组为空,和默认为0
我的代码;
 def positive_sum(arr):
# Your code here
sum = 0
if arr == []:
return 0
else:
for i in arr:
if i >0:
sum = sum + i
return sum
 #示例代码1:
def positive_sum(arr):
return sum(x for x in arr if x > 0) #示例代码2:
def positive_sum(arr):
return sum(filter(lambda x: x > 0,arr)) #示例代码3:
def positive_sum(arr):
return sum(map(lambda x: x if x > 0 else 0, arr))
总结:因没仔细看需求,瞄了一眼就以为是把列表中的每个数求和,导致因为存在负数使得求和结果和测试的期望值不同,为了解决这个不必要的问题浪费了许多时间。