파이썬 두개의 문자열을 비교해서 두개가 같거나 하나만 다른 문자열 구하기
조회수 2427회
q3a(string1, string2)
가 True이려면, string1과 string2의 length가 같고 한 자리만 다른 단어여야 합니다. 예를 들면, q3a("bat", "bet")
은 True, q3a('nat' , 'ant')
은 False가 되어야 합니다.
지금 짠 코드는 여기까진데, string1 or string2가 5자리가 넘어가면 인덱스 에러가 떠서 질문드립니다. 간단한 loop 이외에는 쓸 수 없어요.
def q3a(string1, string2):
index = 0
while index <= len(string1) and len(string2):
if len(string1) == len(string2):
if string1 == string2:
return True
elif string1 != string2:
while index <= len(string1) and len(string2):
if string1[index] == string2[index]:
index = index + 1
if string1[index] != string2[index]:
index = index + 1
if string1[index] == string2[index]:
return True
else:
return False
elif string1[index] != string2[index]:
index = index + 1
if string1[index] == string2[index]:
index = index + 1
return True
elif string1[index] != string2[index]:
return False
index = index + 1
else:
return False
index = index + 1
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
3 답변
-
이런식으로 하면 안되나요?
def question(str_1, str_2): if len(str_1) == len(str_2): count_not_equal = 0 for match_index in range(len(str_1)): if str_1[match_index] == str_2[match_index]: pass else: count_not_equal += 1 if count_not_equal == 1: return True else: return False else: return False
"""
-
내장 함수들은 사용해도 되는가보네요.
아 zip 이라는 함수는
zip('aaa', 'bbb')
할 때[('a', 'b'), ('a', 'b'), ('a', 'b')]
이렇게 묶어주는 겁니다.def q3a(string1, string2): """문자열의 갯수가 같고 각 문자열의 문자 인덱스 비교시 1개 이하로 틀린 경우 True""" return True if len(string1) == len(string2) and [c1 == c2 for c1, c2 in zip(string1, string2)].count(False) < 2 else False print(q3a('ant', 'nat')) # False print(q3a('bat', 'bet')) # True
- zip 함수 없는 버전
def q3a(string1, string2): """문자열의 갯수가 같고 각 문자열의 문자 인덱스 비교시 1개 이하로 틀린 경우 True""" return True if len(string1) == len(string2) and [string1[i] == string2[i] for i in range(len(string1))].count(False) < 2 else False print(q3a('ant', 'nat')) # False print(q3a('bat', 'bet')) # True
-
scala 버전.
scala 도 python 만큼 표현력이 좋습니다.(사실 더 좋습니다.)
def q3a(s1: String, s2: String): Boolean = if ((s1.length == s2.length) && (for (pair_letter <- s1.zip(s2)) yield { pair_letter._1 == pair_letter._2 }).count(_ == false) < 2) true else false q3a("ant", "nat") // false q3a("bat", "bet") // true
댓글 입력