ブリブリ備忘録 おっ、python

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

Mutations

・問題

ソースコード

def mutate_string(string, position, character):
    l=list(string)
    l[position]=character
    l="".join(l)
    return l

if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)

・コメント

入力された文字のn+1番目の文字を置き換える問題

これも前回までの問題が分かって入れば全然難しくない。

・URL

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

What's Your Name?

・問題

You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:

Hello firstname lastname! You just delved into python.

Input Format

The first line contains the first name, and the second line contains the last name.

Constraints

The length of the first and last name ≤ .

Output Format

Print the output as mentioned above.

Sample Input 0

Ross
Taylor

Sample Output 0

Hello Ross Taylor! You just delved into python.

Explanation 0

The input read by the program is stored as a string data type. A string is a collection of characters.

ソースコード

def print_full_name(a, b):
    list=['Hello ',a,' ',b,'! You just delved into python.']
    list=''.join(list)
    print(list)

if __name__ == '__main__':
    first_name = input()
    last_name = input()
    print_full_name(first_name, last_name)

・コメント

あまり面白くない問題。

一行目にfirst name,二行目にlast nameが書かれた入力からそれらを読み取り、適当な文章に放り込むだけ。

・URL

https://www.hackerrank.com/challenges/whats-your-name/problem

 

String Split and Join

・問題

In Python, a string can be split on a delimiter.

Example:

>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings. 
>>> print a
['this', 'is', 'a', 'string']

Joining a string is simple:

>>> a = "-".join(a)
>>> print a
this-is-a-string 

Task 
You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

Input Format 
The first line contains a string consisting of space separated words.

Output Format 
Print the formatted string as explained above.

Sample Input

this is a string   

Sample Output

this-is-a-string

ソースコード

def split_and_join(line):
    line=line.split(" ")
    line="-".join(line)
    return line    

if __name__ == '__main__':
    line = input()
    result = split_and_join(line)
    print(result)

・コメント

標準入力で与えられたスペースを含む文字列のスペースをハイフンに置き換える問題。

問題文の指示に従って行けばいいので難しくはないが、今後の問題でも頻出なので重要。

まず、スペースで区切ってリストに入れた後に、中身を抽出しハイフンで区切ればよい。

・URL

https://www.hackerrank.com/challenges/python-string-split-and-join/problem

sWAP cASE

・問題

You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

For Example:

Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2

Input Format

A single line containing a string .

Constraints

 

Output Format

Print the modified string .

Sample Input 0

HackerRank.com presents "Pythonist 2".

Sample Output 0

hACKERrANK.COM PRESENTS "pYTHONIST 2".

ソースコード

def swap_case(s):
    swap=s.swapcase()
    return swap
if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

・コメント

標準入力で与えられた文字列の大文字小文字を入れ替えるだけの問題。

入れ替えるときに用いる関数(swapcase()なるもの)が用意されているのでそれにぶち込めば終わり。

あまり使い所もなさそう(知らんけど...)

・URL

https://www.hackerrank.com/challenges/swap-case/problem

Detect Floating Point Number

・問題

 
 
 

ソースコード

import re
if __name__ == '__main__':
    N=int(input())
    a=[input() for i in range(N)]
    n=0
while n<=N-1:
    print (bool(re.match(r'[-+]?[0-9]*\.[0-9]+$',a[n])))
    n=n+1

・コメント

標準入力から入ったものが、浮動小数点表示かどうかを判別するプログラムを書く問題。

 

reモジュールをインポートするところからスタートする。reとは正規表現操作ということらしい....(良く分からない)

 

どうも、入力から得られた文字列に一致するところがないかなどを調べるときに使うらしい。

 

reにはmatch()やsearch()など様々なメソッドが存在するが、今回はmatch()を用いる。

 

bool(re.match(r'条件',a[n]))

という形ならば、条件を満たすものがa[n]の先頭にあればTrueを返すし、満たしていなければ、Falseを返すという塩梅で用いる。

 

一見難しくなさそうだが、この条件の書き方が何とも難解である。

以下の表を参考にして議論を進めることにしよう。

正規表現パターン 意味 ヒット例 ヒットしない例
. 任意一文字 c.t cat, cut cast
^ 先頭 ^get getName mygetName
$ 文字列末尾 foo$ foo, barfoo foobar
* 0回以上反復 ab* a,ab,abbb bb
+ 1回以上反復 ab+ ab,abbb a,bb
? 0or1回登場 ab? a,ab abb
{m} m回反復 a{3} aaa aa,aaaa
{m,n} m~n回反復 a{3,5} aaa,aaaa,aaaaa aa,aaaaaa
*?, +*, ??, {m,n}? non-greedyマッチ
最も小さくマッチする
- - -
[ ] 集合 [aiu] a,i,u e,o
[ - ] 集合:範囲指定 [a-z] a,i,u,w,z 1,!,$
    [a-m0-9] a,g,m,0,5 !,$
[^] 集合:否定 [^a-z] 1,!,$ a,i,u,q,z
| 和集合 a|b a,b c,d
( ) グループ化
反復をグループに適用
(abc){2} abcabc abc
\ エスケープ
特殊文字直前に置く
- - -

 

 今回は浮動小数点表示かどうかを判断する問題であり、問題文には浮動小数点表示について以下のようなことが書かれている。

まず、先頭に+か-がある場合とない場合があり、その次に0~9の数字が0個以上存在し、かつその次に小数点があり、その後に、0~9の数字が1個以上存在する。

そこで、先ほどのソースコードに戻ってみよう。すると、re.match()の中に

[-+]?[0-9]*\.[0-9]+$

というものが含まれているがこれを分割して考えてみると、

[-+]? : -または+が0回または1回出現する

[0-9]* : 0~9の数字が0回以上出現する

\. : 小数点(\が無ければ、上表一番上のように認識されてしまう)

[0-9]+ : 0~9の数字が1回以上出現する

$ : 終了

となることが、表より見て取れる。

・URL

https://www.hackerrank.com/challenges/introduction-to-regex/problem

Tuples 配列とタプルの違いや、標準入力から配列を作成する方法

・問題

Task 
Given an integer, , and  space-separated integers as input, create a tuple, , of those  integers. Then compute and print the result of .

Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.

Input Format

The first line contains an integer, , denoting the number of elements in the tuple. 
The second line contains  space-separated integers describing the elements in tuple .

Output Format

Print the result of .

Sample Input 0

2
1 2

Sample Output 0

3713081631934410656

ソースコード

if __name__ == '__main__':
    n = int(input())
    list =list(map(int, input().split()))
print (hash(tuple(list)))

・コメント

問題内で出てくるhash()という関数の意味が分からないという点に一番苦労する問題。

1 2という入力に対して3713081631934410656という意味のわからない出力が得られてしまうので余計に混乱をしてしまう。

しかし、この問題の本質はhash()を理解するということではないし、理解できていなくても解ける問題なので、hash()については詳しく説明はしない。

問題文の中に

The second line contains  space-separated integers describing the elements in tuple .

との記述があるのでtはtupleである。

さらに、出力は hash(t)なのでhashはtupleを括弧内にとる関数であると分かる。

そこで、入力からtupleを作成する方法をまず考えることにする。

与えられる入力を見れば、スペースで区切られただけの文字列である。

前にもやったようだが、python3では、スペースで区切られた文字列から配列を取得するには

list =list(map(int, input().split()))

のようにするらしい...(間隔が空きすぎて覚えていない)

また、list =[int(x) for x in input().split()]

という形にしてもよい。

・URL

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

Lists 配列の様々な操作(追加や削除など)

・問題

 
 
 

ソースコード

if __name__ == '__main__':
    N = int(input())
    a = [input().split() for i in range(N)]
n=0
list=[]
while n<=N:
    if a [n][0]=="insert":
        list.insert (int(a[n][1]),int(a[n][2]))
        n+=1
    elif a [n][0]=="remove":
        list.remove (int(a[n][1]))
        n+=1
    elif a [n][0]=="append":
        list.append (int(a[n][1]))
        n+=1
    elif a [n][0]=="sort":
        list.sort()
        n+=1
    elif a[n][0]=="pop":
        list.pop()
        n+=1
    elif a[n][0]=="reverse":
        list.reverse()
        n+=1
    elif a[n][0]=="print":
        print (list)
        n+=1

・コメント

問題というか、配列の使い方確認みたいな感じ。

スペースで区切られたものを配列に入れたり、二重配列を扱ったりする問題。

insert,remove,append,sort,pop,reverse,printの使い方を再確認!!

list.pop(1)なら配列listの二番目の要素を削除するのに対し、list.pop()のようにインデックスを指定しなければ、配列の最後の要素を削除するという点に注意

・URL

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