task_id
int64
1.59k
65.3k
prompt
stringlengths
15
46
suffix
stringlengths
0
23
canonical_solution
stringlengths
5
244
test_start
stringlengths
22
167
test
sequence
entry_point
stringlengths
6
7
intent
stringlengths
5
84
library
sequence
37,146
def f_37146(arr): return
arr[:, 0]
import numpy as np def check(candidate):
[ "\n arr = np.array([[1,2],[3,4]])\n assert all(candidate(arr) == np.array([1,3]))\n", "\n arr = np.array([[3,4,5]])\n assert all(candidate(arr) == np.array([3]))\n" ]
f_37146
2次元配列`arr`の要素となっている1次元配列から先頭の値のみを抜き出す
[ "numpy" ]
25,263
def f_25263(df): return
df.to_dict()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[1,2,3], [4,5,6], [6,5,4], [2,1,0]], columns=[\"AA\", \"b\", \"3\"])\n assert candidate(df) == {'AA': {0: 1, 1: 4, 2: 6, 3: 2},\n 'b': {0: 2, 1: 5, 2: 5, 3: 1},\n '3': {0: 3, 1: 6, 2: 4, 3: 0}}\n", "\n df = pd.DataFrame([[1,2,3], [4,5,6], [6,5,4], [2,1,0]])\n assert candidate(df) == {0: {0: 1, 1: 4, 2: 6, 3: 2},\n 1: {0: 2, 1: 5, 2: 5, 3: 1},\n 2: {0: 3, 1: 6, 2: 4, 3: 0}}\n" ]
f_25263
データフレームを辞書型オブジェクトに変換する
[ "pandas" ]
28,178
def f_28178(soup): return
soup.find('tbody').find_all('tr')
from bs4 import BeautifulSoup def check(candidate):
[ "\n soup = BeautifulSoup(\"<td><b>Address:</b></td><tbody><tr>My home address</tr></tbody>\")\n result = candidate(soup)\n assert len(result) == 1\n assert result[0].contents == ['My home address']\n" ]
f_28178
HTMLテーブルから各行を取得する
[ "bs4" ]
8,656
def f_8656():
return handler
class handler(http.server.BaseHTTPRequestHandler): def do_POST(self): os.environ['REQUEST_METHOD'] = 'POST' form = cgi.FieldStorage(self.rfile, self.headers)
import cgi import http.server def check(candidate):
[ "\n try:\n handler = candidate()\n srvr = http.server.HTTPServer(('127.0.0.1', 8889), handler)\n except:\n assert False\n" ]
f_8656
POSTデータをcgi.FieldStrageで受け取る
[ "cgi", "http" ]
9,836
def f_9836(li): return
random.choice(li)
import random def check(candidate):
[ "\n assert candidate([1,2,3]) in [1,2,3]\n" ]
f_9836
リスト`li`の中からランダムに一つの要素を選択する
[ "random" ]
1,589
def f_1589(d):
return
X = np.array(d, dtype='float32') X.tofile('binaryVec.bin')
import numpy as np def check(candidate):
[ "\n f = open('binaryVec.bin', 'w')\n f.close()\n \n d = np.array([1., 2., 3.])\n candidate(d)\n d1 = np.fromfile('binaryVec.bin', dtype='float32')\n assert np.all(d == d1)\n" ]
f_1589
要素が数値のリスト型データ`d`をバイナリデータ`binaryVrc.bin`として保存する
[ "numpy" ]
38,532
def f_38532(f):
return
f.close()
def check(candidate):
[ "\n f = open('tmp.txt', 'w')\n candidate(f)\n assert f.closed\n" ]
f_38532
開いているファイル'f'を閉じる
[]
37,696
def f_37696(files, url, data): return
requests.post(url, files=files, data=data)
import requests from unittest.mock import Mock def check(candidate):
[ "\n r = requests.Response()\n r.status_code = 200\n requests.post = Mock(return_value = r)\n file_path = 'a.txt'\n with open (file_path, 'w') as f:\n f.write('abc')\n files = {'file': open(file_path, 'rb')}\n assert candidate(files, 'https://def.xyz', {'key':'value'}).status_code == 200\n" ]
f_37696
multipartのリクエストで複数のデータ`files`, `data`を`url'にPOSTする
[ "requests" ]
29,368
def f_29368(X, y):
return sss
sss = StratifiedShuffleSplit() sss.get_n_splits(X, y)
import numpy as np import sklearn from sklearn.model_selection import StratifiedShuffleSplit def check(candidate):
[ "\n X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])\n y = np.array([0, 0, 0, 1, 1, 1])\n assert candidate(X, y).__class__ == sklearn.model_selection._split.StratifiedShuffleSplit\n" ]
f_29368
クラス数の比率を保ったままデータを分割する
[ "numpy", "sklearn" ]
40,699
def f_40699(low, high): return
plt.yticks(range(low,high))
import matplotlib.pyplot as plt def check(candidate):
[ "\n assert len(candidate(20, 50)[0]) == 30\n", "\n assert len(candidate(0, 10)[0]) == 10\n" ]
f_40699
y軸のプロットの範囲を下限`low`、上限`high`に設定する
[ "matplotlib" ]
11,011
def f_11011(fig, onclick):
return
fig.canvas.mpl_connect('pick_event', onclick)
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def check(candidate):
[ "\n def onclick(event):\n pass\n fig = plt.figure()\n X = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]\n Y = [[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]]\n Z = [[10,11,13,14,16],[5,8,7,7,7,],[0,0,0,9,8]]\n ax = Axes3D(fig)\n ax.scatter3D(np.ravel(X),np.ravel(Y),np.ravel(Z))\n try:\n candidate(fig, onclick)\n except:\n assert False\n" ]
f_11011
グラフ上で選択されたデータの座標を表示する
[ "matplotlib", "mpl_toolkits", "numpy" ]
42,344
def f_42344(): return
re.compile('[ぁ-んァ-ン一-龥]+')
import re def check(candidate):
[ "\n pattern = candidate()\n words = ['あいうえお', '546', 'たぬき', '饅頭', 'abdf', '#%&', ' ']\n ja_words = [pattern.findall(w) for w in words]\n ja_words = [a for jw in ja_words for a in jw]\n assert ja_words == ['あいうえお', 'たぬき', '饅頭']\n" ]
f_42344
日本語(ひらがな、カタカナ、漢字)の判別をする正規表現を得る
[ "re" ]
17,145
def f_17145(br): return
br.submit().read()
import mechanize import urllib.request from unittest.mock import Mock def check(candidate):
[ "\n br = mechanize.Browser()\n x = urllib.request.urlopen('https://www.wikipedia.org')\n br.submit = Mock(return_value = x)\n assert b'Wikipedia' in candidate(br)\n" ]
f_17145
ブラウザオブジェクト`br`からsubmitした際の返り値を読みこむ
[ "mechanize", "urllib" ]
38,824
def f_38824(data): return
[print(*i) for i in data]
import sys from io import StringIO def check(candidate):
[ "\n stdout = sys.stdout\n s = StringIO()\n sys.stdout = s\n candidate([[1],[2],[3],[4],[5],[6]])\n sys.stdout = stdout \n s.seek(0)\n assert len(s.read()) == 12\n" ]
f_38824
タプル`data`を空白区切りで表示する
[ "io", "sys" ]
38,824
def f_38824(data):
return
for i in data: print(' '.join(str(j) for j in i))
import sys from io import StringIO def check(candidate):
[ "\n stdout = sys.stdout\n s = StringIO()\n sys.stdout = s\n candidate([[1],[2],[3],[4],[5],[6]])\n sys.stdout = stdout \n s.seek(0)\n assert len(s.read()) == 12\n" ]
f_38824
タプル`data`を空白区切りで表示する
[ "io", "sys" ]
38,824
def f_38824(data):
return
for i in data: print(' '.join(map(str, i)))
import sys from io import StringIO def check(candidate):
[ "\n stdout = sys.stdout\n s = StringIO()\n sys.stdout = s\n candidate([[1],[2],[3],[4],[5],[6]])\n sys.stdout = stdout \n s.seek(0)\n assert len(s.read()) == 12\n" ]
f_38824
タプル`data`を空白区切りで表示する
[ "io", "sys" ]
35,299
def f_35299(n):
return result
t = 5 z = tf.constant(0, shape=[n, n], dtype=tf.int32) abs = tf.maximum(t, z) result = tf.reduce_sum(abs)
import tensorflow as tf def check(candidate):
[ "\n assert str(type(candidate(4))).split(' ')[1] == \"'tensorflow.python.framework.ops.EagerTensor'>\"\n" ]
f_35299
`n`×`n`のテンソルの要素のうち0以上の値の和を計算する
[ "tensorflow" ]
38,328
def f_38328(df, pat): return
df.x.str.extract(pat)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'x': ['車5(0.8km)', '5', '車27(8.6km)']}, index=[1, 2, 3])\n pat = r'車(\\d*)'\n ref = df.x.str.extract(pat)\n assert candidate(df, pat).count()[0] == 2\n" ]
f_38328
データフレーム`df`の列ラベル`x`の各行のデータに対して正規表現`pat`を適用する
[ "pandas" ]
37,418
def f_37418(file): return
open(file, 'w')
def check(candidate):
[ "\n f = candidate('test.txt')\n assert f.name == 'test.txt'\n assert f.mode == 'w'\n" ]
f_37418
ファイル`file`を上書きモードで開く
[]
41,200
def f_41200(x_list, y_list): return
plt.plot(x_list, y_list)
import matplotlib.pyplot as plt def check(candidate):
[ "\n assert isinstance(candidate([1, 3, 5], [2, 4, 6]), list)\n" ]
f_41200
データ`x_list`、`y_list`からなるグラフを描画する指定する
[ "matplotlib" ]
43,369
def f_43369(a, b): return
pd.DataFrame([a, b])
import numpy as np import pandas as pd def check(candidate):
[ "\n assert candidate([1,1,1], [2,2,2]).equals(pd.DataFrame([[1,1,1], [2,2,2]]))\n", "\n assert candidate([1,2,1], [2,3,4]).equals(pd.DataFrame([[1,2,1], [2,3,4]]))\n", "\n assert candidate([0], [1]).equals(pd.DataFrame([[0], [1]]))\n" ]
f_43369
2つのデータフレーム`a`と`b`を行方向に結合する
[ "numpy", "pandas" ]
24,438
def f_24438(file): return
codecs.open(file, 'r', 'utf-8')
import codecs def check(candidate):
[ "\n with open('test.txt', 'w') as fw:\n fw.write('hello world!')\n fr = candidate('test.txt')\n assert fr.name == 'test.txt'\n" ]
f_24438
文字コードをutf-8に指定してファイル`file`を開く
[ "codecs" ]
10,215
def f_10215(file):
return data
with open(file, 'rb') as f: data = f.read()
def check(candidate):
[ "\n with open('tmp.pkl', 'wb') as fw:\n fw.write(b\"hello world!\")\n assert candidate('tmp.pkl') == b\"hello world!\"\n" ]
f_10215
ファイル`file`をバイナリデータとして開く
[]
18,992
def f_18992(x): return
pickle.dump(x, open('hoge.pkl', 'wb'))
import pickle def check(candidate):
[ "\n x = [100, 435, 56, 2, 99]\n candidate(x)\n with open('hoge.pkl', 'rb') as fr:\n data = pickle.load(fr)\n assert data == x\n" ]
f_18992
オブジェクト`x`をファイル`hoge.pkl`に保存する
[ "pickle" ]
38,400
def f_38400(df, change_dict): return
df.replace(change_dict)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'kai': ['2', 'B1', '23-49', 'M2']}, index=[1, 2, 3, 4])\n change_dict = {'2': '22', 'B1': 'B2'}\n assert candidate(df, change_dict).equals(df.replace(change_dict))\n" ]
f_38400
データフレーム`df`の複数の異なる要素を辞書型オブジェクト`change_dict`のキーと要素のペアに従って置き換える
[ "pandas" ]
35,793
def f_35793():
return data
data = [] i = 0 while(i<100): data.append(pd.read_csv('file_%d.csv'%i)) i+=1
import pandas as pd def check(candidate):
[ "\n for i in range(0, 100):\n with open ('file_'+str(i)+'.csv', 'w') as f:\n f.write(str(i))\n \n assert len(candidate()) == 100\n" ]
f_35793
連番になっている100個のCSVファイル'file_%d'をリストに取り込む
[ "pandas" ]
20,549
def f_20549(vectorized):
return
numpy.save('my_vector.npy', vectorized.toarray())
import os import numpy from sklearn.feature_extraction import DictVectorizer def check(candidate):
[ "\n measurements = [\n {'city': 'Dubai', 'temperature': 33.},\n {'city': 'London', 'temperature': 12.},\n {'city': 'San Francisco', 'temperature': 18.},\n ]\n vec = DictVectorizer()\n candidate(vec.fit_transform(measurements))\n assert os.path.exists('my_vector.npy')\n" ]
f_20549
学習データのベクトル`vectorized`をファイル'my_vector.npy`に保存する
[ "numpy", "os", "sklearn" ]
9,518
def f_9518(li):
return
for i, name in enumerate(li): print(i, name)
import sys def check(candidate):
[ "\n file_name = 'output.txt'\n f = open(file_name, 'w')\n sys.stdout = f\n candidate([1, 3])\n f.close()\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert lines[0] == '0 1\\n'\n assert lines[1] == '1 3\\n'\n \n f = open(file_name, 'w')\n sys.stdout = f\n candidate(['abc', 'def'])\n f.close()\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert lines[0] == '0 abc\\n'\n assert lines[1] == '1 def\\n'\n" ]
f_9518
リスト'li'のインデックスと要素に繰り返し処理を行って表示する
[ "sys" ]
38,760
def f_38760(arr, n): return
arr[arr > n].sum(), numpy.sum(arr > n)
import numpy import numpy as np def check(candidate):
[ "\n assert candidate(np.array([1,2,3,4]), 3) == (4, 1)\n" ]
f_38760
numpy配列`arr`に対して数値`n`より大きい要素の合計及び個数を求めて表示する
[ "numpy" ]
35,102
def f_35102(data):
return results
results = {} for item in data: results[item.find('areacode').text] = item.find('prefecture').text
import xml.etree.ElementTree as ET def check(candidate):
[ "\n data_temp = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\" ?><root><areacode>area1</areacode><prefecture>prefecture1</prefecture></root>', \n '<?xml version=\"1.0\" encoding=\"UTF-8\" ?><root><areacode>area2</areacode><prefecture>prefecture2</prefecture></root>'\n ]\n data = []\n for tr in data_temp:\n data.append(ET.ElementTree(ET.fromstring(tr)))\n \n res = candidate(data)\n assert \"area1\" in res\n assert \"area2\" in res\n assert \"prefecture1\" == res[\"area1\"]\n assert \"prefecture2\" == res[\"area2\"]\n" ]
f_35102
イテラブルオブジェクト`data`の要素から文字列`area_code`と`prefecture`を探し、それぞれキーと要素に持つ辞書`results`を作る
[ "xml" ]
41,440
def f_41440(arr_list): return
np.stack(arr_list)
import numpy as np def check(candidate):
[ "\n arr_list = [np.array([1,2]), np.array([3,4]), np.array([5,6])]\n assert candidate(arr_list).tolist() == [[1, 2], [3, 4], [5, 6]]\n" ]
f_41440
要素がNumPy配列のリスト`arr_list`を2次元のNumPy配列に変換する
[ "numpy" ]
35,741
def f_35741(soup): return
soup.find_all('p')
from bs4 import BeautifulSoup def check(candidate):
[ "\n soup = BeautifulSoup('<p>text</p>')\n assert candidate(soup)[0].contents == ['text']\n" ]
f_35741
HTMLをパースしたオブジェクト`soup`からタグ`p`をすべて見つける
[ "bs4" ]
40,444
def f_40444(df, c_label): return
df.groupby([c_label]).last()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'利用者ID': [1, 2], 'コンテンツID': ['a', 'b'], '値': [170, 45]})\n c_label = ['利用者ID', 'コンテンツID']\n assert candidate(df, c_label).equals(df.groupby([c_label]).last())\n" ]
f_40444
データフレーム`df`の列`c_label`をGroupbyでまとめたデータの最後の行を取り出す
[ "pandas" ]
39,240
def f_39240(a_list, b_list): return
[i for i in b_list if i in a_list]
def check(candidate):
[ "\n assert candidate([1,2,3], [4,1,2]) == [1,2]\n", "\n assert sorted(candidate([1,2,3,4,5], [4,1,2])) == [1,2,4]\n", "\n assert candidate([1,2,3], []) == []\n" ]
f_39240
リスト`a_list`の要素の中のリスト`b_list`の要素と一致するものを表示する
[]
39,375
def f_39375(dt_s): return
datetime.strptime(dt_s,'%d%b%Y')
from datetime import datetime def check(candidate):
[ "\n assert candidate('10OCT2017') == datetime.strptime('10OCT2017','%d%b%Y')\n" ]
f_39375
英名の月を含む日付フォーマット'%d%b%Y'の文字列`dt_s`をdatetime型に変換する
[ "datetime" ]
38,960
def f_38960(n): return
[int(c) for c in n]
def check(candidate):
[ "\n assert candidate('12345') == [1,2,3,4,5]\n", "\n assert candidate('') == []\n", "\n assert candidate('0') == [0]\n" ]
f_38960
数値`n`を分割してリストに格納する
[]
33,908
def f_33908():
return profile
profile = webdriver.FirefoxProfile() profile.DEFAULT_PREFERENCES['frozen']['javascript.enabled'] = False profile.set_preference("app.update.auto", False) profile.set_preference("app.update.enabled", False) profile.update_preferences()
import selenium from selenium import webdriver from selenium.webdriver.firefox.options import Options def check(candidate):
[ "\n profile = candidate()\n assert profile.__class__ == selenium.webdriver.firefox.firefox_profile.FirefoxProfile\n" ]
f_33908
seleniumtでFirefox仕様時にjavascriptを無効にする
[ "selenium" ]
33,908
def f_33908():
return options
options = Options() options.set_preference('javascript.enabled', False)
import selenium from selenium import webdriver from selenium.webdriver.firefox.options import Options def check(candidate):
[ "\n options = candidate()\n assert options.preferences == {'javascript.enabled': False}\n" ]
f_33908
seleniumtでFirefox仕様時にjavascriptを無効にする
[ "selenium" ]
19,770
def f_19770(s): return
s.isnumeric()
def check(candidate):
[ "\n assert candidate('1') == True\n", "\n assert candidate('a') == False\n" ]
f_19770
文字列`s`が数を表す文字かどうか判定する
[]
29,614
def f_29614(): return
socket.socket()
import socket def check(candidate):
[ "\n assert candidate().__class__ == socket.socket\n" ]
f_29614
ソケット情報を保存する
[ "socket" ]
41,032
def f_41032(dir): return
os.listdir(dir)
import os def check(candidate):
[ "\n assert candidate('.') == os.listdir('.')\n" ]
f_41032
ディレクトリ`dir`内にあるファイルのリストを取得する
[ "os" ]
37,709
def f_37709(img): return
img is None
import cv2 import numpy as np def check(candidate):
[ "\n assert candidate(None) == True\n blank_image = np.zeros((10,5,3), np.uint8)\n assert candidate(blank_image) == False\n" ]
f_37709
画像`img`が空かどうかを判定する
[ "cv2", "numpy" ]
33,677
def f_33677(f):
return coeffs
p = Poly(f, x) coeffs = p.coeffs()
from sympy import Poly, var def check(candidate):
[ "\n var('x a b')\n f = a*(2*x**2 - 1) + 4*x**3 + x*(b - 3)\n co = candidate(f)\n assert co == [4, 2*a, b - 3, -a]\n" ]
f_33677
`x`に関する多項式`f`の各次数の係数を求めてリストにする `coeffs`
[ "sympy" ]
37,449
def f_37449(a, b): return
a & b
def check(candidate):
[ "\n assert candidate(22, 56678) == 6\n", "\n assert candidate(0, -1) == 0\n", "\n assert candidate(1000, 1) == 0\n", "\n assert candidate(479, 234) == 202\n" ]
f_37449
変数`a`と`b`のビット演算
[]
42,442
def f_42442(): return
globals()
def check(candidate):
[ "\n assert candidate() == globals()\n" ]
f_42442
グローバル変数の一覧を得る
[]
38,030
def f_38030(word_list): return
Counter(word_list)
from collections import Counter def check(candidate):
[ "\n assert candidate(['this', 'is', 'a', 'word', 'List']) == Counter({'List': 1, 'a': 1, 'is': 1, 'this': 1, 'word': 1})\n", "\n assert candidate(['List']) == Counter({'List': 1})\n", "\n assert candidate(['this', 'this', 'this', 'this', 'this']) == Counter({'this': 5})\n", "\n assert candidate([]) == Counter({})\n" ]
f_38030
リスト`word_list'内に出現する単語を数える
[ "collections" ]
38,724
def f_38724(f, g):
return add_functions
def add_functions(f, g): return lambda x: f(x) + g(x)
def check(candidate):
[ "\n def f(x): return x\n def g(y): return 1\n assert candidate(f,g)(f,g)(3) == 4\n" ]
f_38724
関数`f`と`g`を受け取って関数同士の和を計算する関数`add_functions`を定義する
[]
22,439
def f_22439(obj): return
type(obj)
def check(candidate):
[ "\n assert candidate('this is a string') == str\n", "\n assert candidate(123.4) == float\n", "\n assert candidate(400) == int\n", "\n assert candidate({}) == dict \n", "\n assert candidate([{}]) == list\n" ]
f_22439
オブジェクト`obj`のクラスを得る
[]
22,439
def f_22439(obj): return
obj.__class__
def check(candidate):
[ "\n assert candidate('this is a string') == str\n", "\n assert candidate(123.4) == float\n", "\n assert candidate(400) == int\n", "\n assert candidate({}) == dict \n", "\n assert candidate([{}]) == list\n" ]
f_22439
オブジェクト`obj`のクラスを得る
[]
39,340
def f_39340(url): return
urllib.request.urlopen(url).read()
import urllib def check(candidate):
[ "\n url = \"http://www.google.com\"\n text = b\"google\"\n assert text in candidate(url)\n" ]
f_39340
指定したURL`url`の内容を表示する
[ "urllib" ]
39,589
def f_39589(foldername, filename): return
os.path.join(foldername, filename)
import os def check(candidate):
[ "\n assert candidate('folder', 'file') == 'folder/file'\n", "\n assert candidate('', 'file') == 'file'\n", "\n assert candidate('.', 'file') == './file'\n" ]
f_39589
フォルダ名`foldername'とファイル名`filename`を結合したパスを得る
[ "os" ]
23,577
def f_23577(ax, l, h): return
ax.set_xlim(l, h)
import matplotlib.pyplot as plt def check(candidate):
[ "\n fig, ax = plt.subplots()\n assert candidate(ax, 10, 100) == (10.0, 100.0)\n" ]
f_23577
X軸の範囲を下限`l`と上限`h`に指定する
[ "matplotlib" ]
41,087
def f_41087(src, range): return
int(math.ceil(src/float(range)) * range)
import math def check(candidate):
[ "\n assert candidate(22, 50) == 50\n", "\n assert candidate(100, 23) == 115\n", "\n assert candidate(0, 13) == 0\n", "\n assert candidate(12, 1) == 12\n", "\n assert candidate(34, 23) == 46\n" ]
f_41087
整数`src`を特定の範囲`range`の倍数で切り上げる
[ "math" ]
41,087
def f_41087(src, range): return
src if src % range == 0 else src + range - src % range
def check(candidate):
[ "\n assert candidate(22, 50) == 50\n", "\n assert candidate(100, 23) == 115\n", "\n assert candidate(0, 13) == 0\n", "\n assert candidate(12, 1) == 12\n", "\n assert candidate(34, 23) == 46\n" ]
f_41087
整数`src`を特定の範囲`range`の倍数で切り上げる
[]
40,711
def f_40711(n, N):
return answer
random_numbers = np.random.rand(n) answer = N * random_numbers / np.sum(random_numbers)
import numpy as np def check(candidate):
[ "\n answer = candidate(20, 5)\n assert answer.shape == (20,)\n assert max(answer) < 5\n" ]
f_40711
要素数の総和が`N`となる制約の下、`n`次元のランダムベクトル`answer`を生成する
[ "numpy" ]
40,711
def f_40711(n, N):
return answer
answer = np.random.dirichlet(np.ones(n)) * N
import numpy as np def check(candidate):
[ "\n answer = candidate(20, 5)\n assert answer.shape == (20,)\n" ]
f_40711
要素数の総和が`N`となる制約の下、`n`次元のランダムベクトル`answer`を生成する
[ "numpy" ]
31,924
def f_31924(li):
return li
random.shuffle(li)
import random def check(candidate):
[ "\n li_a = [i for i in range(10)]\n li_a = candidate(li_a)\n assert sorted(li_a) == [i for i in range(10)]\n" ]
f_31924
リスト`li`をランダムに並び替える
[ "random" ]
40,343
def f_40343(a, b): return
itertools.product(a,b)
import itertools def check(candidate):
[ "\n assert list(candidate([1,2],[3,4])) == [(1, 3), (1, 4), (2, 3), (2, 4)]\n" ]
f_40343
複数のリスト`a`と`b`の直積(デカルト積)を生成し、要素の組み合わせの結果を得る
[ "itertools" ]
36,217
def f_36217(df, reg): return
df['a'].str.extract(reg, expand=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([['abc def'],['123 567'], ['qqq eee']], columns=['a'])\n reg = r'(.{3})$'\n assert candidate(df, reg).equals(df['a'].str.extract(reg, expand=True))\n" ]
f_36217
データフレーム`df`の列`a`を正規表現`reg'で抽出する
[ "pandas" ]
27,871
def f_27871(factories, shops, costs): return
{f+s : cost for ((f,s), cost) in zip(product(factories,shops), costs)}
from itertools import product def check(candidate):
[ "\n assert candidate(['A', 'B'], ['1', '2'], [8, 10, 12, 16]) == {'A1': 8, 'A2': 10, 'B1': 12, 'B2': 16}\n" ]
f_27871
2つのリスト`factories'と`shops`の要素の組み合わせをキーとし、タプル`costs`各要素を要素等する辞書型オブジェクトを作る
[ "itertools" ]
27,871
def f_27871(factories, shops, cost):
return d
root = [''.join((x, y)) for x, y in itertools.product(factories, shops)] d = dict(zip(root, cost))
import itertools def check(candidate):
[ "\n factories = ['A', 'B', 'C', 'D']\n shops = ['1', '2', '3', '4', '5']\n costs = ( 8, 10, 12, 16, 20,\n 12, 8, 6, 10, 16,\n 18, 7, 4, 3, 4,\n 12, 10, 12, 16, 20 ) \n res_dict = candidate(factories, shops, costs)\n assert list(res_dict.items()) == [\n ('A1', 8), ('A2', 10), ('A3', 12), ('A4', 16), ('A5', 20), \n ('B1', 12), ('B2', 8), ('B3', 6), ('B4', 10), ('B5', 16), \n ('C1', 18), ('C2', 7), ('C3', 4), ('C4', 3), ('C5', 4), \n ('D1', 12), ('D2', 10), ('D3', 12), ('D4', 16), ('D5', 20), \n ] \n" ]
f_27871
2つのリスト`factories'と`shops`の要素の組み合わせをキーとし、タプル`costs`各要素を要素等する辞書型オブジェクトを作る
[ "itertools" ]
40,676
def f_40676(soup): return
soup.find_all(attrs={"data-locate": "address"})
from bs4 import BeautifulSoup def check(candidate):
[ "\n soup = BeautifulSoup('<div data-locate=\"address\">foo!</div>')\n res = candidate(soup)\n assert len(res) == 1\n assert res[0].attrs == {'data-locate': 'address'} \n assert res[0].text == \"foo!\"\n" ]
f_40676
キーワード引数として用いる事ができないHTML5のdata-属性、例えば`data-locel`が`address`に一致するものをオブジェクト`soup`から検索する
[ "bs4" ]
42,256
def f_42256(li):
return s
s = ''.join(i[0] for i in li)
def check(candidate):
[ "\n assert candidate(['sda', 'dahkdja', 'uehjkw', 'ebhjda']) == 'sdue'\n", "\n assert candidate(['happy', 'apple', 'pear', 'pie', 'yummy']) == 'happy'\n", "\n assert candidate(['a', 'b', 'c', 'd']) == 'abcd'\n", "\n assert candidate([str(i) for i in range(10)]) == '0123456789'\n" ]
f_42256
文字列を要素に持つリスト`li`の頭文字を結合した文字列`s`を得る
[]
42,256
def f_42256(li):
return s
s = '' for line in li: s += line[0]
def check(candidate):
[ "\n assert candidate(['sda', 'dahkdja', 'uehjkw', 'ebhjda']) == 'sdue'\n", "\n assert candidate(['happy', 'apple', 'pear', 'pie', 'yummy']) == 'happy'\n", "\n assert candidate(['a', 'b', 'c', 'd']) == 'abcd'\n", "\n assert candidate([str(i) for i in range(10)]) == '0123456789'\n" ]
f_42256
文字列を要素に持つリスト`li`の頭文字を結合した文字列`s`を得る
[]
18,967
def f_18967(li, i): return
i not in li
def check(candidate):
[ "\n assert candidate(['sda', 'dahkdja', 'uehjkw'], \"sda\") == False\n", "\n assert candidate(['happy', 'apple', 'pear', 'pie', 'yummy'], \"dog\") == True\n", "\n assert candidate([str(i) for i in range(10)], 10) == True\n" ]
f_18967
リスト`li`の中に要素`i`が含まれていない条件分岐を行う
[]
37,648
def f_37648(req_data): return
json.dumps(req_data).encode('utf-8')
import json def check(candidate):
[ "\n assert candidate({'test': 'just a test'}) == b'{\"test\": \"just a test\"}'\n" ]
f_37648
サーバーに送信するデータ`req_data`をUTF-8で符号化する
[ "json" ]
39,502
def f_39502(str): return
re.sub('([あ-んア-ン一-鿐ー])\s+((?=[あ-んア-ン一-鿐ー]))',r'\1\2', str)
import re def check(candidate):
[ "\n assert candidate('日 本 語 で 挟 ま れ た 空 白 を 削 除 す る') == '日本語で挟まれた空白を削除する'\n" ]
f_39502
文字列`str`内の、日本語で挟まれた空白を削除する
[ "re" ]
16,805
def f_16805(s, n): return
u'{0}{1}'.format(s, n)
def check(candidate):
[ "\n assert candidate('abd', 35) == 'abd35'\n", "\n assert candidate('', 12.34) == '12.34'\n", "\n assert candidate([1,2,3], 'string') == '[1, 2, 3]string'\n" ]
f_16805
文字列の変数`s`と`n`をUTF-8に変換して結合する
[]
40,978
def f_40978(M, N): return
[x+1 for x in range(M) for y in range(N)]
def check(candidate):
[ "\n assert candidate(2, 3) == [1,1,1,2,2,2]\n", "\n assert candidate(2, 1) == [1,2]\n" ]
f_40978
1が`N`個, 2が`N`個, ..., `M`が`N`個並ぶリストを生成する
[]
40,978
def f_40978(M, N): return
[i // N + 1 for i in range(N * M)]
def check(candidate):
[ "\n assert candidate(2, 3) == [1,1,1,2,2,2]\n", "\n assert candidate(2, 1) == [1,2]\n" ]
f_40978
1が`N`個, 2が`N`個, ..., `M`が`N`個並ぶリストを生成する
[]
39,379
def f_39379(x): return
[h.get_height() for h in sns.distplot(x).patches]
import seaborn as sns import numpy as np sns.set() np.random.seed(0) def check(candidate):
[ "\n x = np.random.rand(100)\n res = candidate(x)\n assert res == [\n 1.2707405677074517,\n 0.8132739633327691,\n 1.0674220768742593,\n 1.0674220768742597,\n 0.8641035860410673\n ]\n" ]
f_39379
distplotで表示したデータ`x`に関するヒストグラム上のピンの高さをリストとして得る
[ "numpy", "seaborn" ]
38,415
def f_38415():
return ax
ax=plt.subplot(aspect='equal')
import matplotlib.pyplot as plt def check(candidate):
[ "\n res_ax = candidate()\n assert res_ax.get_xlim() == res_ax.get_ylim()\n" ]
f_38415
グラフの描画範囲`ax`を正方形にする
[ "matplotlib" ]
37,757
def f_37757(string): return
eval(string)
def check(candidate):
[ "\n assert candidate(\"[1,1,1,2,2,2]\") == [1,1,1,2,2,2]\n", "\n assert candidate(\"[1,2]\") == [1,2]\n" ]
f_37757
文字列型変数`string`の値を数値型のインスタンス変数として評価する
[]
34,422
def f_34422(s_json):
return d
d = json.loads(s_json)
import json def check(candidate):
[ "\n assert candidate('{\"a\":123,\"b\":45.6}') == {'a':123, 'b':45.6}\n" ]
f_34422
JSONを表す文字列`s_json`から辞書型オブジェクト`d`を得る
[ "json" ]
27,686
def f_27686(soup): return
soup.get('a_id')
from bs4 import BeautifulSoup def check(candidate):
[ "\n soup = BeautifulSoup('<p>riginsf</p>')\n soup['a_id'] = 'some value'\n assert candidate(soup) == 'some value'\n" ]
f_27686
HTMLパースオブジェクト`soup`の中でHTMLタグの`a_id`の属性値を取得する
[ "bs4" ]
41,054
def f_41054(): return
[os.rename(f, f.replace('.dat', '.gui')) for f in os.listdir('.') if not f.startswith('.')]
import os def check(candidate):
[ "\n assert all([((item is None) or item.endswiths('.gui')) for item in candidate()])\n" ]
f_41054
カレントディレクトリにある特定の拡張子`.dat`をもつファイルの拡張子を`.gui`にすべて書き換える
[ "os" ]
43,303
def f_43303(df):
return df2
df2 = df.reset_index(drop=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(data={'col1':[0,1,2,3], 'col2': pd.Series([2,3], index=[2,3])}, index=[0,2,1,3])\n assert candidate(df).equals(pd.DataFrame(data={'col1': [0,1,2,3], 'col2': pd.Series([2,3], index=[1,3])}, index=[0,1,2,3]))\n" ]
f_43303
データフレーム`df`のインデックスをリセットした新たなデータフレーム`df2`を得る
[ "pandas" ]
43,322
def f_43322(df): return
df.resample('1min').ffill()
import io import pandas as pd def check(candidate):
[ "\n data = (\n \"年月日時,気温(℃),降水量(mm),風速(m/s),日射量(MJ/㎡)\\n\"\n \"2017-01-01 00:00:00,5.8,0.0,1.5,0.0\\n\"\n \"2017-01-01 01:00:00,4.9,0.0,0.8,0.0\\n\"\n \"2017-01-01 02:00:00,4.9,0.0,1.5,0.0\\n\"\n \"2017-01-01 03:00:00,4.2,0.0,0.8,0.0\\n\"\n \"2017-01-01 04:00:00,4.4,0.0,1.0,0.0\\n\"\n )\n df = pd.read_csv(io.StringIO(data), parse_dates=['年月日時'], index_col='年月日時')\n res = candidate(df)\n assert len(res) == 241\n" ]
f_43322
時系列データの入ったデータフレーム`df`を1分ごとにリサンプルし、間の値は直前の値で補完する
[ "io", "pandas" ]
35,683
def f_35683(z): return
z.real
def check(candidate):
[ "\n assert candidate(1.23-0j) == 1.23\n", "\n assert candidate(1.23+0j) == 1.23\n", "\n assert candidate(0.0-1j) == 0.0\n" ]
f_35683
複素数`z`の実数部のみを得る
[]
41,058
def f_41058(iter, r): return
list(itertools.combinations(iter, r))
import itertools def check(candidate):
[ "\n assert candidate([1,2,3], 2) == [(1, 2), (1, 3), (2, 3)]\n", "\n assert candidate([1], 2) == []\n", "\n assert candidate([1], 1) == [(1, )]\n" ]
f_41058
イテラブルオブジェクト`iter`の`r`個の要素の組み合わせをリストとして得る
[ "itertools" ]
42,573
def f_42573(sheet, row, col): return
sheet.cell_value(row, col)
import xlrd from xlwt import Workbook def check(candidate):
[ "\n file_location = \"test.xlsx\"\n\n book = Workbook()\n sheet1 = book.add_sheet('Sheet 1')\n sheet1.write(0, 0, 'A1')\n sheet1.write(0, 1, 'B1')\n sheet1.write(8, 5, \"Hello, world!\")\n book.save(file_location)\n\n workbook = xlrd.open_workbook(file_location)\n sheet = workbook.sheet_by_index(0)\n assert candidate(sheet, 0, 0) == \"A1\"\n assert candidate(sheet, 0, 1) == \"B1\"\n assert candidate(sheet, 8, 5) == \"Hello, world!\"\n" ]
f_42573
Excelシートオブジェクト`sheet`内の行`row`、列`col`のセルの値を得る
[ "xlrd", "xlwt" ]
40,361
def f_40361(func, args): return
func(*args)
def check(candidate):
[ "\n def func1(x, y, z): return x + y + z \n assert candidate(func1, [1,2,3]) == 6\n", "\n def func2(a): return 0.8\n assert candidate(func2, ['random']) == 0.8\n" ]
f_40361
引数`args`をアンパックして関数`func`に渡す
[]
43,333
def f_43333(r, l): return
pd.DataFrame(data={'range': r, 'result': l})
import pandas as pd def check(candidate):
[ "\n r, l = [1,2,3], [4,5,6]\n assert candidate(r, l).equals(pd.DataFrame(data={'range': r, 'result': l}))\n" ]
f_43333
列名`range`の要素をリスト`r`、列名`result`の要素をリスト`l`としてデータフレームを作る
[ "pandas" ]
11,582
def f_11582(): return
open('C:\\Users\\Documents\\python programs', 'r', encoding='utf-8')
import builtins from unittest.mock import Mock def check(candidate):
[ "\n with open('a.txt', 'w') as f:\n f.write('t')\n f1 = open('a.txt')\n builtins.open = Mock(return_value = f1)\n assert candidate() == f1\n" ]
f_11582
ファイル`C:\Users\Documents\python programs`を開く
[ "builtins" ]
12,174
def f_12174(): return
sys.path
import sys def check(candidate):
[ "\n assert candidate() == sys.path\n" ]
f_12174
PYTHONPATHを表示する
[ "sys" ]
6,225
def f_6225(): return
sum(1 for line in open('myfile.txt'))
def check(candidate):
[ "\n with open('myfile.txt', 'w') as fw:\n for i in range(10): fw.write(f\"{i}\\n\")\n assert candidate() == 10\n", "\n with open('myfile.txt', 'w') as fw:\n for i in range(88): fw.write(f\"{i}\\n\")\n assert candidate() == 88\n" ]
f_6225
テキストファイル`myfile.txt`の行数を取得する
[]
6,225
def f_6225(): return
len(open('myfile.txt').readlines())
def check(candidate):
[ "\n with open('myfile.txt', 'w') as fw:\n for i in range(10): fw.write(f\"{i}\\n\")\n assert candidate() == 10\n", "\n with open('myfile.txt', 'w') as fw:\n for i in range(88): fw.write(f\"{i}\\n\")\n assert candidate() == 88\n" ]
f_6225
テキストファイル`myfile.txt`の行数を取得する
[]
47,199
def f_47199(a): return
a is not None
def check(candidate):
[ "\n assert candidate(None) == False\n", "\n assert candidate(0) == True\n", "\n assert candidate(0.00) == True\n", "\n assert candidate([]) == True\n", "\n assert candidate(102) == True\n" ]
f_47199
変数`a`がNoneでない場合に変数を表示する
[]
23,332
def f_23332(data):
return list
list = [] for r in data: list.append(', '.join(r))
def check(candidate):
[ "\n data = [['a','b','c','x','y','z'],\n ['f', 'g', 'h', 'i', 'j', 'k']]\n assert candidate(data) == [\"a, b, c, x, y, z\", \"f, g, h, i, j, k\"]\n" ]
f_23332
二次元リスト`list`の中身を全て
[]
34,431
def f_34431():
return f
f = open('all_names.csv', 'w', encoding='UTF-8')
def check(candidate):
[ "\n f = candidate()\n assert f.name == 'all_names.csv'\n assert f.mode == 'w'\n assert f.encoding == 'UTF-8'\n" ]
f_34431
文字コード
[]
33,700
def f_33700(list):
return newlist
newlist = [] for s in list: if s.endswith('string'): newlist.append(s)
def check(candidate):
[ "\n assert candidate(['abcstring', 'bbbb', 'fhstringyjn', '1326546']) == ['abcstring']\n" ]
f_33700
リスト`list`から条件となる文字列`string`と部分一致する要素を取り出して新しいリスト`newlist`を作る
[]
33,700
def f_33700(list):
return newlist
newlist = [] for s in list: if 'string' in s: newlist.append(s)
def check(candidate):
[ "\n assert candidate(['abcstring', 'bbbb', 'fhstringyjn', '1326546']) == ['abcstring', 'fhstringyjn']\n" ]
f_33700
リスト`list`から条件となる文字列`string`と部分一致する要素を取り出して新しいリスト`newlist`を作る
[]
27,556
def f_27556(): return
plt.figure()
import matplotlib import matplotlib.pyplot as plt def check(candidate):
[ "\n assert isinstance(candidate(), matplotlib.figure.Figure)\n" ]
f_27556
グラフを表示する
[ "matplotlib" ]
37,060
def f_37060(data_frame): return
display(data_frame)
import pandas as pd from IPython.display import display def check(candidate):
[ "\n df = pd.DataFrame([1, 2, 3])\n try:\n candidate(df)\n except:\n assert False\n" ]
f_37060
データフレーム`data_frame`を表示する
[ "IPython", "pandas" ]
12,310
def f_12310():
return table
table = Texttable() print(table.draw())
from texttable import Texttable def check(candidate):
[ "\n try:\n candidate()\n except:\n assert False\n" ]
f_12310
表`table`を画面に表示する(texttable)
[ "texttable" ]
19,311
def f_19311(): return
pd.read_csv('arena.txt', header=None, delim_whitespace=True, decimal=',')
import pandas as pd def check(candidate):
[ "\n file_name = 'arena.txt'\n with open(file_name, 'w') as f:\n f.write('1 0,000000 4,219309 4,219309 8,988674 8,988674 10,848450\\n')\n f.write('2 4,219309 7,414822 7,414822 12,430150 12,430150 14,198310\\n')\n f.write('3 8,000000 10,478795 10,478795 15,417747 15,417747 17,297929\\n')\n f.write('1 11,000000 14,257995 14,257995 19,009302 19,009302 20,873072\\n')\n df = candidate()\n assert df.shape[0] == 4\n assert df.shape[1] == 7\n" ]
f_19311
少数点にコンマが使われているファイル`arena.txt`を読み込む
[ "pandas" ]
42,268
def f_42268(json_data):
return json_str
json_str = json.dumps(json_data)
import json def check(candidate):
[ "\n assert candidate({'a': 134, 'bvgdfbh': 46.7576}) == '{\"a\": 134, \"bvgdfbh\": 46.7576}'\n", "\n assert candidate(['foo', {'bar': ('baz', None, 1.0, 2)}]) == '[\"foo\", {\"bar\": [\"baz\", null, 1.0, 2]}]'\n" ]
f_42268
オブジェクト`json_data`をJSON文字列`json_str`に変換する
[ "json" ]
51,387
def f_51387():
return data
data = np.genfromtxt('file.csv')
import numpy as np from unittest.mock import Mock def check(candidate):
[ "\n np.genfromtxt = Mock(return_value = np.array([[2, 3, 5], [1, 5, 6]]))\n assert candidate().shape == (2, 3)\n", "\n np.genfromtxt = Mock(return_value = np.array([['abc'], ['lkm']]))\n assert candidate().shape == (2, 1)\n" ]
f_51387
CSVファイル`file.csv`を`data`に読み込む
[ "numpy" ]
38,598
def f_38598(df):
return
df.drop(df.index[df.row == "condition"], inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'row': ['同意します', 'condition', '同意します', '同意しません',]},\n index=[1, 2, 3, 4, ])\n candidate(df)\n assert df.shape == (3, 1)\n" ]
f_38598
条件`condition`を満たす行を削除する
[ "pandas" ]
20,094
def f_20094(list, x, y): return
list[x][y]
import json def check(candidate):
[ "\n mat = [[i+j for i in range(2)] for j in range(3)]\n assert candidate(mat, 0, 0) == 0\n", "\n mat = [[i+j for i in range(2)] for j in range(3)]\n assert candidate(mat, 2, 1) == 3\n" ]
f_20094
二次元リスト`list`内の要素
[ "json" ]