Skip to content

Instantly share code, notes, and snippets.

@16Yongjin
Created September 9, 2018 11:53
Show Gist options
  • Save 16Yongjin/d31a439ab0e70147c7f0007c72eff3ea to your computer and use it in GitHub Desktop.
Save 16Yongjin/d31a439ab0e70147c7f0007c72eff3ea to your computer and use it in GitHub Desktop.
import re
"""
1. 문자열에서 모든 중복 단어를 제거하고 단일 단어 항목만 남기세요.
예시:
입력:
'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
출력:
'alpha beta gamma delta'
"""
def remove_duplicate(s):
s = s.split(' ')
return ' '.join(sorted(set(s), key=s.index))
s1 = 'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
assert remove_duplicate(s1) == 'alpha beta gamma delta', '1번 땡'
"""
2. 문자열에서 연속된 모든 중복 단어를 제거하고, 첫 단어 항목만 남기세요.
예시:
입력:
'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
출력:
'alpha beta gamma delta alpha beta gamma delta'
"""
def remove_consecutive_duplicate(s):
s = s.split(' ')
res = []
for i in s:
if len(res) == 0 or res[-1] != i:
res.append(i)
return ' '.join(res)
s2 = 'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
assert remove_consecutive_duplicate(s2) == 'alpha beta gamma delta alpha beta gamma delta', '2번 땡'
"""
3. 주어진 문자열이 모두 숫자로만 되있는지 확인하세요. (정규식 사용해보세요.)
"""
def is_number(s):
return bool(re.compile('^\d+$').match(s))
assert is_number('123432') == True, '3번 땡'
assert is_number('a132') == False, '3번 땡'
"""
4. 주어진 문자열이 모두 한글만 이루어져있는지 확인하세요.
입력: 가나다
출력: True
입력: a가나
출력: False
"""
def is_hangul(s):
return bool(re.compile('^[ㄱ-ㅎㅏ-ㅣ가-힣]+$').match(s))
assert is_hangul('가나다') == True, '4번 땡'
assert is_hangul('a가나') == False, '4번 땡'
"""
5. 리스트를 flat하게 만드세요.
입력: [[1, 2], [3, 4], [5, 6]]
출력: [1, 2, 3, 4, 5, 6]
"""
def flatten(l):
return sum(l, [])
assert flatten([[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6], '5번 땡'
assert flatten([]) == [], '5번 땡'
"""
6. .과 |로 문자열을 나누세요. (정규식 사용하세요)
입력: 'a.b|ca|b.b|a'
출력: [ 'a', 'b', 'ca', 'b', 'b', 'a' ]
"""
def split_dot_pipe(s):
return re.compile('\.|\|').split(s)
assert split_dot_pipe('a.b|ca|b.b|a') == [ 'a', 'b', 'ca', 'b', 'b', 'a' ], '6번 땡'
"""
7. 차집합. 뒤 리스트에 있는 값들이 앞 리스트에 없도록 만드세요.
입력: [1, 2, 3, 1, 3, 5, 6, 6, 6, 6, 7], [1, 3, 4, 2]
출력: [5, 6, 6, 6, 6, 7]
"""
def diff(a, b):
return [i for i in a if not i in b]
assert diff([1, 2, 3, 1, 3, 5, 6, 6, 6, 6, 7], [1, 3, 4, 2]) == [5, 6, 6, 6, 6, 7], '7번 땡'
"""
8. 리스트에 있는 값들을 빈도 순으로 정렬하세요. (Counter 쓰지 않고 풀어보세요.)
입력: [2, 7, 8, 3, 4, 1, 3, 2, 2, 9, 5, 4, 6, 7, 4, 9, 2, 3, 2, 3, 8, 8, 3, 4, 2, 5, 8, 9, 8, 9]
출력: {2: 6, 8: 5, 3: 5, 4: 4, 9: 4, 7: 2, 5: 2, 1: 1, 6: 1}
"""
def sorted_freq(l):
count = {}
for i in l:
count[i] = (count.get(i) or 0) + 1
return dict(sorted(list(count.items()), key=lambda x: x[1], reverse=True))
l1 = [2, 7, 8, 3, 4, 1, 3, 2, 2, 9, 5, 4, 6, 7, 4, 9, 2, 3, 2, 3, 8, 8, 3, 4, 2, 5, 8, 9, 8, 9]
res1 = [(2, 6), (8, 5), (3, 5), (4, 4), (9, 4), (7, 2), (5, 2), (1, 1), (6, 1)]
assert list(sorted_freq(l1).items()) == res1, '8번 땡'
"""
9. 아래 xml 포맷의 문자열을 라이브러리를 사용해서 파싱하고 title, text 속성을 가져와서 문자열 리스트로 변환하세요. [[title, text], [title, text], ...] 형식
10. 울고있는(ㅜ, ㅠ 2개 이상) 글의 개수를 세보세요.
"""
xml = """
<response>
<moim id="370454" name="서울캠 자유게시판" info="" picture="" type="2" layout="21" priv_anonym="0" priv_comment_anonym="0" is_primary="1" is_schoolcommunity="1" is_secret="0" is_manageable="0" is_searchable="1" is_member="0" join_to_write="0" join_to_comment="0" auth_to_write="0" auth_to_comment="0" placeholder="여기를 눌러서 글을 작성할 수 있습니다. &lt;br />아래 내용을 모두 지켜서 깨끗한 에브리타임을 만들어주세요 :) &lt;br />&lt;br />[정보통신망법에 의한 홍보 게시물 작성 금지] &lt;br />1. 쇼핑몰, 오픈마켓, 소셜커머스 등 홍보 &lt;br />2. 광고가 있는 카페, 블로그, 커뮤니티, 앱의 추천, 홍보, 방문 유도 등 &lt;br />3. 토익, 한자 등 어학원 &lt;br />4. 연극, 영화 티켓 할인 서비스 &lt;br />5. 안과, 치과, 피부과 등 의료업체 &lt;br />&lt;br />[커뮤니티 이용규칙에 어긋나는 행위 금지] &lt;br />1. 비밀게시판 등 인증 후 사용할 수 있는 게시판의 스크린샷, 게시물 내용 유출 &lt;br />2. 욕설, 비하, 음란물, 개인정보가 포함된 게시물 게시 &lt;br />3. 특정인이나 단체/지역을 비방하는 행위 &lt;br />4. 기타 현행법에 어긋나는 행위 &lt;br />&lt;br />자세한 내용은 홈화면 상단 [내 정보]의 [커뮤니티 이용규칙]을 참고하시기 바랍니다." is_quick="0" is_accessible="1" is_readable="1" is_commentable="1" is_writable="1"/>
<hashtags/>
<article id="52069286" is_mine="0" title="중국경서의이해" text="발표있나요?? ㅠㅠ 제발 ㅠㅠㅠㅠ" created_at="2018-09-05 13:42:58" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52069174" is_mine="0" title="히브리어" text="히브리어의 이해랑 국제사회와국제구 화 56이나 스포츠글로벌문화 화 56이랑 교환하실분 .. 제가 히브리어입ㄴ다.." created_at="2018-09-05 13:41:43" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52069066" is_mine="0" title="금융기관론 교재 필요한가요?ㅜㅠ" text="알려주세용" created_at="2018-09-05 13:40:44" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52069049" is_mine="0" title="경영정보학개론 김용석교수님 ot들으신분" text="OT때 뭐라고 하셨나요..? 자리나서 잡았는데 궁금해요ㅜㅜ" created_at="2018-09-05 13:40:34" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068844" is_mine="0" title="범죄와 형벌2 버리실분 계신가요" text="ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ살려주세요" created_at="2018-09-05 13:38:25" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068770" is_mine="0" title="외대 WBC" text="이번 학기는 제발 하면 안되나요?? 매년 전통이었는데 15년도 이후로 안하더라고요... 축구는 월드컵부터 시작해서 아시안컵 삼건물 유로파도 하는" created_at="2018-09-05 13:37:50" posvote="0" comment="1" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068687" is_mine="0" title="이번에 불어 기욤 들으시는 분들" text="이번에 교재 tendance쓰나요 아니면 a propos쓰나요? 답변해주시면 장말 감사합니다ㅜㅜㅜ ㅜ" created_at="2018-09-05 13:37:11" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068556" is_mine="0" title="수12 거래와 계약의 이해 오티 들으신 분" text="좀 전에 잡아서 그런데 혹시 오티 때 뭐하셨나요..?" created_at="2018-09-05 13:35:51" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068518" is_mine="0" title="논리학입문이랑 추리논증 김신 교수님" text="오티 첫날부터 풀강하시나여" created_at="2018-09-05 13:35:28" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068365" is_mine="0" title="중국고전문학사(2) 수 34" text="오티 가신분.. 내용좀 알려주세요 ㅠㅠ 교제나 수업방식 발표여부 좀요 ㅠㅠ" created_at="2018-09-05 13:33:59" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068284" is_mine="0" title="중급베트남어회화" text="중급베트남어회화 교재 이거 2권 맞나요?" created_at="2018-09-05 13:33:05" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png">
<attach filename="everytime-1536121979229.jpg" filesize="307950" id="9562375" fileurl="https://cf-ea.everytime.kr/attach_thumbnail/335/9562375/everytime-1536121979229.jpg?Expires=1536122885&amp;Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9jZi1lYS5ldmVyeXRpbWUua3IvYXR0YWNoX3RodW1ibmFpbC8zMzUvOTU2MjM3NS9ldmVyeXRpbWUtMTUzNjEyMTk3OTIyOS5qcGciLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE1MzYxMjI4ODV9fX1dfQ__&amp;Signature=nMMnfQPcYMl~Tdpydmc6NCfFlCLf0vLdxCI6N~bIJliLuAqHAgB5rZDwKNCm7s89zUg81JdbnbidcwPEXDEyzu5tcnGAjnLYeEWswNK1rBTp~aDS4MLhdWQvbL082jzg-6s9bUEBMHhURmK45~-t63VIq4F~S9jRIIpkV2VaW9TI8xvr-uXTDGDR~5ATpoToPgmgPPJNkaNHRI-J0inBowIyhOXhtVHIt2Vm-qLHYJUQV5Kh1n3~ylQXmlCatn7vPMnuRjMaKCIT4xbGN4cu5YvHPOKxddeJ73Xy9pEtznrZpll~f-I7fDYhNH9WsvTH2wiqIbv1F1QbMl7oE5oelw__&amp;Key-Pair-Id=APKAICU6XZKH23IGASFA" isThumb="1"/>
</article>
<article id="52068271" is_mine="0" title="월 789 파생 필요하신분?" text="~_&amp;lt;" created_at="2018-09-05 13:32:58" posvote="0" comment="1" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068218" is_mine="0" title="중국학개론" text="최은경교수님오티내용머있었나요??ㅠㅠ" created_at="2018-09-05 13:32:28" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068215" is_mine="0" title="정경원 중문사&amp;lt;->김현철 스문사 교환" text="제가 중남미" created_at="2018-09-05 13:32:27" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068201" is_mine="0" title="교양중국어 신세리교수님" text="화요일날 오티를 못갔는데 무슨 말씀하셨나요?? 혹시 수업나가셨나요..? 답변 부탁드려요! ㅠㅜ" created_at="2018-09-05 13:32:20" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068095" is_mine="0" title="현정건 책 팔아요" text="현정건 책 팔아요 쪽지주세요" created_at="2018-09-05 13:31:28" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52068043" is_mine="0" title="국통 과사무실이 민희철교수님 학과장실 맞나요??" text="ㅈㄱㄴ" created_at="2018-09-05 13:30:53" posvote="0" comment="1" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52067986" is_mine="0" title="남유럽문화의이해" text="방금 주웠는데 혹시 오티 들어보신분 계신가요" created_at="2018-09-05 13:30:22" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52067978" is_mine="0" title="경영 증원" text="이거 진짜 서명운동이라도 하면 안되냐 돈 안내는 것도 아니고 낼거 다 내고 내가 듣고싶은거 듣게 해달라는데 시바 왜 안해줘 ㅡㅡ" created_at="2018-09-05 13:30:17" posvote="1" comment="1" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
<article id="52067954" is_mine="0" title="인자관 오승희 제발 저 주세요ㅠㅠㅠㅠ" text="사례할게요ㅠㅠㅠㅠ" created_at="2018-09-05 13:30:04" posvote="0" comment="0" comment_anonym="0" scrap_count="0" user_type="" user_id="0" user_nickname="익명" user_picture="https://cf-fpi.everytime.kr/0.png"/>
</response>
"""
from xml.etree import ElementTree
def parse_article(xml):
root = ElementTree.fromstring(xml)
articles = [[article.attrib['title'], article.attrib['text']] for article in root.findall('article')] # 각 게시물의 id 가져오기
return articles
def countTears(articles):
tear = re.compile('[ㅜㅠ]{2,}')
return len([1 for article in articles if tear.search(''.join(article))])
print(countTears(articles)) # 9개
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment