月度归档:2018年04月

批量转换ipynb

点击量:7

一段脚本将ipython notebook转化为py文件。

It’s hard to make notebook file to import so it’s important to make notebook importable.

#!/usr/bin/env python
# coding: utf-8
import nbformat
from nbconvert import PythonExporter
def convertNotebook(notebookPath, modulePath):
  with open(notebookPath) as fh:
    nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
  exporter = PythonExporter()
  source, meta = exporter.from_notebook_node(nb)
  with open(modulePath, 'w+') as fh:
    fh.writelines(source)
def trans_all():
    import os
    path = '.'
    list_dirs = os.listdir(path)
    for filename in list_dirs:
        if filename.endswith('.ipynb'):
            print(filename, filename[:-5] + 'py')
            convertNotebook(filename, filename[:-5] + 'py')
trans_all()

与所有单词相关联的字串

点击量:5

题目

  • https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/description/

给定一个字符串 s 和一些长度相同的单词 words,找出 s 与 words 中所有单词(words 每个单词只出现一次)串联一起(words 中组成串联串的单词的顺序随意)的字符串匹配的所有起始索引,子串要与串联串完全匹配,中间不能有其他字符。

举个例子,给定:
s:”barfoothefoobarman”
words:[“foo”, “bar”]

你应该返回的索引: [0,9]。(任意顺序)

题解

代码写的比较清楚,应该不需要题解。。

code

class Solution:
    def match(self, ss, word_dic):
        len_ss = len(ss)
        word_number = 0
        i = 0
        while True:
            word = ss[i:i+self.len_of_word]
            # keys() update
            if word in word_dic:
                if word_dic[word] > 0:
                    word_dic[word] -= 1
                    word_number += 1
                    # is update
                    if word_number is self.len_of_words:
                        return True
                # repeat
                else:
                    return False
            # not exist
            else:
                return False
            i += self.len_of_word
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        self.len_of_word = len(words[0])
        self.len_of_words = len(words)
        self.len_of_str = len(s)
        a = dict()
        for word in words:
            if word in a:
                a[word] = a[word] + 1
            else:
                a.update({word: 1})
        index_recorder = []
        len_substr = self.len_of_word * self.len_of_words
        search_range = self.len_of_str - len_substr + 1
        for i in range(search_range):
            ss = s[i:i+len_substr]
            word_dic = a.copy()
            if self.match(ss, word_dic):
                index_recorder.append(i)
        return index_recorder
if __name__ == '__main__':
    s = "wordgoodgoodgoodbestword"
    words = ["word","good","best","good"]
    so = Solution()
    print(so.findSubstring(s, words))