數據結構3.5

Problem: Implement Fizz Buzz.

What is fizz buzz?

Return the string representation of numbers from 1 to n

Multiples of 3 -> Fizz

Multiples of 5 -> Buzz

Multiples of 3 and 5 -> FizzBuzz

Test Cases

* None -> Exception

* < 1 -> Exception

* 15 ->

[

1,

2,

Fizz,

4,

Buzz,

Fizz,

7,

8,

Fizz,

Buzz,

11,

Fizz,

13,

14,

FizzBuzz

]

import numpy as npimport stringclass Solution(object): def fizz_buzz(self, num): # TODO: Implement me if num is None: raise TypeError(num cannot be None) if num<1: raise ValueError(num cannot less than one) a=np.arange(num)+1 results = [] for x in a: if x%5==0 and x%3==0: results.append(FizzBuzz) elif x%3==0: results.append(Fizz) elif x%5==0: results.append(Buzz) else: results.append(str(x)) return results

Problem: Compress a string such that AAABCCDDDD becomes A3BCCD4. Only compress the string if it saves space.

Test Cases

  • None -> None
  • ->
  • AABBCC -> AABBCC
  • AAABCCDDDD -> A3BCCD4

解法一def compress_string(string): # TODO: Implement me if string is None or len(string)==0: return string prev_w=string[0] cnt=1 result=[] for w in string[1:]: if w==prev_w: cnt+=1 prev_w=w if w!=prev_w: result.append(prev_w) if cnt>2: result.append(cnt) elif cnt==2: result.append(prev_w) else: pass cnt=1 prev_w=w result.append(w) if cnt>2: result.append(cnt) elif cnt==2: result.append(prev_w) else: pass out= for r in result: out+=str(r) return out

解法2def compress_string(string): # TODO: Implement me if string is None or len(string)==0: return string def compress_word(word): #壓縮塊 if len(word)<=2: return word else: return word[0]+str(len(word)) def split_word(string): #切割塊 block= for i,j in zip(string, string[1:]+ ): block+=i if i!=j: yield block block = content=(compress_word(s) for s in split_word(string) ) out=.join(content) if len(out)<len(string): return out else: return string

推薦閱讀:

Python新人應該如何進一步提高?
唯一值、值計數以及成員資格
Python非同步io的Web框架-Sanic源碼分析(核心篇)
使用cryptography進行AES的cbc模式加密
NumPy和MATLAB哪個強大,Numpy能替代MATLAB嗎?

TAG:數據結構 | Python |