๐ŸŒฑ → ๐ŸŒณ

[๋ฐฑ์ค€] 2750, 2751 - ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 1,2 python ๋ณธ๋ฌธ

Algorithms

[๋ฐฑ์ค€] 2750, 2751 - ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 1,2 python

BAY 2022. 10. 2. 12:26
728x90

2750 - ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ

์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(n²)์ธ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ex) ์‚ฝ์ž… ์ •๋ ฌ, ๋ฒ„๋ธ” ์ •๋ ฌ

a = int(input())
arr = []
for i in range(a):
  arr.append(int(input()))

arr = sorted(arr)
for i in range(len(arr)):
  print(arr[i])

 

2751 - ์ˆ˜ ์ •๋ ฌํ•˜๊ธฐ 2

์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(nlogn)์ธ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ex) ๋ณ‘ํ•ฉ ์ •๋ ฌ, ํž™ ์ •๋ ฌ ๋“ฑ

์•„์ง ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋ฐฐ์šฐ์ง€ ์•Š์€ ์ƒํƒœ์ด๋ฏ€๋กœ ๋‚ด์žฅ ํ•จ์ˆ˜ ์‚ฌ์šฉ

→ import sys๋ฅผ ํ•˜์—ฌ input()์˜ ์‹œ๊ฐ„์„ ์ค„์˜€์Œ

import sys

a = int(input())
num = []
for i in range(a):
  num.append(int(sys.stdin.readline()))
num.sort()
for i in num:
  print(i)

 

 

[ Python ] sort(), sorted() ์ฐจ์ด

โœ… sort ํ•จ์ˆ˜

: ๋ฆฌ์ŠคํŠธ๋ช….sort( ) ํ˜•์‹์œผ๋กœ "๋ฆฌ์ŠคํŠธํ˜•์˜ ๋ฉ”์†Œ๋“œ"์ด๋ฉฐ ๋ฆฌ์ŠคํŠธ ์›๋ณธ๊ฐ’์„ ์ง์ ‘ ์ˆ˜์ •

โœ… sorted ํ•จ์ˆ˜

: sorted( ๋ฆฌ์ŠคํŠธ๋ช… ) ํ˜•์‹์œผ๋กœ "๋‚ด์žฅ ํ•จ์ˆ˜"์ด๋ฉฐ ๋ฆฌ์ŠคํŠธ ์›๋ณธ ๊ฐ’์€ ๊ทธ๋Œ€๋กœ์ด๊ณ  ์ •๋ ฌ ๊ฐ’์„ ๋ฐ˜ํ™˜

 

์‹ค์Šต ์˜ˆ์ œ )

โœ”๏ธ sort ํ•จ์ˆ˜

a1 = [6, 3, 9]
print('a1:', a1)
a2 = a1.sort() # ์›๋ณธ์„ ์ •๋ ฌํ•˜๊ณ  ์ˆ˜์ •ํ•ฉ๋‹ˆ๋‹ค(in-place)
print('-----์ •๋ ฌ ํ›„-----')
print('a1:', a1)
print('a2:', a2)
a1: [6, 3, 9]
-----์ •๋ ฌ ํ›„-----
a1: [3, 6, 9]
a2: None

 

โœ”๏ธ sorted ํ•จ์ˆ˜

b1 = [6, 3, 9]
print('b1:', b1)
b2 = sorted(b1) # ์›๋ณธ์€ ์œ ์ง€ํ•˜๊ณ  ์ •๋ ฌํ•œ ์ƒˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค
print('-----์ •๋ ฌ ํ›„-----')
print('b1:', b1)
print('b2:', b2)
b1: [6, 3, 9]
-----์ •๋ ฌ ํ›„-----
b1: [6, 3, 9]
b2: [3, 6, 9]

์›๋ณธ ๋ฆฌ์ŠคํŠธ b1 ๊ฐ’์€ ์œ ์ง€๋˜๊ณ  ์ •๋ ฌ๋œ ์ƒˆ ๋ฆฌ์ŠคํŠธ๋Š” b2์— ์ €์žฅ๋จ

728x90