Python3関連のことを調べてみた2019年11月26日

Python3関連のことを調べてみた2019年11月26日

PEP8の警告が出たときの対応

## 動作環境
python3
PyCharm(無料版)

# PEP8に準拠したコーディングをしたい場合の設定
PyCharm左上のメニュー欄から
File -> Settings -> Editor -> Inspections -> Python -> PEP8 coding style violation から week warning を warning に上げる。
また、その下の PEP8 naming convention violation の設定も warningに変更する。

# エラーの表示文と直し方
以下、具体的なエラーの対応方法です。
これらのエラーは、静的解析といい、PyCharmでは無料版においても即時にチェックしてくれます。この結果、バグの防止や可読性が上がります。

## PEP8 do not use bare except
と警告が出たら
except:

except FileNotFoundError:
というように、エラーのパターンを記載しましょう。
一度エラーを出して確認すれば、何のエラーかわかります。

## Function nam

元記事を表示

Pandasユーザーガイド「mergeとjoinとconcatenate」(公式ドキュメント日本語訳)

本記事は、Pandas の公式ドキュメントの[User Guide – Indexing and Selecting Data](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html)を機械翻訳した後、一部の不自然な文章を手直ししたものである。

誤訳の指摘・代訳案・質問等があればコメント欄や編集リクエストでお願いします。

# mergeとjoinとconcatenate

pandasは、SeriesまたはDataFrameを簡単に結合するための、join・merge型操作におけるインデックスおよびリレーショナル代数機能のさまざまな種類の集合演算とさまざまな機能を提供します。

## オブジェクトのconcatenate

[`concat()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html#pandas.concat)関数(メインのpandas名前空間に存在します)は、(ある場合)他の

元記事を表示

googleトレンドを用いて投資対象となる分野のトレンドを解析してみた!

今回は、流行りのgoogle トレンドを用いて伸びそうな投資分野のグラフを書いてみようと思います。

#自己紹介
趣味でプログラミングやっているゴンです。
スマートトレードは卒業しました。

ゴンについて、知りたい方はこちら。
ブログ読んでねー

https://www.investor-gon.com/

ツイッターはこちら

#何を作るのか(完成目標)
Googleトレンドからデータを読み込んで、Pythonでグラフ化する。
検索が増加しているのか減少してるのかを読み解く!

#投資対象になりそうな分野
近い将来に爆伸びする産業
・AI
・VR / AR
・共有経済
・IoT
・自動運転
・電気自動車
・ゲノム編集
・遠隔医療
・マリファナ
・3Dプリンター

#完成コード
##コード1

“`python
%matplotlib inline
from pytrends.request import TrendReq
import matplotlib.pyplot as plt
plt.rcParams[‘

元記事を表示

Githubの使い方を忘れないようにメモする。

#とりあえずgitを使う
そもそもgitを使おうと思ったのは、就活用として必要なのでは?と言うこととあまりにもtwitterの強い人たちがGitHubやらなんやら言っていあせってました。くそおお!!!自分もつかいたい!!

そんなこんなで使い始めようと決意。まず、GitとGitHubの違いって何?みたいなレベルなのでその段階から調べることにしました。
↓を参考にしました。
https://t.co/g9Bp31FtKM?amp=1

目標は以下の環境でコードを書いてgithubにpushすること
windows10
vscode
python3.7
コマンドプロンプト
gitのダウンロード(調べれば出てくる)

#gitにpushするまでの流れ

GitHubの使い方
①コードを書く「保存)
②コマンドプロンプトでコードが書いてある(cd)フォルダを開く
③git init (すでにレポジトリがあるときはいらない)
④git add 書いたファイルの名前~.py
⑤git commit -m “なんかコメント”
⑥録GitHubでニューレポジトリを作る。(すでにレポジトリがあるときはい

元記事を表示

81. Search in Rotated Sorted Array II

#Description
“`
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
“`
#Submission
“`python:submission.py
class Solution:
def search(self, nums: List[int]

元記事を表示

33. Search in Rotated Sorted Array

#Description
“`
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], t

元記事を表示

お手軽なサンプルデータ作成手順

ホームページ:https://program-board.com

##モチベーション
今回色々、サンプルデータを使って遊びたいと思ったが、お手軽に作れるAPIは存在するが自由度が低いと感じたため、自作で作ることを決めました。

##モジュール
モジュールのインストールを行います.ここではpandas,numpyと偽データを簡単に生成できるfakerというモジュールを使います.

“`
pip install faker
“`
##fakerについて
fakerの基本的な使い方を記述します.Faker(‘ja_JP’)で日本語用の偽データを生成する準備をします. あとは,好きな種類のデータを生成してみてください.英語ですが,以下のサイトにFakerが生成できるデータが載っています.

PythonにてFakerを用いてテストデータを生成する方法

ここでは,名前,都道府県,会社,生年月日,職業を生成します.

“`python
# 日本語偽データの設定
from faker import Faker

# 日本語偽データの設定
fakege

元記事を表示

Xiaomi Mijia Bluetoothを使用した温湿度ロギング環境構築

# Xiaomi Mijia Bluetoothを使用した温湿度ロギング環境構築
AliExpressで入手した格安温湿度計を使った温湿度ロギング環境構築方法。
![xiomi.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/457056/75860452-c66e-35a5-9add-b195316e4896.jpeg)

## 環境
Debian 9.8
mysql Ver 15.1 Distrib 10.1.37-MariaDB
MySQL Workbench 8.0
Power BI Desktop

Raspberry Pi Zero W
Xiaomi Mijia Bluetooth 2個、1個あたり1300円くらいかと。
dynabook EX/56LWH、Windows10 Home 64bit

## 方針
Raspberry Pi Zero WとXiaomi Mijia Bluetooth 2個をBluetoothでペアリングし、Raspberry Pi Zero WのMySQLにデー

元記事を表示

Pythonの標準入力 (初学者向け)

#はじめに
PaizaでPythonの学習を始めたのですが、Dランクに挑戦するときに
標準入力の受け取り方でわからないものがあったのでまとめました。

※以下はDランクに挑戦する段階のものです。for文などは使わずに書いています。

##標準入力パターン① (1行に1文字の数値)

**◾️標準入力**
1

**◾️コード**
`# input関数は文字列として返されるので、int関数で整数に変換します`

`a = int(input())`
`print(a)`

**◾️出力結果**
1

##標準入力パターン② (1行に複数の数値)

**◾️標準入力**
1 2

**◾️コード**
`# 入力値の1と2の間はスペースが入っています`
`# split関数で引数なしの場合は自動でスペース等を区切りとして分割されます`

`a, b = input().split()`
`print(a, b)`

**◾️出力結果**
1 2

##標準入力パターン③ (複数行に分かれた数値)

**◾️標準入力**
1
2

**◾️コード**
`a = int(input())`
`b

元記事を表示

1011. Capacity To Ship Packages Within D Days

#Description
“`
A conveyor belt has packages that must be shipped from one port to another within D days.

The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

Example 1:

Input:

元記事を表示

7. Reverse Integer

#Description
“`
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
“`
#Submission
“`python:submission.py
class Solution:
def reverse

元記事を表示

Firebase CLI を Windows10 にインストールして、FirestoreエミュレーターをPython3で試してみる

# FirestoreエミュレーターをWindows10で起動させる

## Firebase CLI のダウンロードとインストール
npm(Node Package Manager)を使用して、Firebase CLI をインストールします。

まずは、[Node.js](https://www.nodejs.org/) をインストールします。

コマンドプロンプトを起動し、次のコマンドで Firebase CLI をインストールします。

“` コマンドプロンプト.
npm install -g firebase-tools
“`

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/252891/042bd505-fa30-218f-3eba-1c82ad114745.png)

これにより、グローバルに使用できる firebase コマンドが有効になります。

“` コマンドプロンプト.
firebase –version
“`

## Firebase CLI にログイン

元記事を表示

1. Two Sums

#Description
“`
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
“`
#Submission
“`submission.py
#Brute Force
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for first in range(0, len(

元記事を表示

Pythonの再帰の落とし穴

# Pythonの再帰呼び出しの落とし穴

競技プログラミングでPython3を使用してDFSしたときに再帰の深さ制限が思ったよりもきつく,ハマってしまったので記録として残しておく.
PythonでDFSするときにはこの設定を気にしたい.

# 再帰の深さ制限の確認と変更
– 確認

“`python
>>> sys.getrecursionlimit()
1000
“`

– 変更

“`python
>>> sys.setrecursionlimit(1000000)
>>> sys.getrecursionlimit()
1000000
“`

# デバッグ時の注意
AtCoderで使用できるPython3.4.3と3.6や3.7で再帰の制限を超えた時のエラー内容が異なる.
バグの可能性のある箇所を例外処理でキャッチしてデバッグするときには気をつける必要がある.

– 検証用プログラム

“` Python
def func():
func()
try:
func()
except Exception as e:
print(type(e),e)

元記事を表示

【Python】文字列と数値(asciiコード)の変換まとめ

# はじめに
自分向けにPythonでの文字とasciiコードの計算方法をまとめました。
AtCoder上のPython3.4.3で動作確認済みです。

# 変換方法
`ord(‘文字’)` と `chr(数値)` で相互に変換できます。

“`python
s = ‘A’

ord_s = ord(s)
print(ord_s) # 65

chr_s = chr(ord_s)
print(chr_s) # A
“`

# 変換表
まとめとしてasciiコードと文字の対応表を記載します。
なお、以下の表の`asciiコード`という項目は10進数での表記を表しています。

## 重要な変換ピックアップ
|asciiコード|16進数|文字|
|:–:|:—-:|:-:|
| 48 | 0x30 | 0 |
| 57 | 0x39 | 9 |
| …| … |…|
| 65 | 0x41 | A |
| 90 | 0x5a | Z |
| …| … |…|
| 97 | 0x61 | a |
| 122 | 0x7a | z |

例えば、大文字と

元記事を表示

Reverse Number

#Python program to reverse a number
(Solving using integer properties)

“`reverse.py
# coding: utf-8
# Your code here!
def reverseNumber(n):
reversedNumber = 0
while n > 0:
remainNumber = n % 10
reversedNumber = (reversedNumber * 10) + remainNumber
n //= 10
print(reversedNumber)

reverseNumber(123)
#->321
“`

元記事を表示

412. FizzBuzz

#Submission
“`submission.py
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for nums in range(1, n + 1):
if nums % 15 == 0:
ans.append(“FizzBuzz”)
elif nums % 5 == 0:
ans.append(“Buzz”)
elif nums % 3 == 0:
ans.append(“Fizz”)
else:
ans.append(str(nums))
return ans
“`

元記事を表示

104. Maximum Depth of Binary Tree

#Description
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

“`example.py
Given binary tree [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
return its depth = 3.
“`
#Submission
“`submidssion.py
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left =

元記事を表示

617. Merged Two Binary Trees

#Description
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

“`example.py

Example 1:

Input:
Tree 1 Tree 2
1

元記事を表示

COTOHA APIを使って数行で言語処理(形態素解析、感情分析)をする

# はじめに
[COTOHA Community Slack](https://api.ce-cotoha.com/contents/community.html)でCOTOHA APIのレスポンスを読みやすくするライブラリが紹介されていました (恐らく非公式)
今回は、そのライブラリを使って五行で形態素解析したいと思います。

# 事前準備
## 環境
Python 3.9.0
cotohappy 0.4.2

## インストール
ライブラリの名前は[cotohappy](https://pypi.org/project/cotohappy/)です。

インストールは簡単にpipでできます。
`pip install cotohappy`

>Python 3.7 and 3.8 are supported

とのことなので注意が必要です。

## 認証情報をおく
`Payload.json` に認証情報を記述して置いておくと、accesstokenも取得してくれます。
名前を指定すればPayloadじゃなくても大丈夫そうです。
参考: https://github.com/278

元記事を表示

OTHERカテゴリの最新記事