Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

목록에서 양수와 음수를 계산하는 Python 프로그램


이 기사에서는 주어진 문제 설명을 해결하기 위한 솔루션과 접근 방식에 대해 알아볼 것입니다.

문제 설명

목록 iterable이 주어지면 iterable에서 사용 가능한 모든 양수와 음수를 계산해야 합니다.

그녀는 두 가지 접근 방식에 대해 논의할 것입니다 -

  • 무차별 대입 접근
  • 람다 인라인 함수 사용

접근법 1 - 무차별 대입 방식

예시

list1 = [1,-9,15,-16,13]
pos_count, neg_count = 0, 0
for num in list1:
   if num >= 0:
      pos_count += 1
   else:
      neg_count += 1
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)

출력

Positive numbers : 3
Negative numbers : 2

접근법 2 - 람다 및 필터 기능 사용

예시

list1 = [1,-9,15,-16,13]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)

출력

Positive numbers : 3
Negative numbers : 2

결론

이 기사에서는 목록에서 양수 및 음수를 계산하는 접근 방식에 대해 배웠습니다.