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.
▼sample input
python
s=[1,2,1,1,3,2]
d,m=3,2
▼sample output
python
2

▼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()
·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)
▼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