ブリブリ備忘録 おっ、python

HackerRankの問題とコメント(python3) 拙いですが...

Finding the percentage 少数第二位まで出力する方法

・問題

 
 
 

ソースコード

if __name__ == '__main__':
    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()
print ('%0.2f' %((((student_marks[query_name][0])+(student_marks[query_name][1])+(student_marks[query_name][2]))/3)))

・コメント

いつも通り、名前とスコアが入力として与えられる問題。

入力の最後にある名前の人の点数を平均して出力するだけなので難しくはないが、出力は少数第二位までなければならないのでそこが唯一難しいところ。

print ('%0.2f' %(なんちゃら))

という形にすれば出力できることさえ分かればできる。

・URL

https://www.hackerrank.com/challenges/finding-the-percentage/problem

Write a function 関数の定義

・問題

We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February. 
In the Gregorian calendar three criteria must be taken into account to identify leap years:

  • The year can be evenly divided by 4, is a leap year, unless:
    • The year can be evenly divided by 100, it is NOT a leap year, unless:
      • The year is also evenly divisible by 400. Then it is a leap year.

This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.Source

Task 
You are given the year, and you have to write a function to check if the year is leap or not.

Note that you have to complete the function and remaining code is given as template.

Input Format

Read y, the year that needs to be checked.

Constraints

 

Output Format

Output is taken care of by the template. Your function must return a boolean value (True/False)

Sample Input 0

1990

Sample Output 0

False

Explanation 0

1990 is not a multiple of 4 hence it's not a leap year.

ソースコード

def is_leap(year):
    if (year)%4!=0:
        leap = False
        return leap
    elif (year)%4==0 and (year)%100==0 and (year)%400!=0:
        leap = False
        return leap
    else:
        leap = True
        return leap

year = int(input())
print(is_leap(year))

・コメント

うるう年の問題。西暦を入力して、その年がうるう年かどうかを判断する関数を定義する問題。

4年に一回だと思いがちだが、100で割り切れるが、400で割り切れない年はうるう年ではないという分かりにくいルールを関数に落とすことさえできれば、解ける問題。

まず、4で割り切れない年は間違いなくうるう年ではないのでFalseを出力。

4で割り切れたものの中から、100で割り切れ、400で割り切れないものもFalseを出力し、それ以外の場合のみTrueを出力する。

・URL

https://www.hackerrank.com/challenges/write-a-function/problem

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 0

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Sample Output 0

Berry
Harry

Explanation 0

There are  students in this class whose names and grades are assembled to build the following list:

python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]

The lowest grade of  belongs to Tina. The second lowest grade of  belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.

ソースコード

if __name__ == '__main__':
l1=[]
l2=[]
l3=[]
l4=[]
a=int(input())
for _ in range(a):
name = input()
score = float(input())
l1=[name,score]
l2.append(l1)
l3.append(score)
b=min(l3)
while min(l3)==b:
l3.remove(b) 
b=min(l3)
n=0
while n<a:
if l2 [n][1]==b:
l4.append(l2[n][0])
n+=1
l4.sort()
syuturyoku = '\n'.join(l4) 
print (syuturyoku)

・コメント

名前と点数が交互に並んだ入力から、点数が二番目に低い人の名前を抜き出し、出力する問題。また、複数人いる場合には名前をアルファベット順に並べる必要がある。

 

まず、名前と点数をコンマで挟んだ配列を作製し、その配列を空の配列に追加していくことで、二重配列を作っている。

さらにもう一つの配列を用意し、その中には点数のみを入れる。そして、前の問題でも行った、二番目に低い点数を見つける方法を用いて、その点数を得る

参考記事:↓二番目に低い点数を見つける方法

oltupython.hatenablog.com

そして二重配列の中からその点数の名前を見つけ出し、配列に追加する。そして、sortを用いて名前をアルファベット順に整理し、最終結果を出力する。

ただし、そのまま出力すれば、配列の形で出てきてしまうので、joinを用いてリスト内の文字を結合する。また、名前は改行して出力しなければならないので'\n'.join(l4) のように、joinの前に改行を意味する'\n'.が挿入されている。

・URL

https://www.hackerrank.com/challenges/nested-list/problem

Find the Runner-Up Score!  リスト 削除

・問題

Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.

Input Format

The first line contains . The second line contains an array   of  integers each separated by a space.

Constraints

・2≤n≤10

・-100≤A[i]≤100

Output Format

Print the runner-up score.

Sample Input 0

5
2 3 6 6 5

Sample Output 0

5

Explanation 0

Given list is . The maximum score is , second maximum is . Hence, we print  as the runner-up score.

ソースコード

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    l= list(arr)
    a = max (l)
while max(l)==a:
    l.remove(a)
print (max(l))

・コメント

2番目のスコアを探し、出力する問題。

まず、与えられたデータを全てリストに入れる。

その中からMAXのデータを見つける。

まず、そのデータをリストから削除する。

最高点の人が二人以上いる場合は、一度削除しただけではダメなので、削除後のデータのMAXが最初のデータのMAXとは一致しなくなるまで削除を繰り返す必要がある。

・URL

https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem

 

List Comprehensions for文 if文

・問題

Let's learn about list comprehensions! You are given three integers  and  representing the dimensions of a cuboid along with an integer . You have to print a list of all possible coordinates given by  on a 3D grid where the sum of is not equal to . Here, 

Input Format

Four integers  and  each on four separate lines, respectively.

Constraints

Print the list in lexicographic increasing order.

Sample Input 0

1
1
1
2

Sample Output 0

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Explanation 0

Concept

You have already used lists in previous hacks. List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one. This example might help.

Example: You are given two integers x and y . You need to find out the ordered pairs ( i , j ) , such that ( i + j ) is not equal to n and print them in lexicographic order.( 0 <= i <= x ) and ( 0 <= j <= y) This is the code if we dont use list comprehensions in Python.

python x = int ( raw_input()) y = int ( raw_input()) n = int ( raw_input()) ar = [] p = 0 for i in range ( x + 1 ) : for j in range( y + 1): if i+j != n: ar.append([]) ar[p] = [ i , j ] p+=1 print ar 
Other smaller codes may also exist, but using list comprehensions is always a good option. Code using list comprehensions:

python x = int ( raw_input()) y = int ( raw_input()) n = int ( raw_input()) print [ [ i, j] for i in range( x + 1) for j in range( y + 1) if ( ( i + j ) != n )]

Sample Input 1

2
2
2
2

Sample Output 1

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 2], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 2], [1, 1, 1],

ソースコード

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
print ([[i,j,k] for i in range (x+1) for j in range (y+1) for k in range (z+1)if ((i+j+k)!=n) ])

・コメント

print関数の中にforを入れ込んでいる。 さらにその中にif文が含まれているところが少し難解。慣れが必要。 

・URL

https://www.hackerrank.com/challenges/list-comprehensions/problem

Polar Coordinates  複素数

・問題

A complex number  

                   z=x+yj

is completely determined by its real part  and imaginary part 
Here,  is the imaginary unit.

 

A polar coordinate (

is completely determined by modulus  and phase angle .

If we convert complex number  to its polar coordinate, we find:
: Distance from  to origin, i.e., 
: Counter clockwise angle measured from the positive -axis to the line segment that joins to the origin.

Python's cmath module provides access to the mathematical functions for complex numbers.

 
This tool returns the phase of complex number  (also known as the argument of ).

>>> phase(complex(-1.0, 0.0))
3.1415926535897931

 
This tool returns the modulus (absolute value) of complex number .

>>> abs(complex(-1.0, 0.0))
1.0

Task 
You are given a complex . Your task is to convert it to polar coordinates.

Input Format

A single line containing the complex number . Note: complex() function can be used in python to convert the input as a complex number.

Constraints

Given number is a valid complex number

Output Format

Output two lines: 
The first line should contain the value of 
The second line should contain the value of .

Sample Input

  1+2j

Sample Output

 2.23606797749979 
 1.1071487177940904

Note: The output should be correct up to 3 decimal places.

ソースコード

import cmath
c = complex(input())
print (abs(c))
print (cmath.phase(c))

・コメント

 複素数を扱うために最初に

import cmath

を挿入する

絶対値は組み込みのabs()関数で計算でき、絶対値を扱うcmathモジュールの関数はないので、以下のようになっている。

 

abs(c)

また、偏角を求めるのには以下の関数を用いている

cmath.phase(c)

・URL

https://www.hackerrank.com/challenges/polar-coordinates/problem

Print Function import math

・問題

Read an integer .

Without using any string methods, try to print the following:

 

Note that "" represents the values in between.

Input Format

The first line contains an integer .

Output Format

Output the answer as explained in the task.

Sample Input 0

3

Sample Output 0

123

ソースコード

import math
if __name__ == '__main__':
    n = int(input())
a=1
b=0
while n>=a:
    c=int(math.log10(a))+1
    b=b*(10**c)+a
    a=a+1
print (b)

・コメント

サンプルが1,2,3なので、12=1×10+2, 123=12×10+3というように前の数に10をかけて足せばよいと考えたが、1,2,3,・・・・,10などとなった時に、うまくいかなかったので、アルゴリズムを変更した。

c=int(math.log10(a))+1

 の部分aの桁数を求め、それを前の数にかけることによって問題を解決した。

さらに、logの関数を用いれるように最初に

import math

 を挿入する必要があることに注意。

・URL

https://www.hackerrank.com/challenges/python-print/problem