找到给定字符串中的不同字符
在不考虑字符排列的条件下,对于相差只有一个字符的两个字符串,实现一个算法来识别相差的那个字符。要求如下:
- 当传入的字符串为
'aad'
和'ad'
时,结果为'a'
。 - 当传入的字符串为
'aaabccdd'
和'abdcacade'
时,结果为'e'
。
class Solution(object): def find_diff(self, str1, str2): if str1 is None or str2 is None: raise TypeError('str1 or str2 cannot be None') result = 0 for char in str1: result ^= ord(char) for char in str2: result ^= ord(char) return chr(result)
Fizz Buzz 经典问题
给定一个整数 num
,从 1
到 num
按照下面的规则返回每个数:
- 如果这个数被
3
整除,返回'Fizz'
。 - 如果这个数被
5
整除,返回'Buzz'
。 - 如果这个数能同时被
3
和5
整除,返回'FizzBuzz'
。 - 如果这个数既不能被
3
也不能被5
整除,返回这个数字的字符串格式。
class Solution(object): def fizz_buzz(self, num): if num is None: raise TypeError('num cannot be None') if num < 1: raise ValueError('num cannot be less than one') results = [] for i in range(1, num + 1): if i % 3 == 0 and i % 5 == 0: results.append('FizzBuzz') elif i % 3 == 0: results.append('Fizz') elif i % 5 == 0: results.append('Buzz') else: results.append(str(i)) return results
实现链表类
实现链表的插入,增加,查找,删除,查看长度和打印的方法。链表的介绍如下:
- 链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
- 链表中每一个元素称为结点,链表由一系列结点组成,结点可以在运行时动态生成。
- 链表的每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
class Node(object): def __init__(self, data, next=None): self.next = next self.data = data def __str__(self): return self.data class LinkedList(object): def __init__(self, head=None): self.head = head def __len__(self): curr = self.head counter = 0 while curr is not None: counter += 1 curr = curr.next return counter def insert_to_front(self, data): if data is None: return None node = Node(data, self.head) self.head = node return node def append(self, data): if data is None: return None node = Node(data) if self.head is None: self.head = node return node curr_node = self.head while curr_node.next is not None: curr_node = curr_node.next curr_node.next = node return node def find(self, data): if data is None: return None curr_node = self.head while curr_node is not None: if curr_node.data == data: return curr_node curr_node = curr_node.next return None def delete(self, data): if data is None: return if self.head is None: return if self.head.data == data: self.head = self.head.next return prev_node = self.head curr_node = self.head.next while curr_node is not None: if curr_node.data == data: prev_node.next = curr_node.next return prev_node = curr_node curr_node = curr_node.next def print_list(self): curr_node = self.head while curr_node is not None: print(curr_node.data) curr_node = curr_node.next def get_all_data(self): data = [] curr_node = self.head while curr_node is not None: data.append(curr_node.data) curr_node = curr_node.next return data
记得先自己做一遍再看答案哦~
Love&Share
[ 完 ]