ARTS-21(leetcode-438找到字符串中所有字母异位词,tensorflow小例子,C++,被讨厌的勇气)

Algorithm
leetcode-438 找到字符串中所有字母异位词

滑动窗口秘籍

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        unordered_map<char, int> need, window;
        for (char c : p) need[c]++;

        int left = 0, right = 0;
        int valid = 0;
        vector<int> res; // 记录结果
        while (right < s.size()) {
            char c = s[right];
            right++;
            // 进行窗口内数据的一系列更新
            if (need.count(c)) {
                window[c]++;
                if (window[c] == need[c]) 
                    valid++;
            }
            // 判断左侧窗口是否要收缩
            while (right - left >= p.size()) {
                // 当窗口符合条件时,把起始索引加入 res
                if (valid == need.size())
                    res.push_back(left);
                char d = s[left];
                left++;
                // 进行窗口内数据的一系列更新
                if (need.count(d)) {
                    if (window[d] == need[d])
                        valid--;
                    window[d]--;
                }
            }
    }
    return res;
    }
};

Review

总结TensorFlow开发的步骤流程

1.定义TensorFlow输入节点

2.定义“学习参数”的变量

3.定义“运算”

4.优化函数,优化目标

5.初始化所有变量

6.迭代更新参数到最优解

7.测试模型

8.使用模型

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Creates a graph.
train_X = np.linspace(-1,1,100)
train_Y = 2*train_X+np.random.rand(*train_X.shape) * 0.3

plt.plot(train_X, train_Y, 'ro', label='Orignal data')

plt.legend()
plt.show()

X = tf.placeholder("float")
Y = tf.placeholder("float")

W = tf.Variable(tf.random_normal([1]), name = "weight")
b = tf.Variable(tf.zeros([1]),name="bias")

z = tf.multiply(X,W) + b

cost = tf.reduce_mean(tf.square(Y-z))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

init = tf.global_variables_initializer()

training_epochs = 20
display_step = 2

plotdata={"batchsize":[], "loss":[]}
def moving_average(a, w=10):
    if len(a)<w:
        return a[:]
    return {val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)}

with tf.Session() as sess:
    sess.run(init)
    plotdata = {"batchsize":[], "loss":[]}
    for epoch in range(training_epochs):
        for (x,y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X:x, Y:y})

        if epoch % display_step == 0:
            loss = sess.run(cost, feed_dict={X:train_X, Y:train_Y})
            print("Epoch:", epoch+1, "cost=", loss, "W=",sess.run(W), "b=", sess.run(b))
            if not (loss == "NA"):
                plotdata["batchsize"].append(epoch)
                plotdata["loss"].append(loss)
    print("finished!")
    print("cost=",sess.run(cost, feed_dict={X:train_X,Y:train_Y}), "W=",sess.run(W), "b=", sess.run(b))

    plt.plot(train_X, train_Y, 'ro',label='original data')
    plt.plot(train_X, sess.run(W)*train_X+sess.run(b), label="fittedline")
    plt.legend()
    plt.show()

    plotdata["avgloss"] = moving_average(plotdata["loss"])
    plt.figure(1)
    plt.subplot(211)
    plt.plot(plotdata["batchsize"],plotdata["avgloss"], "b--")
    plt.xlabel("Minibatch number")
    plt.ylabel("Loss")
    plt.title("Minibatch run vs. training loss")

    plt.show()

print("x=0.2, z=", sess.run(z,feed_dict={X:0.2}))

Tips

对于C++中this指针的应用 ,将类引用类型写上,能使用myScreen.move(2,3).set(‘C’).display(cout); 就能写的很漂亮。

#include
#include 

using namespace std;

class Person{

public:
    Person(const string &nm, const string &addr){
        this->name = nm;
        this->address = addr;
    }
    string getName() const{
        return this->name;
    }
    string getAddress() const{
        return this->address;
    }

private:
    string name;
    string address;
};

class Screen{
public:
    typedef string::size_type index;
    Screen(index ht = 0, index wd = 0):contents(ht*wd, 'A'),cursor(0),height(ht),width(wd){}
    char get() const {return contents[cursor];}
    char get(index r, index c) const{
        index row = r * width;
        return contents[row + c];
    }
    Screen& move(index r, index c);
    Screen& set(index, index, char);
    Screen& set(char);
    void display(ostream &os){
        do_display(os);
    }
private:
    string contents;
    index cursor;
    index height, width;
    void do_display(ostream &os) const{
        os << contents;
    }

};

Screen& Screen::move(index r, index c){
    index row = r * width;
    cursor = row + c;
    return *this;
}

Screen& Screen::set(index r ,index c, char ch){
    index row = r*width;
    contents[row + c] = ch;
}

Screen& Screen::set(char c){
    contents[cursor] = c;
}


// 命令行选项
int main() {

    Person p("zdq","street");
    Person p2("zengdiqing","street2");
    cout << p.getName() <<endl;
    cout << p2.getName() <<endl;

    Screen myScreen(5,3);
    cout << myScreen.get() <<endl;
    myScreen.set(3,2,'B');
    cout << myScreen.get(3,2)<< endl;
    // 这两行是重点
//    myScreen.move(2,3);
//    myScreen.set('C');
    myScreen.move(2,3).set('C').display(cout); //这种写法非常漂亮
    cout << myScreen.get() << endl;

    return 0;
}

然后下面的代码是析构函数,如果写了析构函数,要记住三法则:如果写了析构函数就必须写拷贝构造函数和赋值操作符。

#include 
#include 
#include 
using namespace std;

class NoName{
public:
    NoName():pstring(new string), i(0),d(0){
        cout << "构造函数被掉用了"<<endl;
    }
    NoName(const NoName & other);
    ~NoName();

    NoName& operator = (const NoName &rhs);
private:
    string *pstring;
    int i;
    double d;
};

NoName::NoName(const NoName & other){
    pstring = new string;
    *pstring = *(other.pstring);
    i = other.i;
    d = other.d;
}

NoName& NoName::operator = (const NoName &rhs){
    pstring = new string;
    *pstring = *(rhs.pstring);
    i = rhs.i;
    d = rhs.d;
    return *this;
}
NoName::~NoName() {
    cout << "析构函数被调用了"<<endl;
    delete pstring;
}

int main() {

    NoName a;
    NoName *p = new NoName;
    cout << "hello" <<endl;

    delete p;
    return 0;
}


Share
被讨厌的勇气,推荐给你,看不看是你的课题

你可能感兴趣的:(ARTS专栏)