Skip to content

Instantly share code, notes, and snippets.

@arduinocc04
Created May 11, 2022 02:38
Show Gist options
  • Save arduinocc04/6074bcf548f3d00917a3f3009ac92048 to your computer and use it in GitHub Desktop.
Save arduinocc04/6074bcf548f3d00917a3f3009ac92048 to your computer and use it in GitHub Desktop.
import os
import helper
def getHistoryOfStudent(name):
ans = []
for fileName in os.listdir('history/'):
if fileName[-3:] != 'txt': continue
tmp = helper.Seat.commasToList(None, 'history/' + fileName)
n = -1
for i in range(len(tmp)):
if tmp[i] == name:
n = i+1
break
ans.append(n)
return ans
def getHistoryOfSeat(n):
ans = []
for fileName in os.listdir('history/'):
if fileName[-3:] != 'txt': continue
tmp = helper.Seat.commasToList(None, 'history/' + fileName)
ans.append(tmp[n-1])
return ans
def getSeat(studentName, fileName):
tmp = helper.Seat.commasToList(None, fileName)
return tmp.index(studentName) + 1
def getStudent(num, fileName):
tmp = helper.Seat.commasToList(None, fileName)
return tmp[num - 1]
def getSquaredDist(x, y):
return (x[0] - y[0])**2 + (x[1] - y[1])**2
def getSurroundings(n, maxSquaredDist = 2): #Euclidean distance 1:upbelowleftright 2:+diag 4: +uubbllrr
ans = []
origin = ((n-1) % 5, (n-1)//5)
for i in range(1, 29):
if i == n: continue
if getSquaredDist(origin, ((i-1)%5, (i-1)//5)) <= maxSquaredDist:
ans.append(i)
return ans
def friendShipTxtToGraph(fileName):
tmp = helper.Seat.commasToList(None, fileName)
graph = [[False]*len(tmp) for i in range(len(tmp))]
with open('friendShip.txt', 'r', encoding='utf8') as f:
for line in f.readlines():
s, a = line.split(':')
for st in a.split(','):
tmp = st.rstrip()
if tmp == '': continue
graph[getSeat(s, fileName)-1][getSeat(tmp, fileName)-1] = True
return graph
def historyToXl(txtName, xlName): #앞자리 입력하라고 뜰 수 있는데 아무렇게나 입력하면 됨. 영향 없음.
history = helper.Seat.commasToList(None, txtName)
a = helper.Seat(False, False)
a.resList = history
a.MAX_NUM = len(history)
a.exportSeatByXl(xlName)
def evaluateSeat(graph):
ans = 0
ans2 = 0
ans3 = 0
for i in range(len(graph)):
t = 0
for j in range(len(graph[i])):
if graph[i][j] and j + 1 in getSurroundings(i + 1):
ans += 1
t += t+1
if graph[i][j]:
ans3 -= getSquaredDist((i%5, i//5), (j%5, j//5))
ans2 += 2**t
return ans, ans2, ans3
if __name__ == "__main__":
for fileName in os.listdir('history/'):
if fileName[-3:] != 'txt': continue
print(evaluateSeat(friendShipTxtToGraph('history/' + fileName)))
tmp = helper.Seat.commasToList(None, 'history/' + fileName)
import helper
seat = helper.Seat(DEBUG=False)
seat.changeSeat()
if not seat.SAME_SEAT_AVAILABLE:
while seat.returnSame(seat.SET_FRONT_SEAT_MANUALLY): seat.changeSeat()
seat.exportSeatByFile("history/" + seat.exportFileName + ".txt")
if not seat.DEBUG: seat.exportSeatByFile('latest.txt')
seat.exportSeatByPrint()
for st in seat.returnSame():
print(st + "는(은) 저번과 같은 자리입니다.")
seat.exportSeatByXl("history/" + seat.exportFileName + ".xlsx")
input("종료하고 싶으면 엔터를 누르세요.")
import time
import openpyxl as xl
import shutil
import random
class Seat:
def __init__(self, DEBUG):
self.SET_FRONT_SEAT_MANUALLY = self.textFileToBool('config/SET_FRONT_SEAT_MANUALLY.txt')
self.SAME_SEAT_AVAILABLE = self.textFileToBool('config/SAME_SEAT_AVAILABLE.txt')
self.FRONT_END = self.textFileToInt('config/FRONT_END.txt')
self.students = self.commasToList('config/students.txt')
self.wantToFront = self.commasToList('config/wantToFront.txt')
self.wantToFront = set(self.wantToFront)
self.latest = self.commasToList('latest.txt')
self.MAX_NUM = len(self.students)
self.exportFileName = self.makeYMD()
self.DEBUG = DEBUG
if DEBUG:
print('SAME_SEAT_AVAILABLE', self.SAME_SEAT_AVAILABLE)
print('MAX_NUM', self.MAX_NUM)
print('FRONT_END', self.FRONT_END)
print('students', self.students)
print('wantToFront', self.wantToFront)
if not self.SET_FRONT_SEAT_MANUALLY:
FRONT_END = max(FRONT_END, len(self.wantToFront))
else:
self.frontSeat = {}
self.cannotUse = set()
for st in list(self.wantToFront):
flag = True
while flag:
num = int(input(st + "의 자리를 입력해주세요 >>>"))
if not num in self.cannotUse:
self.frontSeat[st] = num
self.cannotUse.add(num)
flag = False
else:
print("이미 사용된 자리입니다.")
def makeYMD(self):#Y-M-D 형식 문자열 만들어줌.
tm = time.localtime(time.time())
year = tm.tm_year
month = tm.tm_mon
day = tm.tm_mday
return str(year) + "-" + str(month) + "-" + str(day)
def commasToList(self, fileName): #컴마로 구분된 한줄짜리 파일 list형으로 바꿔주는 함수.
with open(fileName, 'r', encoding="UTF-8") as f:
tmp = f.readline().replace("\ufeff", "")
res = tmp.split(',')
for i in range(len(res)):
res[i] = res[i].rstrip()
res[i] = res[i].lstrip()
return res
def textFileToBool(self, fileName): #한줄짜리 true/false 정보 담긴 파일 bool형으로 바꿔주는 함수.
with open(fileName, 'r', encoding="UTF-8") as f:
tmp = f.readline().replace("\ufeff", "")
s = tmp.rstrip()
s = s.lstrip()
if s == 'True' or s == 'TRUE' or s == '1':
return True
return False
def textFileToInt(self, fileName): #한줄짜리 정수 담긴 파일 int형으로 바꿔주는 함수
with open(fileName, 'r', encoding="UTF-8") as f:
tmp = f.readline().replace("\ufeff", "")
return int(tmp)
def returnSame(self, exceptFront=True):
res = []
i = 0
while i < min(len(self.latest), len(self.resList)):
if self.latest[i] == self.resList[i]:
if not (exceptFront and self.latest[i] in self.wantToFront):
res.append(self.latest[i])
i += 1
return res
def exportSeatByFile(self, fileName):
with open(fileName, 'w', encoding="UTF-8") as f:
for i in range(len(self.resList)):
if i == len(self.resList) - 1:
f.write(self.resList[i])
else:
f.write(self.resList[i] + ', ')
if self.SET_FRONT_SEAT_MANUALLY:
f.write('\n')
tmp = list(self.wantToFront)
for i in range(len(tmp)):
if i == len(tmp) - 1:
f.write(tmp[i])
else:
f.write(tmp[i] + ', ')
def exportSeatByPrint(self, mod=5):#mod는 한줄에 몇명씩 출력할지 정하는것.
i = 1
MAXLEN = 4
for st in self.resList:
if i%mod:
print(st, end=' ')
if len(st) < MAXLEN: print(' '*(MAXLEN-len(st)), end='')
else: print(st)
i += 1
print()
def exportSeatByXl(self, fileName):
shutil.copyfile("./config/template.xlsx", "./" + fileName)
wb = xl.load_workbook(fileName)
sheet = wb['template']
for stNum in range(1, self.MAX_NUM + 1):
for rowData in sheet.iter_rows(min_row = 1):
for cell in rowData:
if cell.value == "$" + str(stNum) + "$":
cell.value = self.resList[stNum-1]
wb.save(fileName)
def changeSeat(self):
res = dict()
if self.SET_FRONT_SEAT_MANUALLY:
forGeneral = []
for i in range(1, self.MAX_NUM + 1):
if not i in self.cannotUse:
forGeneral.append(i)
random.shuffle(forGeneral)
generalCnt = 0
for st in self.students:
if not st in self.wantToFront:
res[st] = forGeneral[generalCnt]
generalCnt += 1
for st in self.frontSeat.keys():
res[st] = self.frontSeat[st]
else:
forWantToFront = [i for i in range(1, self.FRONT_END + 1)]
forGeneral = [i for i in range(self.FRONT_END + 1, self.MAX_NUM + 1)]
random.shuffle(forWantToFront)
if len(forWantToFront) > len(self.wantToFront):
for i in range(len(self.wantToFront), len(forWantToFront)):
forGeneral.append(forWantToFront[i])
for i in range(len(self.wantToFront), len(forWantToFront)): del forWantToFront[-1]
random.shuffle(forGeneral)
if self.DEBUG:
print('forWantToFront', forWantToFront)
print('forGeneral', forGeneral)
wantToFrontCnt = 0
generalCnt = 0
for st in self.students:
if st in self.wantToFront:
res[st] = forWantToFront[wantToFrontCnt]
wantToFrontCnt += 1
else:
res[st] = forGeneral[generalCnt]
generalCnt += 1
if self.DEBUG:
print(res)
tmp = []
for i in range(len(self.students)):
for st in res.keys():
if res[st] == i+1:
tmp.append(st)
self.resDict = res
self.resList = tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment