# 2回目

n, k = map(int, input().split())
h = list(map(int, input().split()))

dp = [-1]*n

for i in range(min(k, n)):
    dp[i] = abs(h[i]-h[0])
# print(dp)

for i in range(k, n):
    # print(i)
    mindp = 10**9
    for j in range(i-k, i):
        # print(j)
        mindp = min(mindp, abs(h[i]-h[j])+dp[j])

    dp[i] = mindp
 #   print(dp[i])
# print(dp)
print(dp[-1])

"""

#1回目

n,x=map(int,input().split())
a=list(map(int,input().split()))
if n<=x:#ｎこのDPを作りたいのでｘが超えたらそれを変える必要がある
    x=n-1#でもこれは実際甘え

dp=[-1]*n

dp[0]=0#さいしょのところは０かかる
for i in range(1,x+1):#飛べる距離までとべるところから最初の値を引く
    dp[i]=abs(a[i]-a[0])

for i in range(x+1,n):#さいしょのいちから飛べないところからDPを入れる
    min1=10**9
    for j in range(i-(x),i): # 最小を調べる繰り返し
        if min1>dp[j]+abs(a[j]-a[i]):
            min1=dp[j]+abs(a[j]-a[i])#Xの数最小の値を調べる
    dp[i]=min1
print(dp[-1])
"""


"""
Input	                        Output                              Comment
o e a o e a i                   Word found: rose                    Start by taking the first volew "o" and the last consonant "r". They are found in words "rose", "lotus", and "daffodil".
p r s x r	                    Vowels left: o e a i                Then, take "e" and "x". They are found in the word "rose".
                                Consonants left: p r                Then, take "a" and "s". They are found in words "rose", "lotus", and "daffodil".
                                                                    The word "rose" is found, so we print it. Then we print the remaining letters in each sequence.

a a a                           Cannot find any word!
x r l t p p	                    Consonants left: x r l

u a o i u y o e                 Word found: tulip
p m t l	                        Vowels left: u y o e
"""
from collections import deque

vowels = deque(input().split())
consonants = deque(input().split())
words = {"rose": "rose", "tulip": "tulip", "lotus": "lotus", "daffodil": "daffodil"}
found_word = False

while vowels and consonants:
    v = vowels.popleft()
    c = consonants.pop()
    for word in words.keys():
        words[word] = words[word].replace(v, '')
        words[word] = words[word].replace(c, '')
        if words[word] == '':
            print(f"Word found: {word}")
            found_word = True
            break
    if found_word:
        break

if not found_word:
    print("Cannot find any word!")
if vowels:
    print(f"Vowels left: {' '.join(vowels)}")
if consonants:
    print(f"Consonants left: {' '.join(consonants)}")

Python Programming Advanced/Ex_10_Exam Preparation/Ex_10_04 Flower Finder v2.py


#!/usr/bin/env python
# coding=utf-8
import torch
import torch.nn as nn
from torch.jit.annotations import Dict, List, Tuple, Optional
from torch import Tensor

from collections import OrderedDict
import warnings

class GeneralizedRCNN(nn.Module):

    def __init__(self, transform, backbone, rpn, roi_heads):
        super(GeneralizedRCNN, self).__init__()
        self.transform = transform
        self.backbone = backbone
        self.rpn = rpn
        self.roi_heads = roi_heads
        self._has_warned = False
        self.trace_module = False

    @torch.jit.unused
    def eager_outputs(self, losses, detections):
        # type: (Dict[str, Tensor], List[Dict[str, Tensor]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
        if self.training:
            return losses

        return detections

    def forward(self, images, targets=None):
        # type: (List[Tensor], Optional[List[Dict[str, Tensor]]])
        if self.training and targets is None:
            raise ValueError("Targets should be passed during training time")
        original_image_sizes = torch.jit.annotate(List[Tuple[int, int]], [])
        for img in images:
            img_size = img.shape[-2:]
            assert len(img_size) == 2
            original_image_sizes.append((img_size[0], img_size[1]))
        images, targets = self.transform(images, targets)
        features = self.backbone(images.tensors)
        if isinstance(features, Tensor):
            features = OrderedDict([("0", features)])
        proposals, proposal_losses = self.rpn(images, features, targets)
        detections, detector_losses = self.roi_heads(features, proposals,
                                                     images.image_sizes,
                                                     targets)
        detections = self.transform.postprocess(detections,
                                                images.image_sizes,
                                                original_image_sizes)
        losses = {}
        losses.update(detector_losses)
        losses.update(proposal_losses)
        if self.trace_module:
            return detections
        elif torch.jit.is_scripting():
            if not self._has_warned:
                warnings.warn("RCNN always returns a (loss, detections) tuple in scripting")
                self._has_warned = True
            return (losses, detections)
        else:
            return self.eager_outputs(losses, detections)


class Persona:
    def __init__(self, nombre, edad):
        self.nombre = nombre
        self.edad = edad

    def __str__(self):
        return f"Nombre: {self.nombre}, Edad: {self.edad}"

# Crear instancias con edades por debajo de 18
personas = [
    Persona("Juan", 14),
    Persona("María", 16),
    Persona("Carlos", 17),
    Persona("Ana", 15),
    Persona("Pedro", 21),
    Persona("Luisa", 30),
    Persona("Laura", 19),
    Persona("Miguel", 25)
]

menores = filter(lambda persona: persona.edad < 18, personas)

for person in menores:
    print(person)


# longest Peak
"""
A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find length of peak how long it is. If the array contains multiple peaks, return the
longest peak available.

You may imagine that nums[-1] = nums[n] = -∞.
eg - Input: nums = [1,2,3,1]
Output: 4

"""

import math

# O(n) Time Complexity | O(1) Space Complexity
def longestPeak(array):
    longestPeakLength = 0
    i = 1
    while i < len(array)-1:
        isPeak = array[i-1] < array[i] and array[i] > array[i+1]
        if not isPeak:
            i += 1
            continue
        leftIdx = i - 2
        while leftIdx <= 0 and array[leftIdx] < array[leftIdx +1]:
            leftIdx -= 1
        rightIdx = i + 2
        while rightIdx < len(array) and array[rightIdx] < array[rightIdx - 1]:
            rightIdx += 1
        currentLongestPeak = rightIdx - leftIdx - 1
        longestPeakLength = max(longestPeakLength,currentLongestPeak)
        i = rightIdx
    return longestPeakLength

print(longestPeak([1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]))
print(longestPeak([1,2,3,1]))


class NumArray:
    #Using Hash map is quicker than using a cumulative array
    def __init__(self, nums: List[int]):
        self.result={}
        self.result[-1]=0
        sum=0
        for i in range(0,len(nums)):
            sum+=nums[i]
            self.result[i]=sum

    def sumRange(self, i: int, j: int) -> int:
        return self.result[j]-self.result[i-1]

# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)