Implement-Strstr——python

“””
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
“”“

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(haystack) == len(needle):
            if haystack == needle:
                return 0
            else:
                return -1

        for i in xrange(0, len(haystack)):
            k = i
            j = 0
            while j < len(needle) and k < len(haystack) and haystack[k] == needle[j]:
                j += 1
                k += 1
            if j == len(needle):
                return i
        return -1 if needle else 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sorry, as an AI language model, I am not able to write code. However, here is an overview of the Lee-Carter model in Python: The Lee-Carter model is a mortality forecasting model that estimates age-specific and time-specific mortality rates. It assumes that the logarithm of mortality rates follows a linear trend and a set of age-specific factors that evolve over time. Here is how you can implement the Lee-Carter model in Python: 1. Import the necessary libraries: ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm ``` 2. Load the data: ```python data = pd.read_csv('mortality_data.csv') ``` 3. Preprocess the data: ```python # Convert the data into a matrix mortality = data.iloc[:, 1:].values # Take the logarithm of the mortality rates log_mortality = np.log(mortality) # Calculate the age-specific and time-specific means mu = np.mean(log_mortality, axis=1) kappa = np.mean(log_mortality, axis=0) # Create the design matrix T, A = mortality.shape X = np.ones((T, A)) for i in range(T): for j in range(A): X[i, j] = j + 1 - mu[j] ``` 4. Fit the Lee-Carter model: ```python # Fit the Lee-Carter model model = sm.OLS(log_mortality.T, X) fit = model.fit() # Extract the estimated parameters b = fit.params[0] a = fit.params[1:] ``` 5. Forecast the mortality rates: ```python # Create the forecast matrix T_forecast = 10 A_forecast = A X_forecast = np.ones((T_forecast, A_forecast)) for i in range(T_forecast): for j in range(A_forecast): X_forecast[i, j] = j + 1 - mu[j] # Forecast the mortality rates log_mortality_forecast = np.zeros((T_forecast, A_forecast)) for i in range(T_forecast): for j in range(A_forecast): log_mortality_forecast[i, j] = b + a[j]*X_forecast[i, j] + kappa[j] # Convert the logarithm of the mortality rates into mortality rates mortality_forecast = np.exp(log_mortality_forecast) ``` 6. Visualize the results: ```python # Plot the mortality rates t = np.arange(T + T_forecast) for j in range(A): plt.plot(t, mortality[:, j], 'o', markersize=3) plt.plot(t[T:], mortality_forecast[:, j], '-') plt.xlabel('Year') plt.ylabel('Mortality rate') plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值