-
2023.7.22.토요일TIL( Today I Learned) 2023. 7. 22. 23:05
7.22
- 문자열 잘라서 정렬하기
문제 설명
문자열 myString이 주어집니다. "x"를 기준으로 해당 문자열을 잘라내 배열을 만든 후 사전순으로 정렬한 배열을 return 하는 solution 함수를 완성해 주세요.
단, 빈 문자열은 반환할 배열에 넣지 않습니다.
myString result "axbxcxdx" ["a","b","c","d"] "dxccxbbbxaaaa" ["aaaa","bbb","cc","d"] def solution(myString):
# Split the string based on "x" and create a list of substrings
substrings = myString.split("x")
# Remove any empty strings from the list
substrings = [substring for substring in substrings if substring != '']
# Sort the list in alphabetical order
substrings.sort()
return substrings
뭐가 다른지 모르겠어
내꺼
def solution(myString):
answer = []
answer = myString.split('x')
answer.remove('')
answer.sort()
return answer
거의 내꺼
def solution(myString):
answer = myString.split('x')
answer.remove('') # Remove empty strings from the list
answer.sort() # Sort the list in alphabetical order
return answer
다른 사람 것
def solution(myString):
return sorted(ch for ch in myString.split('x') if ch)
def solution(myString):
return sorted([i for i in myString.split("x") if len(i)!=0])
def solution(myString):
answer = ' '.join(myString.split('x')).split()
return sorted(answer)
def solution(myString):
return sorted(filter(lambda x : x !="", myString.split('x')))
def solution(myString):
a=[]
for x in myString.split('x'):
if x: a.append(x)
return sorted(a)
def solution(myString):
substrings = myString.split("x")
substrings = [s for s in substrings if s != ""]
substrings.sort()
return substrings
def solution(myString):
return sorted([s for s in myString.split('x') if s != ''])
- 9로 나눈 나머지
문제 설명
음이 아닌 정수를 9로 나눈 나머지는 그 정수의 각 자리 숫자의 합을 9로 나눈 나머지와 같은 것이 알려져 있습니다.
이 사실을 이용하여 음이 아닌 정수가 문자열 number로 주어질 때, 이 정수를 9로 나눈 나머지를 return 하는 solution 함수를 작성해주세요.def solution(number):
answer = 0
for i in number:
j = int(i)%9
answer += j
an1 = answer%9
return an1
def solution(number):
answer = 0
for i in number:
if int(i)%9 == j:
answer += j
return answer. 약간이 오류가 있다 for 를 쓸 필요가 없다
def solution(number):
n=0
for x in number:
n+=int(x)
return n%9
def solution(number):
return sum(list(map(int, number))) % 9
def solution(number):
return int(number) % 9
- 수 조작하기 2
문제 설명
정수 배열 numLog가 주어집니다. 처음에 numLog[0]에서 부터 시작해 "w", "a", "s", "d"로 이루어진 문자열을 입력으로 받아 순서대로 다음과 같은 조작을 했다고 합시다.
- "w" : 수에 1을 더한다.
- "s" : 수에 1을 뺀다.
- "d" : 수에 10을 더한다.
- "a" : 수에 10을 뺀다.
그리고 매번 조작을 할 때마다 결괏값을 기록한 정수 배열이 numLog입니다. 즉, numLog[i]는 numLog[0]로부터 총 i번의 조작을 가한 결과가 저장되어 있습니다.
주어진 정수 배열 numLog에 대해 조작을 위해 입력받은 문자열을 return 하는 solution 함수를 완성해 주세요.
def solution(numLog):
answer = ''
current_number =numLog[0]
for i in range(1 , len(numLog)):
diff = numLog[i]-numLog[i-1]
if diff == 1:
answer += 'w'
current_number += 1
elif diff == -1:
answer += 's'
current_number +=-1
elif diff ==10:
answer += 'd'
current_number +=10
elif diff ==-10:
answer += 'a'
current_number -= -10
return answer
def solution(log):
res=''
joystick=dict(zip([1,-1,10,-10],['w','s','d','a']))
for i in range(1,len(log)):
res+=joystick[log[i]-log[i-1]]
return res
- 등차수열의 특정한 항만 더하기
문제 설명
두 정수 a, d와 길이가 n인 boolean 배열 included가 주어집니다. 첫째항이 a, 공차가 d인 등차수열에서 included[i]가 i + 1항을 의미할 때, 이 등차수열의 1항부터 n항까지 included가 true인 항들만 더한 값을 return 하는 solution 함수를 작성해 주세요.
def sum_of_arithmetic_sequence(a, d, included):
n = len(included)
sequence_sum = 0
for i in range(n):
if included[i]:
term = a + (i * d)
sequence_sum += term
return sequence_sum
def solution(a, d, included):
# 등차수열의 특정한 항만 더하기
# a: 첫째항
# d: 공차
# included: boolean 배열
# 반환값: true인 항들만 더한 값
result = 0
for i in range(len(included)):
if included[i]:
result += a + (i * d)
return result
def solution(a, d, included):
# 등차수열의 특정한 항만 더하기
# a: 첫째항
# d: 공차
# included: boolean 배열
# 반환값: true인 항들만 더한 값
result = 0
for i in range(len(included)):
if included[i]:
result += a + ((included.index(True, i) - i) * d)
return result
def solution(a, d, included):
answer = 0
for i in range(len(included)):
answer += (a + d * i) * int(included[i])
return answer
물론! 주어진 함수 solution(a, d, included)에서 * int(included[i]) 표현은 산술 수열 항인 (a + d * i)을 included[i]의 값에 따라 0 또는 1로 곱하는 것을 의미합니다.
단계별로 설명하겠습니다:
- a는 산술 수열의 첫 번째 항입니다.
- d는 연속하는 항들 사이의 공차(common difference)입니다.
- included는 0 또는 1의 이진 값들을 가진 리스트입니다. 여기서 included[i]는 산술 수열에서 인덱스 i의 항이 계산에 포함되는지 여부를 나타냅니다.
이제 (a + d * i) * int(included[i]) 표현을 살펴봅시다:
- (a + d * i)는 산술 수열의 i번째 항의 값을 계산합니다.
- int(included[i])는 included[i]의 이진 값을 정수로 변환합니다. 이 단계는 파이썬에서 True와 False를 각각 1과 0으로 암묵적으로 변환하기 때문에 필요합니다.
(a + d * i)를 int(included[i])와 곱하는 목적은 included[i]의 값에 따라 합에 항을 포함하거나 제외하기 위함입니다. included[i]가 1일 때, 해당 항은 포함됩니다(값이 합에 더해짐). 그리고 included[i]가 0일 때, 해당 항은 제외됩니다(값이 0으로 곱해져서 합에 기여하지 않음).
따라서, 함수 solution은 산술 수열의 합을 계산하되, included[i]의 값이 1인 항들만 포함하여 합을 구합니다. 다른 항들은 계산에 전혀 기여하지 않습니다.
쳇도 틀린다는 거 명심
d included result
3 4 [true, false, false, true, true] 37 Included 참인 값은 0,3,4
코드에서 `(included.index(True, i) - i)`는 `i` 이후에 처음으로 나타나는 `True` 값의 인덱스에서 `i`를 빼서 해당하는 항의 번호를 구합니다. 이것을 예시를 통해 설명해보겠습니다.
예를 들어, `included` 배열이 `[False, True, False, True, True]~~~ 1,3`이고, `i`가 `1`일 때를 가정해봅시다. 이 경우, `included[1]`은 `True`이므로 해당하는 등차수열에서 2항을 의미합니다. 따라서, `a + (1 * d)`를 계산해야 합니다. 이때, `(included.index(True, i) - i)`는 `(3 - 1)`이므로, 2항을 의미하는 값인 `1`이 반환됩니다.
즉, `(included.index(True, i) - i)`는 `i` 이후에 처음으로 등장하는 `True` 값의 인덱스와 `i`의 차이를 구해서, 해당하는 등차수열에서의 항 번호(`i+1`)를 구하는 것입니다.
- 날짜 비교하기
문제 설명
정수 배열 date1과 date2가 주어집니다. 두 배열은 각각 날짜를 나타내며 [year, month, day] 꼴로 주어집니다. 각 배열에서 year는 연도를, month는 월을, day는 날짜를 나타냅니다.
만약 date1이 date2보다 앞서는 날짜라면 1을, 아니면 0을 return 하는 solution 함수를 완성해 주세요.
def solution(date1, date2):
answer = 0
if date1[0]< date2[0]:
answer = 1
elif (date1[0]== date2[0]) and (date1[1] <date2[1]):
answer =1
elif (date1[0]== date2[0]) and (date1[1]==date2[1]) and (date1[2]<date2[2]):
answer =1
else:
answer =0
return answer
def solution(date1, date2):
return int(date1 < date2)
def solution(date1, date2):
answer = 0
a=int(str(date1[0])+str(date1[1])+str(date1[2]))
b=int(str(date2[0])+str(date2[1])+str(date2[2]))
if a<b:
answer+=1
else:
answer+=0
return answer
'TIL( Today I Learned)' 카테고리의 다른 글
2023.7.24.월요일. 100개 (0) 2023.07.24 2023.7.23.일요일 D-8, "Forward, 8 days left" 96 to ? (0) 2023.07.23 2023.7.21.금요일 (0) 2023.07.21 2023.7.20.목요일 (0) 2023.07.20 2023.7.19 (0) 2023.07.19