使用python解决codewar中问题,个人答题思路及代码总结(2)

7kyu Strings: starts with
Challenge: Given two null-terminated strings in the arguments “string” and “prefix”, determine if “string” starts with the “prefix” string. Return true or false.
Example:
startsWith(“hello world!”, “hello”); // should return true
startsWith(“hello world!”, “HELLO”); // should return false
startsWith(“nowai”, “nowaisir”); // should return false
Addendum: For this problem, an empty “prefix” string should always return true for any value of “string”.
If the length of the “prefix” string is greater than the length of the “string”, return false.
The check should be case-sensitive, i.e. startsWith(“hello”, “HE”) should return false, whereas startsWith(“hello”, “he”) should return true.
思路:通过阅读题目,可知具体需求是判断str中开头字符是否和prefix一样,如果一样就返回真,否则为假。还有附加条件是:两个都为空时返回真,str不为空但是perfix为空是返回真,其他为假。
所以我的思路是先把两者是否为空判断以后,在判断两者字符长度关系,如果长度关系满足str短,prefix长直接返回假,当长度关系符合str大于等于prefix在判断str前几个字母和prefix一样,这时我想到了字符串中的find()方法。
详细代码:
def starts_with(st, prefix):
# your code here
if st == “” and prefix == “”:
return True
elif len(st)>0 and prefix == “”:
return True
elif len(st)<len(prefix) :
return False
elif len(st)>=len(prefix):
if st.find(prefix,0,len(prefix)):
return False
else:return True
7 kyu Switcheroo
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.
Example:
‘acb’ --> ‘bca’
‘aabacbaa’ --> ‘bbabcabb’
题意:给定只含有三个字母 a b c 的字符串,将字符串中 a替换成b ,b替换成a,c不变。
思路:最开始的想法是利用字典中的键值对来进行替换,但是好像没法下手,所以就用了最基础的循环if判断,新建一个列表,将字符串遍历,出现 a 便向列表里追加一个b,出现b 则追加一个 a,不是a 和b 时直接添加c,直到字符串遍历完毕。
具体代码:
def switcheroo(s):
#your code here
t = []
for i in s:
if i == “a”:
t.append(“b”)
elif i ==“b”:
t.append(“a”)
else:t.append(“c”)
return “”.join(t) 列表要转换为字符串

利用字典的解决方案
def switcheroo(string):
swap = {
‘a’: ‘b’,
‘b’: ‘a’,
}

return ''.join(swap.get(ch, ch) for ch in string)

7 kyu Collatz Conjecture Length
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continuously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[ 20, 10, 5, 16, 8, 4, 2, 1 ]
Write a program that will output the length of the Collatz Conjecture for any given n.
In the example above, the output would be 8.
题意:给定一个数字n,如果n为偶数,直接除以2,如果n为奇数则n要乘与3并加1,直到n变为1,输入n计算到1需要的次数
思路:因为循环次数未知,所以需要使用while循环,然后在循环里判断n是为奇还是为偶数,根据条件进行计算即可。
详细代码:
def collatz(n):
count = 0
while n != 1:
if n%2 == 0 :
n = n//2 此处一定要用 // 如果用/会出问题 / 是浮点数除法 // 是整数除法
count += 1
else:
n=n*3+1
count += 1
return count + 1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值