# 从右上角开始遍历,如果目标值大于右上角的值,去掉所在的行,对所在的列进行遍历,反之,小于,去掉所在的列,对所在的行进行遍历 class Solution: # array 二维列表 def Find(self, target, array): # write code here row = 0 col = len(array[0])-1 while row<len(array) and col>=0: if array[row][col] == target: return True elif array[row][col] > target: col -= 1 else: row += 1 return False
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# 首先从前往后遍历字符串,找出空格的个数,然后从后往前遍历字符串,找到空格并将其替换。
def replace_space(s): space_count = 0 s_length = len(s) for i in s: if i.isspace(): space_count += 1 new_s_length = s_length + space_count * 2 new_s_list = [" "] * new_s_length # 创造一个新的列表储存新的字符串 while s_length: if s[s_length-1].strip(): new_s_list[s_length - 1 + space_count * 2] = s[s_length - 1] s_length -= 1 else: new_s_list[s_length - 1 + space_count * 2] = "0" new_s_list[s_length - 1 + space_count * 2 - 1] = "2" new_s_list[s_length - 1 + space_count * 2 - 2] = "%" space_count -= 1 s_length -= 1 return "".join(new_s_list) a = "I am nxr" ret = replace_space(a) print(ret)
从一个字符串中找到有且只有出现过两次的字符,并将其索引返回。
def two_times(a): dic = {} for value, key in enumerate(a): if key in dic: if dic[key][1] == 2: dic.pop(key) else: dic[key][1] += 1 else: dic[key] = [value, 1] for key in dic: if dic[key][1] == 2: return [key, dic[key][0]]
打印矩阵 斜对角线上的数
def print_right(matrix): if not matrix: # 检验输入的合法性 return [] row = len(matrix) col = len(matrix[0]) k = 0 # 设置变量控制j的值 result = [] # 存储结果 for i in range(row): for j in range(k, col): lst = [] # 存储每一条对角线上的值 i1, j1 = i, j # 防止因i,j改变导致循环变量的出错 while i1 <= row - 1 and j1 >= 0: lst.append(matrix[i1][j1]) j1 -= 1 i1 += 1 result.append(lst) if i == 0 and j == col-1: # 当遍历完右上角开头的一条对角线后,让j固定为col-1 k = col-1 return result
判断输入是否合法,例如“(【{}】)”
def func(a): dic = {"]": "[", ")": "(", "}": "{"} lis = [] # 堆栈
for i in a:
if i not in dic:
lis.append(i)
elif not lis or dic[i] != lis.pop(): # 栈为空或左右扩号不匹配
return False
return not lis
原文:https://www.cnblogs.com/nxrs/p/10504427.html