대문자 → 소문자, 소문자 → 대문자
str = input()
str = str.swapcase()
str = input()
a = ""
for i in str:
if i.isupper():
a = a + i.lower()
else:
a = a + i.upper()
print(a)
일부 특수문자 출력
작은따옴표('), 큰따옴표(") 같은 경우 백슬래시(\)를 활용 ex) \'\"
print("!@#$%^&*(\\'\"<>?:;)")
양쪽 공백 제거, 개행문자(\n) 제거
s = " Hello World "
s = s.strip() # 양쪽 공백 제거
print(s)
홀짝구분
a = int(input())
if a % 2 == 0:
print(f"{a} is even")
else:
print(f"{a} is odd")
임의의 수 다섯개를 배열에 저장하고 한 줄에 하나씩 출력
from array import *
import random
num = array("i", [])
for i in range(0, 5):
random_num = random.randint(1, 100)
num.append(random_num)
for i in num:
print(i)
두 배열 합치기
from array import *
import random
ary1 = array("i", [])
ary2 = array("i", [])
for i in range(0, 3):
add_ary1 = int(input("Add ary1 : "))
ary1.append(add_ary1)
for x in range(0, 5):
random_num = random.randint(1, 100)
ary2.append(random_num)
ary1.extend(ary2)
ary1 = sorted(ary1)
for a in ary1:
print(a)
실수 반올림
pi = 3.14159265359
rounded_pi = round(pi, 2)
print(rounded_pi) # 3.14
특정 배열값 제거 후 새로운 배열에 저장
from array import *
nums = array("i", [])
for i in range(0, 5):
num = int(input("Enter the number : "))
nums.append(num)
nums = sorted(nums)
for i in nums:
print(i)
num = int(input("Select number from array : "))
if num in nums:
nums.remove(num)
num2 = array("i", [])
num2.append(num)
print(nums)
print(num2)
else:
print("Not a value in the array")
2차원리스트에서 데이터 추가, 변경
# 추가
grades = [[45, 37, 54], [62, 58, 89], [78, 83, 54]]
grades[0].append(2)
print(grades)
# 대체
grades = [[45, 37, 54], [62, 58, 89], [78, 83, 54]]
grades[0][1] = 1
print(grades)
2차원 딕셔너리 출력, 추가, 삭제
# 출력
data_set = {"A": {"x": 54, "y": 51, "z": 45}, "B": {"x": 54, "y": 51, "z": 45}}
print(data_set)
# 각 행의 Y열 출력
data_set = {"A": {"x": 54, "y": 51, "z": 45}, "B": {"x": 54, "y": 51, "z": 45}}
for i in data_set:
print(data_set[i]["y"])
# 삭제
del list[getrid]
list = {}
for i in range(0, 4):
name = input("Enter the name : ")
age = int(input("What is your age? : "))
shoe = int(input("write your shoe size : "))
list[name] = {"Age": age, "Shoe": shoe}
getrid = input("remove from the list? Enter the name : ")
del list[getrid]
for name in list:
print(name, list[name]["Age"], list[name]["Shoe size"])
홀짝에 따라 다른 값 반환
def solution(n):
if n % 2 == 0:
# n이 짝수일 때 n이하 모든 짝수를 2제곱으로 곱한후 return
# sum으로 리스트 내의 값을 전부 더함
answer = sum([i**2 for i in range(2, n+1, 2)])
else:
# n이 홀수일 때 n이하 모든 홀수를 더한 값을 return
answer = sum([i for i in range(1, n+1, 2)])
return answer
조건 문자열 eval을 이용하여 문자열로 이루어진 식 반환
def solution(ineq, eq, n, m):
strlize1, strlize2 = str(n), str(m)
if eq in "!":
eq = eq.replace("!", "")
answer = eval(strlize1 + ineq + eq + strlize2)
if answer == True:
return 1
else:
return 0
#다르게 표현한 경우
def solution(ineq, eq, n, m):
return int(eval(str(n)+ineq+eq.replace('!', '')+str(m)))
등차수열의 특정한 항만 더하기
def solution(a, d, included):
result = 0
for i in range(len(included)):
if included[i]:
result += a + d * i
return result
세 개의 숫자 중 하나만 다른 경우 & 세 개의 숫자 모두가 다른경우
# 세개의 숫자 중 하나가 다른 경우
def is_two_numbers_same(a, b, c):
if a == b and a != c:
return True
elif a == c and a != b:
return True
elif b == c and b != a:
return True
else:
return False
# 간결하게 표현
def two_are_same(a, b, c):
return a == b or b == c or c == a
# 세개의 숫자 모두가 다른 경우
if a != b and b != c and a != c:
# 중복을 허용하지 않는 set을 이용한 경우
def check_numbers(a, b, c):
if len(set([a, b, c])) == 3:
print("세 숫자는 모두 다릅니다.")
else:
print("두 숫자는 같고, 나머지 하나는 다릅니다.")
리스트 안의 모든 수 더하기, 곱하기
# 더하기 (sum)
num_list = [3, 4, 5, 2, 1]
answer = 0
for i in num_list:
answer = sum(num_list)
print(answer)
# 곱하기 (math 라이브러리의 prod)
import math
num_list = [3, 4, 5, 2, 1]
answer = math.prod(num_list)
print(answer)
# 원소들의 곱과 합 문제
import math
def solution(num_list):
multiply = math.prod(num_list)
square = sum(num_list)**2
if multiply < square:
answer = 1
else:
answer = 0
return answer
# *= 사용
numlist = [1, 2, 3, 4, 5, 6, 5, 6]
num = int(1)
for i in numlist:
num *= i
print(num)
특정 조건을 만족하는 리스트의 요소를 int형으로 변환
def solution(num_list):
trans = "".join(map(str, num_list))
a, b = "", ""
for i in trans:
if int(i) % 2 == 0:
a += i
elif int(i) % 2 == 1:
b += i
return int(a) + int(b)
# 다른 방법으로 표현한 경우
def solution(num_list):
num1 = [str(num_list[i]) for i in range(len(num_list)) if num_list[i] % 2 == 1]
num2 = [str(num_list[i]) for i in range(len(num_list)) if num_list[i] % 2 == 0]
return int("".join(num1)) + int("".join(num2))
'자료구조 & 알고리즘' 카테고리의 다른 글
Tool Box 3 (0) | 2023.05.24 |
---|---|
Tool Box 2 (0) | 2023.05.16 |
자료구조 : 큐 (Quene) (0) | 2021.12.22 |
자료구조 : 배열(Array) (0) | 2021.12.21 |
컴퓨터 메모리의 간략한 개념과 선형 데이터 구조의 개념 (0) | 2021.12.21 |