[python ๊ธฐ์ดˆ] code-kata week1-4

EMMAยท2022๋…„ 3์›” 17์ผ
0

[wecode] Code-kata

๋ชฉ๋ก ๋ณด๊ธฐ
4/12

๐Ÿ–ฅ Code-kata week1-4


๋ฌธ์ œ

์ˆซ์ž์ธ num์„ ์ธ์ž๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด, ๋’ค์ง‘์€ ๋ชจ์–‘์ด num๊ณผ ๋˜‘๊ฐ™์€์ง€ ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.

num: ์ˆซ์ž
return: true or false (๋’ค์ง‘์€ ๋ชจ์–‘์ด num์™€ ๋˜‘๊ฐ™์€์ง€ ์—ฌ๋ถ€)
num: ์ˆซ์ž
return: true or false (๋’ค์ง‘์€ ๋ชจ์–‘์ด num์™€ ๋˜‘๊ฐ™์€์ง€ ์—ฌ๋ถ€)
์˜ˆ๋ฅผ ๋“ค์–ด,

num = 123
return false => ๋’ค์ง‘์€ ๋ชจ์–‘์ด 321 ์ด๊ธฐ ๋•Œ๋ฌธ
num = 1221
return true => ๋’ค์ง‘์€ ๋ชจ์–‘์ด 1221 ์ด๊ธฐ ๋•Œ๋ฌธ
num = -121
return false => ๋’ค์ง‘์€ ๋ชจ์–‘์ด 121- ์ด๊ธฐ ๋•Œ๋ฌธ
num = 10
return false => ๋’ค์ง‘์€ ๋ชจ์–‘์ด 01 ์ด๊ธฐ ๋•Œ๋ฌธ


ํ’€์ด

๋จผ์ €, ์Œ์ˆ˜์˜ ๊ฒฝ์šฐ์—๋„ ๊ทธ๋Œ€๋กœ ์—ญ์ˆœํ•ด์ค˜์•ผ ํ•˜๋ฏ€๋กœ int > str๋กœ ๋ฐ”๊ฟ”์„œ ๋น„๊ตํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค.
1) ๋ฐ›์€ ์ธ์ž num์„ ๋ณ€์ˆ˜์— ๋‹ด์•„์„œ strํ™” ํ•ด์ฃผ๊ณ ,
2) ๋‹ค์‹œnum์„ strํ™” ํ•˜๊ณ  ์—ญ์ˆœ์‹œ์ผœ ๋‹ค๋ฅธ ๋ณ€์ˆ˜์— ๋‹ด์•„์ค€๋‹ค.
3) 2๊ฐœ๋ฅผ ๋น„๊ตํ•ด์„œ ๊ฐ™์œผ๋ฉด true, ๋‹ค๋ฅด๋ฉด false ์ถœ๋ ฅ

def same_reverse(num):
	reverse_num = str(num)
    reverse_num.reverse()

ํ•˜์ง€๋งŒ reverse()๋Š” iterableํ•œ ํ˜•ํƒœ์—๋งŒ ์ ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
๊ทธ๋ž˜์„œ list๋ฅผ ์ž…ํžˆ๊ณ  reverse ์ ์šฉํ•ด์ค€ ๋‹ค์Œ, ๋ณ€์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ˜•ํƒœ๋กœ ๊ฐ€์•ผ ํ•œ๋‹ค.

a = str(1234)
x = list(a)
x.reverse()	#reverse๋Š” ์—ญ์ˆœ์˜ ์ƒํƒœ๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š” ๊ฒƒ(return๊ฐ’: none)
print(x)

๊ทธ๋ž˜์„œ slicing ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฐ”๊ฟ”์„œ ์ž‘์„ฑํ•˜๋ฉด ํ•œ ์ค„๋กœ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•˜๋‹ค.

  • slicing ์‚ฌ์šฉํ•˜๋ฉด ๋ฐ”๋กœ ์—ญ์ˆœ ๊ฐ€๋Šฅ -> [::-1]
  • ๋”ฐ๋กœ if๋ฌธ ์ž‘์„ฑํ•  ํ•„์š” ์—†์ด, return์— ์ž‘์„ฑํ•˜๋ฉด ๋จ
def same_reverse(num):
	return str(num) == str(num)[::-1]
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

0๊ฐœ์˜ ๋Œ“๊ธ€