for person in people:
try:
if person['age'] > 20:
print(person['name'])
except:
print('error')
남용하면 안되고 왠만하면 안쓰는게 좋은게 무슨 오류가 난지 모르고 지나칠 경우가 발생하기에
from 파일이름 import 불러올 함수(*하면 전부 가져오는것)
if문의 3항 연산자 -> 변수 = (true결과물 if 조건 else false결과물)
if num %2 == 0:
result ='짝수'
else:
result = '홀수'
print(f'{num} {result}')
와
result = ('짝수' if num%2 == 0 else '홀수')
같은 결과를 낸다.
for문
리스트2 = []
for 변수 in 리스트1
리스트.append(변수*2)
리스트2 = [변수*2 for 변수 in 리스트1]
리스트1 안에 있는 것을 돌려 a
알고리즘과 친해지기 강의(2)를 듣는데 어려운게 많다.
아스키코드 변환 https://lsjsj92.tistory.com/201
알파뱃은 순서가 정해져있으니 리스트에 순서대로 빈도수만 넣으면 어떤 알파벳의 빈도수인지 알 수 잇음
def find_alphabet_occurrence_array(string):
alphabet_occurrence_array = [0] * 26
for char in string:
if not char.isalpha():
continue
a = ord(char) - ord('a')
alphabet_occurrence_array[a] += 1
return alphabet_occurrence_array
받은 string을 for문으로 돌리면서 char에 넣는다. 이때 if문에서 char.isalpha()를 이용해 알파벳이 아닌것을 거르고 나온 char의 리스트 순서를 정해줘야 하는데 a = ord(char) - ord('a') 알파벳을 아스키코드로 변환 해서 기준이 되는 a를 빼줌으로 리스트 번호를 만들고 비어있는 26개의 리스트에 1씩 더하면서 넣는다.
위의 코드로 문자열의 전체 빈도수를 구했으면 이제 최대 빈도수인 알파벳을 찾아야 한다.
1. 빈도수를 비교해서 최대 빈도수 인것을 구하기
2. 최대 빈도수인 알파벳 출력하기
1과정을 위해 빈도수를 비교해줄 새로운 변수를 생성 max_occurrence(최대발생)
리스트 번호를 저장할 변수를 생성 max_alphabet_index
for문을 통해 1번 구하기->index in range방식으로 사용 - index를 알아야 변환 가능 : index값을 구하기 위해서 range사용
for index in range(len(alphabet_occurrence_array)):
alphabet_occurrence_array의 인덱스를 index라는 변수에 넣음 (비슷한 단어가 많이 중복되서 햇갈릴 수 있음)
for 변수 in range(len(리스트)):
리스트의 인덱스를 변수에 넣는다.
알파벳의 빈도수를 꺼내오기
alphabet_occurrence = alphabet_occurrence_array[index]
#index 0 -> alphabet_occurrence 3 형식으로 저장이됨
드디어 비교하기 한다.
if alphabet_occurrence > max_occurrence:
max_occurrence = alphabet_occurrence
max_alphabet_index = index
return chr(max_alphabet_index + ord('a'))
alphabet_array = [0] * 26
for char in string:
if not char.isalpha():
continue
a = ord(char) - ord('a')
alphabet_array[a] += 1
max_count = 0
max_alphabet_index = 0 #max_alphabet_index는 알파벳 순서
for index in range(len(alphabet_array)):
# index 0 -> alphabet_occurrence 3
alphabet_count = alphabet_array[index] #alphabet_array[index]값은 알파벳 겹치는 숫자 센것
if alphabet_count > max_count:
max_count = alphabet_count
max_alphabet_index = index
return chr(max_alphabet_index + ord('a'))