[제로베이스 데이터 취업 스쿨 15기] 4-1주차 (자료구조/문제풀이)

김지환·2023년 5월 18일
0
post-thumbnail

4-1주차: 5/22/2023 - 5/28/2023


List


Definition

  • An ordered and changeable collection of data objects

Index

  • Numbered position of the item
students = ['Kim', 'Shin', 'Park', 'Choi', 'Hwang']

for i in range(5):
    if i % 2 == 0:
        print('even index -> students[{}]: {}'.format(i, students[i]))
    else:
        print('odd index -> students[{}]: {}'.format(i, students[i]))

Length

  • Number of items in a list
students = ['Hong', 'Park', 'Lee']

sLength = len(students)
print('Length of students: {}'.format(sLength))

for i in range(len(students)):
    print('i: {}'.format(i))
    print(students[i])

str = 'Hello python'
print(len(str))

myFavoriteSports = ['Swimming', 'Volleyball', 'Baseball']

for i in range(len(myFavoriteSports)):
    print(myFavoriteSports[i])

for item in myFavoriteSports:
    print(item)

n = 0
while n < len(myFavoriteSports):
    print(myFavoriteSports[n])
    n += 1

For loop

cars = ['BMW', 'Mercedes', 'Toyota']

for i in range(len(cars)):
    print(cars[i])

for car in cars:
    print(car)

studentCnts = [[1, 19], [2, 20], [3, 22], [4, 18], [5, 21]]

for i in range(len(studentCnts)):
    print('Number of students in class {}: {}'.format(studentCnts[i][0], studentCnts[i][1]))

for classNo, cnt in studentCnts:
    print('Number of students in class {}: {}'.format(classNo, cnt))

# Exercise

studentCnts = [[1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]
sum = 0
avg = 0
for classNo, cnt in studentCnts:
    print('Number of students in class {}: {}'.format(classNo, cnt))
    sum += cnt

print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
minScore = 60

scores = [['Korean', 58],
          ['English', 77],
          ['Math', 89],
          ['Science', 99],
          ['History', 50]]

for item in scores:
    if item[1] < minScore:
        print('Failed class: {}, score: {}'.format(item[0], item[1]))

for subject, score in scores:
    if score < minScore:
        print('Failed class: {}, score: {}'.format(subject, score))

for subject, score in scores:
    if score >= minScore: continue
    print('Failed class: {}, score: {}'.format(subject, score))
students = [['Class 1', 18],
            ['Class 2', 19],
            ['Class 3', 23],
            ['Class 4', 21],
            ['Class 5', 20],
            ['Class 6', 22],
            ['Class 7', 17]]

minClassNum = 0
minStudentNum = 0
maxClassNum = 0
maxStudentNum = 0

for classNum1, studentNum in students:
    if minStudentNum == 0 or minStudentNum > studentNum:
        minClassNum = classNum1
        minStudentNum = studentNum

    if maxStudentNum == 0 or maxStudentNum < studentNum:
        maxClassNum = classNum1
        maxStudentNum = studentNum

print('Class with the least students (number of students): {}({})'.format(minClassNum, minStudentNum))
print('Class with the most students (number of students): {}({})'.format(maxClassNum, maxStudentNum))

While loop

cars = ['Toyota', 'BMW', 'Mercedes']

n = 0

while n < len(cars):
    print(cars[n])
    n += 1

n = 0
flag = True
while flag:
    print(cars[n])
    n += 1

    if n == len(cars):
        flag = False

n = 0
while True:
    print(cars[n])
    n += 1

    if n == len(cars):
        break

# Exercise

studentCnts = [[1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]

sum = 0
avg = 0
n = 0
while n < len(studentCnts):
    classNo = studentCnts[n][0]
    cnt = studentCnts[n][1]
    print('Number of students in Class {}: {}'.format(classNo, cnt))

    sum += cnt
    n += 1

print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = [[1, 18],
               [2, 19],
               [3, 23],
               [4, 21],
               [5, 20],
               [6, 22],
               [7, 17]]

minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0

n = 0
while n < len(studentCnts):

    if minCnt == 0 or minCnt > studentCnts[n][1]:
        minClassNo = studentCnts[n][0]
        minCnt = studentCnts[n][1]

    if maxCnt == 0 or maxCnt < studentCnts[n][1]:
        maxClassNo = studentCnts[n][0]
        maxCnt = studentCnts[n][1]

    n += 1

print('Class with the most students (number of students): Class {} ({})'.format(maxClassNo, maxCnt))
print('Class with the least students (number of students): Class {} ({})'.format(minClassNo, minCnt))

enumerate()

  • List all items with index and value
message = input('Input message: ')
cnt = 0
for idx, value in enumerate(message):
    if value == ' ':
        cnt += 1

print('Number of spaces: {}'.format(cnt))

append()

  • Add an item to the list at the end
myFamilyAge = [['Dad', 40], ['Mom', 38], ['Me', 9]]
print(myFamilyAge)

myFamilyAge.append(['Brother', 1])
print(myFamilyAge)

for name, age in myFamilyAge:
    print('Age of {}: {}'.format(name, age))

insert()

  • Specify where to include the item and push the original to the right
numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNumber = int(input('Input an integer: '))
insertIdx = 0

for idx, number in enumerate(numbers):
    print(idx, number)

    if insertIdx == 0 and inputNumber < number:
        insertIdx = idx

numbers.insert(insertIdx, inputNumber)
print('numbers: {}'.format(numbers))

pop()

  • Delete the item with the last index
  • pop(3): delete the item with the index 3 and moves the items on the right to the left
playerScores = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScores: {}'.format(playerScores))

minScore = 0; maxScore = 0
minScoreIdx = 0; maxScoreIdx = 0

for idx, score in enumerate(playerScores):
    if minScoreIdx == 0 or minScore > score:
        minScoreIdx = idx
        minScore = score

print('minScore: {}, minScoreIdx: {}'.format(minScore, minScoreIdx))
playerScores.pop(minScoreIdx)

for idx, score in enumerate(playerScores):
    if maxScoreIdx == 0 or maxScore < score:
        maxScoreIdx = idx
        maxScore = score

print('maxScore: {}, maxScoreIdx: {}'.format(maxScore, maxScoreIdx))
playerScores.pop(maxScoreIdx)

print('playerScores: {}'.format(playerScores))

remove()

  • Remove only one specific item
subjects = ['Korean', 'English', 'Math', 'Science', 'History']
print('Test subjects: {}'.format(subjects))

removeSubject = input('Input a subject to remove: ')
while removeSubject in subjects:
    subjects.remove(removeSubject)

print('Test subjects: {}'.format(subjects))

extend()

  • Append a list to another list
  • list3 = list1 + list2: add list1 to list2 to form list3
myFavoriteNumbers = [1, 3, 5, 6, 7]
friendFavoriteNumbers = [2, 3, 5, 8, 10]
print('myFavoriteNumbers: {}'.format(myFavoriteNumbers))
print('friendFavoriteNumbers: {}'.format(friendFavoriteNumbers))

addList = myFavoriteNumbers + friendFavoriteNumbers
print('addList: {}'.format(addList))

result = []
for number in addList:
    if number not in result:
        result.append(number)

print('result: {}'.format(result))

sort()

  • Sort items in an ascending order
  • sort(reverse=True): sort items in a descending order
playerScore = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScore = {}'.format(playerScore))

playerScore.sort()
print('playerScore = {}'.format(playerScore))

playerScore.pop(0)
playerScore.pop(len(playerScore)-1)
print('playerScore = {}'.format(playerScore))

sum = 0
avg = 0
for score in playerScore:
    sum += score

avg = sum / len(playerScore)

print('sum: %.2f' % sum)
print('avg: %.2f' % avg)

reverse()

  • Reverse the order of items
secret = '27156231'
secretList = []
solvedList = ''

for cha in secret:
    secretList.append(int(cha))

secretList.reverse()
print('secretList: {}'.format(secretList))

val = secretList[0] * secretList[1]
secretList.insert(2, val)

val = secretList[3] * secretList[4]
secretList.insert(5, val)

val = secretList[6] * secretList[7]
secretList.insert(8, val)

val = secretList[9] * secretList[10]
secretList.insert(11, val)

print('secretList: {}'.format(secretList))

Slicing

  • [2:4]: slice items with index 2 <= n < 4 to create a list
  • -1: last index
students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
print('students: {}'.format(students[2:4]))
print('students: {}'.format(students[:4]))
print('students: {}'.format(students[2:]))
print('students: {}'.format(students[2:-2]))
print('students: {}'.format(students[-5:-2]))

numbers = [2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14]
print('numbers: {}'.format(numbers))
print('numbers: {}'.format(numbers[2:-2]))
print('numbers: {}'.format(numbers[2:-2:2]))
print('numbers: {}'.format(numbers[:-2:2]))
print('numbers: {}'.format(numbers[::2]))

students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
students[1:4] = ['John Hong', 'Kevin Park', 'Jack Kim']
print('students: {}'.format(students))

students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
print('students: {}'.format(students[slice(2, 4)]))
print('students: {}'.format(students[slice(4)]))
print('students: {}'.format(students[slice(2, len(students))]))
  • list * 2: items in the list added to the list again

index(item)

  • Find the first index of the item
  • index(item, 2, 6): find the item with the index between 2 and 5
import random
sampleList = random.sample(range(1, 11), 10)

selectIdx = int(input('Input the index of 7: '))
searchIdx = sampleList.index(7)

if searchIdx == selectIdx:
    print('Correct')
else:
    print('Wrong')

print('sampleList: {}'.format(sampleList))
print('searchIdx: {}'.format(searchIdx))

count()

  • Find the number of the times the item appears in the list
students = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
print('students: {}'.format(students))

searchCnt = students.count('Park')
print('searchCnt: {}'.format(searchCnt))

del

  • del list[i]: delete the item with index i in the list
students = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
del students[1]
print('students: {}'.format(students))
students = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
del students[1:4]
print('students: {}'.format(students))

Exercises

inputNum = int(input('Input an integer > 1: '))
listA = []
listB = []

for n in range(1, inputNum+1):
    if n == 1:
        listA.append(n)
    else:
        if inputNum % n == 0:
            listA.append(n)

for number in range(2, inputNum+1):
    flag = True
    for n in range(2, number):
        if number % n == 0:
            flag = False
            break
    if flag:
        listB.append(number)

print('listA: {}'.format(listA))
print('listB: {}'.format(listB))
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
print(f'numbers = {numbers}')

idx = 0
while True:
    if idx >= len(numbers):
        break

    if numbers.count(numbers[idx]) >= 2:
        numbers.remove(numbers[idx])
        continue

    idx += 1

print(f'numbers = {numbers}')

Tuple


Definition

  • An ordered and unchangeable collection of data objects

Index

students = ['Hong', 'Kim', 'Park', 'Lee', 'Choi', 'Chung']

print('--Students with even indices--')
for idx, student in enumerate(students):
    if idx % 2 == 0:
        print('student[{}]: {}'.format(idx, student))

print('--Students with odd indices--')
for idx, student in enumerate(students):
    if idx % 2 != 0:
        print('student[{}]: {}'.format(idx, student))

in, not in

  • in: True if the item is in the tuple, list, str, etc.
  • not in: True if the item is not in the tuple, list, str, etc.
studentsTuple = ('Hong', 'Kim', 'Park', 'Lee')

searchName = input('Input student name: ')
if searchName in studentsTuple:
    print('{} is in our class.'.format(searchName))
else:
    print('{} is not in our class.'.format(searchName))

len(tuple)

  • Length of the tuple
myFavoriteSports = ('Swimming', 'Soccer', 'Volleyball', 'Baseball')

for i in range(len(myFavoriteSports)):
    print('myFavoriteSports[{}]: {}'.format(i, myFavoriteSports[i]))

n = 0
fLength = len(myFavoriteSports)
while n < len(myFavoriteSports):
    print('myFavoriteSports[{}]: {}'.format(n, myFavoriteSports[n]))
    n += 1

for f in myFavoriteSports:
    print('myFavoriteSports: {}'.format(f))

tuple3 = tuple1 + tuple2

  • extend() cannot be used for tuples
myNumbers = (1, 3, 5, 6, 7)
friendNumbers = (2, 3, 5, 8, 10)

print('myNumbers = {}'.format(myNumbers))
print('friendNumbers = {}'.format(friendNumbers))

for number in friendNumbers:
    if number not in myNumbers:
        myNumbers += (number, )

print('myNumbers = {}'.format(myNumbers))

Slicing

  • [2:4]: slice items with index 2 <= n < 4
  • Slicing cannot be used to change items in a tuple
  • Slicing can change items in a list with a tuple
students = ['Hong', 'Kim', 'Park', 'Lee', 'Chung', 'Choi']
print('students: {}'.format(students))
students[1:4] = ('John Hong', 'Jack Kim', 'Steve Park')
print('students: {}'.format(students))
print(type(students))

Differences between lists and tuples

  • Parentheses can be omitted for tuples
  • Tuples can be changed to lists, and vice versa
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
print('playerScore: {}'.format(playerScore))
print('playerScore type: {}'.format(type(playerScore)))

playerScore = list(playerScore)
print('playerScore type: {}'.format(type(playerScore)))

playerScore.sort()
print('playerScore: {}'.format(playerScore))

playerScore.pop(0)
playerScore.pop(len(playerScore) - 1)
print('playerScore: {}'.format(playerScore))

playerScore = tuple(playerScore)
print('playerScore: {}'.format(playerScore))

sorted()

  • Sort a tuple and return a list
students = ('Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung')
sortedStudents = sorted(students)
print('sortedStudents type: {}'.format(type(sortedStudents)))
print('sortedStudents: {}'.format(sortedStudents))

For loop

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

sum = 0
avg = 0

for classNo, cnt in studentCnts:
    print('Number of students in Class {}: {}'.format(classNo, cnt))
    sum += cnt

print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0

for classNo, cnt in studentCnts:
    if minCnt == 0 or minCnt > cnt:
        minClassNo = classNo
        minCnt = cnt
    if maxCnt == 0 or maxCnt < cnt:
        maxClassNo = classNo
        maxCnt = cnt

print('Class with the least students (number of students): Class {} ({} students)'.format(minClassNo, minCnt))
print('Class with the most students (number of students): Class {} ({} students)'.format(maxClassNo, maxCnt))

While loop

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

sum = 0
avg = 0
n = 0
while n < len(studentCnts):
    classNo = studentCnts[n][0]
    cnt = studentCnts[n][1]
    print('Number of students in Class {}: {}'.format(classNo, cnt))

    sum += cnt
    n += 1

print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0

n = 0
while n < len(studentCnts):
    if minCnt == 0 or minCnt > studentCnts[n][1]:
        minClassNo = studentCnts[n][0]
        minCnt = studentCnts[n][1]
    if maxCnt == 0 or maxCnt < studentCnts[n][1]:
        maxClassNo = studentCnts[n][0]
        maxCnt = studentCnts[n][1]
    n += 1

print('Class with the least students: Class {} with {} students'.format(minClassNo, minCnt))
print('Class with the most students: Class {} with {} students'.format(maxClassNo, maxCnt))

Exercises

tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)

tempUnion = list(tuple1)
tempInter = list()

for n in tuple2:
    if n not in tempUnion:
        tempUnion.append(n)
    else:
        tempInter.append(n)

tempUnion = tuple(sorted(tempUnion))
tempInter = tuple(sorted(tempInter))

print(f'Union: {tempUnion}')
print(f'Intersection: {tempInter}')
fruits = ({'Watermelon':8}, {'Grape':13}, {'Cantaloupe':7}, {'Apple':17}, {'Plum':19}, {'Grapefruit':15})
fruits = list(fruits)

cIdx = 0; nIdx = 1
eIdx = len(fruits) - 1

flag = True
while flag:
    cDic = fruits[cIdx]
    nDic = fruits[nIdx]

    cDicCnt = list(cDic.values())[0]
    nDicCnt = list(nDic.values())[0]

    if nDicCnt < cDicCnt:
        fruits.insert(cIdx, fruits.pop(nIdx))
        nIdx = cIdx + 1
        continue

    nIdx += 1
    if nIdx > eIdx:
        cIdx += 1
        nIdx = cIdx + 1

        if cIdx == 5:
            flag = False

fruits = tuple(fruits)
print(fruits)

Dictionary


Definition

  • A collection of key-value pairs
  • Keys should be unique and immutable
    - Lists cannot be keys
  • Values can be identical

get()

  • no error even if the specified key does not exist (None)

Adding items

factorialDic = {}

for i in range(11):
    if i == 0:
        factorialDic[i] = 1
    else:
        for j in range(1, i+1):
            factorialDic[i] = factorialDic[i-1] * j

print(f'factorialDic: {factorialDic}')

Modifying values

myBodyInfo = {'name': 'John', 'weight': 83.0, 'height': 1.8}
myBMI = myBodyInfo['weight'] / myBodyInfo['height'] ** 2
print(f'myBodyInfo: {myBodyInfo}')
print(f'myBMI: {round(myBMI, 2)}')

date = 0
while True:
    date += 1

    myBodyInfo['weight'] = round(myBodyInfo['weight'] - 0.3, 2)
    print('weight: {}'.format(myBodyInfo['weight']))

    myBodyInfo['height'] = round(myBodyInfo['height'] + 0.001, 3)
    print('height: {}'.format(myBodyInfo['height']))

    myBMI = myBodyInfo['weight'] / myBodyInfo['height'] ** 2

    if date >= 30:
        break

print(f'myBodyInfo: {myBodyInfo}')
print(f'myBMI: {round(myBMI, 2)}')

Accessing keys and values

  • keys(): return an iterable collection of keys
  • values(): return an iterable collection of values
  • items(): return an iterable collection of items
memInfo = {'name':'Hong', 'email':'hong@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}

ks = memInfo.keys()
print(f'ks: {ks}')
print(f'ks type: {type(ks)}')

vs = memInfo.values()
print(f'vs: {vs}')
print(f'vs type: {type(vs)}')

items = memInfo.items()
print(f'items: {items}')
print(f'items type: {type(items)}')

list()

  • Change a collection into a list
memInfo = {'name':'Hong', 'email':'hong@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}

ks = memInfo.keys()
ks = list(ks)
print(f'ks: {ks}')
print(f'ks type: {type(ks)}')

Deleting items

  • del: delete an item
  • pop(): delete an item and return the deleted item
memInfo = {'name':'Hong', 'email':'john@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}
print(f'memInfo: {memInfo}')

returnValue = memInfo.pop('name')
print(f'memInfo: {memInfo}')
print(f'returnValue: {returnValue}')
print(f'returnValue type: {type(returnValue)}')

Other functions

  • in: True if in keys
  • not in: True if not in keys
  • len(): length of a dict
  • clear(): delete all items in a dict

Exercises

import string
import random


def randomPassword(length=7):

    password_characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(password_characters) for i in range(length))


def randomID(length=5):

    id_characters = string.ascii_uppercase
    return ''.join(random.choice(id_characters) for i in range(length))


members = {}
n = 0
flag = True
while flag:

    members[randomID()] = randomPassword()
    n += 1

    if n >= 10:
        flag = False

for key, value in members.items():
    print(key, ': ', value)

memID = input('Input ID: ')
memPW = input('Input PW: ')

if memID in members:
    if members[memID] == memPW:
        print('Login successful')
    else:
        print('Check your password')
else:
    print('Check your ID')
members = {}

n = 1
while n < 6:
    email = input('Input email: ')
    pw = input('Input password: ')

    if email in members:
        print('This email is already being used')
        continue
    else:
        members[email] = pw
        n += 1

for key in members.keys():
    print(f'{key}: {members[key]}')

while True:
    delMail = input('Input email to delete: ')

    if delMail in members:
        delPw = input('Input password: ')
        if members[delMail] == delPw:
            del members[delMail]
            print(f'{delMail} has been deleted')
            break
        else:
            print('Check your password')
    else:
        print('Check your email')

for key in members.keys():
    print(f'{key}: {members[key]}')
students = {
    'S21-0001': {'name': 'Choi',
                 'gender': 'M',
                 'major': 'design',
                 'phone': '010-1234-5678',
                 'email': 'choi@gmail.com',
                 'hobby': ['Basketball', 'Music']},
    'S21-0002': {'name': 'Kim',
                 'gender': 'F',
                 'major': 'economics',
                 'phone': '010-1234-5678',
                 'email': 'kim@gmail.com',
                 'hobby': ['Soccer', 'Weightlifting']},
    'S21-0003': {'name': 'Park',
                 'gender': 'F',
                 'major': 'history',
                 'phone': '010-1234-5678',
                 'email': 'park@gmail.com',
                 'hobby': ['Game', 'MMA']}
}

for k1 in students.keys():
    print('-' * 40)
    print('Student ID: {}'.format(k1))

    student = students[k1]
    for k2 in student.keys():
        print('{}: {}'.format(k2, student[k2]))

print('-' * 40)

studentID = input('Input student ID: ')

student = students[studentID]
for k3 in student.keys():
    print('{}: {}'.format(k3, student[k3]))
profile
데이터 분석 공부하고 있습니다

0개의 댓글