레이블이 python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 python인 게시물을 표시합니다. 모든 게시물 표시

2018년 10월 29일 월요일

[python] 월별로 난수 생성하기

파이썬에는 아쉬운게 timedelta에 month를 더하는 것이 없다. 다른 유틸을 받아서 사용하면 된다고 하는데 이렇게 해도 잘 되는 것 같다.
import random
import string
import csv
import datetime
import calendar

random_numbers = set()
for _ in range(120):
res = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(16))
random_numbers.add(res)

def add_months(sourcedate, months) -> datetime.date:
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
return datetime.date(year,month,1)


somedate = datetime.date(2018, 4, 1)
with open('random_number.txt', 'w', newline='\n') as f:
w = csv.writer(f, delimiter=' ', quoting=csv.QUOTE_NONE)
for idx, num in enumerate(random_numbers):
w.writerow([add_months(somedate, idx).strftime('%Y-%m'), num])


# print(len(random_numbers))

[codility][python] max counter

codility max counter

https://app.codility.com/demo/results/trainingUBUCBJ-RVE/

def solution(N, A):
  res = [0] * N
  max_counter = 0

  for a in A:
    if a <= N:  # N카운터 존재
      res[a-1] +=1  # 카운터 올림
      if max_counter < res[a-1]: # max_counter 보다 크면 현재 카운터를 tmp_max로 변경
        max_counter = res[a-1] 
    else: # max counter 실행
      for i in enumerate(res):  # 전부 max_counter로 덮어씌운다.
        res[i] = max_counter
  return res
빅오노테이션이 O(MxN) 인 관계로 이중포문에서 하나를 없애야 한다.
# N 카운터가 있음. 0으로 세팅
# max counter : 모든 카운터들이 아무 카운터의 최대 값으로 세팅됨.

# A[K] = X 이면, K오퍼레이션은 X를 증가시킨다.
# -> 값이 X면 X를 증가시킴 (X범위 1<=X<=N)
# A[K] = N + 1 이면 K는 max counter  (??? K가 N보다 크면 max??)
# 아아아 max counter라는 걸 실행함!!!

def solution(N, A):
  res = [0] * N
  max_counter = 0
  tmp_max = 0
  for a in A:
    if a <= N:  # N카운터 존재
      if max_counter > res[a-1]:  # 1 max_counter가 더 크면 max_counter가 갱신된 것
        res[a-1] = max_counter  # 2 max_counter 값으로 변경해준다.
      res[a-1] +=1  # 3 그리고 그 다음에 카운터 시킨다
      if tmp_max < res[a-1]:  # 4 tmp_max보다 크면 현재 카운터를 tmp_max로 변경
        tmp_max = res[a-1]

    else:  # max_counter 에 현재 tmp_max를 넣는다. (max_counter는 그때그때 실행할 것이다.)
      max_counter = tmp_max

  # 아직 max_counter가 변경 된 이후에 counter가 변경된 이력이 없으면 max_counter로 덮어씌워준다.
  # 물론 max_counter보다 작은 경우.
  for idx, _ in enumerate(res):  
    if (res[idx] < max_counter):
      res[idx] = max_counter

  return res

a = [3,4,4,6,1,4,4]
N = 5

print(solution(5, a))

[hackerrank][python]Journey to the Moon

hackerrank: Journey to the Moon


1st attempt

# Determine how many pairs of astronauts from different countries they can choose from.
# UN 연합은 달에 사람들을 보내려고 한다.
# 그들은 이 사람들이 서로 다른 나라였으면 한다.
# 당신은 두 쌍의 우주조종사 id 리스트를 받을 것이다.
# 각 쌍은 같은 나라 우주조종사 id의 두 쌍으로 이루어져 있다.
# - 얼마나 많은 조종사 쌍을 만들 수 있는지 말해라.

# n : number of astronaut
# p : the number of pairs
from collections import defaultdict

# 일단 연결된 것들을 만든다.
def dfs(graph, start):
  visited, stack = set(), [start]
  while stack:
    v = stack.pop()
    visited.add(v)
    # 해당 정점에 연결된 것들을 stack에 넣는다.
    # 방문한 것은 제외
    stack.extend(graph[v] - visited)
  # 연결된 것들을 리턴.
  return visited

def journeyToMoon(n, ast_pairs):
  graph = defaultdict(set)
  asts = set()
  # 그래프 연결...
  for a1, a2 in ast_pairs:
    graph[a1].add(a2)
    graph[a2].add(a1)
    asts.add(a1)
    asts.add(a2)
  
  # 고립된 애들이 있을 수 있나? 일단 받아놔... (있는듯...)
  iso_asts = set([i for i in range(n)]) - asts
  
  groups = []  # divied by contry
  while asts:
    ast = asts.pop()
    connected_asts = dfs(graph, ast)
    groups.append(connected_asts)
    # 한번 방문한 팀은 다시 방문하지 않는다.
    asts = asts - connected_asts
  
  for i in iso_asts:
    groups.append({i})
  
  idx1, idx2 = 0, 1
  group_sum = 0
  while idx1 < len(groups)-1:
    idx2 = idx1 + 1
    while idx2 < len(groups):
      group_sum += len(groups[idx1]) * len(groups[idx2])
      idx2 += 1
    idx1 += 1
 
  return group_sum
    
  
n, p = list(map(int, input().strip().split(' ')))
ast_pairs = []
for _ in range(p):
   astronaut = [int(a) for a in input().strip().split(' ')]
   ast_pairs.append(astronaut)
   
result = journeyToMoon(n, ast_pairs)
print(result)
def dfs(graph, start):
  visited, stack = set(), [start]
  while stack:
    v = stack.pop()
    visited.add(v)
    stack.extend(graph[v] - visited)
  return visited

def journeyToMoon(n, ast_pairs):
  graph = defaultdict(set)
  asts = set()
  for a1, a2 in ast_pairs:
    graph[a1].add(a2)
    graph[a2].add(a1)
    asts.add(a1)
    asts.add(a2)
  
  iso_asts = set([i for i in range(n)]) - asts
  
  groups = []  # divied by contry
  while asts:
    ast = asts.pop()
    connected_asts = dfs(graph, ast)
    groups.append(connected_asts)
    # 한번 방문한 팀은 다시 방문하지 않는다.
    asts = asts - connected_asts
  
  for i in iso_asts:
    groups.append({i})
  
  # 뒤에 추가된 것들을 따로 분리해야 한다. 그래야 추가된 녀석들이 만드는
  # 패턴을 알 수 있다.
  # A*B + A*C + B*C -- A*B + A*C + B*C -- A*B + (A+B)*C 
  # A*B + A*C + A*D + B*C + B*D + C*D 
  # - A*B + (A+B)*C (A+B+C)*D
  # A*B + A*C + A*D + A*E + B*C + B*D + B*E + C*D + C*E + D*E
  # - A*B + (A+B)*C + (A+B+C)*D + (A+B+C+D)*E 
  idx1, idx2 = 0, 1
  group_sum = 0
  tmp_sum = 0
  while idx1 < len(groups):
    group_sum += tmp_sum*len(groups[idx1])
    tmp_sum += len(groups[idx1])

    # group_sum += tmp_sum*(len(groups[idx1 + 1]))
    idx1 += 1
  
  return group_sum
    
  
n, p = list(map(int, input().strip().split(' ')))
ast_pairs = []
for _ in range(p):
   astronaut = [int(a) for a in input().strip().split(' ')]
   ast_pairs.append(astronaut)
   
result = journeyToMoon(n, ast_pairs)
print(result)

2018년 7월 13일 금요일

[python][hackerrank] Repeated String

https://www.hackerrank.com/challenges/repeated-string/problem

strings = input()

# number_of_a = len(''.join(x for x in strings if x == 'a'))
number_of_a = strings.count('a')

n = int(input())

_div, _mod = divmod(n, len(strings))
res = _div * number_of_a

for s, m in zip(strings, range(_mod)):
  if s == 'a':
    res += 1
    
print(res)

python cookbook Strings and Text

String

2.1. Splitting Strings on Any of Multiple Delimiters
>>> line = 'asdf fjdk; afed, fjek,asdf,       fo'
>>> import re
>>> re.split(r'[;,\s]\s*', line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']

>>> files = re.split(r'(;|,|\s)\s*', line)
>>> files
['asdf', ' ', 'fjdk', ';', 'afed', ',', 'fjek', ',', 'asdf', ',', 'fo']
>>> values = files[::2]
>>> values
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']
>>> delimiters = files[1::2]
>>> delimiters
[' ', ';', ',', ',', ',']
>>> ''.join(v+d for v,d in zip(values, delimiters))
'asdf fjdk;afed,fjek,asdf,'

>>> re.split(r'(?:,|;|\s)\s*',line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']


2.2 Matching Text at the Start or End of a String
>>> filename = 'peter.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('peter')
True

>>> choices = ['http:', 'ftp:']
>>> url = 'http://www.python.org'
>>> url.startswith(tuple(choices))
>>> re.match('http:|https:|ftp', url)
<_sre.SRE_Match object; span=(0, 5), match='http:'>

2.3 Matching Strings Using Shell Wildcard Patterns
>>> from fnmatch import fnmatch, fnmatchcase
>>> names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
>>> [name for name in names if fnmatch(name, 'Dat*.csv')]
['Dat1.csv', 'Dat2.csv']

>>> fnmatchcase('foo.txt.','*TXT')
False


2.4. Matching and Searching for Text Patterns
>>> from fnmatch import fnmatch, fnmatchcase
>>> names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
>>> [name for name in names if fnmatch(name, 'Dat*.csv')]
['Dat1.csv', 'Dat2.csv']

>>> fnmatchcase('foo.txt.','*TXT')
False

2018년 4월 22일 일요일

조합/중복조합 [파이썬]

역시 파이썬이 더 재미있다.
def factorial(n):
  if n <= 1:
    return 1
  else:
    result = 1
    for i in range(2, n+1):
      result *= i
    return result

# nCk = n! / (n-k)! * k!
def comb_slow(n, k):
  return factorial(n) / (factorial(k)*factorial(n-k))
  
print(comb_slow(6,3))

def comb_fast(n, k):
  numerator = 1
  denominator = 1
  k = min(n-k, k)  # nCk에서 더 적은 수로 계산하기 위해서.
  den_list = []
  num_list = []
  for i in range(k):  # 기존 소스에서 이곳을 변경함.
    denominator *= i + 1
    numerator *= n-i
    den_list.append(i+1)
    num_list.append(n-i)
  print('den_list={}'.format('*'.join(str(x) for x in den_list)))
  print('num_list={}'.format('*'.join(str(x) for x in num_list)))
  
  return numerator/denominator
  
print(comb_fast(6,3))

# 번외 중복조합
# nHr = n+r-1Cr
def ham(n, k):
  return comb_fast(n+k-1, k)
  
print(ham(6, 3))
# 참고문헌 : https://smlee729.github.io/python/algorithm/2015/03/08/1-nchoosek.html

2018년 4월 9일 월요일

[python] property 알기

# property

class Square(object):
  def __init__(self, side):
    self.side = side
  def aget(self):
    return self.side ** 2
  def aset(self, value):
    print('no')
  def adel(self, value):
    print('no')
  area = property(aget, aset, adel, doc='area') # 이게 중요!!
  
s = Square(5)
print(s.area)



"""Properties with decorators.
데코레이터를 사용하게 된다. 위에 내용과 같다.
"""

from __future__ import print_function

class Square(object):
    """A square using properties with decorators.
    """
    def __init__(self, side):
        self.side = side
    @property
    def area(self):
        """Calculate the area of the square when the
        attribute is accessed."""
        return self.side * self.side
    @area.setter
    def area(self, value):
        """Don't allow setting."""
        print("Can't set the area")
    @area.deleter
    def area(self):
        """Don't allow deleting."""
        print("Can't delete the area.")

if __name__ == '__main__':

    square = Square(5)
    print('area:', square.area)
    print('try to set')
    square.area = 10
    print('area:', square.area)
    print('try to delete')
    del square.area
    print('area:', square.area)

[python] 스레드 상속하기(subclass)

import time
import threading

class MyThread(threading.Thread):
  def __init__(self, number, style, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.number = number
    self.style = style

  def run(self, *args, **kwargs):
    print('thread starting')
    super().run(*args, **kwargs)
    print('thread has ended')

  def sleeper(num, style):
    print('sleeping for {} {}'.format(num, style))
    time.sleep(num)


t = MyThread(number=3, style='yellow', target=sleeper, args=[3, 'yellow'])
t.start()

[python] 난수 생성하기

출처 : https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python

파이썬에서 난수를 생성할때 알파벳과 숫자를 더해서 만들 수 있겠다.


파이썬의
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
random_numbers = set()
for _ in range(240):
    res = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
    random_numbers.add(res)

with open('random_number.txt', 'w', newline='\n') as f:
    [f.write(num+'\n') for num in random_numbers]
print(len(random_numbers))

하지만 이건 좀 안전하지 않다.
res = ''.join(random.SystemRandom()
                    .choice(string.ascii_uppercase + string.digits) for _ in range(10))
이렇게 사용하는게 좋겠다.

[largorithm][mergesort] 머지소트 (C / Python)

C Language


main.c

#include 
#include 
#include "mergesort.h"

void printArray(int value[], int count);

int main()
{
    int values[] = { 80, 75, 10, 60, 15, 49, 12, 25 };
    int count = sizeof(values)/sizeof(int);

    mergesort(values, count);
    printArray(values, count);
    return 0;
}


void printArray(int value[], int count)
{
    int i = 0;
    for(i = 0; i < count; i++) {
        printf("%d ", value[i]);
    }
    printf("\n");
}

mergesort.h

#ifndef MERGESORT_H_INCLUDED
#define MERGESORT_H_INCLUDED

void mergesort(int* arr, int count);

#endif // MERGESORT_H_INCLUDED

mergesort_impl.c

#include 
#include 

#include "mergesort.h"

void _mergesort(int* arr, int* pBuffer, int start, int end);
void _mergesort_division(int* arr, int* pBuffer, int start, int middle, int end);

void mergesort(int* arr, int count)
{
    int* pBuffer = (int*)malloc(sizeof(int) * count);
    if(pBuffer != NULL)
    {
        _mergesort(arr, pBuffer, 0, 7);

        free(pBuffer);
    }
}

void _mergesort(int* arr, int* pBuffer, int start, int end)
{
    int middle = 0;
    if (start < end)
    {
        middle = (start + end) / 2;
        _mergesort(arr, pBuffer, start, middle);
        _mergesort(arr, pBuffer, middle+1, end);
        _mergesort_division(arr, pBuffer, start, middle, end);
    }
}

void _mergesort_division(int* arr, int* pBuffer, int start, int middle, int end)
{
    int i = 0, j = 0, k = 0, t = 0;
    i = start;
    j = middle + 1;
    k = start;

    while(i <= middle && j <= end)
    {
        if(arr[i] <= arr[j])
        {
            pBuffer[k] = arr[i];
            i++;
        }
        else
        {
            pBuffer[k] = arr[j];
            j++;
        }
        k++;
    }

    if(i <= middle)
    {
        for(t = i; t <= middle; t++, k++)
        {
           pBuffer[k] = arr[t];
        }
    }
    else
    {
        for(t = j; t <= end; t++, k++)
        {
            pBuffer[k] = arr[t];
        }
    }

    for (t = start; t <= end; t++)
    {
        arr[t] = pBuffer[t];
    }
}

Python

def merge_sort(arr):
    print('split', arr)
    if len(arr) > 1:
        mid = len(arr) // 2
        left = arr[:mid]
        right = arr[mid:]
        
        merge_sort(left)
        merge_sort(right)

        i, j, k = 0, 0, 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            arr[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            arr[k] = right[j]
            j += 1
            k += 1
    print('merge', a)
a = [80, 75, 10, 60, 15, 49, 12, 25]
merge_sort(a)
print(a)

[quicksort] 퀵소트 (quicksort with C / Python)

C-language


main.c

#include 
#include 
#include 

#include "selection_sort.h"
#include "quicksort.h"

void printArray(int value[], int count);

int main()
{
    int values[] = { 80, 75, 10, 60, 15, 49, 12, 25 };
    int count = sizeof(values)/sizeof(int);


    printf("quicksort\n");
    // selection_sort(values, count);
    quicksort(values, count);
    printArray(values, count);
    return 0;
}


void printArray(int value[], int count)
{
    int i = 0;
    for(i = 0; i < count; i++) {
        printf("%d ", value[i]);
    }
    printf("\n");
}

quicksort.h

#ifndef QUICKSORT_H_INCLUDED
#define QUICKSORT_H_INCLUDED

void quicksort(int* value, int count);
void _quicksort(int* value, int start, int end);
int quicksort_division(int* value, int left, int right);
void swap(int* left, int* right);
#endif // QUICKSORT_H_INCLUDED

quicksort.c

#include 
#include "quicksort.h"

void quicksort(int* value, int count)
{
    _quicksort(value, 0, count -1);
}

void _quicksort(int* value, int start, int end)
{
    int pivot = 0;

    if (start < end) {
        pivot = quicksort_division(value, start, end);
        _quicksort(value, start, pivot - 1);
        _quicksort(value, pivot+1, end);
    }
}

int quicksort_division(int* value, int left, int right)
{
    int pivot = left;

    while(left = value[pivot]) && (left < right))
            right--;

        if(left < right)
        {
            swap(&value[left], &value[right]);
        }
    }

    swap(&value[pivot], &value[right]);

    return left;
}
void swap(int* left, int* right)
{
    int temp = *left;
    *left = *right;
    *right = temp;
}

Python

def quicksort(arr):
    _quicksort(arr, 0, len(arr)-1)

def _quicksort(arr, start, end):
    if start < end:
        pivot = _quicksort_division(arr, start, end)
        _quicksort(arr, start, pivot-1)
        _quicksort(arr, pivot+1, end)

def _quicksort_division(arr, left, right):
    pivot = left
    while left < right:
        while arr[left] < arr[pivot] and left < right:
            left += 1
        while arr[right] >= arr[pivot] and left < right:
            right -= 1

        if left < right:
            arr[left], arr[right] = arr[right], arr[left]

    arr[left], arr[pivot] = arr[pivot], arr[left]

    return left

a = [80, 75, 10, 60, 15, 49, 12, 25]

quicksort(a)

[python][hackerrank] Append and Delete


link : https://www.hackerrank.com/challenges/append-and-delete/problem
#!/bin/python3
from itertools import zip_longest

s = input().strip()
t = input().strip()
k = int(input().strip())
output = 0

for idx, (i,j) in enumerate(zip_longest(s, t)):
    if i is None or j is None or i != j:
        output = len(s[idx:] + t[idx:])
        break

if k >= len(s+t):
    print('Yes')
elif k >= output and (k - output) & 1 == 0:
    print('Yes')
else:
    print('No')

[python][hackerrank] Find Digits (3 ways)



input1 = '1012'

number = int(input1)
n = len(input1)
res = 0
for i in range(n):
    _in = int(input1[i])
    if (_in != 0 and number % _in == 0):
        res += 1
       
print(res)

input2 ='1012'
number2 = int(input2)
a = (int(x) for x in input1)
res2 = 0
for i in a:
    if i != 0 and (number2 % i) == 0:
        res2 += 1
print(res2)

input3 = '1012'
number3 = int(input3)
# int_generator = (int(x) for x in input1)
res3 = sum( 1 for y in (int(x) for x in input1)
                    if y != 0 and number3 % y == 0)

print(res3)

2018년 3월 31일 토요일

[hackerrank][python]Roads and Libraries

https://www.hackerrank.com/challenges/torque-and-development/problem


#!/bin/python3
from pprint import pprint
import sys
from collections import defaultdict

def dfs(graph, start):
  visited, stack = set(), [start]
  while stack:  # dfs는 stack을 이용한다.
    vertex = stack.pop()
    if vertex not in visited:
      visited.add(vertex)
      stack.extend(graph[vertex] - visited)  # 해당 정점에 연결된 것들을 stack에 넣는다.
  return visited
  

def roadsAndLibraries(n, c_lib, c_road, cities):
  total_cost = 0
  
  if c_road >= c_lib or len(cities) == 0: 
    return n*c_lib  # 도서관이 싸니까 도로를 만들 이유가 없다.
  else:  # here be real shits
    city_graph = defaultdict(set)  # 저절로 set이 만들어지기 때문에 add만 하면 됨.
    connected_cities = set() # might make this into a set
    for i in cities:
      city_graph[i[0]].add(i[1])
      city_graph[i[1]].add(i[0])
      connected_cities.add(i[0])
      connected_cities.add(i[1])
    
    # print(city_graph)
    # print(connected_cities)
    isolated_cities = set([i+1 for i in range(n)]) - connected_cities
    
    while connected_cities:  # dfs를 이용하여 도시들을 돌아다닌다. 그리고 도시들이 비어질 때까지 돌아다닌다. 그리고 도시들은 한 묶음(여러그룹일 것이다.)에 끝나지 않는 경우가 많기 때문에 dfs를 여러번 실행해야 한다.
    # if connected_cities:  # it's wrong. Becuase the cities will have multiple groups.
      temp = connected_cities.pop()
      component = dfs(city_graph, temp)
      # print('component', component)
      total_cost += (len(component) - 1)*c_road + c_lib  # 라이브러리 하나에 도로 여러개
      connected_cities -= component  # 지들끼리  연결된 component connected_ciites에서 제외
    return total_cost + len(isolated_cities)*c_lib
    

# 모든 도시가 도서관을 접할 수 있도록 해야 한다.
# 모든 도시에 도서관을 만들거나
# 도서관을 하나 만들어서 연결되어 있는 도시(정점)끼리 도로를 만들어야 한다.
# (도로가 연결되어 있지 않다면 도서관을 연결해야 하겠지...)
#if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
    n, m, c_lib, c_road = input().strip().split(' ')
    n, m, c_lib, c_road = [int(n), int(m), int(c_lib), int(c_road)]
    cities = []
    for cities_i in range(m):
       cities_t = [int(cities_temp) for cities_temp in input().strip().split(' ')]
       cities.append(cities_t)

    result = roadsAndLibraries(n, c_lib, c_road, cities)
    print(result)

2018년 3월 28일 수요일

[hackerrank][python] Cut the sticks

https://www.hackerrank.com/challenges/cut-the-sticks/problem


def cut_sticks(sticks):
  count = 0
  if sticks:
    min_stick = min(sticks)
  else:
    return
  new_sticks = []
  for ele in sticks:
    count += 1
    new_ele = ele - min_stick
    if new_ele != 0:
      new_sticks.append(new_ele)
  print(count)
  cut_sticks(new_sticks)

input()
arr = [int(x) for x in input().strip().split(' ')]
cut_sticks(arr)

from collections import Counter

n = int(input())
arr =  [int(x) for x in input().strip().split(' ')]
counter = Counter(arr)

for i in range(1000):
  if counter[i]:
    print(n)
    n -= counter[i]
  
  if n == 0: break


def cut_sticks(sticks):
  count = 0
  sticks.sort()
  
  while sticks:
    print(len(arr))
    min_stick = sticks[0]
    arr[:] = [ s - min_stick for s in sticks if s > min_stick]

input()
arr = [int(x) for x in input().strip().split(' ')]
cut_sticks(arr)

문제 요약: 막대기 중에 가장 작은 막대기로 나머지 막대기들을 잘라낸다. 한번 자를 때마다 남아있는 막대기를 출력한다.

2018년 3월 25일 일요일

[python][hackerrank] Library Fine

https://www.hackerrank.com/challenges/library-fine/problem

d1, m1, y1 = (int(a) for a in input().split(' '))
d2, m2, y2 = (int(a) for a in input().split(' '))

yd = y1 - y2
md = m1 - m2
dd = d1 - d2

if yd < 0:
  print(0)
elif yd > 0:
  print(10000 * yd)
elif md < 0:
  print(0)
elif md > 0:
  print(500 * md)
elif dd < 0:
  print(0)
elif dd > 1:
  print(15 * dd)
else:
  print(0)

[python][cpp] 백준 알고리즘 2750 번 풀이

n = int(input())
a = []
for _ in range(n):
  a.append(int(input()))

print('\n'.join(str(e) for e in sorted(a)))


#include iostream
#include vector
#include algorithm


using namespace std;
int main() {
  int n;
  int number;
  cin >> n;
  vector numbers;  
  
  for(int i = 0; i < n; ++i) {
    cin >> number;
    numbers.push_back(number);
  }
  
  sort(numbers.begin(), numbers.end());
  for(auto i : numbers)
    cout << i << endl;
}

2018년 3월 5일 월요일

[python][algospot] 외발뛰기 (JUMPGAME)

[구종만의 알고리즘 문제해결전략] 내용을 파이썬으로 변경

n = 7
board = [[2,5,1,6,1,4,1],
         [6,1,1,2,2,9,3],
         [7,2,3,2,1,3,1],
         [1,1,3,1,7,1,2],
         [4,1,2,3,4,1,2],  # [4,1,2,3,4,1,3], [4,1,2,3,4,1,2]
         [3,3,1,2,3,4,1],
         [1,5,2,9,4,7,0]]

def jump(x,y):
    if x >= n or y >= n: return  False  # 게임판 밖을 벗어남.
    if x == n-1 and y == n-1:
        # print(board[x][y], x, y)
        return True  # 마지막칸에 도착한경우.
    jump_size = board[x][y]
    
    return jump(x+jump_size, y) or jump(x, y+jump_size)

print(jump(0,0))


# 동적 계획법
cache = [ [None]*n for _ in range(n)]
# print('cache', cache)
def jump2(x,y):
    if x >= n or y >= n: return False
    if x == n-1 and y == n-1: return True

    if cache[x][y] is not None:
        return cache[x][y]
    else:
        jump_size = board[x][y]
        cache[x][y] = jump2(x+jump_size, y) or jump2(x, y+jump_size)
        return cache[x][y]
print(jump2(0,0))

[python][hackerrank] Sherlock and Squares


https://www.hackerrank.com/challenges/sherlock-and-squares/problem
import math

q = int(input().strip())
for _ in range(q):
    a, b = map(int, input().strip().split(' '))
    _start = math.ceil((math.sqrt(a)))
    ret = 0
    while _start**2 <= b:
        ret += 1
        _start += 1
    print(ret)

[algorithm] 선택정렬 (selction sort with C and Python)

선택정렬 C언어와 파이썬 비교

main.c

#include 
#include 

#include "selection_sort.h"

void printArray(int value[], int count);

int main()
{
    int values[] = { 80, 75, 10, 60, 15, 49, 12, 25 };
    int count = sizeof(values)/sizeof(int);

    printArray(values, count);

    printf("\n선택 정렬이 시작됩니다 \n");
    selection_sort(values, count);

    printArray(values, count);

    return 0;
}
void printArray(int value[], int count)
{
    int i = 0;
    for(i = 0; i < count; i++) {
        printf("%d ", value[i]);
    }
    printf("\n");
}

selection_sort.h

#ifndef SELECTION_SORT_H_INCLUDED
#define SELECTION_SORT_H_INCLUDED

void selection_sort(int value[], int count);

#endif // SELECTION_SORT_H_INCLUDED

selection_sort.c