c언어 네이버 지식인 풀이
https://kin.naver.com/qna/detail.nhn?d1id=11&dirId=1113&docId=314491480
/*
작성자 : sleep4725
윈도우 10 환경
visual studio 2013
*/
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define _CRT_SECURE_NO_WARNINGS
# define LEN 20
typedef struct {
char idNumber[LEN]; // 번호
char stuName[LEN]; // 학생이름
int kor; // 국어
int eng; // 영어
int math; // 수학
int tot; // 총점
double avg; // 평균
}STU, *pSTU;
// function prototype ============================
pSTU retNode(int); // func (1)
void stuInfoSetting(STU**, int*); // func (2)
void bubbleSort(STU**, int*); // func (3)
void sortPrintf(STU**, int*); // func (4)
// ===============================================
int main(void) { // main function
pSTU stuInfor = NULL;
unsigned int stuCount = 0x0;
printf("성적을 처리할 학생들은 몇 명 입니까? ");
scanf("%d", &stuCount);
stuInfor = retNode(stuCount);
if (stuInfor == NULL) {
printf("malloc fail ... \n");
exit(1);
}
stuInfoSetting(&stuInfor, &stuCount);
//bubbleSort(&stuInfor, &stuCount);
sortPrintf(&stuInfor, &stuCount);
return 0;
} // end of main function
// ===========================================
pSTU retNode(int cnt) { // func (1)
pSTU tmp = NULL;
tmp = (pSTU)malloc(sizeof(STU)*cnt);
return tmp;
} // end of retNode function
// ===========================================
void stuInfoSetting(STU** pNode, int* cnt) { // func (2)
int i; // index
for (i = 0; i < *cnt; i++) {
// 학생 이름 입력 : string
printf("학생 이름 입력: ");
rewind(stdin); // 버퍼 비우기
gets((*pNode + i)->stuName); // gets_s 함수는 비표준
// 학생 학번 입력 : string
printf("학생 학번 입력: ");
gets((*pNode + i)->idNumber);
// 국어 점수 입력 : int
printf("국어 점수 입력: ");
scanf("%d", &(*pNode + i)->kor);
// 영어 점수 입력 : int
printf("영어 점수 입력: ");
scanf("%d", &(*pNode + i)->eng);
// 수학 점수 입력 : int
printf("수학 점수 입력: ");
scanf("%d", &(*pNode + i)->math);
rewind(stdin); // 버퍼 비우기
// 총점
(*pNode + i)->tot = (*pNode + i)->kor + (*pNode + i)->eng + (*pNode + i)->math;
(*pNode + i)->avg = (double)(** pNode).tot / 3;
} // endfor
} // end of stuInfoSetting function
// ===========================================
void bubbleSort(STU** pNode, int* cnt) { // func (3)
int i, j; // index
STU swapNode;
for (i = 0; i < (*cnt)-1; i++) {
for (j = 0; j < (*cnt)-1; j++) {
// 총점을 기준으로 오름차순 정렬
if ((*pNode)[j].tot > (*pNode)[j + 1].tot) {
memcpy(&swapNode, &(*pNode)[j], sizeof(STU));
memcpy(&(*pNode)[j], &(*pNode)[j + 1], sizeof(STU));
memcpy(&(*pNode)[j + 1], &swapNode, sizeof(STU));
}
} // endfor
} // endfor
} // end of bubbleSort function
void sortPrintf(STU** pNode, int* cnt) { // func (4)
int i; // index
for (i = 0; i < (*cnt); i++) {
printf("학번 : %s\n", (*pNode)[i].idNumber);
printf("이름 : %s\n", (*pNode)[i].stuName);
printf("국어 : %d\n", (*pNode)[i].kor);
printf("영어 : %d\n", (*pNode)[i].eng);
printf("수학 : %d\n", (*pNode)[i].math);
printf("총점 : %d\n", (*pNode)[i].tot);
printf("평균 : %0.2lf\n", (*pNode)[i].avg);
printf("=================================\n");
}
} // end of sortPrintf function
'언어 > c언어' 카테고리의 다른 글
선택정렬 (0) | 2018.11.18 |
---|---|
버블 정렬 (0) | 2018.11.18 |
네이버 지식인 풀이 (0) | 2018.11.14 |
네이버 지식인 답변 (0) | 2018.11.12 |
네이버 지식인 풀이 (0) | 2018.11.10 |
selenium + pandas + 연습 중
# ===========================================================
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import pandas as pd
import pprint as ppr
import numpy as np
import re
# ===========================================================
options = Options() # 객체 생성
options.headless = True
driver = webdriver.Chrome(executable_path=r"C:\Users\sleep\Desktop\chrom_driver\chromedriver.exe",
chrome_options=options)
driver.get("https://ko.wikipedia.org/wiki/{0}".format("대한민국의_인구"))
assert "대한민국의 인구 - 위키백과, 우리 모두의 백과사전" in driver.title
print (driver.title)
html = driver.page_source
bsObject = BeautifulSoup(html, "html.parser")
f = bsObject.select('table.wikitable.sortable.jquery-tablesorter > tbody > tr')
info = dict()
for i in f:
year = i.select_one("td:nth-of-type(1)") # 년도
man_count = i.select_one("td:nth-of-type(2)") # 년도
year = re.sub("[\n, \t, \r]", "", str(year.string))
man_count = re.sub("[\n, \t, \r]", "", str(man_count.string))
info[year] = man_count
# ppr.pprint (info)
s = pd.Series(list(info.values()), index=list(info.keys()))
print (s)
'언어 > python' 카테고리의 다른 글
기록 1 (0) | 2018.12.15 |
---|---|
실패 - (0) | 2018.11.28 |
python selenium (0) | 2018.11.15 |
hexcolor 사이트 python 크롤링 (0) | 2018.11.06 |
사람인 크롤링 (version 2.3 - 2018-11-07) (2) | 2018.11.05 |
python selenium
https://stackoverflow.com/questions/10629815/handle-multiple-windows-in-python
#-----------------------------------------------------
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill
import pprint as ppr
#-----------------------------------------------------
class STU(object):
# 생성자
def __init__(self):
self.RealTimeChart = dict() # type of dictionary
self.hexColorList = list() # type of list
self.options = Options() # 객체 생성
self.options.headless = True
self.driver = webdriver.Chrome(executable_path=r"C:\Users\sleep\Desktop\chrom_driver\chromedriver.exe",
chrome_options=self.options)
self.html = None
# Excel
self.sheetIndex = [['B', 3], ['C', 3]]
self.workBook = None
self.workSheet = None
# func (1)
def get_url_requests(self):
self.driver.get("https://www.naver.com/")
assert "NAVER" in self.driver.title
print (self.driver.title)
html = BeautifulSoup(self.driver.page_source, "html.parser")
tmp_li_list = html.find_all("span", {"class": "ah_k"})
for n, i in enumerate(tmp_li_list):
self.RealTimeChart[str(n+1) + "순위"] = i.string
print("{0:02d} : {1:s}".format(n + 1, i.string))
self.driver.execute_script("window.open()") # 새로운 창 open
self.driver.switch_to.window(self.driver.window_handles[1])
# func (2)
def get_hex_color_list(self):
self.driver.get("https://www.color-hex.com/")
assert "Color Hex Color Codes" in self.driver.title
print (self.driver.title)
html = BeautifulSoup(self.driver.page_source, "html.parser")
tmp_color_lst = html.select("div.colordvcon > a")
for i in tmp_color_lst:
hexColorValue = str(i.attrs['title']).split(sep=' ')
hexColorValue = hexColorValue[0]
self.hexColorList.append(hexColorValue)
ppr.pprint (self.hexColorList)
# func (3)
def xlWrite(self):
self.workBook = Workbook() # 객체 생성
self.workSheet = self.workBook.create_sheet(title="실시간 순위")
# 셀에 너비 =====================================================
self.workSheet.column_dimensions['B'].width = 8.1
self.workSheet.column_dimensions['C'].width = 17.2
# =============================================================
self.workSheet[self.sheetIndex[0][0] + str(self.sheetIndex[0][1])] = "순위";self.sheetIndex[0][1]+=1
self.workSheet[self.sheetIndex[1][0] + str(self.sheetIndex[1][1])] = "내용";self.sheetIndex[1][1]+=1
for n, w in enumerate(self.RealTimeChart.items()):
self.workSheet[self.sheetIndex[0][0] + str(self.sheetIndex[0][1])] = w[0]
self.workSheet[self.sheetIndex[0][0] + str(self.sheetIndex[0][1])].fill = \
PatternFill(patternType='solid', fgColor=Color(self.hexColorList[n][1:]))
self.sheetIndex[0][1]+=1
self.workSheet[self.sheetIndex[1][0] + str(self.sheetIndex[1][1])] = w[1]
self.workSheet[self.sheetIndex[0][0] + str(self.sheetIndex[1][1])].fill = \
PatternFill(patternType='solid', fgColor=Color(self.hexColorList[n][1:]))
self.sheetIndex[1][1]+=1
# 소멸자
def __del__(self):
self.workBook.save(r'C:\Users\sleep\Desktop\cor_list\cartList.xlsx')
def main():
sNode = STU() # STU에 해당하는 인스턴스 객체 생성
sNode.get_url_requests()
sNode.get_hex_color_list()
sNode.xlWrite()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
실패 - (0) | 2018.11.28 |
---|---|
selenium + pandas + 연습 중 (0) | 2018.11.15 |
hexcolor 사이트 python 크롤링 (0) | 2018.11.06 |
사람인 크롤링 (version 2.3 - 2018-11-07) (2) | 2018.11.05 |
python mysql (0) | 2018.11.04 |
네이버 지식인 풀이
https://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=314316632
# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>
# define _CRT_SECURE_NO_WARNINGS
typedef struct {
unsigned int height;
unsigned int choice;
}STAR, *ptrSTAR;
// 함수 원형_________________________________
void _init_(STAR** param); // func (1)
void _choice_(STAR** param); // func (2)
void _one_(STAR** param); // func (3)
void _two_(STAR** param); // func (4)
void _three_(STAR** param); // func (5)
// _________________________________________
int main(void) {
ptrSTAR node = NULL;
node = (ptrSTAR)malloc(sizeof(STAR));
if (node == NULL) {
printf("malloc fail ... \n");
exit(1);
}
// node != NULL
_init_(&node);
_choice_(&node);
// 동적할당 해제
free(node);
return 0;
} // end of main function
// ================================
void _init_(STAR** param) { // func (1)
(** param).height = 0x0;
while (true) {
printf("높이 입력해줘: ");
scanf("%d", &(** param).height);
if ((** param).height % 2 == 0) {
printf("높이는 반드시 홀수여야 합니다.\n");
}
else { // 높이 값이 홀수 인 경우
break;
}
}
} // end of _init_ function
// ================================
void _choice_(STAR** param) { // func (2)
while (true) {
printf("1,2,3 중 한개 선택: ");
scanf("%d", &(** param).choice);
if (1 <= (** param).choice && (** param).choice <= 3) {
break;
}
else {
printf("잘못 입력하셨습니다. \n");
}
}
switch ((**param).choice) {
case 1:
_one_(param);
break;
case 2:
_two_(param);
break;
case 3:
_three_(param);
break;
}
} // end of _choice_ function
// ================================
void _one_(STAR** param) { // func (3)
/*
ex)
*****
***
*
*/
unsigned int i, j, k;
// 높이
for (i = (** param).height; i >= 1; i--) {
// 공백
for (j = i; j < (**param).height; j++) {
printf(" ");
} // end
// 별
for (k = 2*i-1; k >=1 ; k--) {
printf("*");
} // end for2
printf("\n"); // 개행
} //
} // end of _one_ function
// ================================
void _two_(STAR** param) { // func (4)
/*
ex)
*
***
*****
***
*
*/
unsigned int i, j, k;
// 상단
for (i = 1; i <= (**param).height; i++) {
// 공백
for (j = i; j < (**param).height; j++) {
printf(" ");
} // end
// 별
for (k = 1; k <= 2 * i - 1; k++) {
printf("*");
} // end for2
printf("\n"); // 개행
if (i == (**param).height) {
// 하단
for (i = (**param).height - 1; i >= 1; i--) {
// 공백
for (j = i; j <= (**param).height-1; j++) {
printf(" ");
} // endfor
// 별
for (k = 2 * i - 1; k >= 1; k--) {
printf("*");
} // endfor
printf("\n"); // 개행
} // endfor
i = (**param).height;
} // endif
} //
} // end of _two_ function
// ================================
void _three_(STAR** param) { // func (5)
/*
ex)
*****
***
*
***
*****
*/
unsigned int i, j, k;
// 상단
for (i = (**param).height; i >= 1; i--) {
// 공백
for (j = i; j < (**param).height; j++) {
printf(" ");
} // end
// 별
for (k = 2 * i - 1; k >= 1; k--) {
printf("*");
} // end for2
printf("\n"); // 개행
if (i == 1) {
// 하단
for (i = 1; i <= (**param).height - 1; i++) {
// 공백
for (j = i; j < (**param).height - 1; j++) {
printf(" ");
} // endfor
// 별
for (k = 1; k <= 2 * i + 1; k++) {
printf("*");
} // endfor
printf("\n"); // 개행
} // endfor
i = 1;
} // endif
} //
} // end of _three_ function
'언어 > c언어' 카테고리의 다른 글
버블 정렬 (0) | 2018.11.18 |
---|---|
c언어 네이버 지식인 풀이 (0) | 2018.11.17 |
네이버 지식인 답변 (0) | 2018.11.12 |
네이버 지식인 풀이 (0) | 2018.11.10 |
네이버 풀이 (0) | 2018.11.10 |
네이버 지식인 답변
# include <stdio.h>
typedef struct {
int left_x;
int left_y;
int right_x;
int right_y;
}RECT;
// function prototype ------------------
void _init_(RECT*); // func (1)
void insert(RECT*); // func (2)
void temp_coordi(RECT*); // func (3)
// -------------------------------------
int main(void) {
RECT rect_node;
_init_(&rect_node);
insert(&rect_node);
temp_coordi(&rect_node);
return 0;
} // end of main function
//--------------------------------------
void _init_(RECT* param) { // func (1)
// 데이터 초기화
// 좌상단
param->left_x = 0x0;
param->left_y = 0x0;
// 우하단
param->right_x = 0x0;
param->right_y = 0x0;
} // end of _init_ function
//--------------------------------------
void insert(RECT* param) { // func (2)
int temp_x = 0x0;
int temp_y = 0x0;
int flag = 0x0;
printf("좌상단점/우하단점의 좌표를 입력하세요(left, top, right, bottom 순)\n");
scanf("%d %d %d %d",
¶m->left_x, ¶m->left_y,
¶m->right_x, ¶m->right_y);
printf("입력된 직사각형: 좌상단점=(%d,%d), 우하단점=(%d,%d)\n",
param->left_x, param->left_y, param->right_x, param->right_y);
while (1) {
if (param->left_x < param->right_x) {
if (param->left_y < param->right_y) {
break;
}
else if (param->left_y > param->right_y) {
// case1-2) 좌상단의 x좌표가 우하단의 x좌표보다 작고
// 좌상단의 y좌표가 우상단의 y좌표보다 큰 경우
// y좌표를 서로 교체
temp_y = param->left_y;
param->left_y = param->right_y;
param->right_y = temp_y;
flag = 1;
break;
}
else {
// case1-3) 좌상단의 y좌표와 우하단의 y좌표가 서로 같은 경우
printf("사각형 영역을 형성할 수 없습니다.\n");
}
}
else if (param->left_x > param->right_x) {
// 좌상단의 x값이 우하단의 x값보다 더 큰 경우
if (param->left_y < param->right_y) {
// 좌상단의 y값이 우하단의 y값보다 더 작은 경우
// x값을 서로 교체
temp_x = param->left_x;
param->left_x = param->right_x;
param->right_x = temp_x;
flag = 1;
break;
}
else if (param->left_y > param->right_y) {
// 좌상단의 y값이 우하단의 y값보다 더 큰 경우
// 좌상단과 우하단의 좌표를 서로 교체
temp_x = param->left_x;
temp_y = param->left_y;
param->left_x = param->right_x;
param->left_y = param->right_y;
param->right_x = temp_x;
param->right_y = temp_y;
flag = 1;
break;
}
else { // param->left_y == param->right_y
printf("사각형 영역을 형성할 수 없습니다.\n");
}
}
else { // param->left_x == param->right_x
printf("사각형 영역을 형성할 수 없습니다.\n");
}
}
if (flag) {
printf("수정된 직사각형: 좌상단점=(%d,%d), 우하단점=(%d,%d)\n",
param->left_x, param->left_y, param->right_x, param->right_y);
}
} // end of insert function
//--------------------------------------
void temp_coordi(RECT* param) { // func (3)
int temp_x = 0;
int temp_y = 0;
printf("한점의 좌표를 입력하세요(x, y) : ");
scanf("%d %d", &temp_x, &temp_y);
if (param->left_x <= temp_x && param->right_x >= temp_x) {
if (param->left_y <= temp_y && param->right_y >= temp_y) {
printf("(%d, %d)는 직사각형 내부에 있습니다. \n", temp_x, temp_y);
}
else {
printf("(%d, %d)는 직사각형 내부에 없습니다. \n", temp_x, temp_y);
}
}
else {
printf("(%d, %d)는 직사각형 내부에 없습니다. \n", temp_x, temp_y);
}
} // end of temp_coordi function
'언어 > c언어' 카테고리의 다른 글
c언어 네이버 지식인 풀이 (0) | 2018.11.17 |
---|---|
네이버 지식인 풀이 (0) | 2018.11.14 |
네이버 지식인 풀이 (0) | 2018.11.10 |
네이버 풀이 (0) | 2018.11.10 |
네이버 지식인 풀이 (0) | 2018.11.07 |
네이버 지식인 풀이
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
// ================================
typedef struct {
int** Mat;
int size; // 행렬의 크기
int sum; // 행과열의 합
}Matrix;
// function prototype =============
void size_setting(Matrix**); // func (1)
void element_insert(Matrix**); // func (2)
void row_col_totalSum(Matrix**); // func (3)
// ================================
int main(void) {
Matrix* pMat = NULL;
pMat = (Matrix*)malloc(sizeof(Matrix)); // 메모리 할당
if (pMat == NULL) {
printf("malloc fail ... !!!\n");
exit(1);
}
size_setting(&pMat);
element_insert(&pMat);
row_col_totalSum(&pMat);
// 메모리 해제
free(pMat);
return 0;
} // end of main function
// ================================
void size_setting(Matrix** p) { // func (1)
int i, j; // index
printf("행렬 크기 입력: ");
scanf("%d", &(**p).size);
(*p)->Mat = (int**)malloc(sizeof(int*)*(**p).size);
for (i = 0; i < (**p).size; i++) {
*((*p)->Mat + i) = (int*)malloc(sizeof(int)*(**p).size);
}
// 배열 초기화
for (i = 0; i < (**p).size; i++) {
for (j = 0; j < (**p).size; j++) {
(*p)->Mat[i][j] = 0;
}
}
// 합 초기화
(** p).sum = 0x0;
// 확인
/*
for (i = 0; i < (**p).size; i++) {
for (j = 0; j < (**p).size; j++) {
printf("%d", (*p)->Mat[i][j]);
if (j != (**p).size - 1) {
printf(" ");
}
}
printf("\n");
}
*/
} // end of size_setting function
// ================================
void element_insert(Matrix** p) { // func (2)
int i, j;
srand((unsigned)time(NULL));
// 데이터 삽입
for (i = 0; i < (**p).size; i++) {
for (j = 0; j < (**p).size; j++) {
(*p)->Mat[i][j] = rand() % 20 + 1;
}
}
for (i = 0; i < (**p).size; i++) {
for (j = 0; j < (**p).size; j++) {
printf("%02d", (*p)->Mat[i][j]);
if (j != (**p).size - 1) {
printf(" ");
}
}
printf("\n");
}
} // end of element_insert function
// ================================
void row_col_totalSum(Matrix** p) { // func (3)
int r = 0; // 행
int c = 0; // 열
int i;
while (1) {
printf("행 입력 : ");
scanf("%d", &r);
printf("열 입력 : ");
scanf("%d", &c);
if (r < 0 || r >=(** p).size) {
printf("행 값이 범위를 벗어납니다.\n");
}
else {
// r >= 0 && r < (** p).size
if (c < 0 || c >= (** p).size) {
printf("열 값이 범위를 벗어납니다.\n");
}
else {
break;
}
}
}
for (i = 0; i < (**p).size; i++) {
// 행에 대한 합
(** p).sum += (** p).Mat[r][i];
}
for (i = 0; i < (**p).size; i++) {
// 열에 대한 합
(** p).sum += (** p).Mat[i][c];
}
printf("입력한 값의 행과 열의 전체 합은 : %02d\n", (** p).sum);
} // end of row_col_totalSum function
'언어 > c언어' 카테고리의 다른 글
네이버 지식인 풀이 (0) | 2018.11.14 |
---|---|
네이버 지식인 답변 (0) | 2018.11.12 |
네이버 풀이 (0) | 2018.11.10 |
네이버 지식인 풀이 (0) | 2018.11.07 |
네이버 지식인 풀이, c언어 숫자 거꾸로 출력 (0) | 2018.11.03 |
https://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=314071036&viewType=original
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
//=====================
typedef struct {
double x_coor;
double y_coor;
double z_coor;
}Coord, *ptrCoord;
// =============================
ptrCoord genNode(); // func (1)
void init(Coord**); // func (2)
void OnePrintf(Coord**); // func (3)
void DotDistance(Coord**);// func (4)
double Calc(Coord*, Coord*);//func (5)
// =============================
void main(void) { // main function
ptrCoord coodNode = NULL;
coodNode = genNode();
if (coodNode == NULL) {
printf("malloc error ... !!!\n");
exit(1);
}
init(&coodNode);
OnePrintf(&coodNode);
DotDistance(&coodNode);
// memory 해제
free(coodNode);
} // end of main function
// =============================
ptrCoord genNode() { // func (1)
ptrCoord newNode = NULL;
newNode = (ptrCoord)malloc(sizeof(Coord) * 4);
return newNode;
} // end of genNode function
// =============================
void init(Coord** param) { // func (2)
int i, j; // index
double tmp[][3] = {
{ 00.510, 7.620, 15.230},
{ 04.320, 4.990, 07.190},
{ 06.780, 5.230, 02.690},
{ 12.430, 1.120, 23.110} }; // 4x3 행렬
for (i = 0; i < 4; i++) {
j = 0x0;
((*param) + i)->x_coor = tmp[i][j++]; // x좌표
((*param) + i)->y_coor = tmp[i][j++]; // y좌표
((*param) + i)->z_coor = tmp[i][j]; // z좌표
}
} // end of init function
// =============================
void OnePrintf(Coord** param) { // func (3)
int i; // index
for (i = 0; i < 4; i++)
printf("%d번째 점의 : x : %0.3lf, y : %0.3lf, z : %0.3lf\n", i+1,
((*param) + i)->x_coor, ((*param) + i)->y_coor, ((*param) + i)->z_coor);
printf("\n");
} // end of OnePrintf function
// =============================
void DotDistance(Coord** param) { // func (4)
int i, j; // index
double result = 0.;
int flag = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (i != j) {
printf("%d번째 점과 %d번째 점 사이의 거리는 : ", i+1, j+1);
result = Calc(((*param) + i), ((*param) + j));
printf("%0.3lf\n", result);
flag = 1;
}
}
if (flag) {
printf("\n");
flag = 0;
}
}
} // end of DotDistance function
// =============================
double Calc(Coord* param1, Coord* param2) {
double retDouble = 0.;
retDouble = \
sqrt((pow(param1->x_coor - param2->x_coor, 2.0) +
pow(param1->y_coor - param2->y_coor, 2.0) +
pow(param1->z_coor - param2->z_coor, 2.0)), 2.0);
return retDouble;
} // end of Calc function
'언어 > c언어' 카테고리의 다른 글
네이버 지식인 답변 (0) | 2018.11.12 |
---|---|
네이버 지식인 풀이 (0) | 2018.11.10 |
네이버 지식인 풀이 (0) | 2018.11.07 |
네이버 지식인 풀이, c언어 숫자 거꾸로 출력 (0) | 2018.11.03 |
네이버 지식인 풀이 (0) | 2018.10.14 |
네이버 지식인 풀이
https://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=313858105
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <Windows.h>
# include <conio.h>
# define LEN 60
# define ERROR_ 1
typedef struct {
char my_passwd[LEN];
char input_passwd[LEN];
}PASSWRD;
// function prototype
// =========================================
PASSWRD* ret_new_node();
void init(PASSWRD** param);
void password_write(PASSWRD** param);
void compare(PASSWRD** param);
// =========================================
int main(void) {
PASSWRD* mPass = NULL;
mPass = ret_new_node();
if (mPass == NULL) {
printf("malloc fail ... !!!\n");
exit(ERROR_);
}
init(&mPass);
password_write(&mPass);
compare(&mPass);
free(mPass);
return 0;
} // end of main function
PASSWRD* ret_new_node() { // function (1)
PASSWRD* tmpNode = NULL;
tmpNode = (PASSWRD*)malloc(sizeof(PASSWRD));
return tmpNode;
} // end of ret_new_node function
// =========================================
void init(PASSWRD** param) { // function (2)
// 데이터 초기화
strcpy((*param)->input_passwd, "\0");
strcpy((*param)->my_passwd, "\0");
// 패스워드 설정
strcpy((*param)->my_passwd, "hello1234");
} // end of init function
// =========================================
void password_write(PASSWRD** param) {
int i = 0; // index
printf("PassWord: ");
while (1) {
if (_kbhit()) {
(*param)->input_passwd[i] = _getch();
if ((int)((*param)->input_passwd[i]) == 13) {
break;
}
i += 1;
printf("*");
//rewind(stdout);
}
}
printf("\n");
(*param)->input_passwd[i] = '\0';
printf("%s\n", (*param)->input_passwd);
} // end of password_write function
// =========================================
void compare(PASSWRD** param) {
if (!strcmp((*param)->input_passwd, (*param)->my_passwd)) {
printf("same \n");
}
else {
printf("not same\n");
}
} // end of compare function
'언어 > c언어' 카테고리의 다른 글
네이버 지식인 풀이 (0) | 2018.11.10 |
---|---|
네이버 풀이 (0) | 2018.11.10 |
네이버 지식인 풀이, c언어 숫자 거꾸로 출력 (0) | 2018.11.03 |
네이버 지식인 풀이 (0) | 2018.10.14 |
네이버 지식인 풀이 링크드 리스트 (0) | 2018.10.13 |
hexcolor 사이트 python 크롤링
from selenium import webdriver
import pandas as pd
import time
from bs4 import BeautifulSoup
import re
import pprint as ppr
#==============================
class STU:
def __init__(self):
self.path = "C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe"
self.driver = webdriver.Chrome(self.path)
self.html = None
self.bs_object = None
self.color_info = dict() # dictionary
self.target_url = "https://www.color-hex.com"
"""
{'#1234':{'sub_url':'/#1234', 'list':[]}}
"""
# Func (1)
def step01(self):
self.driver.get(self.target_url)
# https://www.color-hex.com/color/750a64
time.sleep(2)
self.html = self.driver.page_source
self.bs_object = BeautifulSoup(self.html, "html.parser")
t = self.bs_object.select("div.colordvcon > a")
for i in t:
clr_key = str(i.attrs['title']).split(sep=" ")
clr_key = clr_key[0][1:]
self.color_info[clr_key] = {
'sub_url':self.target_url + i.attrs['href'], # ex) /color/750a64
'sub_color_list':[],
}
ppr.pprint (self.color_info)
for n, k in enumerate(self.color_info.keys()):
print ("{} 작업 중 ...".format(n+1))
# 새창
self.driver.execute_script("window.open()")
self.driver.switch_to.window(self.driver.window_handles[1])
self.driver.get(self.color_info[k]['sub_url'])
time.sleep(3) # 3 seconds
self.html = self.driver.page_source
self.bs_object = BeautifulSoup(self.html, "html.parser")
t = self.bs_object.find_all('div', {"class":"colordvconline"}) # type list
for i in t:
color_text = re.sub('[\n\t\r ]', '', i.text)
self.color_info[k]['sub_color_list'].append(color_text)
time.sleep(1)
self.driver.close()
# 원래 창으로 회귀
self.driver.switch_to.window(self.driver.window_handles[0])
self.driver.close()
# Func (2)
def step2(self):
for k in self.color_info.keys():
for i in k:
ppr.pprint (self.color_info[i]['sub_color_list'])
def main():
sNode = STU() # 인스턴스 객체 생성
sNode.step01()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
selenium + pandas + 연습 중 (0) | 2018.11.15 |
---|---|
python selenium (0) | 2018.11.15 |
사람인 크롤링 (version 2.3 - 2018-11-07) (2) | 2018.11.05 |
python mysql (0) | 2018.11.04 |
간단한 주말 프로젝트 (0) | 2018.11.03 |
사람인 크롤링 (version 2.3 - 2018-11-07)
#=============================================
import selenium.webdriver as selWeb
import openpyxl
from openpyxl.styles import Color, PatternFill
import time
import mysql.connector
from mysql.connector import Error, errorcode
import sys
from bs4 import BeautifulSoup
import datetime
import pprint as ppr
import re
import pymongo_stu
import Chat_pie
import os
#=============================================
class DB:
# 생성자
def __init__(self):
self.user_Info = {'id': None, 'pw': None}
self.database_conn_info = {
'DB_ID': 'root',
'DB_PW': '1234',
'DB_SRV_IP': '127.0.0.1',
'DB_name': 'saramin',
}
"""
func (1)
MySQL server에 접근
"""
def F_db_connect(self):
try: # 접근시도
conn = mysql.connector.connect(
user = self.database_conn_info['DB_ID'], # user id
password = self.database_conn_info['DB_PW'], # user pw
host = self.database_conn_info['DB_SRV_IP'], # server ip
database = self.database_conn_info['DB_name']) # database
except Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("접근 계정이 잘못된 것 같습니다.")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print ("해당 DB가 존재하지 않습니다.")
else:
print (err)
sys.exit(1)
else:
print ("DB에 정상적으로 접근 되었습니다.")
cursor = conn.cursor()
try:
sql = "SELECT * FROM `INFO`"
cursor.execute(sql)
except Error as err:
if err.errno == errorcode.ER_NO_SYSTEM_TABLE_ACCESS_FOR_SYSTEM_TABLE:
print ("해당 Database에 table이 존재하지 않습니다.")
else:
print (err)
sys.exit(1)
else:
t_info = cursor.fetchone()
self.user_Info['id'], self.user_Info['pw'] = t_info
cursor.close()
conn.close()
"""
func (2)
회사 이름 적재
"""
def F_table_data_insert(self, data_list):
try: # 접근시도
conn = mysql.connector.connect(
user = self.database_conn_info['DB_ID'], # user id
password = self.database_conn_info['DB_PW'], # user pw
host = self.database_conn_info['DB_SRV_IP'], # server ip
database = self.database_conn_info['DB_name']) # database
except Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("접근 계정이 잘못된 것 같습니다.")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print ("해당 DB가 존재하지 않습니다.")
else:
print (err)
sys.exit(1)
else:
print ("DB에 정상적으로 접근 되었습니다.")
cursor = conn.cursor()
sql = "INSERT INTO `cor_info` (c_name) VALUES (%s)"
for i in data_list:
try:
cursor.execute(sql, (i,))
except Error as err:
if err.errno == errorcode.ER_INSERT_INFO:
print ("데이터 삽입이 이루어지지 못했습니다.")
else:
print (err)
else:
print ("데이터 삽입 성공")
conn.commit()
cursor.close()
conn.close()
class XL:
# 생성자
def __init__(self):
# 디렉토리 이동
self.current_work_dir = os.chdir("C:\\Users\\sleep\\Desktop\\cor_list")
self.time_info = datetime.datetime.now().strftime("%Y-%m-%d")
# self.readWb = openpyxl.load_workbook()
self.wb = openpyxl.Workbook() # workbook
self.ws = None # worksheet
self.wbRead = None
self.xlIndx = [['c', 4], ['D', 4], ['E', 4], ['F', 4], ['G', 4], ['H', 4]]
self.xlTag = ['회사이름', '내용', '조건1', '조건2', '위치', '마감일']
self.me_support_cor_list = list() # 내가 지원한 회사 정보
# func (1)
"""
{'회사이름': '(주)지금컴퍼니', '조건1': '2년 up', '조건2': '고졸↑', '위치': '서울 송파구'}
c_info_data => [ { ... } ]
엑셀 적재 부분
"""
def sheetSetting(self, c_info_data):
# matplotlib을 사용하여 그래프
label_data = {'경력무관': 0,
'신입': 0,
'신입 · 경력': 0,
'경력자': 0}
# 엑셀에 데이터를 적재하는 부분]
self.ws = self.wb.create_sheet(title=self.time_info) # worksheet
print ("sheet가 정상적으로 생성 되었습니다.")
# 셀에 열너비 ========================================================
self.ws.column_dimensions["C"].width = 28.9 # 회사이름
self.ws.column_dimensions["D"].width = 60.1 # 내용
self.ws.column_dimensions["E"].width = 14.7 # 조건1
self.ws.column_dimensions["F"].width = 13.9 # 조건2
self.ws.column_dimensions["G"].width = 17.9 # 위치
self.ws.column_dimensions["H"].width = 11.0 # 마감일
# ==================================================================
for i, j in zip(self.xlIndx, self.xlTag):
self.ws[i[0] + str(i[1])] = j; i[1] += 1
t_num_i = ['B', 5]
cnt = 1
for e in c_info_data:
for k, i in zip(e.keys(), self.xlIndx):
self.ws[t_num_i[0] + str(t_num_i[1])] = cnt; # 번호
self.ws[i[0]+str(i[1])] = e[k]
if k == '조건1':
if e[k] == "경력무관":
self.ws[self.xlIndx[0][0] + str(self.xlIndx[0][1])].fill = \
PatternFill(patternType='solid', fgColor=Color('ff5e67'))
label_data["경력무관"] += 1
elif e[k] == "신입":
self.ws[self.xlIndx[0][0] + str(self.xlIndx[0][1])].fill = \
PatternFill(patternType='solid', fgColor=Color('b4eeb4'))
label_data["신입"] += 1
elif e[k] == "신입 · 경력":
self.ws[self.xlIndx[0][0] + str(self.xlIndx[0][1])].fill = \
PatternFill(patternType='solid', fgColor=Color('efc253'))
label_data["신입 · 경력"] += 1
else:
self.ws[self.xlIndx[0][0] + str(self.xlIndx[0][1])].fill = \
PatternFill(patternType='solid', fgColor=Color('969696'))
label_data["경력자"] += 1
for tmp in self.xlIndx:
tmp[1] += 1
cnt += 1
t_num_i[1] += 1
# 데이터 적재 후 저장
self.wb.save("today_{}.xlsx".format(datetime.datetime.now().strftime("%M")))
# 그래프 출력 함수
Chat_pie.pie_chart(label_data)
'''
def readXlfile(self):
for xf in os.listdir():
fname, fexf = os.path.splitext(xf)
"""
fname : 확장자를 제외한 파일 이름/ fexf : 파일 확장자
"""
if fexf == ".xlsx":
# 엑셀 파일 read
self.wbRead = openpyxl.load_workbook(filename=xf)
tmp_filter = re.compile(pattern='(\d{4})-(\d{2})-(\d{2}')
for s in self.wbRead.sheetnames:
if tmp_filter.search(s):
print (s)
'''
class STU01(XL, DB, pymongo_stu.MongoDBstu):
def __init__(self):
XL.__init__(self) # 부모 클래스 초기화
DB.__init__(self) # 부모 클래스 초기화
pymongo_stu.MongoDBstu.__init__(self) # 부모 클래스 초기화
# ===============================================================
self.target_url = "https://www.saramin.co.kr/zf_user/"
self.chromDriver_path = "C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe"
self.selHandler = None
self.html = None
self.saramin_data = list() # 사람인에 지원한 회사 리스트
"""
날짜, 시간, 회사, 지원
"""
self.day_filter = re.compile("(\d{4})-(\d{2})-(\d{2})")
self.time_filter = re.compile("(\d{2}):(\d{2}):(\d{2})")
"""
func (2)
"""
def F_web_requests(self):
""" 사람인 사이트에 접근 시도 """
self.selHandler = selWeb.Chrome(executable_path=self.chromDriver_path)
self.selHandler.get(url=self.target_url)
time.sleep(2)
assert "사람인" in self.selHandler.title
self.selHandler.find_element_by_id('login_person_id').send_keys(self.user_Info['id'])
self.selHandler.find_element_by_id('login_person_pwd').send_keys(self.user_Info['pw'])
self.selHandler.find_element_by_xpath('//*[@id="login_frm"]/fieldset/div/button').click()
time.sleep(2)
"""
전체 스크린
: 전체 스크린을 하지 않으면 아바타서치 버튼이 활성화가 안됨
"""
self.selHandler.fullscreen_window()
# 아바타 서치 : a_tag
time.sleep(2)
self.selHandler.find_element_by_link_text('아바타서치').click()
time.sleep(2)
self.selHandler.execute_script("window.scrollTo(0, document.body.scrollHeight);")
temp = self.selHandler.page_source
self.html = BeautifulSoup(temp, "html.parser")
lis_avatar = self.html.find("div", {"class":"list_avatar"})
data_list = lis_avatar.find_all("ul", {"class":"info_list"})
date_list = lis_avatar.select("div.date > span") # 날짜 정보
self.selHandler.close() # selenium 닫기
"""
데이터 조회
"회사이름":None, # 구글
"내용":None, # 서울아산병원 DeepBrain 연구실 및 회사 연구원 채용
"조건1":None, # 신입, 경력
"조건2":None, # 대학
"위치":None # 서울
"""
for v, d in zip(data_list, date_list):
t_insert = {"회사이름":None, "내용":None, "조건1":None,
"조건2":None, "위치":None, "마감날짜":None}
# =====================================================
# 1. 회사명
c_name = v.select_one("li.company_name.avatar_list > a")
c_name = c_name.string
t_insert["회사이름"] = c_name
# =====================================================
# 2. 내용
c_text = v.select_one("li.recruit_name > a")
c_text = c_text.string
t_insert["내용"] = c_text
# =====================================================
# 3.
t = v.select("li.recruit_sector > a > span")
t_0 = str(t[0].string)
if '↑' in t_0:
t_0 = t_0.replace('↑', ' up')
t_1 = str(t[1].string)
if '↑' in t_1:
t_1 = t_1.replace('↑', ' up')
t_insert["조건1"] = t_0 # ex) 신입 - 1. 빨/ 2. 노/ 3. 초
t_insert["조건2"] = t_1 # ex) 대학교(4년)
t_insert["위치"] = t[2].string # ex) 서울 강남구
# =====================================================
# 4. 마감날짜
t_insert["마감날짜"] = d.string
# =====================================================
# print("{0} : {1}".format(indx+1, c_name))
self.saramin_data.append(t_insert)
"""
func (4)
"""
def F_data_check(self):
for indx, valu in enumerate(self.saramin_data):
print (indx+1, ": ", valu)
self.sheetSetting(self.saramin_data)
"""
func (5)
: 지원 list (Saram IN)
"""
def F_saramin_supp_list(self):
""" 사람인 사이트에 접근 시도 """
self.selHandler = selWeb.Chrome(executable_path=self.chromDriver_path)
self.selHandler.get(url=self.target_url)
time.sleep(2)
assert "사람인" in self.selHandler.title
self.selHandler.find_element_by_id('login_person_id').send_keys(self.user_Info['id'])
self.selHandler.find_element_by_id('login_person_pwd').send_keys(self.user_Info['pw'])
self.selHandler.find_element_by_xpath('//*[@id="login_frm"]/fieldset/div/button').click()
time.sleep(2)
self.selHandler.find_element_by_link_text("지원현황").click()
print ("지원현황 리스트를 확인 중 입니다.")
time.sleep(2) # 2초 딜레이
# 처음 페이지 ===============================================================
t_html = self.selHandler.page_source
html = BeautifulSoup(t_html, "html.parser")
list_v = html.select_one("#applyStatusList > tbody")
# 날짜/ 시간 정보
info_day = list_v.select("tr > td.apply_date_row")
info_day = [re.sub("[\n,\r,\t, ,]", "", i.text) for i in info_day]
# 회사 이름
cor_name = list_v.select("tr > td.apply_comp > a")
cor_name = [e.attrs['title'] for e in cor_name]
# 지원 내역
info_sup = list_v.select("tr > td.apply_comp_cont > strong > a")
info_sup = [e.attrs['title'] for e in info_sup]
for d, c, s in zip(info_day, cor_name, info_sup):
tmp_data = {"날짜":None, "시간":None, "회사":None, "지원":None}
d_result = self.day_filter.search(d)
t_result = self.time_filter.search(d)
if d_result and t_result:
# 날짜 정보
indx = d_result.span()
result_day = d[indx[0]:indx[1]]
# 시간 정보
indx = t_result.span()
result_time = d[indx[0]:indx[1]]
"""
날짜, 시간, 회사, 지원
"""
tmp_data['날짜'] = result_day
tmp_data['시간'] = result_time
tmp_data['회사'] = c
tmp_data['지원'] = s
self.saramin_data.append(tmp_data) # 데이터 적재
# print (result_day, result_time, c, s)
# =========================================================================
page_list = self.selHandler.find_elements_by_css_selector("#content > div > div.manage_list_wrap > div.page_nation > a")
for p in page_list:
p.click() # 페이지 클릭
t_html = self.selHandler.page_source
html = BeautifulSoup(t_html, "html.parser")
list_v = html.select_one("#applyStatusList > tbody")
# 날짜/ 시간 정보
info_day = list_v.select("tr > td.apply_date_row")
info_day = [re.sub("[\n,\r,\t, ,]", "", i.text) for i in info_day]
# 회사 이름
cor_name = list_v.select("tr > td.apply_comp > a")
cor_name = [e.attrs['title'] for e in cor_name]
# 지원 내역
info_sup = list_v.select("tr > td.apply_comp_cont > strong > a")
info_sup = [e.attrs['title'] for e in info_sup]
for d, c, s in zip(info_day, cor_name, info_sup):
tmp_data = {"날짜": None, "시간": None, "회사": None, "지원": None}
d_result = self.day_filter.search(d)
t_result = self.time_filter.search(d)
if d_result and t_result:
# 날짜 정보
indx = d_result.span()
result_day = d[indx[0]:indx[1]]
# 시간 정보
indx = t_result.span()
result_time = d[indx[0]:indx[1]]
"""
날짜, 시간, 회사, 지원
"""
tmp_data['날짜'] = result_day
tmp_data['시간'] = result_time
tmp_data['회사'] = c
tmp_data['지원'] = s
self.saramin_data.append(tmp_data) # 데이터 적재
# print(result_day, result_time, c, s)
time.sleep(2)
# =========================================================================
"""
데이터 출력
"""
for i, u in enumerate(self.saramin_data):
print ("{} : {}".format(i+1, u))
"""
MongoDB에 데이터 적재
"""
self.mongodb_insert(element=self.saramin_data)
# 소멸자
# def __del__(self):
# self.wb.save("today.xlsx")
def main():
sNode = STU01() # 객체생성
sNode.F_db_connect() # 사람인 로그인 계정
"""
내게 추천하는 회사 정보를 보시겠습니까?
본다 (Y) / 안본다 (N)
"""
sNode.F_web_requests() # 사람인 사이트 요청
sNode.F_data_check()
"""
사람인 사이트에서 지원환 회사 정보들
"""
# sNode.F_saramin_supp_list()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
python selenium (0) | 2018.11.15 |
---|---|
hexcolor 사이트 python 크롤링 (0) | 2018.11.06 |
python mysql (0) | 2018.11.04 |
간단한 주말 프로젝트 (0) | 2018.11.03 |
카라바오 컵 파이썬 크롤링 (0) | 2018.11.01 |