LoginSignup
3
4

More than 5 years have passed since last update.

「自作Python100本ノック」12日目(81本〜88本目)

Last updated at Posted at 2018-05-20

「自作Python100本ノック」12日目です。

やばい。
まじで、問題のネタがない。

めちゃめちゃ漁ってなんとか8問ゲットしてきました。

あ、後それと先日受けたGoogleのエンジニアスマーインターンシップオンライン選考の結果が返って来ており、結果は不合格でした。
不合格した後に、他の人たちの過去のインターン体験記みたいなブログを読んでたんですが、うわやっぱレベル感違うんだなと再確認しました。
なんだよ、「とりあえず、この本の問題は全部2週しました」って。。。
自分も言ってみたいものだな。

さて、
「自作Python100本ノック」とはそもそも何ぞや?
どの程度のレベル感なのか?
どのように進めて行くのか?
など気になる方は詳しくはこちらに整理してありますのでまずはそちらを確認するようお願いします。
それでは始めていきます。

Q81: TwoSums

問題:整数配列とターゲットが渡された時、整数配列の内足したら答えがターゲットになる2つの数字を返しなさい。
例: twosums([2, 7, 11, 15],9) ==> 2,7

combinationモジュール知りませんでした!
   

q81.py
from itertools import combinations

def twosums(x, target):
    for item in combinations(x, 2):
            if sum(item) == target:
                return item

nums = [2, 7, 11, 15]
target = 9
twosums(nums, target)

[出典]言語処理100本ノック with Python(第1章)

Q82: Reverse Integer

問題: 渡される整数を逆にして返せ

(あれ?さっきから全然文章問題じゃなくない??....)

x[::-1]で文字列を逆数にできるの面白いですね!

ちなみに、これが原因で私はしばらくエラーと戦ってました。
逆数に関してはそのほかにも、ここを見ると面白いです。
   

q82.py
def reverse_integer(x):
    return int(str(x)[::-1])

reverse_integer(1534236469)

[出典]言語処理100本ノック with Python(第1章)

Q83:Roman to Int (ローマ字から整数へ)

問題:
(0~4999)までのローマ字を数字に変換せよ。ちなみにローマ数字と整数は以下。

let romanValues = [“M”, “CM”, “D”, “CD”, “C”, “XC”, “L”, “XL”, “X”, “IX”, “V”, “IV”, “I”]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

q83.py
def roman_to_int(roman):
    values={'M': 1000, 'D': 500, 'C': 100, 'L': 50, 
                                'X': 10, 'V': 5, 'I': 1}
    """Convert from Roman numerals to an integer."""
    numbers = []
    for char in roman:
        numbers.append(values[char]) 
    total = 0
    for num1, num2 in zip(numbers, numbers[1:]):
        if num1 >= num2:
            total += num1
        else:
            total -= num1
    return total + num2

roman_to_int("XI")

[出典]言語処理100本ノック with Python(第1章)

Q84: Valid Parentheses

問題: (), {}, []など,括弧が有効であるかチェックをしてBoolを返しない。

上記の確固が有効に使われている場合は、文字としては認識されないはずなので、それを利用していく解き方となります。
辞書の使い方としても良い練習になるかと。
    

q84.py
def isvalid(x):
    table = {'(': ')', '{': '}', '[': ']'}
    stack = []
    for elm in x:
        if elm in table.keys():
            stack.append(table[elm])
        elif elm in table.values() and elm != stack.pop():
                return False
    return False if len(stack) else True

isvalid('[aaa]'), isvalid('('), isvalid('()[]{}'), isvalid('(]'), isvalid('([)]'), isvalid('{()}')

[出典]言語処理100本ノック with Python(第1章)

Q85: 「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ

   

q85.py
stre = 'パタトクカシーー'
print(stre[0::2])#str[::2]でも同様

[出典]言語処理100本ノック with Python(第1章)

Q86: 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ

zip()でそれぞれから要素を1つずつ持って来ます。
   

q86.py
str1 = 'パトカー'
str2 = 'タクシー'

print(''.join([a + b for a, b in zip(str1, str2)]))

[出典]言語処理100本ノック with Python(第1章)
   

Q87: 単語の文字数

q87.py
strr = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
strr = strr.replace('.', "")
strr = strr.replace(',', "")
strr = strr.split()

a_list = []

for word in strr:
    a_list.append(len(word))

print(list)

[出典]言語処理100本ノック with Python(第1章)
   

Q88: Typoglycemia

問題:
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
条件:
長さが4以下の単語は並び替えない。

(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ.
    

q88.py
import random

text = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
words = text.split()
shuffled_list = []

for word in words:
    if len(word) < 4:
        pass
    else:
        char_list = list(word)
        mid_list = char_list[1:-1]
        random.shuffle(mid_list)
        word = word[0] + "".join(mid_list) + word[-1]
    shuffled_list.append(word)

shuffled_str = " ".join(shuffled_list)
print(shuffled_str)

[出典]言語処理100本ノック with Python(第1章)

感想

ちょっとあまりにも問題のネタがないので、今回は自然言語処理の方の100本ノックから問題を8問頂戴して来ました。
いや、ほんと良い問題ばかりで羨ましいです。

90問までやるつもりだったのですが、色々ダメになっちゃった問題もあり、今日は8問で閉めます。
明日調子が良ければ、100問目まで行きます。(多分頑張って95問目まで)

それでは!

→  13日目

3
4
2

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
3
4