2014년 9월 30일 화요일

python. 문자열


문자열 조작 / list 조작 / split() / join() / strip() / find() / %(forma) 설명..
FIXME: 예제 추가

문자열 조작:
  • a[start:end:shift]
  • repr(): 문법 내에 표현들을 문자열로 표현해줌. 예를들면, 배열이나 숫자, 함수 등. 아무거나 넣으면 error exception

list 조작:
  • documentation의 string section 참고..너무많다.

자르기:
  • split(): 나누기
  • join(): 합치기

삭제:
  • strip(): 원래 문자열에서 공백(arg가 있으면 문자) 제거
  • lstrip(): 원래 문자열에서 왼쪽 여백 제거
  • rstrip(): 원래 문자열에서 오른쪽 여백 제거
--> 여기서 공백/여백은 string.whitespace variable에서 확인 가능함.

치환:
  • replace(): 치환
  • maketrans() / translate():강력한 치환..

검색:
  • find(): 첫 번째 substring의 string에서의 index, 없으면 -1
  • rfind(): reverse find()
  • index() / rindex(): find와 동일하지만 substring이 없으면 -1이 아니라 error return
  • count(): substring이 몇 번 있는지
  • startswith() / endswith(): 시작과 끝을 검색하고 boolean return

format:
  • "xxx{0}yyy{1}".format(":", ";") --> xxx:yyy;
  • 0, 1 등의 정수 대신에 dict 표현도 가능함
  • "%s: test" % "yongk" --> yongk: test
참고: http://lapee79.blogspot.kr/2013/08/python-strings.html

2014년 9월 25일 목요일

algorithm. Introduction to Algorithms 3rd 15.1 Rod cutting

Rod cutting(Dynamic programming)



문제: 위의 가격이 정해져 있을 때 n length인 막대기를 짤라 파는 경우 중 가장 수익이 높은 값은?

생각은 간단하다.
MaxPrice[n] = Max(p[i] + MaxPrice[n - i])
이 것을 코드화 하면
import sys 
P = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30] 

def rodCut(p, n): 
        if n == 0: return 0
        ret = 0 
        for i in range(1, n + 1): 
                ret = max(ret, P[i] + rodCut(p, n - i)) 
        return ret 

rl = lambda: sys.stdin.readline()
print(rodCut(P, int(rl())))

이고
dynamic programming을 적용해서 r에 저장하면
def memorizedCutRodAux(p, n, r): 
        if n == 0:
                r[n] = 0 
                return r[n]
        if r[n] >= 0:
                return r[n]
        ret = 0 
        for i in range(1, n + 1): 
                r[n] = ret = max(ret, P[i] + memorizedCutRodAux(p, n - i, r)) 
        return r[n]

def memorizedCutRod(p, n): 
        r = [-1] * (n + 1)
        return memorizedCutRodAux(p, n, r)
print(memorizedCutRod(P, int(rl())))

그리고 이 것을 bottom up 방식으로 구현하면
def bottomUpMemorizedCutRod(p, n): 
        r = [-1] * (n + 1)
        r[0] = 0 
        for i in range(1, n + 1): 
                ret = 0 
                for j in range(i + 1): 
                        r[n] = ret = max(ret, p[i] + r[n - i]) 
        return r[n]
print(bottomUpMemorizedCutRod(P, int(rl())))

이다.
시간 제약에 걸릴 때 가장 먼저 생각해보는 방법이다..

덧. TopCoder 알고리즘 책에는 변수가 여러가지 인 경우 배열로 저장하기 위한 방법을 표현한 문제가 있다.

2014년 9월 22일 월요일

java. 자료구조의 methods 간단 정리


java의 자료구조는 java.util.Collection으로 간단 정리 한다.
Collection의 자료구조는 Collections로 algorithm이 구현되어 있음.
Arrays는 덤.(Collection : Collections = 배열 : Arrays)

java.util.Collection

Collection interface는 기본적으로 다음 methods를 이용한다.
  • Iterable을 implements 하는건 당연
  • add() ,  addAll() : 데이터 담기용 메소드
  • contains() ,  containsAll() ,  isEmpty() ,  equals() ,  size() : 데이터 확인용
    메소드
  • clear() ,  remove() ,  removeAll() : 데이터 삭제용 methods

java에서 data 저장은 배열(Array)과 다음 네 가지 자료구조이다.
  • 순서가 있는 목록(List) 형
    • ArrayList
    • AttributeList
    • LinkedList
    • RoleList
    • Stack
    • Vector
    • methods
  • 순서가 중요하지 않은 셋(Set) 형
    • 동일 key에 값이 중복될 수 없어  unique한 값을 저장할 때 필요함.
    • EnumSet
    • HashSet / LinkedHashSet
    • TreeSet
    • methods
      • contains(Object o) /containsAll(Collections c): o / c가 모두 포함된지 확인.
  • 먼저 들어온 것이 먼저 나가는 큐(Queue) 형
    • ArrayDeque
    • DelayQueue
    • LinkedList
    • methods
      • offer(): put
      • poll() / peek(): 꺼내기 / 들여다보기
  • 키-값(key-value) 으로 저장되는 맵(Map) 형 --> Map
    • List와 다른 점은 key값에 값이 매칭 되어 있다는 점이 다르다.
    • 당연히 key는 중복 불가.
    • EnumMap
    • HashMap
    • TreeMap
    • methods
      • get() / put() / putAll(Map m) / size() / isEmpty()
      • clear()
      • containsKey() / containsValue(): key나 value가 있는지 확인
      • equals()
      • hashCode(): map의 hash code를 return
      • keySet(): key를 Set 형태로 return
      • values(): Collection<>을 return.

java.util.Collections
Collection을 쉽게 제어하는데 쓰임.
methods:
  • addAll() / copy() / binarySearch() / fill()
  • checkedCollection() / checkedMap() / checkedList() / checkedSet()
  • checkedSortedMap()/ ~Set()
  • disjoint(Collection c1, Collection c2) 하나도 안겹치면 return true
  • emptyxxx(): 깡통 List / Map / Set 등을 return
  • frequency(Collection c, Object o): c에 o가 몇 개 있는지?
  • indexOfSubList(List l, Object o) / lastIndexOfSubList(): l에 o의 첫 번째 index / 마지막 index
  • list(): ArrayList로 return
  • max() / min()
  • nCopy(): n번 복사한 배열
  • reverse(): 순서를 꺼꾸로
  • rotate() / suffle(): 돌리고 섞기
  • swap(a, b): a, b swap
  • 그 외 매우 많다! 생략함..

java.util.Arrays
 Array를 쉽게 제어하는데 쓰임
methods:
  • asList(): List 형으로 변환해서 return.
  • binarySearch(Object[] o, key):key 값으로 순서를 찾음.
  • copyOf() / copyOfRange()
  • equals() / deepEquals()
  • fill(Object[] a, b): a를 b로 전부 채움
  • hashCode(): hash code return
  • sort(): 앞의 post에서 소개함.
뭐 워낙 자주 쓰는거라 당연히 알고 있어야 한다고 생각함.


쓰다보니 길어졌지만 이게 간단 정리한 것이다.
TODO: 너무 뻔한건 지우자

2014년 9월 18일 목요일

java. sort()

sort()를 사용하기 위해 필요한 것들은:

-->git; java.util.Comparator,  java.util.Collections
알고리즘 공부하면서.. 배열만 보면 '닥치고 소팅!' 하고싶은 순간이 여러번 오게 된다.
그 때마다 검색해서 Compare 어쩌구.. Descending / ascending 등 매 번 잘 몰라 고민할 때가 많아 정리해 보려고 한다.
한 줄 요약하자면, Comparable을 implements 한 객체를 compare()해서 sort() 하는 것이다.
세부 내용은 다음과 같다.

sort()를 쓰기 위해서는 다음이 필요하다.
  •  Arrays, Collections의 object들을 sort() 하여 정렬하려면 자연정렬 하거나.. Comparator를 인자로 주어야 한다.
  • 자연정렬은 Arrays.sort(int[] array)로간단하게되지만, (물론 2차 배열은 Comparator 필요)
  • List를 정렬하는 Collections.sort()와 같은 것은 Comparator를 인자로 주어야 한다. 어떻게 주느냐..
  • Comparator instance를 생성해보면 알겠지만 public int compare()를 override 하게 된다. 여기에 Compare 방법을 구현하면 됨. 음수는 작다 0이면 같다 양수면 크다이다. 쉽지?
  • Comparable를 상속한 Object는 compareTo()를 override하면 된다. 아래 예시에 잘 나와 있음. javadoc에는 다음과 같이 되어 있다.
     * Sorts the specified list into ascending order, according to the
     * {@linkplain Comparable natural ordering} of its elements.
     * All elements in the list must implement the {@link Comparable}
     * interface.  Furthermore, all elements in the list must be
     * mutually comparable (that is, {@code e1.compareTo(e2)}
     * must not throw a {@code ClassCastException} for any elements
     * {@code e1} and {@code e2} in the list).
  • 즉, Comparable을 implement 한 객체만 비교 가능하고 compare()를 override 하여야 한다는 말. 이게 핵심이다. 쉽지? ㅋㅋ

인터넷에서 검색한 예제를 하나 살펴보자.
(출처:http://java67.blogspot.kr/2012/10/how-to-sort-object-in-java-comparator-comparable-example.html)

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * Java program to test Object sorting in Java. This Java program
 * test Comparable and Comparator implementation provided by Order
 * class by sorting list of Order object in ascending and descending order.
 * Both in natural order using Comparable and custom Order using Comparator in Java
 *
 * @author http://java67.blogspot.com
 */
public class ObjectSortingExample {

    public static void main(String args[]) {
     
        //Creating Order object to demonstrate Sorting of Object in Java
        Order ord1 = new Order(101,2000, "Sony");
        Order ord2 = new Order(102,4000, "Hitachi");
        Order ord3 = new Order(103,6000, "Philips");
     
        //putting Objects into Collection to sort
        List orders = new ArrayList();
        orders.add(ord3);
        orders.add(ord1);
        orders.add(ord2);
     
        //printing unsorted collection
        System.out.println("Unsorted Collection : " + orders);
     
        //Sorting Order Object on natural order - ascending
        Collections.sort(orders); //sorting here.
     
        //printing sorted collection
        System.out.println("List of Order object sorted in natural order : " + orders);
     
        // Sorting object in descending order in Java
        Collections.sort(orders, Collections.reverseOrder());
        System.out.println("List of object sorted in descending order : " + orders);
             
        //Sorting object using Comparator in Java
        Collections.sort(orders, new Order.OrderByAmount());
        System.out.println("List of Order object sorted using Comparator - amount : " + orders);
     
        // Comparator sorting Example - Sorting based on customer
        Collections.sort(orders, new Order.OrderByCustomer());
        System.out.println("Collection of Orders sorted using Comparator - by customer : " + orders);
    }
}

/*
 * Order class is a domain object which implements
 * Comparable interface to provide sorting on natural order.
 * Order also provides copule of custom Comparators to
 * sort object based uopn amount and customer
 */
class Order implements Comparable {

    private int orderId;
    private int amount;
    private String customer;

    /*
     * Comparator implementation to Sort Order object based on Amount
     */
    public static class OrderByAmount implements Comparator {

        @Override
        public int compare(Order o1, Order o2) {
            return o1.amount > o2.amount ? 1 : (o1.amount < o2.amount ? -1 : 0);
        }
    }

    /*
     * Anohter implementation or Comparator interface to sort list of Order object
     * based upon customer name.
     */
    public static class OrderByCustomer implements Comparator {

        @Override
        public int compare(Order o1, Order o2) {
            return o1.customer.compareTo(o2.customer);
        }
    }

    public Order(int orderId, int amount, String customer) {
        this.orderId = orderId;
        this.amount = amount;
        this.customer = customer;
    }

 
    public int getAmount() {return amount; }
    public void setAmount(int amount) {this.amount = amount;}

    public String getCustomer() {return customer;}
    public void setCustomer(String customer) {this.customer = customer;}

    public int getOrderId() {return orderId;}
    public void setOrderId(int orderId) {this.orderId = orderId;}

    /*
     * Sorting on orderId is natural sorting for Order.
     */
    @Override
    public int compareTo(Order o) {
        return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
    }
 
    /*
     * implementing toString method to print orderId of Order
     */
    @Override
    public String toString(){
        return String.valueOf(orderId);
    }
}

Output
Unsorted Collection : [103, 101, 102]
List of Order object sorted in natural order : [101, 102, 103]
List of object sorted in descending order : [103, 102, 101]
List of Order object sorted using Comparator - amount : [101, 102, 103]
Collection of Orders sorted using Comparator - by customer : [102, 103, 101]

위에서 Order를 sorting 하는방법을 보면
  • Order가 Comparable을 implements 하여 compareTo()를 override 했기 때문에 Collections.sort()로 sorting 하는 방법
  • Order의 내부에 Comparator를 상속받은 class(OrderByAmount와 OrderByCustomer)를 구현해서 sorting 하는 방법을 구현하고 있다. 잘 안보이나? 코드를 잘 뜯어보면 보인다.

사용하는 관점에서 한번 더 정리를 하자면,
  • List를 sorting 하려면 Collections의 sort()를 쓰고 Comparator를 넘겨줘야 하고
  • 배열을 sorting 하려면 Arrays의 sort()를 쓰면 된다. 2차 배열은 마찬가지로 Comparator를 넘겨줘야 한다.
  • 비교를 하려면 비교 대상(Object)이 Comparable이어야 한다.

java. java.lang.Scanner() methods

java lib '간단' 정리에 맛들렸다 ㅋㅋ
이번엔 최근 가장 많이 쓰는 것 중 하나인 Scanner().

- close(): 다 쓰고 나서 꼭 쓰자!
- next() / nextLine() / nextInt() 등등: 알지?
  - nextBigInteger() / hasNextBigInteger(): BigInteger()도됨
- radix() / useRadix(): 10진수인지 16진수인지 지수 return; / Radix 설정
- findInLine(pattern): 패턴에 맞는거 return. delimiter 무시함. - findWithinHorizon() = findWithinHorizon(Pattern.compile(pattern, horizon))
- locale() / useLocale(): input의 언어정보 출력 /  언어 설정
추가로.. 설명이 필요한 몇 개.
- delimiter() / useDelimiter() / skip(): 구분자(패턴) 설정. / skip은 무시하는 구분자 설정.
     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 
- match(): MatchResult 출력
public class ScannerDemo {

   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6 ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // check if next token is "Hello"
      System.out.println("" + scanner.hasNext("Hello"));

      // find the last match and print it
      System.out.println("" + scanner.match());

      // print the line
      System.out.println("" + scanner.nextLine());

      // close the scanner
      scanner.close();
   }
}
결과:
 
true
java.util.regex.Matcher[pattern=Hello region=0,25 lastmatch=Hello]
Hello World! 3 + 3.0 = 6 

-

Ubuntu 14.04 썰

Ubuntu 14.04를 사용하면서 필요했던 것, 불편한 것들을 나열해본다.
경험상 안되는 것은 많이 없다. 꼭 필요한 것은 간단하게 구현해서 사용하도록.

PROS.
>한글 입력 문제.
  • 다들 동일한 문제로 고민하는데 ibus는 오류가 많다.
  • ibus 오류들:
  • 맞춤법 검사 안됨. 한타는 무조건 빨간줄
  • 타자를 치다가 마우스를 특정 위치에 클릭하면 마지막 글자가 마우스 포인터 위치에 입력됨 -_-;;
  • 한/영키로 한영 전환을 하려면 dconf등을 이용해 수정해야 함.

>onenote와 같은 메모 프로그램..
  • nix note나 저널 같은걸로 대충 쓸 수는 있지만 매우 아쉽다.
  • web base의 google keep으로 대체하고는 있지만 pen 역할을 할 수 있는게 없네 -_-;;

>UI
  • 반응이 유기적이지 못하고 끌리는 듯한 느낌을 지울 수 없다.

>기타
  • 많은 부분이 shell이 없으면 할 수 없는 것 들이 있다. 물론 배포된 프로그램들에는 매뉴얼이 항상 있는 것도 신기함.
  • 리눅스 지식이 없으면 쓰기 힘들다
  • 필요한 것들이 리눅스로 만들어 진 것들이 많이 없어서 할수없이 만들어서 사용해야 한다.
  • 윈도우에서 누리던 모든 것들이 부럽다. 그냥 윈도우를 쓸까 생각한 적이 한두번이 아니다.
CONS.
>개발 편의
  • 개발자들에게는 여러가지로 편함. 확장성 짱임
  • 무료 무료 모두 무료!

결론. 공짜 OS에 바라는게 많다고 할 수 있지만 아직 불편하다.

2014년 9월 17일 수요일

Algorithm. Scanning(스캐닝) algorithm

algospot의 MAXSUM 문제:
scanning algorithm을 사용해야 함. scanning algorithm은 기본 concept는
--> '최대값 계산 시, 음수가 포함된다면 잘라내기'
라고 요약할 수 있겠다.

먼저 내가 작성한 source를 보자
package com.yongk.algospot.MAXSUM;

import java.util.Scanner;

public class MAXSUM {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int T = Integer.parseInt(sc.nextLine());
  while(T-- > 0) {
   int N = sc.nextInt();
   sc.nextLine();
   int[] input = new int[N];
   String[] temp = sc.nextLine().split(" ");
   for (int i = 0; i < N; i++) {
    input[i] = Integer.parseInt(temp[i]);
   }
   System.out.println(getMaximumSetFast(input));
  }
  sc.close();
 }
 private static int getMaximumSetFast(int[] input) { //scanning algorithm
  int max = 0;
  int from = 0;
  for (int i = 0; i < input.length; i++) {
   from = Math.max(from + input[i], 0);
   max = Math.max(max, from);
  }
  return max;
 }
 private static int getMaximumSetSlow(int[] input) { //처음 생각한 O(n^2)의 저속한 algorithm
  int[] sum = new int[input.length];
  sum[0] = input[0];
  int max = 0;
  for (int i = 1; i < input.length; i++) {
   sum[i] = sum[i - 1] + input[i];
   max = Math.max(max, sum[i]);
  }
  
  for (int i = 0; i < sum.length; i++) {
   for (int j = i; j < sum.length; j++) {
    max = Math.max(max, sum[j] - sum[i]);
   }
  }
  return max;
 }
}

- 처음 생각한 것이 getMaximumSetSlow()인데 나름 짱구를 굴려 미리 계산한 값으로 중복 계산을 줄이자는 생각이었지만 미개한 생각이었다.
- getMaximumSetFast()가 scanning algorithm. input[0]에서부터 더해가다가 그 값이 0보다 작아지면 당연히 거기까진 더할 필요가 없다. 왜냐하면 거기서부터 더하는건 0보다 크기 때문.
- 덕분에 scanning algorithm은 O(n)의 속도이다.
- 사람도 이렇게 생각하지 않을까?

덧1, python으로 같은 것을 구현하면
import sys 
def getMaximumSetFast(input):
        maxVal = 0 
        fromVal = 0 
        for i in input:
                fromVal = max(fromVal + i, 0)
                maxVal = max(fromVal, maxVal)
        return maxVal

rl = lambda: sys.stdin.readline()
T = int(rl())
for i in range(T):
        rl()
        input = [int(j) for j in rl().split()] 
        print(getMaximumSetFast(input))

덧2. 그리고 java.util.Scanner()는 느리다..대따 느리다 ㅠㅠ 가급적이면 nextInt()보다는 nextLine()을 parseInt()할 것! 처음엔 다음과 같이 작성했었는데..참담한 속도였다. 적어도 5배 이상 느림.
  while(T-- > 0) {
   int N = sc.nextInt();
   int[] input = new int[N];
   for (int i = 0; i < N; i++) {
    input[i] = sc.nextInt(); //slow!!!
   }
   System.out.println(getMaximumSetFast(input));
  }


'no branches ready for upload' 발생시 대처법

checkout 하면 upload 하려고 할 때 다음 error가 발생한다.
no branches ready for upload
해결책:
  - 요지는 'branch를 새로 생성해서 upload 하면 됨'
  - 예시
    $ git branch -b for_upload
    $ repo upload .
간단하지? ㅋㅋ

java. java.lang.Math methods

아주 간략화하여 기억하기 쉽도록 정리해보자!

- abs(x) = |x|
- cbrt() / sqrt(): cube root / square root
- ceil() / round() / floor(): 올림 / 반올림 / 버림
- exp(n) = e^n
- expml() = e^x - 1
- hypot(x, y) = sqrt(x^2, y^2)
- log(x) = ln(x)
- max() / min(): 최대 / 최소값
- pow(): 제곱수
- random(): 랜덤값
- scalb(x,n) = x^n
- signum(x): 0.0(x=0), 1.0(x>0), -1.0(x<0 br="">- toDegrees() / toRadians(): 라디안을 각도로 / 각도를 라디안으로
- 삼각함수: cos() sin() tan() 등과 acos()(아크코사인) 등등

참고 page: http://java.lang.math/

Algorithm. 실수 연산

프로그래밍 중 실수 연산이 문제가 되는 경우가 왕왕 있음.

오늘도 algorithm 문제 풀다 한번 위기에 봉착해서 오답노트겸 적어놓는다.

package com.yongk.algospot.RATIO;
import java.util.Scanner;

public class RATIO {

 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int T = Integer.parseInt(sc.nextLine());
  while(T-- > 0) {
   long N = sc.nextLong();
   long M = sc.nextLong();
   System.out.println(getMinimumTick(N, M));
  }
 }

 private static long getMinimumTick(long N, long M) {
  
  long Z = (long)(1 + M * 100 / N);
  if (Z >= 100) return -1;
  return (long)Math.ceil((Z * N - 100 * M) / (100 - Z));

 }
}
위에서 틀린 것을 찾아보면..
Math.ceil에 들어가는 인자가 long으로 연산되어 double로 cast 되어 Math.ceil에 입력됨.
 private static long getMinimumTick(long N, long M) {
  
  long Z = (long)(1 + M * 100 / N);
  if (Z >= 100) return -1;
  return (long)Math.ceil((double)(Z * N - 100 * M) / (100 - Z));

 }
로 변경이 필요하다. 별 것 아닌데 개고생함.

결론:
1. 가급적이면 실수 연산을 정수 연산에 섞지 않고
2. 섞어야 한다면 캐스팅 반드시 할 것

2014년 9월 1일 월요일

python과 java

하도 파이선으로 스크립팅 하는 것들이 많아 궁금하기도 의무감도 들어서 검색을 하고 좀 봤는데..
한 마디로 요약하자면 매우 게으르고 발전된 언어인 것 같다.
C로 프로그래밍을 시작하고 자바를 접하면서 발전된 언어라는 것을 느꼈는데
파이선은 그보다 더 발전한 언어인것 같다
인상깊었던 것은
ㅡ 튜플
ㅡ 간단한 string 편집.. 구아바랑 비교를 함 해봐야 할 듯..
ㅡ 간단한 함수 모듈 클래스 등등 oop 구현
ㅡ 간단한 간단한 간단한.. 불필요한 반복적인 문구들 다 간단함.
ㅡ 리턴이 있는지 보이드인지도 선언 안해도 알아서 됨
진짜 게으른 언어다. 짱인듯. Pydev 설치해노코 익숙해지는것만 남았다. 되게쉽네 진짜..