lintcode python语法熟系(132道)

写在开头

只是为了熟系一遍python基础语法,所以有一些解法可能是会比较通俗,会参考一些比较好的思路,在这里罗列出来,方便回顾和学习。因为时间比较有限,所以可能会更多的选择在前三档的题目侧重,困难和超难的两道题目会先看看。

入门(119道)

字符串23道

字符串是不可变的,不能对原字符串做修改

" "可以直接创建

len()字符串的长度,str()数字转换为字符串,利用方括号做提取,replace('old','new',次数)实现字符串的替换

split(‘分隔符’)分割【基于指定的分隔符将字符串分割成多个字符串,返回的是列表】,join()作用和split()相反,用于将一系列字符串连接起来

strip()去除字符串首尾指定信息,lstrip(),rstrip()

startwith()指定字符串开头,endwith()

find()第一次出现指定字符串的位置,rfind()最后

title(),upper(),lower(),swapcase()

capitalize()产生新的字符串,并且只有首字母大写

isalnum()是否全为字母或者数字,isalpha()【字母】,isdigit()【数字】

2401.字母变换

题目:给定一个只由大写字母组成的字符串 s,按照字母表的中第 i 个字母变成第 (26 - i + 1) 个字母(如 AZ),变换字符串中的所有字母,通过 print 语句输出变换后的字符串到标准输出流(控制台)。

循环遍历写法:

s=input()
lis=[]
for i in s:
    if ord(i)<=90:
        lis.append(chr(155-ord(i)))
    else:
        lis.append(chr(219-ord(i)))
print(''.join(lis))

这里的ord内置函数,就是得到对应的编码大小,根据相差,得到反转的字符,最后用join方法拼接。

熟系一下join的写法:

''.join(str(e) for e in mylist[a:b])

686.删除多余的空格

题目:从句子中删除多余空格

取巧的内置方法:

class Solution:
    """
    @param s: the original string
    @return: the string without arbitrary spaces
    """
    def removeExtra(self, s):
        # write your code here
        return ' '.join(s.strip().split())

内置的方法

正确的循环输出的方法:

class Solution:
    """
    @param: : the original string
    @return: the string without arbitrary spaces
    """

    def removeExtra(self, s):
        # write your code here
        ans = ""
        i = 0
        while i < len(s):
            if s[i] == ' ':
                isntBegin = i != 0
                while i < len(s) and s[i] == ' ':
                    i += 1
                if isntBegin and i < len(s):
                    ans += ' '
            
            while  i < len(s) and s[i] != ' ':
                ans += s[i]
                i += 1
        return ans

转换为数组遍历,再用join拼接输出

class Solution:
    """
    @param s: the original string
    @return: the string without arbitrary spaces
    """
    def removeExtra(self, s):
        # write your code here
        s = s.lstrip().rstrip()
        arr = s.split(' ')
        res = []
        for i in range(len(arr)):
            if arr[i].strip() != '':
                res.append(arr[i])
        return ' '.join(res)

2263.字符串的拼接

join回顾写法

''.join(str(e) for e in mylist[a:b])
def str_join(seq: tuple) -> tuple:
    """

    :param seq: The source tuple
    :return: a tuple contain two str after jion
    """
    # write your code here
    return '-'.join(seq),''.join(seq)

​​​2379.链接列表元素

n=int(input())
list_in = str(input())
print('-'.join(list_in.split(' ')))

就算是用空格拼接,在括号的引号中也要打出来。

还有一个用的是replace函数的:

n=int(input())
list_in=input()
list_in=list_in.replace(' ','-')
print(list_in)

2907 求两个参数的和

import sys

# try to import the function plus from a_plus_b.py in the same directory
# - write your code here -
from a_plus_b import plus

# read two parameters from command like `python main.py 1 2` by sys.argv
# - write your code here -
a=int(sys.argv[1])
b=int(sys.argv[2])
# call plus function and add them up
# - write your code here -
result=plus(a,b)
# print the sum to the console
# - write your code here -
print(result)

Python中的sys.argv

Python中argv使用问题

2908.修改字符串的第k个字符

tips:可变序列:列表,字典,集合 不可变序列:元组,字符串

replace对不可变序列的操作

可变序列和不可变序列的注意

def change_str(txt, k, s) -> str:
    # write your code here
    return txt.replace(txt[k],s)

2407.计算a+aa+aaa+aaaa的值

def calculate_sum(int_1: int) -> None:
    """
    :param int_1: Input number
    :return: None
    """
    # -- write your code here --
    temp = 0
    result = 0
    n = 1
    for i in range(4):
        temp = int(str(int_1) * n)
        result += temp
        n += 1
    print(result)

还是对字符串的使用,对字符串的复制的实现,相似的还有,加法在字符串操作中实现的是字符串的拼接。注意在python中没有自增自减的概念。

看到一个一行的代码,理解一下

 print(sum([int(str(int_1) * i) for i in range(1,5)]))

测试如下:

print(int(str(5)*i) for i in range(1,5))
print([int(str(5)*i) for i in range(1,5)])
print(sum([int(str(5)*i) for i in range(1,5)]))

结果是:

加上中括号后,即是创建了列表对象,如第二行所展示的。

sum()对列表元素的求和操作,类似的还有max和min之类的。

 不得不提到的迭代器对象(这里的range()产生的就是一个迭代器对象), python generator object,只要记得在这种语句直接出来的是迭代器对象,需要转换为其他的类型输出。详见

其实就是python的又一重要体现,各种类型的推导式的原因。

2405.字符串的替换

def replace_string(str_1: str, str_2: str) -> None:
    '''
    :param str_1: Input string
    :param str_2: Input string
    :return: None
    '''
    # -- write your code here --
    t=str_1.replace('*','career')
    m=str_2.replace('*','career',1)
    print(t)
    print(m)

没啥好说的了,前面已经提到的,replace存在的三个参数的使用,那个1就是说明替换几次

2395.统计字符串出现的次数

def count_string(str_1: str) -> tuple:
    '''
    :param str_1: Input string
    :return: Count the number of occurrences of a string
    '''
    # -- write your code here --
    t=str_1.count('a')
    m=str_1.count('going',0,40)
    return t, m

其实就是字符串的简单操作,是常用的查找方法,其实对序列有相同的操作方式。

2390.按要求完成字符串的判断

内置方法startwith判断是以谁开头的,还有endwith相类似的。注意这里也是可以指定查询的始末位置。

def check_string(str_in: str) -> None:
    # 判断 str_in 是否以 Nobody 作为开头
    if str_in.startswith('Nobody'):
        print('str_in starts with Nobody')
    else:
        print('str_in does not start with Nobody')
    # 判断 str_in 从下标为 13 的字符开始是否以 with 开头
    if str_in.startswith('with', 13):
        print('str_in starts with the character with a subscript of 13')
    else:
        print('str_in starts with a subscript of 13 and does not begin with with')
    # 判断 str_in 下标从 23 到 29 的字符片段中是否以 people 开头
    if str_in.startswith('people', 23, 29):
        print('The str_in subscript starts with people in the character fragment from 23 to 29')
    else:
        print('str_in subscript from 23 to 29 in a character fragment that does not start with people')

还有一个就是用正则匹配,这里不做陈述了。

# 判断 str_in 下标从 23 到 29 的字符片段中是否以 people 开头
    if re.match(r'\w{23}^people$', str_in):
        print('The str_in subscript starts with people in the character fragment from 23 to 29')
    else:
        print('str_in subscript from 23 to 29 in a character fragment that does not start with people')

2383.标题化字符串

str_in.title()

这个是直接用了,那就再补充两个:upper&#

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

励步野

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值