Last active
April 15, 2019 13:29
-
-
Save DonghoonPark12/cdcc9c214b7ef4088ee1a989b500402b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
RandomCharacter.py | |
from random import randint # randint를 임포트한다. | |
# 랜덤 소문자를 생성한다. | |
def getRandomLowerCaseLetter(): | |
return getRandomCharacter('a', 'z') | |
''' | |
import sys | |
sys.path.append('./') | |
import RandomCharacter as RC | |
cnt = 0 | |
arr = [] | |
print("소문자:") | |
for i in range(100): | |
a = RC.getRandomLowerCaseLetter() | |
arr.append(a) | |
print(a, end=' ') | |
cnt = cnt + 1 | |
if cnt%20 ==0: | |
print() | |
#print(arr) | |
dic = {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0, 'v':0, 'w':0, 'x':0, 'y':0, 'z':0} | |
for j in range(len(arr)): | |
dic[arr[j]] = dic[arr[j]] + 1 | |
#print(dic) | |
print('각 문자의 빈도수는:') | |
for k in sorted(dic.keys()): #정렬한 key 값을 가지고 | |
print(dic[k], k, end=' ') #다시 value를 읽어 들인다. | |
cnt = cnt + 1 | |
if cnt%10 ==0: | |
print() | |
''' | |
출력 결과 | |
소문자: | |
f k p b f h s r y r z m w o a x g b q l | |
b s v d r s u r n n s h n h f r p u x h | |
r i n w b x l v b f t j f k h x n k j n | |
v k j v c m m g n r p d u i y k t l z t | |
t w x k p v p e o w k p v a t d z l t m | |
각 문자의 빈도수는: | |
2 a 5 b 1 c 3 d 1 e 5 f 2 g 5 h 2 i 3 j | |
7 k 4 l 4 m 7 n 2 o 6 p 1 q 7 r 4 s 6 t | |
3 u 6 v 4 w 5 x 2 y 3 z | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
문제 정의 : 랜덤으로 100개의 소문자 알파벳을 생성하고, 빈도수를 찾는다.
해결 방법: dictionary를 만들어서 value 값을 +1 시켜준다.
개선 사항 : O(N)으로 풀 수 있다. 20개씩 출력하기 위해서 처음에
if i%20 == 0 and i>0:
조건을 주었으나, 첫번째가 21개가 출력되고, 이후 20개씩 출력 되었다. i의 인덱스는 0부터 시작되는 반면 위의 코드는 cnt 가 1부터 인덱스가 시작되는 차이가 있어서 결과가 다른 것이었다.알아둘 것
sorted(dic)
와sorted(dic.keys())
는 결과가 동일하다. 하지만 실제 dic(dictionary 자료형)이 정렬된 것은 아니다.sorted_x = sorted(dic)
을 해야 한다. 하지만sorted_x
가 딕셔너리 인것은 아니다. 리스트일 뿐이다.item을 출력하고자 할 때,
key
를 기준으로 정렬하고자 한다면sorted(dic.items(), key=lambda x:x[0])
value
를 기준으로 정렬하고자 한다면sorted(dic.items(), key=lambda x:x[1])
을 수행한다.거꾸로 출력하고자 한다면 sorted(~~~, reverse=True)
Reference