python 3日目
pythonのプログラミング学習3日目の記録
目的を考える
・プログラミング学習を通してどうなりたいのかの目的を考えてみる。 以下のように検討した。
プログラミングの目標
何のために? ・プログラミングを勉強することで次々出てくる技術で何ができるようになるのかを追えるようになること。(必ずしもかける必要はないが理解できる程度のスキルが必要) ・自分で物作りをできるようになることで、自分一人でサービスをたちあげるスキル・経験を積むこと。普段の仕事の中では新しいサービスを0から企画することはないので、プライベートの中でそのような経験を積むように意識する。
何をするのか? ・主要言語である、pythonを対象に勉強をしていく。 ・いきなりアプリ開発はハードルが高いため、以下の通りステップを踏んでいく。 1、タイピングゲームの構築 2、★検討中★
いつまでにするのか? ・やることが変わるので明確な期限を設けるのは難しいが、 簡単なアプリをpythonで作れるようになることを2020年内の目標とする。
タイピングゲームについて
・以下のサイトで簡単なタイピングゲームを作成している。これを解釈して、INPUTを変える+GUIで操作できるようにすることを この課題の目標とする。
https://note.com/hungair0925/n/nc32131a4d63f
from bs4 import BeautifulSoup from random import sample from time import time import requests class TypingGame: def __init__(self): #Python公式ドキュメント組み込み関数に関してのページ self.URL = "https://docs.python.jp/3/library/functions.html" #問題リスト self.question_list = [] #出題数 self.question_num = 10 #正解数 self.correct_num = 0 #タイポリスト self.mistake_list = [] #開始時間 self.start_time = 0 #終了時間 self.end_time = 0 #問題生成メソッド def generate_question(self): res = requests.get(self.URL) #文字コードを変換 res.encoding = res.apparent_encoding #レスポンスのテキスト情報をhtmlに解釈する soup = BeautifulSoup(res.text, "html.parser") #組み込み関数一覧が表示されているテーブルタグ全体の情報を抜き出す built_in_func_table = soup.find_all("table", class_="docutils", limit=1) #リストからhtmlの要素を取り出す built_in_func_table = built_in_func_table[0] #テーブル内の組み込み関数のタグを取得 built_in_func_tags = built_in_func_table.find_all("span", class_="pre") #問題リストに組み込み関数の文字列を格納 for tag in built_in_func_tags: self.question_list.append(tag.text) #問題表示 def show_question(self): question = sample(self.question_list, 1) return question[0] #判定メソッド def judge(self, question): user_input = input("=> ") if question == user_input: print("Great!") self.correct_num += 1 else: print("Boo!") self.mistake_list.append(question) #結果表示 def show_result(self): play_time = round(self.end_time - self.start_time, 2) accuracy = round(self.correct_num / self.question_num, 1) * 100 print("---結果発表---") print("正答率:{0}%".format(accuracy)) print("かかった時間{0}秒".format(play_time)) if len(self.mistake_list) == 0: print("パーフェクト!") else: print("--間違えた問題---") for mistake in self.mistake_list: print(mistake) #ゲーム処理 def main(self): #開始時間計測 self.start_time = time() #出題と判定の繰り返し for _ in range(self.question_num): question = self.show_question() print("{0}".format(question)) self.judge(question) #終了時間計測 self.end_time = time() self.show_result() if __name__ == "__main__": game = TypingGame() game.generate_question() print("組み込み関数Pythoタイピングゲーム") while 1: game_flag = int(input("1:スタート/0:終了 ")) if game_flag == 1: game.main() else: break
次回は以下をやってみる。 ・INPUTとなる一覧を変えてみる ・制限時間を設ける
python 2日目
pythonのプログラミング学習1日目の記録
checkiO
やったこと(Elementary)
Number Length
def number_length(a: int) -> int: return len(str(a)) if __name__ == '__main__': print("Example:") print(number_length(10)) # These "asserts" are used for self-checking and not for an auto-testing assert number_length(10) == 2 assert number_length(0) == 1 assert number_length(4) == 1 assert number_length(44) == 2 print("Coding complete? Click 'Check' to earn cool rewards!")
End Zeros
- rstripの使い方(文字列の右側の指定文字を除外する)
def end_zeros(num: int) -> int: return len(str(num)) - len(str(num).rstrip('0')) if __name__ == '__main__': print("Example:") print(end_zeros(0)) # These "asserts" are used for self-checking and not for an auto-testing assert end_zeros(0) == 1 assert end_zeros(1) == 0 assert end_zeros(10) == 1 assert end_zeros(101) == 0 assert end_zeros(245) == 0 assert end_zeros(100100) == 2 print("Coding complete? Click 'Check' to earn cool rewards!")
Backward String
- 逆順の出力方法(str[::-1])
def backward_string(val: str) -> str: return val[::-1] if __name__ == '__main__': print("Example:") print(backward_string('val')) # These "asserts" are used for self-checking and not for an auto-testing assert backward_string('val') == 'lav' assert backward_string('') == '' assert backward_string('ohho') == 'ohho' assert backward_string('123456789') == '987654321' print("Coding complete? Click 'Check' to earn cool rewards!")
Remove All Before
- XX以降の文字列を取得(str[a:])
from typing import Iterable def remove_all_before(items: list, border: int) -> Iterable: if border in items: a = items.index(border) return items[a:] else: return items if __name__ == '__main__': print("Example:") print(list(remove_all_before([1, 2, 3, 4, 5], 3))) # These "asserts" are used for self-checking and not for an auto-testing assert list(remove_all_before([1, 2, 3, 4, 5], 3)) == [3, 4, 5] assert list(remove_all_before([1, 1, 2, 2, 3, 3], 2)) == [2, 2, 3, 3] assert list(remove_all_before([1, 1, 2, 4, 2, 3, 4], 2)) == [2, 4, 2, 3, 4] assert list(remove_all_before([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7] assert list(remove_all_before([], 0)) == [] assert list(remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7, 7, 7, 7, 7, 7, 7, 7, 7] print("Coding complete? Click 'Check' to earn cool rewards!")
All Upper I
- 数字かどうかを判断(isdigit())
- 大文字かどうかを判断(isupper())
def is_all_upper(text: str) -> bool: if (text.replace(' ','').isdigit()) or ( not text.replace(' ','')): return True else: return text.isupper() if __name__ == '__main__': print("Example:") print(is_all_upper('ALL UPPER')) # These "asserts" are used for self-checking and not for an auto-testing assert is_all_upper('ALL UPPER') == True assert is_all_upper('all lower') == False assert is_all_upper('mixed UPPER and lower') == False assert is_all_upper('') == True print("Coding complete? Click 'Check' to earn cool rewards!")
Replace First
- 末尾に要素を追加する(append)
- 文字を切り取る(pop)
from typing import Iterable def replace_first(items: list) -> Iterable: if items: items.append(items.pop(0)) return items if __name__ == '__main__': print("Example:") print(list(replace_first([1, 2, 3, 4]))) # These "asserts" are used for self-checking and not for an auto-testing assert list(replace_first([1, 2, 3, 4])) == [2, 3, 4, 1] assert list(replace_first([1])) == [1] assert list(replace_first([])) == [] print("Coding complete? Click 'Check' to earn cool rewards!")
Max Digit
- 文字列の要素をリストに保存(list())
- 最大値を取得(max)
def max_digit(number: int) -> int: print(max(list(str(number)))) return int(max(list(str(number)))) if __name__ == '__main__': print("Example:") print(max_digit(0)) # These "asserts" are used for self-checking and not for an auto-testing assert max_digit(0) == 0 assert max_digit(52) == 5 assert max_digit(634) == 6 assert max_digit(1) == 1 assert max_digit(10000) == 1 print("Coding complete? Click 'Check' to earn cool rewards!")
python 1日目
pythonのプログラミング学習1日目の記録
progate
やったこと
Lv1
- if文(if,else,elifの使い方)
Lv2
リスト(aaa = [xxx , xxx , xxx])
for文(for ... in ...:)
辞書(aaa = {'xxx' : 'yyy' , ....})
while文(while i <= n:)、break、continue
買い物システム
money = 1000 items = {'apple': 100, 'banana': 200, 'orange': 400} for item_name in items: print('--------------------------------------------------') print('財布には' + str(money) + '円入っています') print(item_name + 'は1個' + str(items[item_name]) + '円です') input_count = input('購入する' + item_name + 'の個数を入力してください:') print('購入する' + item_name + 'の個数は' + input_count + '個です') count = int(input_count) total_price = items[item_name] * count print('支払い金額は' + str(total_price) + '円です') if money >= total_price: print(item_name + 'を' + input_count + '個買いました') money -= total_price # if文を用いて、moneyの値が0のときの条件を分岐してください if money == 0: print('財布が空になりました') else: print('お金が足りません') print(item_name + 'を買えませんでした') break # 変数moneyと型変換を用いて、「残金は◯◯円です」となるように出力してください print('残金は' + str(money) + '円です')
Lv3
関数(def 関数名(引数):)
ジャンケンゲーム
script.py
import utils # randomモジュールを読み込んでください import random print('じゃんけんをはじめます') player_name = input('名前を入力してください:') print('何を出しますか?(0: グー, 1: チョキ, 2: パー)') player_hand = int(input('数字で入力してください:')) if utils.validate(player_hand): # randintを用いて0から2までの数値を取得し、変数computer_handに代入してください computer_hand = random.randint(0 , 2) if player_name == '': utils.print_hand(player_hand) else: utils.print_hand(player_hand, player_name) utils.print_hand(computer_hand, 'コンピューター') result = utils.judge(player_hand, computer_hand) print('結果は' + result + 'でした') else: print('正しい数値を入力してください')
utils.py
def validate(hand): if hand < 0 or hand > 2: return False return True def print_hand(hand, name='ゲスト'): hands = ['グー', 'チョキ', 'パー'] print(name + 'は' + hands[hand] + 'を出しました') def judge(player, computer): if player == computer: return '引き分け' elif player == 0 and computer == 1: return '勝ち' elif player == 1 and computer == 2: return '勝ち' elif player == 2 and computer == 0: return '勝ち' else: return '負け'
Lv4
クラス(class Xxxx:)※classは設計書
インスタンスの生成(menu_item1 = MenuItem())
インスタンス変数(menu_item1.price)
コンストラクタ、initメソッド(def init(self):)
メニュー一覧の作成
script.py
from menu_item import MenuItem menu_item1 = MenuItem('サンドイッチ', 500) menu_item2 = MenuItem('チョコケーキ', 400) menu_item3 = MenuItem('コーヒー', 300) menu_item4 = MenuItem('オレンジジュース', 200) menu_items = [menu_item1, menu_item2, menu_item3, menu_item4] index = 0 for menu_item in menu_items: print(str(index) + '. ' + menu_item.info()) index += 1 print('--------------------') order = int(input('メニューの番号を入力してください: ')) selected_menu = menu_items[order] print('選択されたメニュー: ' + selected_menu.name) # コンソールから入力を受け取り、変数countに代入してください count = int(input('個数を入力してください(3つ以上で1割引): ')) # get_total_priceメソッドを呼び出してください result = selected_menu.get_total_price(count) # 「合計は〇〇円です」となるように出力してください print('合計は' + str(result) + '円です'
menu_item.py
class MenuItem: def __init__(self, name, price): self.name = name self.price = price def info(self): return self.name + ': ¥' + str(self.price) def get_total_price(self, count): total_price = self.price * count # countが3以上のとき、total_priceに0.9をかけてください if count >= 3: total_price = total_price * 0.9 # total_priceを四捨五入して、returnしてください return round(total_price)
Lv5
クラスの継承(food1 = Food(aaa,aaa))
オーバーライド、super()
料理注文システム
script.py
from food import Food from drink import Drink food1 = Food('サンドイッチ', 500, 330) food2 = Food('チョコケーキ', 400, 450) food3 = Food('シュークリーム', 200, 180) foods = [food1, food2, food3] drink1 = Drink('コーヒー', 300, 180) drink2 = Drink('オレンジジュース', 200, 350) drink3 = Drink('エスプレッソ', 300, 30) drinks = [drink1, drink2, drink3] print('食べ物メニュー') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('飲み物メニュー') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('食べ物の番号を選択してください: ')) selected_food = foods[food_order] drink_order = int(input('飲み物の番号を選択してください: ')) selected_drink = drinks[drink_order] # コンソールから入力を受け取り、変数countに代入してください count = int(input('何セット買いますか?(3つ以上で1割引): ')) # selected_foodとselected_drinkのそれぞれに対して、get_total_priceメソッドを呼び出してください result = selected_food.get_total_price(count) + selected_drink.get_total_price(count) # 「合計は〇〇円です」となるように出力してください print('合計は' + str(result) + '円です')
menu_item.py
class MenuItem: def __init__(self, name, price): self.name = name self.price = price def info(self): return self.name + ': ¥' + str(self.price) def get_total_price(self, count): total_price = self.price * count if count >= 3: total_price *= 0.9 return round(total_price)
food.py
from menu_item import MenuItem class Food(MenuItem): def __init__(self, name, price, calorie): super().__init__(name, price) self.calorie = calorie def info(self): return self.name + ': ¥' + str(self.price) + ' (' + str(self.calorie) + 'kcal)' def calorie_info(self): print(str(self.calorie) + 'kcalです')
drink.py
from menu_item import MenuItem class Drink(MenuItem): def __init__(self, name, price, amount): super().__init__(name, price) self.amount = amount def info(self): return self.name + ': ¥' + str(self.price) + ' (' + str(self.amount) + 'mL)'
checkiO
やったこと(Home)
Sum Numbers
- isnumeric関数の扱い方
def sum_numbers(text: str) -> int: words = text.split() print(words) sum_num = 0 for word in words: if word.isnumeric() is True: sum_num += int(word) print(sum_num) else: continue return int(sum_num)
Even the Last
- 偶数盤目の取得方法(array[0::2]2個おきに取得の意味)
def checkio(array: list) -> int: if len(array) > 0 : sum_num = sum(array[0::2])*array[-1] else: sum_num = sum(array[0::2]) return sum_num
Right to Left
replace関数の使い方
joinの使い方
def left_join(phrases: tuple) -> str: return ','.join(phrase.replace('right' , 'left') for phrase in phrases)
Three Words
isalpha関数
インクリメントの考え方
def checkio(words: str) -> bool: count = 0 result = False for word in words.split(): if word.isalpha(): count += 1 else: count = 0 if count >= 3: return True return False
First Word
- replace/splitの使い方
def first_word(text: str) -> str: return text.replace(',',' ').replace('.',' ').split()[0]
Days Between
- datetime関数の使い方
import datetime def days_diff(a, b): td_a = datetime.date(year=a[0], month=a[1], day=a[2]) td_b = datetime.date(year=b[0], month=b[1], day=b[2]) if td_a <= td_b: td = td_b - td_a else: td = td_a - td_b return td.days
Count Digits
findall関数の使い方
reライブラリの使い方
import re def count_digits(text: str) -> int: return len(re.findall('\d',text))
Back Word Each Word
reライブラリの使い方
join/spritの使い方
import re def backward_string_by_word(text: str) -> str: return " ".join([x[::-1] for x in text.split(" ")])
やったこと(Elementary)
Multiply
def mult_two(a, b): return a*b
Easy Unpack
- 最後からのリストの取得方法list[-x]
def easy_unpack(elements: tuple) -> tuple: return (elements[0] , elements[2] , elements[-2])
First Word
- splitの使い方
def first_word(text: str) -> str: return text.split()[0]
Acceptable Password
def is_acceptable_password(password: str) -> bool: return len(password) >6
進捗状況
100日で楽器弾きアプリ作るダーツAフラ
2020/05/19開始
自粛でひまだから中期目標を立ててみる。マルチタスクが好きなのでできるだけ欲張る。
①ダーツAフラ(1/3ブルに入れる) ②アプリ制作(作るアプリ考え中) ③ギター弾く(これくらい自由に弾ける) https://youtu.be/5BIJhw_yEE4 ④TOEIC900点