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 |
---|---|---|---|---|---|---|---|---|
18,780 | def f_18780(x, y):
|
return | for i in range(x):
for j in range(y):
exec("list_" + str(i) + "_" + str(j) + "= [i, j]") |
def check(candidate): | [
"\n try:\n candidate(3, 4)\n except:\n assert False\n"
] | f_18780 | forループで数字を添字に持つ二次元リスト`list`を生成する | [] |
19,552 | def f_19552():
|
return file_name | now = datetime.datetime.now()
file_name = 'file_{0:%Y%m%d-%H%M%S}.txt'.format(now) |
import datetime
def check(candidate): | [
"\n file_name = candidate()\n later_name = 'file_{0:%Y%m%d-%H%M%S}.txt'.format(datetime.datetime.now())\n assert file_name.split('-')[0] == later_name.split('-')[0]\n",
"\n file_time = int(file_name.split('-')[1].split('.')[0])\n later_time = int(later_name.split('-')[1].split('.')[0])\n assert (later_time - file_time) < 100\n"
] | f_19552 | ファイル名に現在の日付を入れる | [
"datetime"
] |
38,755 | def f_38755(x, y):
|
return img |
a, b = np.polyfit(x, y, 1)
linear = a * x + b
img = plt.plot(x, linear,color="black")
|
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def check(candidate): | [
"\n x = np.linspace(0,1,100)\n y = np.random.rand(100)\n try:\n img = candidate(x, y)\n assert type(img[0]) == matplotlib.lines.Line2D\n except:\n assert False\n"
] | f_38755 | グラフに線形回帰直線を追加する | [
"matplotlib",
"numpy"
] |
4,556 | def f_4556():
|
return | class Foo:
def whoAmI(self):
print( "I am " + self.__class__.__name__)
Foo().whoAmI() |
import sys
def check(candidate): | [
"\n f = open('output', 'w')\n sys.stdout = f\n candidate()\n f.close()\n with open ('output', 'r') as f1:\n lines = f1.readlines()\n assert 'I am Foo' in lines[0]\n"
] | f_4556 | メンバ関数からクラスの名前を取得する | [
"sys"
] |
27,922 | def f_27922():
return | {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"} |
import urllib.request
def check(candidate): | [
"\n url = \"https://en.wikipedia.org/wiki/List_of_national_independence_days\"\n request = urllib.request.Request(url=url, headers=candidate())\n response = urllib.request.urlopen(request)\n assert response.getcode() == 200\n"
] | f_27922 | ユーザーエージェントをFirefoxに変更する | [
"urllib"
] |
|
35,394 | def f_35394(file):
return | pd.read_csv(file, sep='\s+') |
import pandas as pd
def check(candidate): | [
"\n file_name = 'a.csv'\n with open (file_name, 'w') as f:\n f.write('1 2\\n')\n df = candidate(file_name)\n assert df.shape == (0, 2)\n",
"\n with open (file_name, 'w') as f:\n f.write('abc def\\nefg hij')\n df = candidate(file_name)\n assert df.shape == (1, 2)\n"
] | f_35394 | 空白で区切られたCSVファイル`file`を読み込む | [
"pandas"
] |
|
35,394 | def f_35394(file):
return | pd.read_csv(file, delim_whitespace=True) |
import pandas as pd
def check(candidate): | [
"\n file_name = 'a.csv'\n with open (file_name, 'w') as f:\n f.write('1 2\\n')\n df = candidate(file_name)\n assert df.shape == (0, 2)\n",
"\n with open (file_name, 'w') as f:\n f.write('abc def\\nefg hij')\n df = candidate(file_name)\n assert df.shape == (1, 2)\n"
] | f_35394 | 空白で区切られたCSVファイル`file`を読み込む | [
"pandas"
] |
|
37,591 | def f_37591(variable, value):
|
return variable | variable = value if variable is None else variable |
def check(candidate): | [
"\n assert candidate(123, 1) == 123\n",
"\n assert candidate(None, 1) == 1\n",
"\n assert candidate([], 1) == []\n"
] | f_37591 | 変数`variable`に値が入っていない場合のみ値を代入をする | [] |
37,591 | def f_37591(variable, value):
|
return variable | variable = value if variable is None else variable |
def check(candidate): | [
"\n assert candidate(123, 1) == 123\n",
"\n assert candidate(None, 1) == 1\n",
"\n assert candidate([], 1) == []\n"
] | f_37591 | 変数`variable`に値が入っていない場合のみ値を代入をする | [] |
11,601 | def f_11601():
|
return | os.startfile('C:\Program Files\....\app.exe') |
import os
from unittest.mock import Mock
def check(candidate): | [
"\n os.startfile = Mock()\n try:\n candidate()\n except:\n assert False\n"
] | f_11601 | Windows上のアプリケーション`app`を実行する | [
"os"
] |
26,837 | def f_26837(number):
|
return num_list |
num_list = []
while number != 0:
num_list.append(number % 10)
number //= 10
num_list.reverse()
|
def check(candidate): | [
"\n assert candidate(123) == [1,2,3]\n"
] | f_26837 | 数値`number`を一桁ずつ取得してリスト`num_list`にする | [] |
26,837 | def f_26837(number):
|
return num_list | num_list = map(int, str(number)) |
def check(candidate): | [
"\n assert list(candidate(123)) == [1,2,3]\n"
] | f_26837 | 数値`number`を一桁ずつ取得してリスト`num_list`にする | [] |
59,780 | def f_59780():
|
return result |
def example(a, b): return b
hello = tf.constant("Hello")
f = tf.function(example)
result = eval(f([], hello))
|
import tensorflow as tf
from tensorflow.keras.backend import eval
def check(candidate): | [
"\n assert candidate() == b'Hello'\n"
] | f_59780 | 定数の評価結果を表示する | [
"tensorflow"
] |
38,276 | def f_38276(text):
|
return list |
pattern = r"([0-9]+)"
list=re.findall(pattern,text)
|
import re
def check(candidate): | [
"\n assert candidate('fg456fgxnd') == ['456']\n"
] | f_38276 | 正規表現で文字列`text`の中から数値だけを抽出してリスト`list`にする | [
"re"
] |
49,558 | def f_49558(x, y, df):
|
return rp | rp = sns.regplot(x, y, data=df, order=1, line_kws={"color":"indianred"})
rp.axes.set_ylim(0,) |
import pandas as pd
import seaborn as sns
def check(candidate): | [
"\n df = pd.DataFrame([[0, 1, 2], [7, 8, 9]])\n rp = candidate(df[0], df[1], df)\n assert 'Axes' in str(type(rp))\n"
] | f_49558 | y軸の下限値を指定し、上限値は自動にする | [
"pandas",
"seaborn"
] |
65,284 | def f_65284(word, h):
|
return word | tmp1 = word[:h]
word = word[h:]
word.extend(tmp1) |
def check(candidate): | [
"\n assert candidate([\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\"], 4) == [\"e\",\"f\",\"g\",\"a\",\"b\",\"c\",\"d\"]\n"
] | f_65284 | 文字列`word`の順番を`h`番目で入れ替える | [] |
31,916 | def f_31916(attributes):
|
return attributes | for i, attribute in enumerate(attributes):
attributes[i] = attribute-1 |
def check(candidate): | [
"\n assert candidate([1,2,3]) == [0,1,2]\n",
"\n assert candidate([100]) == [99]\n"
] | f_31916 | リスト`attributes`の全要素の数値に対してfor文でマイナス1する | [] |
31,916 | def f_31916(attributes):
|
return attributes | for i in range(len(attributes)):
attributes[i] = attributes[i]-1 |
def check(candidate): | [
"\n assert candidate([1,2,3,4]) == [0,1,2,3]\n",
"\n assert candidate([1., 2, 3.4, 5.5]) == [0., 1, 2.4, 4.5]\n"
] | f_31916 | リスト`attributes`の全要素の数値に対してfor文でマイナス1する | [] |
31,916 | def f_31916(attributes):
|
return attributes | attributes = [attribute-1 for attribute in attributes] |
def check(candidate): | [
"\n assert candidate([1,2,3,4]) == [0,1,2,3]\n",
"\n assert candidate([1., 2, 3.4, 5.5]) == [0., 1, 2.4, 4.5]\n"
] | f_31916 | リスト`attributes`の全要素の数値に対してfor文でマイナス1する | [] |
21,171 | def f_21171(list):
return | Counter(map(tuple, list)) |
from collections import Counter
def check(candidate): | [
"\n li=[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[2,3,4],[1,2,3],[2,3,4],[5,6,7]]\n c = candidate(li)\n assert c.most_common() == [((2, 3, 4), 3), ((1, 2, 3), 2), ((3, 4, 5), 1), ((4, 5, 6), 1), ((5, 6, 7), 1)]\n",
"\n li = [['abc', 'def'], ['hij', 'klm']]\n c = candidate(li)\n assert c.most_common() ==[(('abc', 'def'), 1), (('hij', 'klm'), 1)]\n"
] | f_21171 | 二次元リスト`list`から重複する要素のみ抽出する | [
"collections"
] |
|
45,204 | def f_45204(num_of_file):
|
return data | data = [None] * num_of_file
for i in range(num_of_file):
with open('data{}.txt'.format(i + 1), mode="r", encoding="utf-8") as f:
data[i] = f.read() |
def check(candidate): | [
"\n num_of_file = 4\n for i in range(0, num_of_file):\n with open ('data'+str(i + 1)+'.txt', 'w') as f:\n f.write(str(i + 1)+'\\n')\n data = candidate(4)\n for i in range(0, num_of_file):\n assert data[i] == str(i + 1)+'\\n'\n"
] | f_45204 | 連番個数`num_of_file`のtxtファイル`data{}.txt`を読み込む | [] |
24,786 | def f_24786(string):
return | urllib.parse.urlencode(string).encode('ascii') |
import urllib
def check(candidate): | [
"\n s = {'mail':'admin@getgo.com', 'password':34}\n assert candidate(s) == b'mail=admin%40getgo.com&password=34'\n"
] | f_24786 | 文字列`string`をbyte型 | [
"urllib"
] |
|
5,822 | def f_5822(imgAry):
|
return restoredImgAry | pca = PCA()
pca.fit(imgAry)
pca_res = pca.transform(imgAry)
restoredImgAry = pca.inverse_transform(pca_res) |
import numpy as np
from sklearn.decomposition import PCA
def check(candidate): | [
"\n imgAry = np.array([[1, 2], [4, 3]])\n assert np.allclose(candidate(imgAry), np.array([[1,2],[4,3]], dtype=float))\n"
] | f_5822 | 主成分分析 | [
"numpy",
"sklearn"
] |
42,516 | def f_42516(fnameF):
return | plt.savefig(fnameF, dpi=200, bbox_inches="tight", pad_inches=0.1) |
import os
import matplotlib.pyplot as plt
def check(candidate): | [
"\n candidate('v.jpg')\n assert os.path.exists('v.jpg')\n"
] | f_42516 | グラフサイズを調整して保存する | [
"matplotlib",
"os"
] |
|
18,685 | def f_18685(list):
|
return list | list = [x for x in list if x] |
def check(candidate): | [
"\n assert candidate(['afrg ', 'fdbf', 13254, 54765.6]) == ['afrg ', 'fdbf', 13254, 54765.6]\n",
"\n assert candidate(['', None, 0]) == []\n"
] | f_18685 | 二次元リスト`list`から空白の要素を削除する | [] |
18,685 | def f_18685(list):
|
return list | for i in range(len(list) - 1, -1, -1):
if not list[i]:
del list[i] |
def check(candidate): | [
"\n assert candidate([4,3,2,0,1,0]) == [4,3,2,1]\n",
"\n assert candidate([4,3,2,[],1,0]) == [4,3,2,1]\n"
] | f_18685 | 二次元リスト`list`から空白の要素を削除する | [] |
34,692 | def f_34692(json_string):
|
return json_obj | json_obj = json.loads(json_string) |
import json
def check(candidate): | [
"\n assert candidate('{\"a\": 5}') == {'a': 5}\n"
] | f_34692 | JSON文字列`json_string`をオブジェクト`json_obj`に読み込む(json) | [
"json"
] |
35,864 | def f_35864(img):
|
return gray_img | gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
plt.imshow(gray_img)
plt.gray()
plt.show() |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
def check(candidate): | [
"\n im = Image.new('RGBA', (200, 200), (255, 255, 255, 255))\n im.save('v.png')\n img = cv2.imread('v.png')\n gray_img = candidate(img)\n cv2.imwrite('v_gray.png', gray_img)\n assert os.path.exists('v_gray.png')\n"
] | f_35864 | カラー画像`img`をグレースケールで表示する | [
"PIL",
"cv2",
"matplotlib",
"numpy",
"os"
] |
49,478 | def f_49478(ticks, labels):
return | plt.xticks(range(0, len(labels), ticks), labels[::ticks]) |
import matplotlib.pyplot as plt
def check(candidate): | [
"\n ticks = 3\n labels = [1, 4]\n plt = candidate(ticks, labels)\n assert isinstance(plt, tuple)\n",
"\n labels = ['abc', 'xcv']\n plt = candidate(ticks, labels)\n assert isinstance(plt, tuple)\n"
] | f_49478 | X軸の間隔を`ticks`に、ラベルを`labels`にする | [
"matplotlib"
] |
|
16,769 | def f_16769(num_of_file):
|
return book_list | book_list = []
for n in range(1, num_of_file + 1):
file_name = 'excel_file%d.xls' % (n)
book_list.append(xlrd.open_workbook(file_name)) |
import xlrd
import xlwt
def check(candidate): | [
"\n num_files = 3\n for i in range(0, num_files):\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet('test')\n sheet.write(0, 1, 1)\n\n workbook.save('excel_file%d.xls' % (i + 1))\n book_list = candidate(num_files)\n for bk in book_list:\n assert isinstance(bk, xlrd.book.Book)\n"
] | f_16769 | 連番になっている`num_of_file`個のExcelファイル`excel_file`をリストに読み込む | [
"xlrd",
"xlwt"
] |
2,220 | def f_2220(dt):
return | dt.timestamp() |
import pytz
import datetime
def check(candidate): | [
"\n dt = datetime.datetime.fromtimestamp(123456789.123456, pytz.timezone('America/Los_Angeles'))\n assert candidate(dt) == 123456789.123456\n"
] | f_2220 | datetimeオブジェクト`dt`からUnix Timeを求める | [
"datetime",
"pytz"
] |
|
44,723 | def f_44723(df, col_name, string):
return | df[df[col_name].str.contains(string)] |
import pandas as pd
def check(candidate): | [
"\n df = pd.DataFrame({'name': ['Mr. A', 'Ms. B'], 'age': [30, 23]})\n df_sub = pd.DataFrame({'name': ['Mr. A'], 'age': [30]})\n assert candidate(df, 'name', 'A').equals(df_sub)\n"
] | f_44723 | 行`col_name`に特定の文字列`string`を含む行をデータフレーム`df`から抽出する | [
"pandas"
] |
|
46,711 | def f_46711(list, n):
return | list[-n:] |
def check(candidate): | [
"\n assert candidate([1,2,3,4,5,6,7], 2) == [6,7]\n",
"\n assert candidate([1,2,3], 0) == [1,2,3]\n"
] | f_46711 | リスト`list`の末尾から`n`個の要素を取り出す | [] |
|
17,648 | def f_17648(b_string):
return | b_string.decode('unicode-escape') |
import unicodedata
def check(candidate): | [
"\n assert candidate(b'example-string') == 'example-string'\n"
] | f_17648 | Unicodeエスケープされたバイト列`b_string`を文字列に変換 | [
"unicodedata"
] |
|
9,633 | def f_9633(str, old_s, new_s):
return | str.replace(old_s, new_s) |
def check(candidate): | [
"\n assert candidate('mystring', 'my', 'your') == 'yourstring'\n"
] | f_9633 | 文字列`str`内の対象文字列`old_s`を別の文字列`new_s`に置換する | [] |
|
37,327 | def f_37327():
|
return |
while True:
try:
line = input()
if line == '':
break
else:
yield line
except EOFError:
break
|
import sys
def check(candidate): | [
"\n with open('p.txt', 'w') as f:\n f.write('1\\n\\n')\n f = open('p.txt')\n sys.stdin = f\n d = candidate()\n print(type(d))\n assert 'generator' in str(type(d))\n sys.stdin = sys.__stdin__\n"
] | f_37327 | 空行が入力されるまで標準入力を受け付ける | [
"sys"
] |
37,831 | def f_37831(model, X, Y):
|
return | model.fit(X, Y, epochs=200, batch_size=1, verbose=0) |
import numpy as np
from tensorflow.keras import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
def check(candidate): | [
"\n model = Sequential([\n Dense(input_dim=2, units=1), Activation('sigmoid')\n ])\n model.compile(loss='binary_crossentropy', optimizer=SGD(lr=0.1))\n X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])\n Y = np.array([[0], [1], [1], [1]])\n\n try:\n candidate(model, X, Y)\n except:\n assert False\n"
] | f_37831 | ログを出力せずにモデルの学習を行う | [
"numpy",
"tensorflow"
] |
53,340 | def f_53340(str):
return | str.encode('utf-8') |
def check(candidate): | [
"\n assert candidate('mystr') == b'mystr'\n"
] | f_53340 | 文字列`str`をバイト列 | [] |
|
45,120 | def f_45120(n):
return | [pd.DataFrame() for i in range(n)] |
import pandas as pd
def check(candidate): | [
"\n df_list = candidate(3)\n assert len(df_list) == 3\n assert all([type(a)==pd.DataFrame for a in df_list])\n"
] | f_45120 | 要素がデータフレームで、要素数`n`のリストを作る | [
"pandas"
] |
|
24,987 | def f_24987(str):
return | re.sub('[\u3000]{2,}', '\u3000', str) |
import re
def check(candidate): | [
"\n text = u\"名前1 名前2 名前3 名前4 \"\n assert candidate(text) == '名前1 名前2 名前3 名前4 '\n"
] | f_24987 | 文字列`str`の中の連続した複数の全角空白を1つの全角空白で置換する | [
"re"
] |
|
50,500 | def f_50500(img):
return | cv2.imwrite('file.jpg', img) |
import cv2
from os import path
from PIL import Image
def check(candidate): | [
"\n im = Image.new('RGBA', (200, 200), (255, 255, 255, 255))\n im.save('v.png')\n img = cv2.imread('v.png')\n candidate(img)\n assert path.exists('file.jpg')\n"
] | f_50500 | 画像`img`をファイル名`file.jpg`として保存する | [
"PIL",
"cv2",
"os"
] |
|
41,336 | def f_41336(a, b):
return | np.dot(a, b) |
import numpy as np
def check(candidate): | [
"\n arr = np.array([[1,3,-5]])\n arr_1 = np.array([[4],[-2],[-1]])\n assert candidate(np.mat(arr),np.mat(arr_1)) == 3\n",
"\n assert np.array_equal(candidate(np.zeros(shape=(5,2)), np.zeros(shape=(2,5))), np.zeros(shape=(5,5)))\n",
"\n assert np.array_equal(candidate(np.array([[4]]), np.array([[0]])), np.array([[0]]))\n",
"\n assert candidate(3,4) == 12\n"
] | f_41336 | 行列`a`と`b`の積を計算する | [
"numpy"
] |
|
48,742 | def f_48742():
|
return | df = pd.read_table('file.txt', header=None, delim_whitespace=True)
df.to_csv('new_file.csv', index=False, header=False) |
import csv
import pandas as pd
def check(candidate): | [
"\n with open(\"file.txt\", \"w\") as text_file:\n text_file.write('''col1 col2 col3\n''')\n text_file.write('''1 2 3\n''')\n \n candidate()\n import csv\n file = open('new_file.csv')\n csvreader = csv.reader(file)\n rows = []\n for row in csvreader:\n rows.append(row)\n \n assert rows[0] == ['col1', 'col2', 'col3'] and rows[1] == ['1', '2', '3']\n",
"\n with open(\"file.txt\", \"w\") as text_file:\n text_file.write('''col1\n''')\n text_file.write('''1\n''')\n text_file.write('''2\n''')\n \n candidate()\n import csv\n file = open('new_file.csv')\n csvreader = csv.reader(file)\n rows = []\n for row in csvreader:\n rows.append(row)\n \n assert rows[0] == ['col1'] and rows[1] == ['1'] and rows[2] == ['2']\n",
"\n with open(\"file.txt\", \"w\") as text_file:\n text_file.write('''col1 col2 col3 \n''')\n text_file.write(''' 1 2 3 \n''')\n \n candidate()\n import csv\n file = open('new_file.csv')\n csvreader = csv.reader(file)\n rows = []\n for row in csvreader:\n rows.append(row)\n \n assert rows[0] == ['col1', 'col2', 'col3'] and rows[1] == ['1', '2', '3']\n"
] | f_48742 | 空白区切りのテキストファイル`file.txt`をコンマ区切りのcsvファイル`new_file.csv`に変換する | [
"csv",
"pandas"
] |
35,271 | def f_35271(n):
return | str(n) |
def check(candidate): | [
"\n assert candidate(0) == '0'\n",
"\n assert candidate(34.12) == '34.12'\n",
"\n assert candidate(-1) == '-1'\n",
"\n assert candidate(float('inf')) == 'inf'\n",
"\n assert candidate(123412) == '123412'\n"
] | f_35271 | 数値`n`を文字列に変換する | [] |
|
20,048 | def f_20048(li):
|
return result |
c = Counter(tuple(x) for x in li)
result = [list(k) for k,v in c.items() if v >=2]
|
from collections import Counter
def check(candidate): | [
"\n li=[[1,2,3],[5,6,7],[2,3,4,5],[1,2,3],[7,8,9],[2,3,4,5],[1,2,3],[5,6,7]]\n assert candidate(li) == [[1, 2, 3], [5, 6, 7], [2, 3, 4, 5]]\n"
] | f_20048 | 2次元リスト`li`内の重複している要素を取り出す | [
"collections"
] |
21,070 | def f_21070(li, li2):
return | list(filter(lambda x:x not in li2, li)) |
def check(candidate): | [
"\n assert candidate([1, 2, 3], [1, 3, 4]) == [2]\n",
"\n assert candidate(['abc', 'def'], ['abc']) == ['def']\n"
] | f_21070 | 2つのリスト`li`と`li2`を比較し、重複している要素を削除する | [] |
|
19,098 | def f_19098(li):
|
return result |
result=[]
li.sort()
M = len(li) - 1
for i, e in enumerate(li):
j = i + 1
k = M
while k > j:
s = li[i] + li[j] + li[k]
if s == 0:
result.append([li[i], li[j], li[k]])
k -= 1
elif s > 0:
k -= 1
else:
j += 1
|
def check(candidate): | [
"\n li = [1, -1, 0, 2]\n assert len(candidate(li)) == 1\n"
] | f_19098 | 整数を要素に持つリスト`li'から、合計すると0になる3つの整数を求める | [] |
36,377 | def f_36377(ary):
return | np.array2string(ary, separator=', ', formatter={'float_kind': lambda x: '{: .4f}'.format(x)}) |
import numpy as np
def check(candidate): | [
"\n assert candidate(np.array([1, 2, 3])) == \"[1, 2, 3]\"\n",
"\n assert candidate(np.array([])) == \"[]\"\n",
"\n assert candidate(np.array([1, 2, 3, 4, 4])) == \"[1, 2, 3, 4, 4]\"\n",
"\n assert candidate(np.array([1, 2, 3, 4, 5])) != \"[1 2 3 4 5]\"\n"
] | f_36377 | 配列`ary`の各要素にコンマを付けて小数点四桁まで表示する | [
"numpy"
] |
|
23,839 | def f_23839():
return | subprocess.check_output('cat file', shell=True) |
import subprocess
from unittest.mock import Mock
def check(candidate): | [
"\n subprocess.check_output = Mock(return_value = \"Success\")\n assert candidate() == \"Success\"\n"
] | f_23839 | 外部プロセス`cat`を呼び出し、ファイル`file`の中身を読み込む | [
"subprocess"
] |
|
34,981 | def f_34981():
return | cv2.imread('file.png', 0) |
import cv2
from os import path
from PIL import Image
def check(candidate): | [
"\n im = Image.new('RGBA', (200, 200), (255, 255, 255, 255))\n im.save('file.png')\n img = candidate()\n cv2.imwrite('g.png', img)\n assert path.exists('g.png')\n"
] | f_34981 | 画像'file.png'をグレースケールで読み込む | [
"PIL",
"cv2",
"os"
] |
|
33,506 | def f_33506(s):
return | base64.b64decode(s).decode() |
import base64
def check(candidate): | [
"\n assert candidate(b'R2Vla3NGb3JHZWVrcw==') == 'GeeksForGeeks'\n"
] | f_33506 | base64で符号化された文字列`s`ををデコードする | [
"base64"
] |
|
24,190 | def f_24190(x, y):
return | plt.scatter(x, y) |
import matplotlib.pyplot as plt
def extract_data_from_plot(plot):
x_plot, y_plot = plot.get_offsets().data.T
return x_plot, y_plot
def check(candidate): | [
"\n x, y = [0, 1, 2], [0, 1, 2]\n plot = candidate(x, y)\n x_plot, y_plot = extract_data_from_plot(plot)\n assert y_plot.tolist(), float(y).tolist()\n assert x_plot.tolist(), float(x).tolist()\n",
"\n x, y = [10.3, 11.12, 133.44], [4.9, 2.48, 3.67]\n plot = candidate(x, y)\n x_plot, y_plot = extract_data_from_plot(plot)\n assert y_plot.tolist(), float(y).tolist()\n assert x_plot.tolist(), float(x).tolist()\n"
] | f_24190 | 配列データ`x`,`y`の散布図を表示する | [
"matplotlib"
] |
|
40,646 | def f_40646(html):
|
return new_list |
soup = bs4.BeautifulSoup(html, 'lxml')
unorder_list = soup.find_all('ul')
new_list = []
for ul_tag in unorder_list:
for li in ul_tag.find_all('li'):
new_list.append(li.text)
|
import bs4
import urllib
import ssl
def check(candidate): | [
"\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n url = 'https://en.wikipedia.org/wiki/Blue_Moon_of_Josephine'\n html = urllib.request.urlopen(url, context=ctx).read()\n assert 'List of diamonds' in candidate(html)\n"
] | f_40646 | HTMLファイル`html`内の順序なしリストをpythonのリストとして取り込む | [
"bs4",
"ssl",
"urllib"
] |
41,775 | def f_41775(df, col_label):
return | df[df.duplicated(subset=col_label)] |
import pandas as pd
import numpy as np
def check(candidate): | [
"\n df1 = pd.DataFrame(data={'CRcode':['Gk125', 'GK126'], 'client name & address':['Jhone', 'Mike']})\n assert candidate(df1, \"CRcode\").to_dict() == {'CRcode': {}, 'client name & address': {}}\n",
"\n df2 = pd.DataFrame(data={'CRcode':['598', '2598', '341', '796'], 'client name & address':['random', 'random2', 'random3', 'random4']})\n assert candidate(df2, \"client name & address\").to_dict() == {'CRcode': {}, 'client name & address': {}}\n"
] | f_41775 | データフレーム`df`内の列`col_label`が重複している行を抽出する(pandas) | [
"numpy",
"pandas"
] |
|
33,034 | def f_33034(df, col_1, col_2):
return | pandas.crosstab(df[col_1], df[col_2]).plot(kind='bar',stacked=True) |
import pandas
def check(candidate): | [
"\n d = {'col_1':[1, 2], 'col_2':[3, 5]}\n df = pandas.DataFrame(data = d)\n x = candidate(df, 'col_1', 'col_2')\n assert str(type(x)).split(\"'\")[1] == 'matplotlib.axes._subplots.AxesSubplot'\n"
] | f_33034 | データフレーム`df`の列`col_1`と`col_2`についてクロス集計を行った結果を積み上げグラフにする | [
"pandas"
] |
|
23,246 | def f_23246(li, v):
|
return ans | ans = []
for index, value in enumerate(li):
if value == v:
ans.append(index) |
def check(candidate): | [
"\n assert candidate([1,2,3,3,3,4,5], 3) == [2, 3, 4]\n"
] | f_23246 | リスト`li`から検索する値`v`に一致する要素のインデックスをすべて取得して表示する | [] |
23,246 | def f_23246(li, v):
|
return ans | ans = [ i for i, value in enumerate(li) if value == v] |
def check(candidate): | [
"\n assert candidate([1,2,3,3,3,4,5], 3) == [2, 3, 4]\n"
] | f_23246 | リスト`li`から検索する値`v`に一致する要素のインデックスをすべて取得して表示する | [] |
30,088 | def f_30088(d, k):
return | d.pop(k, None) |
def check(candidate): | [
"\n d = {\"a\": 1, \"b\": 2, \"c\": 3}\n assert candidate(d, \"a\") == 1\n",
"\n d = {\"a\": 1, \"b\": 2, \"c\": 3}\n assert candidate(d, \"b\") == 2\n",
"\n d = {\"a\": 1, \"b\": 2, \"c\": 3}\n assert candidate(d, \"c\") == 3\n",
"\n d = {\"a\": 1, \"b\": 2, \"c\": 3}\n assert candidate(d, \"d\") == None\n"
] | f_30088 | 辞書型オブジェクト`d`内の存在しない可能性があるキー`k`を削除する | [] |
|
41,700 | def f_41700(df, col_label):
return | df.drop_duplicates(subset=col_label) |
import pandas as pd
def check(candidate): | [
"\n d1 = {'A': [1, 1, 1, 2], 'B': [2, 2, 2, 3], 'C': [3, 3, 4, 5], 'D' : [1, 2, 3, 3]}\n source_df = pd.DataFrame(d1)\n\n d2 = {'A': [1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3, 4], 'D' : [1, 2, 3]}\n res = pd.DataFrame(d2)\n \n assert candidate(source_df, ['D']).equals(res)\n"
] | f_41700 | データフレーム`df`内の列`col_label`が重複している行を削除する(pandas) | [
"pandas"
] |
|
30,824 | def f_30824():
|
return previous_month | today = datetime.date.today()
previous_month = today - dateutil.relativedelta.relativedelta(months=1) |
import datetime
import dateutil
def check(candidate): | [
"\n assert candidate() == datetime.date.today() - dateutil.relativedelta.relativedelta(months=1)\n"
] | f_30824 | 今日から一ヶ月前の日付を取得する | [
"datetime",
"dateutil"
] |
42,011 | def f_42011(str):
return | str.strip() |
def check(candidate): | [
"\n assert candidate(\" hello \") == \"hello\"\n",
"\n assert candidate(\" hello world ! \") == \"hello world !\"\n",
"\n assert candidate(\"hello\") == \"hello\"\n",
"\n assert candidate(\"\") == \"\"\n"
] | f_42011 | 文字列`str`から空白と改行を取り除く | [] |
|
23,218 | def f_23218(data, fs):
|
return plot |
f, t, Sxx = signal.spectrogram(data, fs)
plot = plt.pcolormesh(t, f, Sxx)
|
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
def check(candidate): | [
"\n data = np.array([1, 4, 6])\n assert str(type(candidate(data, 1.0))).split(' ')[1] == \"'matplotlib.collections.QuadMesh'>\"\n"
] | f_23218 | 信号データ`data`をサンプリング周波数`fs`で周波数解析しスペクトログラムを表示する | [
"matplotlib",
"numpy",
"scipy"
] |
39,255 | def f_39255(sjis_str):
return | sjis_str.decode('shift-jis') |
def check(candidate): | [
"\n sjis_str = b'Wall'\n assert candidate(sjis_str) == 'Wall'\n"
] | f_39255 | Shift_JISで符号化された文字列`sjis_str`をデコードする | [] |
|
41,519 | def f_41519(df, col):
|
return df | df[col] = df[col].astype(str) |
import pandas as pd
def check(candidate): | [
"\n data = [1, 4, 5]\n df = pd.DataFrame(data, columns=['Vals'])\n candidate(df, 'Vals')\n assert str(type(df['Vals'][0])) == \"<class 'str'>\"\n"
] | f_41519 | データフレーム`df`の列`col`を文字列型に変更する | [
"pandas"
] |