[Python] A program that calculates the number of chocolate segments that meet the conditions

[Python] A program that calculates the number of chocolate segments that meet the conditions

This is a memo for myself.

▼ Question

--A list containing positive integers is given. (s) ――Each index represents a block of chocolate bar. --Let Ron's birthday be d and the month of birth be m. --Calculate the number of chocolate split patterns where the total number of blocks satisfies d with the number of blocks m. --The blocks must be continuous.

URL

▼sample input

python


s=[1,2,1,1,3,2]
d,m=3,2

▼sample output

python


2

image.png

▼my answer

python


def birthday(s, d, m): 
    ans = 0
    
    #Make a combination for each specified number of blocks.
    blocks = [s[i:i+m] for i in range(len(s)-0)]

    for block in blocks:
        if len(block)==m and sum(block)==d:
            ans += 1
    return ans  

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    n = int(input().strip())
    s = list(map(int, input().rstrip().split()))
    dm = input().rstrip().split()
    d = int(dm[0])
    m = int(dm[1])
    result = birthday(s, d, m)
    fptr.write(str(result) + '\n')
    fptr.close()

** ・ Inclusive notation ** A simple way to write a for statement. `Expression for variable in iterable` * Iterable: An object that contains consecutive values such as list, set, and renge.

·slice Iterable [Initial value: End value: Step]

python


s=[1,2,1,1,3,2]
print(s[0:2])
print(s[1:4])

#
[1, 2]
[2, 1, 1]

[Click here for slice details](https://qiita.com/yuta-38/items/0d5c55b748d10f83af53#5-abc%E9%96%8B%E5%A7%8B%E7%B5%82%E4%BA% 86% E5% A4% 89% E5% 8C% 96% E9% 87% 8F% E3% 82% 92% E6% 8C% 87% E5% AE% 9A)


## Let's make it simpler by using a single if statement.

▼my answer(simpler)

python


def birthday(s, d, m): 
    blocks = [s[i:i+m] for i in range(len(s)-0)]
    return sum([(1 if len(block)==m and sum(block)==d else 0) for block in blocks])

Expression (True) if conditional expression else expression (False) ↓ "1 if conditional expression else 0" Returns 1 if true, 0 if false.

Recommended Posts

[Python] A program that calculates the number of chocolate segments that meet the conditions
[Python] A program that counts the number of valleys
[Python] A program that calculates the number of socks to be paired
[Python] A program that calculates the number of updates of the highest and lowest records
[Python] A program that compares the positions of kangaroos.
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Python] A program that rounds the score
[Python] A program that rotates the contents of the list to the left
[Python] A program to find the number of apples and oranges that can be harvested
[Python] A program that finds the maximum number of toys that can be purchased with your money
[Python] A program that calculates the difference between the total numbers on the diagonal line.
A python script that gets the number of jobs for a specified condition from indeed.com
A program that summarizes the transaction history csv data of SBI SECURITIES stocks [Python3]
Get the number of specific elements in a python list
[Python] A program that finds the most common bird types
A Python script that compares the contents of two directories
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
The story of writing a program
A formula that simply calculates the age from the date of birth
A story that struggled to handle the Python package of PocketSphinx
A function that measures the processing time of a method in python
[Ev3dev] Create a program that captures the LCD (screen) using python
A program that determines whether a number entered in Python is a prime number
A script that returns 0, 1 attached to the first Python prime number
I made a program that automatically calculates the zodiac with tkinter
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of making a module that skips mail with python
Get the number of readers of a treatise on Mendeley in Python
Create a compatibility judgment program with the random module of python.
[python] [meta] Is the type of python a type?
Set the process name of the Python program
The story of blackjack A processing (python)
A program that plays rock-paper-scissors using Python
Get the number of searches with a regular expression. SeleniumBasic VBA Python
Extract lines that match the conditions from a text file with python
Check the in-memory bytes of a floating point number float in Python
The eval () function that calculates a string as an expression in python
I made a program to check the size of a file in Python
From a book that makes the programmer's way of thinking interesting (Python)
[Python] Note: A self-made function that finds the area of the normal distribution
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
Output the number of CPU cores in Python
Delete vertices that meet the conditions in networkx
Get the caller of a function in Python
Calculate the total number of combinations with python
A program that removes duplicate statements in Python
Around the authentication of PyDrive2, a package that operates Google Drive with Python
Make a copy of the list in Python
Publish a Python module that calculates meteorological factors
Find the number of days in a month
A program that searches for the same image
A note about the python version of python virtualenv
Create a BOT that displays the number of infected people in the new corona
[Python] A program that finds the minimum and maximum values without using methods
[Python] A rough understanding of the logging module
Output in the form of a python array
A program that sends a fixed amount of mail at a specified time by Python
A discussion of the strengths and weaknesses of Python
A shell program that displays the Fibonacci sequence
A python script that generates a sample dataset for checking the operation of a classification tree
A program that notifies slack of the operating status of fully automatic botanical photography equipment