nodejs 설치 및 실행

|

nodejs 설치 및 실행

생활코딩 Node.js 강의

Node.js는 자바스크립트(JavaScript)로 서버 프로그래밍을 할 수 있도록 해주는 플랫폼

설치

  • nodejs.org 에서 파일 다운로드 후 설치
  • 또는 npm 을 통하여 설치 (installing Node.js via package manager)
  • 터미널에서 node --version 명령어 통해서 버전 확인

실행

  • js 파일 작성 (ex. nodejs/hello.js)

    console.log('hello');
    
  • 터미널 > cd nodejs (js 파일이 들어있는 폴더로 이동) > node hello.js

    $ node hello.js
    Hello world
    

hackerrank - Nested Lists

|

문제출처

문제

Given the names and grades for each student in a Physics class of  students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.

Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.

Input Format

The first line contains an integer, , the number of students.
The  subsequent lines describe each student over  lines; the first line contains a student's name, and the second line contains their grade.

Constraints

There will always be one or more students having the second lowest grade.
Output Format

Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.

Sample Input

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output

Berry
Harry

풀이코드

  • 두번째로 작은 점수를 찾는다
  • 해당 점수를 가진 사람 이름을 출력한다
score_list = []
for _ in range(int(input())):
    name = input()
    score = float(input())
    score_list.append([name, score])
second_highest = sorted(set([score for name, score in score_list]))[1]
print('\n'.join(sorted([name for name, score in score_list if score == second_highest])))

배운점

>>>from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

hackerrank - Finding the percentage

|

문제출처

문제

You have a record of  students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer  followed by the names and marks for  students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places.

Input Format

The first line contains the integer , the number of students. The next  lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed.

Constraints

Output Format

Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.

Sample Input

3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
Sample Output

56.00

풀이코드

n = int(input())
student_marks = {}
for _ in range(n):
    name, *line = input().split()
    scores = list(map(float, line))
    student_marks[name] = scores
query_name = input()
score_list = student_marks[query_name]
print("{0:.2f}".format(sum(score_list) / len(score_list)))

배운점

>>> one, *others = [1, 2, 3, 4, 5]
>>> one
1
>>> others
[2, 3, 4, 5]
>>> print("{0:.2f}".format(56.000))
56.00

leetcode 657. Judge Route Circle

|

문제출처

문제

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

풀이코드

  • 풀이 1
    def judge_circle(moves):
      """
      :type moves: str
      :rtype: bool
      """
      location = [0, 0]
      for direction in moves:
          if direction == "R":
              loaction[1] += 1
          if direction == "L":
              loaction[1] -= 1
          if direction == "U":
              loaction[0] += 1
          if direction == "D":
              loaction[0] -= 1
      return True if location.count(0) == 2 else False
    
  • 풀이 2
    def judge_circle(moves):
      """
      :type moves: str
      :rtype: bool
      """
      location = [0, 0]
      dic = {
          "R": [0, 1],
          "L": [0, -1],
          "U": [1, 0],
          "D": [-1, 0]
      }
      for direction in moves:
          location = [a+b for a, b in zip(location, dic[direction])]
      return True if location.count(0) == 2 else False
    

다른사람풀이

  • 간단하다! 앞으로는 좀 쉽게 생각해보자
def judge_circle(moves):
    """
    :type moves: str
    :rtype: bool
    """
    return moves.count("U")==moves.count("D") and moves.count("L")==moves.count("R")

leetcode 461. Hamming Distance

|

문제출처

문제

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 2**31.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

풀이코드

def hamming_distance(x, y):
    bin_x = format(x, "032b")
    bin_y = format(y, "032b")
    result = 0
    for i in range(32):
        if bin_x[i] != bin_y[i]:
            result += 1
    return result
  • format() 함수를 활용 (참고)
>>> format(10, '010b')
# '0000001010'
>>> format(10, 'b')
# '1010'
>>> format(10, '#b')
# '0b1010'

다른사람풀이

  • 비트연산자 XOR연산 활용 (XOR연산은 각 자릿수를 비교하여 다르면 1, 같으면 0)
  • 비트연산자 참고 (codecademy)
def hamming_distance(x, y):
  return bin(x^y).count('1')