LoginSignup
1
0

More than 3 years have passed since last update.

HackerRank 30days of Code Python3で解いてみた

Last updated at Posted at 2019-09-08

はじめに

未来電子テクノロジー(https://www.miraidenshi-tech.jp/intern-content/program/)
でインターンをしているrayaと申します。
プログラミング初心者であるため、内容に誤りがあるかもしれません。
もし、誤りがあれば修正するのでどんどん指摘してください。

今回の内容

HackerRankの30Days of Codeを解いているので、復習で少しずつまとめていきます。

Day0

print関数を使う問題。

input_string=input()
print("Hello, World")
print(input_string)

Day1

入力された値のデータ型を指定する問題。同じデータ型だから足し合わせられる。
double型は、小数の中でも小数点以下の桁数が多い場合のデータ型だそうですが、Python3では扱わないのでfloat型で解きます。

i = 4
d = 4.0
s = 'HackerRank '

a=int(input())
b=float(input())
c=str(input())
print(i+a)
print(d+b)
print(s+c)

Day2

計算問題。関数に渡される引数で式を定義する
・round()関数:round(数値)で浮動小数点数の数値を整数に四捨五入する。第2引数には小数点以下何桁までを四捨五入して示すか指定できる。 

def solve(meal_cost, tip_percent, tax_percent):
    tip = meal_cost * tip_percent / 100
    tax = meal_cost * tax_percent / 100
    total_cost = meal_cost + tip + tax
    print(round(total_cost))

Day3

条件分岐の問題。

if __name__ == '__main__':
    N = int(input())
    if N % 2 != 0:
        print("Weird")
    elif 2 <= N <= 5:
        print("Not Weird")
    elif 6 <= N <= 20:
        print("Weird")
    else:
        print("Not Weird")

Day4

クラスとコンストラクタを定義する問題。コンストラクタ(def --init--())はPersonクラスのインスタンスを作ることで呼び出される。selfはインスタンス自身を示し、インスタンスの引数をinitialAgeに代入し、そのInitialAgeが適切な値(正の数)ならインスタンス変数ageに代入する。インスタンス変数はself.変数名の形で定義して、原則クラス内のメソッドで呼び出せる。

class Person:
    def __init__(self,initialAge):
        if initialAge < 0:
            print("Age is not valid, setting age to 0.")
            self.age = 0
        else:
            self.age = initialAge

    def amIOld(self):
        if self.age < 13:
            print("You are young.")
        elif 13 <= self.age < 18:
            print("You are a teenager.")
        else:
            print("You are old.")

    def yearPasses(self):
        self.age += 1

Day5

for文でループ処理する問題。
・format()メソッド:"文字列{}".format(変数)で、文字列中の{}に引数の変数を順番に代入する。

if __name__ == '__main__':
    n = int(input())
for i in range(1,11):
    result=n*i
    print("{} x {} = {}".format(n, i, result))
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0