Mutations
・問題
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
Let's try to understand this with an example.
You are given an immutable string, and you want to make changes to it.
Example
>>> string = "abracadabra"
You can access an index by:
>>> print string[5]
a
What if you would like to assign a value?
>>> string[5] = 'k'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
How would you approach this?
- One solution is to convert the string to a list and then change the value.
Example
>>> string = "abracadabra"
>>> l = list(string)
>>> l[5] = 'k'
>>> string = ''.join(l)
>>> print string
abrackdabra
- Another approach is to slice the string and join it back.
Example
>>> string = string[:5] + "k" + string[6:]
>>> print string
abrackdabra
Task
Read a given string, change the character at a given index and then print the modified string.
Input Format
The first line contains a string, .
The next line contains an integer , denoting the index location and a character separated by a space.
Output Format
Using any of the methods explained above, replace the character at index with character .
Sample Input
abracadabra
5 k
Sample Output
abrackdabra
・コメント
入力された文字の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.
・コメント
あまり面白くない問題。
一行目に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
・コメント
標準入力で与えられたスペースを含む文字列のスペースをハイフンに置き換える問題。
問題文の指示に従って行けばいいので難しくはないが、今後の問題でも頻出なので重要。
まず、スペースで区切ってリストに入れた後に、中身を抽出しハイフンで区切ればよい。
・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".
・コメント
標準入力で与えられた文字列の大文字小文字を入れ替えるだけの問題。
入れ替えるときに用いる関数(swapcase()なるもの)が用意されているのでそれにぶち込めば終わり。
あまり使い所もなさそう(知らんけど...)
・URL
Detect Floating Point Number
・問題
You are given a string .
Your task is to verify that is a floating point number.
In this task, a valid float number must satisfy all of the following requirements:
Number can start with +
, -
or .
symbol.
For example:
+4.50
-1.0
.5
-.7
+.4
-+4.5
Number must contain at least decimal value.
For example:
12.
12.0
Number must have exactly one .
symbol.
Number must not give any exceptions when converted using .
Input Format
The first line contains an integer , the number of test cases.
The next line(s) contains a string .
Constraints
Output Format
Output True or False for each test case.
Sample Input 0
4
4.0O0
-1.00
+4.54
SomeRandomStuff
Sample Output 0
False
True
True
False
Explanation 0
: O is not a digit.
: is valid.
: is valid.
SomeRandomStuff: is not a number.
・コメント
標準入力から入ったものが、浮動小数点表示かどうかを判別するプログラムを書く問題。
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
・コメント
問題内で出てくる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
Lists 配列の様々な操作(追加や削除など)
・問題
Consider a list (list = []
). You can perform the following commands:
insert i e
: Insert integer at position .print
: Print the list.remove e
: Delete the first occurrence of integer .append e
: Insert integer at the end of the list.sort
: Sort the list.pop
: Pop the last element from the list.reverse
: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
- The elements added to the list must be integers.
Output Format
For each command of type print
, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
・コメント
問題というか、配列の使い方確認みたいな感じ。
スペースで区切られたものを配列に入れたり、二重配列を扱ったりする問題。
insert,remove,append,sort,pop,reverse,printの使い方を再確認!!
list.pop(1)なら配列listの二番目の要素を削除するのに対し、list.pop()のようにインデックスを指定しなければ、配列の最後の要素を削除するという点に注意
・URL