본문 바로가기

알고리즘/해커랭크

Apple and Orange

문제

https://www.hackerrank.com/challenges/apple-and-orange/problem

문제가 너무 길어서 당황했지만 그냥 주어진 숫자를 더해서 범위내에 있는지 확인해서 출력하는 문제

 

입력

범위 시작, 끝

사과나무 오렌지나무 위치

각각 사과 오렌지나무에서 떨어진 과일 갯수

사과가 사과나무로부터 떨어진 거리 음수일경우 왼쪽 양수일경우 오른쪽

오렌지가 오렌지나무로부터 각각 떨어진 거리 음수, 양수 마찬가지

 

출력

범위시작 끝 사이에 떨어진 사과 수

범위시작 끝 사이에 떨어진 오렌지 수

 

입력 예

7 11
5 15
3 2
-2 2 1
5 -6

 출력 예

1
1

제출한 코드

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
    print(len([x for x in apples if x+a >= s and x+a <= t]))
    print(len([y for y in oranges if y+b >= s and y+b <= t]))
    
if __name__ == '__main__':
    st = input().split()

    s = int(st[0])

    t = int(st[1])

    ab = input().split()

    a = int(ab[0])

    b = int(ab[1])

    mn = input().split()

    m = int(mn[0])

    n = int(mn[1])

    apples = list(map(int, input().rstrip().split()))

    oranges = list(map(int, input().rstrip().split()))

    countApplesAndOranges(s, t, a, b, apples, oranges)

 

이렇게 하는 방법도 있다 (discussion)

len말고 sum으로 해도 되겠구나

print(sum([1 for x in apple if (x + a) >= s and (x + a) <= t]))
print(sum([1 for x in orange if (x + b) >= s and (x + b) <= t]))

'알고리즘 > 해커랭크' 카테고리의 다른 글

Between Two Sets  (0) 2020.03.07
Kangaroo  (0) 2020.03.06
Grading Students (python3)  (0) 2020.02.29
Loops (python3)  (0) 2020.02.27
Python If-Else Discussions  (0) 2020.02.27