seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20855741990 | # Exercise 4.3
# 4.3.5
from math import *
from TurtleWorld import *
# For some reason we need to initialise TurtleWorld() otherwise
# error
world = TurtleWorld()
bob = Turtle()
# Speed things up by reducing delay
bob.delay = 0.1
def polygon(thing, lengthOfSide, numberOfSides):
thing = Turtle()
for i in ran... | okeonwuka/PycharmProjects | ThinkPython/swampy-2.1.5/myarc.py | myarc.py | py | 710 | python | en | code | 0 | github-code | 90 |
18159404349 | n = int(input())
zmax = 0
zmin = 10**10
wmax = -10**10
wmin = 10**10
for i in range(n):
x, y = map(int, input().split())
zref = x + y
wref = x - y
zmax = max(zmax, zref)
zmin = min(zmin, zref)
wmax = max(wmax, wref)
wmin = min(wmin, wref)
ans = max(zmax - zmin, wmax - wmin)
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02556/s919774791.py | s919774791.py | py | 316 | python | en | code | 0 | github-code | 90 |
43188100467 | import json
from fake_data_generator.columns_generator import get_columns_info_with_set_generators
from fake_data_generator.columns_generator.column import Column, MultipleColumns
from fake_data_generator.sources_formats.helper_functions import \
get_create_query, create_table_if_not_exists, execute_insertion
def... | maksimowich/fake_table_data_generator | fake_data_generator/sources_formats/generate_table_from_profile.py | generate_table_from_profile.py | py | 1,984 | python | en | code | 0 | github-code | 90 |
17999050760 | kata=str(input("Masukkan kata : "));
def hurufTengah(kata):
kata2=len(kata)//2
if (len(kata)%2==0) and ((len(kata)/2)%2==0):
return kata[(kata2)//2 : ((kata2)//2)*-1]
elif (len(kata)%2==0) and ((len(kata)/2)%2!=0):
return kata[((kata2)//2)+1 : (((kata2)//2)+1)*-1]
elif kata == "In... | yogaagastyar00/UG11_E_71190444 | 2_E_71190444.py | 2_E_71190444.py | py | 528 | python | hu | code | 0 | github-code | 90 |
18242417749 | # 約数の列挙
#############################################################
def make_divisors(n):
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n // i)
i += 1
... | Aasthaengg/IBMdataset | Python_codes/p02722/s780574802.py | s780574802.py | py | 930 | python | ja | code | 0 | github-code | 90 |
18198775189 | import math , sys
N = int( input() )
A = list( map( int, input().split() ))
A.sort()
Cs = [0 for _ in range(10**6+1)]
M = A[-1]
#print(A)
i=0
M = max(A)
for i in range(N):
e = A[i]
if Cs[e]==1:
Cs[e]=2
elif Cs[e]==0:
Cs[e]=1
for i in range(len(Cs)):
Cs[i] = Cs[i]%2
for e in A:
i =... | Aasthaengg/IBMdataset | Python_codes/p02642/s682877940.py | s682877940.py | py | 401 | python | en | code | 0 | github-code | 90 |
15296378166 | from pwn import *
import time
local = 0
if local:
#os.environ['LD_PRELOAD'] = './libc.so.6'
r = process('./guestbook')
e = ELF('./guestbook')
libc = e.libc
else:
r = remote('guestbook.tuctf.com', 4545)
libc = ELF('./libc.so.6')
context.arch = 'i386'
#context.log_level = 'debug'
r.sendlineafter... | Kyle-Kyle/Pwn | ctf/tuctf_2017/guestbook/writeup/solve.py | solve.py | py | 941 | python | en | code | 16 | github-code | 90 |
18582778069 | import numpy as np
def seachPrimeNum(N):
max = int(np.sqrt(N))
seachList = [i for i in range(2,N+1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
re... | Aasthaengg/IBMdataset | Python_codes/p03476/s553281476.py | s553281476.py | py | 1,139 | python | en | code | 0 | github-code | 90 |
18480138429 | N, M = map(int, input().split())
data = [list(map(int, input().split())) + [_] for _ in range(M)]
data = sorted(data, key=lambda x: (x[0], x[1]))
order = 1
for i in range(M):
if not i == 0 and not data[i][0] == data[i-1][0]:
order = 1
data[i].append(str(data[i][0]).zfill(6) + str(order).zfill(6))
o... | Aasthaengg/IBMdataset | Python_codes/p03221/s368947926.py | s368947926.py | py | 404 | python | en | code | 0 | github-code | 90 |
18306789449 | import sys,math,collections,itertools
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
m = 10**9+7
sumA = 0
for i in range(60):
cnt1 = 0
for a in A:
if a>>i & 1:
cnt1 += 1
sumA += (cnt1*(N-cnt1)*2**i)%m
print(sumA%m)
| Aasthaengg/IBMdataset | Python_codes/p02838/s562929689.py | s562929689.py | py | 280 | python | en | code | 0 | github-code | 90 |
18353269959 | #!/usr/bin/env python3
from pprint import pprint
from collections import deque, defaultdict
import itertools
import math
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.buffer.readline
INF = float('inf')
N, Q = map(int, input().split())
tree = [[] for _ in range(N)]
for _ in range(N-1):
u, v = map(i... | Aasthaengg/IBMdataset | Python_codes/p02936/s167826974.py | s167826974.py | py | 840 | python | en | code | 0 | github-code | 90 |
32124808189 | import itertools
from typing import Iterator
from linear_models.linear_circuit import LinearCircuit
from models.circuit import Circuit
from models.circuit_model import CircuitModel
from utils.graph_utils import enumerate_simple_acyclic_digraphs_adjacency_matrices
from utils.string_utils import enumerate_strings
def ... | udragon/circuit-complexity | circuit_enumeration.py | circuit_enumeration.py | py | 2,112 | python | en | code | 0 | github-code | 90 |
24623275291 | import unittest
from unittest.mock import patch, MagicMock
from dragonchain import test_env # noqa: F401
from dragonchain import exceptions
from dragonchain.webserver.lib import transactions
class TestQueryTransactions(unittest.TestCase):
@patch("dragonchain.lib.database.redisearch.search")
def test_query_t... | dragonchain/dragonchain | dragonchain/webserver/lib/transactions_utest.py | transactions_utest.py | py | 3,601 | python | en | code | 701 | github-code | 90 |
6290255481 | # load packages
import numpy as np
import pandas as pd
from sklearn.cross_validation import KFold
import xgboost as xgb
import warnings
warnings.filterwarnings("ignore")
# load data
train = pd.read_csv("../Data/blogData_train.csv",header=None)
test = pd.read_csv("../Data/blogData_test.csv",header=None)
# rename
names... | hncpr1992/BlogFeedBackProject | Code/ModelTraining.py | ModelTraining.py | py | 8,061 | python | en | code | 1 | github-code | 90 |
75117589416 | from telethon import events
from ubi import u
import re
from ubi.modules.strings import KILL_CODE
@u.on(events.NewMessage(pattern=re.compile(r"\.die (.*)")))
async def _(event):
if event.fwd_from:
return
killcode = event.pattern_match.group(1)
print(killcode)
if killcode == KILL_CODE:
... | RobiMez/Bori | ubi/modules/die.py | die.py | py | 486 | python | en | code | 1 | github-code | 90 |
24808382261 | from typing import Tuple, Optional
import torch
from torch import Tensor
from packaging import version
if version.parse(torch.__version__) < version.parse('1.9'):
from torch.nn.modules.linear import _LinearWithBias
else:
from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
from torch.nn.init imp... | PJLab-ADG/SensorsCalibration | SensorX2car/camera2car/auto_calib/models/multi_head_attention.py | multi_head_attention.py | py | 15,197 | python | en | code | 1,730 | github-code | 90 |
5347916044 |
# 单例设计模式
class Singleton:
# 私有变量
__instance = None
__is_first = True
@classmethod
def __new__(cls,*args,**kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
else:
pass
return cls.__instance
# init 这个方法将引用指向对应的内存空间
... | zxm66/python | src/python_base/python_design_patten.py | python_design_patten.py | py | 1,421 | python | en | code | 0 | github-code | 90 |
23328685889 | import tensorflow as tf
import colorsys
import numpy as np
import os
from gymnoscamera.yolo_network.model import yolo_eval
from keras import backend as K
input_names = ['input_1']
output_names = ['conv2d_59/BiasAdd', 'conv2d_67/BiasAdd', 'conv2d_75/BiasAdd']
class Yolo_v3_rt:
_defaults = {
"model_path":... | Gymnos-AI/Gymnos-Camera | gymnoscamera/yolo_network_rt/yolo_v3_rt.py | yolo_v3_rt.py | py | 4,796 | python | en | code | 0 | github-code | 90 |
26884454320 | from persianmeme.translations import admin_messages
from persianmeme.models import User, MemeType
from persianmeme.classes import User as UserClass
def handler(text: str, user: UserClass):
if user.process_meme_tags(text):
user.database.menu = User.Menu.ADMIN_NEW_MEME
if user.database.temp_meme_typ... | Sholex-Team/LilSholex | persianmeme/handlers/message/menus/admin/menus/meme_tags.py | meme_tags.py | py | 640 | python | en | code | 38 | github-code | 90 |
38202887405 | import random
from pathlib import Path
from typing import List
import logging
import numpy
import torch
from transformers import T5Config
from onnxruntime import InferenceSession
logger = logging.getLogger(__name__)
class T5Encoder(torch.nn.Module):
""" T5 encoder outputs only the last hidden state"""
def _... | fengbingchun/PyTorch_Test | src/onnxruntime/onnxruntime/python/tools/transformers/models/t5/t5_encoder.py | t5_encoder.py | py | 5,658 | python | en | code | 14 | github-code | 90 |
30619963015 | from gurobipy import *
from traceProducer.traceProducer import *
from traceProducer.jobClassDescription import *
from datastructures.jobCollection import *
from simulator.simulator import *
import numpy as np
import matplotlib.pyplot as plt
import time
instanceOfAlgo = ["FDLS", "Weaver"]
rawFDLS = []
rawWeaver = []
FD... | Joe0047/Teacher-experiments | Experiments/coflowSim/main_custom_divisible_time_complexity.py | main_custom_divisible_time_complexity.py | py | 5,665 | python | en | code | 0 | github-code | 90 |
9901717670 | # -*- coding: utf-8 -*-
import time
from PyQt5.QtCore import QThread, pyqtSignal
from crawler.controller import Controller
class Worker(QThread):
fetch_finished = pyqtSignal(dict)
def __init__(self, parent, uid, upw):
super().__init__(parent)
self.parent = parent
self.isRunning = F... | bo-lim/Class_Scheduler | worker.py | worker.py | py | 850 | python | en | code | 0 | github-code | 90 |
416925619 | from pathlib import Path
import unittest
import bpy
from mixer.blender_data.bpy_data_proxy import BpyDataProxy
from mixer.blender_data.datablock_proxy import DatablockProxy
from mixer.blender_data.diff import BpyBlendDiff
from mixer.blender_data.filter import test_properties
class DifferentialApply(unittest.TestCa... | ubisoft/mixer | mixer/blender_data/tests/test_diff_apply.py | test_diff_apply.py | py | 12,254 | python | en | code | 1,311 | github-code | 90 |
18511240209 | from pprint import pprint
def main():
D,G = map(int, input().split())
p,c = [0]*D,[0]*D
for i in range(D):
p[i],c[i] = map(int, input().split())
qnum = sum(p)
# dp[i][j] := i問目まででj個解いたときの最大得点
dp = [[0]*(qnum+1) for _ in range(D+1)]
dp[0] = [0]*(qnum+1)
ans = qnum
for i in ran... | Aasthaengg/IBMdataset | Python_codes/p03290/s924866554.py | s924866554.py | py | 835 | python | en | code | 0 | github-code | 90 |
39762692126 | import random
def humanguess():
number=random.randrange(0,10)
print(number)
respuesta=int(input("Dame un numero del 0 al 10: "))
while number != respuesta:
respuesta=int(input("Dame un numero del 0 al 10: "))
if number==respuesta:
print(f"Ganaste el numero era {number}")
... | KabanBot/Guessgame | main.py | main.py | py | 1,142 | python | es | code | 0 | github-code | 90 |
3175221947 | import sys
import subprocess
import glob2
def run_command(_command, _output):
""" run_command """
print("Run command: " + " ".join(_command))
_output.write("Run command: " + " ".join(_command) + "\n")
with subprocess.Popen(
_command,
stdout=subprocess.PIPE,
stderr=subprocess.STD... | freehackquest/fhq-server | tests/server-api-tests/run_tests.py | run_tests.py | py | 1,703 | python | en | code | 35 | github-code | 90 |
34870649900 | import numpy as np
import pytest
from pandas._libs import iNaT
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import DatetimeArray
class TestDatetimeArrayConstructor:
def test_from_sequence_invalid_type(self):
mi = pd.Multi... | pandas-dev/pandas | pandas/tests/arrays/datetimes/test_constructors.py | test_constructors.py | py | 9,234 | python | en | code | 40,398 | github-code | 90 |
11058038380 | from itertools import islice
import os
from os import listdir
from os.path import isfile, join
import re
import shutil
#path = '/home/neha/Desktop/ISI_final/test'
relationPath = '../../Data/Relations'
article_path='../../../2_Event_Filtering/Data/LDA_Filtered_Articles'
taggedArticlePath='../../Data/Tagged_Protest_Art... | neeleshkshukla/PlannedEventForecasting | 3_Information_Extraction/Code/Python/informationExtraction.py | informationExtraction.py | py | 13,329 | python | en | code | 0 | github-code | 90 |
36173898483 | import sys
import os.path
class colaPrioridad():
def __init__(self):
self.minHeap = MinHeap()
def inserta(self,key,value):
self.minHeap.push(key,value)
def encuentraMin(self):
return self.minHeap.peek()
def borraMin(self):
temp = self.minHeap.pop()
def vacio(self... | IsayDBS/Analisis_de_algoritmos | Practica4/Isay_Balderas/src/Main.py | Main.py | py | 7,761 | python | es | code | 0 | github-code | 90 |
41378532087 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from .views import LicenseDetailView
urlpatterns = [
url(
r"^license/(?P<slug>[-\w]+)/$",
LicenseDetailView.as_view(),
name="alibrary-license-detail",
)
]
| digris/openbroadcast.org | website/apps/alibrary/urls_license.py | urls_license.py | py | 286 | python | en | code | 9 | github-code | 90 |
3994929588 | import sys
input = sys.stdin.readline
if __name__ == "__main__":
N = list(map(str, input().strip()))
room = [0 for _ in range(9)]
pack = [1, 1, 1, 1, 1, 1, 2, 1, 1]
for i in range(len(N)):
if N[i] == "9":
room[6] += 1
else:
room[int(N[i])] += 1
for i in ra... | WonyJeong/algorithm-study | WonyJeong/implementation/1475.py | 1475.py | py | 620 | python | en | code | 2 | github-code | 90 |
38396279645 | # Pyramid
import colander
import deform
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.httpexceptions import HTTPFound
# Websauna
from websauna.system.core import messages
from websauna.system.core.route import simple_route
from websauna.system.core.sitemap import include_in_sitemap
from websauna.syste... | websauna/websauna.newsletter | websauna/newsletter/views.py | views.py | py | 2,692 | python | en | code | 1 | github-code | 90 |
35504360257 | # Echo client program
import socket
import sys
#HOST = '70.186.140.93'
HOST = 'mber.pub.playdekgames.com' # The remote host
PORT = 9601
s = None
print( ' Connection test utility' )
print( '@ 2014 Mickey Kawick' )
print( 'address {0}:{1}'.format( HOST, PORT ) );
print( '................................' )
print( 'C... | mkawick/tcp_testing | ErrorCheckingClient.py | ErrorCheckingClient.py | py | 901 | python | en | code | 0 | github-code | 90 |
2776972832 | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameter... | Joshua-Devadas/Image-Captioning | model.py | model.py | py | 2,228 | python | en | code | 0 | github-code | 90 |
2861734805 | class InsertionSort:
def my_insert_sort(self, nums: [int]):
print("Unsorted: ", nums)
# 从头到尾开始逐个放到合适的位置去
p = 1
while p <= len(nums):
# print("while1")
temp = p - 1
while temp > 0:
# print("while 2")
if nums[temp] < n... | Teayyyy/LeetCodeStudy_Python_Algorithm | LeetCode101_Google/Different_Sort_Algorithms/Insertion_Sort.py | Insertion_Sort.py | py | 1,301 | python | en | code | 0 | github-code | 90 |
40673762692 | #!/usr/bin/env python
# -*- coding: utf-8 -*
# gohook @ Python
# Functions: WebHook自动部署代码
# Created By HavenShen on 2016-04-05,Version 0.1
import comm_log
import subprocess
import json
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.options import define, options
#监听端口
define("port", defa... | HavenShen/gohook | main.py | main.py | py | 1,118 | python | en | code | 51 | github-code | 90 |
20465221239 | import sys
n, m = map(int, sys.stdin.readline().split())
result = []
for i in range(1, n+1):
result.append(str(i))
for _ in range(m):
i, j = map(int, sys.stdin.readline().split())
i_value, j_value = result[i-1], result[j-1]
result[i-1], result[j-1] = j_value, i_value
print(' '.join(... | undervi/coding_test_python | 백준/Bronze/10813. 공 바꾸기/공 바꾸기.py | 공 바꾸기.py | py | 328 | python | en | code | 1 | github-code | 90 |
72604514537 | """
DO NOT RUN IN PRODUCTION
Updates a local db with data on the current production site.
"""
from __future__ import unicode_literals
import json
import requests
from dateutil import parser
from tempfile import NamedTemporaryFile
from django.conf import settings
from django.core.files import File
from django.core.ma... | zachcalvert/the_ape_theater | the_ape/pages/management/commands/update_local.py | update_local.py | py | 11,368 | python | en | code | 3 | github-code | 90 |
3588013289 | from flask import Flask, request, redirect
app = Flask(__name__, static_url_path='')
@app.route('/',methods=["POST", "GET"])
def index():
return app.send_static_file('index.html')
@app.route('/login', methods=["POST", "GET"])
def login():
if (request.method == "POST"):
req=request.form
print(re... | gnsensors/website | app.py | app.py | py | 444 | python | en | code | 0 | github-code | 90 |
71940042857 | from Piece import Queen, King, Bishop, Knight, Rook, Pawn
import copy
class Board():
"""
8 ▢▢▢▢▢▢▢▢
▢▢▢▢▢▢▢▢
. ▢▢▢▢▢▢▢▢
. ▢▢▢▢▢▢▢▢
. ▢▢▢▢▢▢▢▢
▢▢▢▢▢▢▢▢
▢▢▢▢▢▢▢▢
1 ▢▢▢▢▢▢▢▢
1 ... 8
(a ... h)
"""
# parent should point at previous position
# children wil... | confusedlama/chess | Board.py | Board.py | py | 2,327 | python | en | code | 0 | github-code | 90 |
5908654689 | # Problem description:
# https://github.com/HackBulgaria/Python-101-Forever/tree/master/C01-Python-Basics/24-C01P13
def is_prime(n):
counter = 0
for i in range(1, n + 1):
if n % i == 0:
counter += 1
return counter == 2
def next_prime(n):
n += 1
w... | keremidarski/python_playground | Python 101 Forever/C01 - Python Basics/c01p13_prime_factorization.py | c01p13_prime_factorization.py | py | 738 | python | en | code | 0 | github-code | 90 |
37030184751 | import argparse
import os
parser = argparse.ArgumentParser(description='Bpe')
parser.add_argument('--data-dir', type=str, default=None,
help='method for bpe')
args = parser.parse_args()
if __name__ == '__main__':
datasets = os.listdir(args.data_dir)
lang1 = open(os.path.join(args.data_dir... | Chris19920210/DipML | preprocess/encode_check.py | encode_check.py | py | 763 | python | en | code | 4 | github-code | 90 |
2713873495 | import Client
import Memento
class Caretaker():
"""
The Caretaker works with all mementos via the base Memento interface.
"""
def __init__(self, Client: Client):
self._mementos = []
self._Client = Client
def backup(self):
self._mementos.append(self._Client.save())
def... | dianabarbo/mementopattern | Caretaker.py | Caretaker.py | py | 533 | python | en | code | 0 | github-code | 90 |
10522601798 | #!/usr/bin/env python3
import sys
import json
import logging
from math import degrees, atan2, tan
logging.basicConfig(filename=r"D:\LibraryOfBabel\Projects\ICPCPlanetoids\MyAdditions\planetoids1.log",
level=logging.DEBUG,
filemode='w',
format='%... | IamMarcIvanov/icpc-gaming-ai-planetoids | planetoids_working_1.py | planetoids_working_1.py | py | 4,324 | python | en | code | 0 | github-code | 90 |
110878862 | plik = open('ciagi.txt')
data = plik.read().splitlines()
halfprime = []
for ciag in data:
liczba = int(ciag ,2)
y = liczba
czynniki = []
i = 2
while i <= y**0.5+1:
if(y%i == 0):
czynniki.append(i)
y //= i
else:
i += 1
if(y > 1):
czynni... | dexterowy/matura_inf | 63/63-3.py | 63-3.py | py | 498 | python | pl | code | 1 | github-code | 90 |
44157837319 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('delivery2', '0003_auto_20161126_1937'),
]
operations = [
migrations.CreateModel(
name='MessageRedirectUrl',
... | denispan1993/vitaliy | applications/delivery2/migrations/0004_auto_20161128_0016.py | 0004_auto_20161128_0016.py | py | 1,877 | python | en | code | 0 | github-code | 90 |
864993384 | # finally = 예외 발생과 상관없이 항상 실행한다.
try:
inputdata = input(" : ")
numint = int(inputdata)
except:
print('exception')
numint = 0
else:
if numint % 2 == 0:
print ('짝수')
else:
print ( '홀수')
finally:
print(f'{inputdata}')
| jungwonguk/Education | 03.python 중급/31_finally/finally.py | finally.py | py | 310 | python | ko | code | 1 | github-code | 90 |
25713061542 | # Exponential search
x = 3
y = 4
n = 100
def good(t):
return t * x + t * y < n
l = 0
r = 1
step = 1
while good(r):
l = r
r += step
step *= 2
print(l, r)
while l < r - 1:
mid = (l + r) // 2
if good(mid):
l = mid
else:
r = mid
print(l, r) | HornbillFromMinsk/EPIC | Algos/Class Materials/Practice/binary_search_exponential_search.py | binary_search_exponential_search.py | py | 257 | python | en | code | 0 | github-code | 90 |
74808759337 | import sys
#ssys.stdin = open('input.txt','rt')
'''
정다면체
두 개의 정 N면체와 정 M면체의 두 개의 주사위를 던져서 나올 수 있는 눈의 합 중 가장 확
률이 높은 숫자를 출력하는 프로그램을 작성하세요.
정답이 여러 개일 경우 오름차순으로 출력합니다.
▣ 입력설명
첫 번째 줄에는 자연수 N과 M이 주어집니다. N과 M은 4, 6, 8, 12, 20 중의 하나입니다.
▣ 출력설명
첫 번째 줄에 답을 출력합니다.
▣ 입력예제 1
4 6
▣ 출력예제 1
5 6 7
'''
n, m = map(in... | dpwns523/coding-test-practice | 섹션2/정다면체.py | 정다면체.py | py | 971 | python | ko | code | 0 | github-code | 90 |
21554767920 | '''
Implementation of an RL environment in a discrete graph space.
'''
import numpy as np
import gym
from gym import spaces
import networkx as nx
import math
from .. import env_configs
#------------------------------------------------------------------------------
'''An ambulance environment over a simple graph. An... | maxsolberg/ORSuite | or_suite/envs/ambulance/ambulance_graph.py | ambulance_graph.py | py | 6,879 | python | en | code | 0 | github-code | 90 |
22659193230 | from collections import OrderedDict
import torch.nn as nn
import math
DEFAULT_LAYER_CONFIG = [
[383, 1024],
[1024, 1024],
[1024, 801]
]
def calculate_bias_bound(weights):
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(weights)
bound = 1 / math.sqrt(fan_in)
return bound
def get_tanh_lin... | teliov/thesislib | thesislib/utils/dl/models.py | models.py | py | 2,082 | python | en | code | 0 | github-code | 90 |
40655067194 | import sys
from PyQt5.QtCore import Qt ,pyqtSignal, QRect
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import QProgressBar
import uuid
import pyqtgraph as pg
import pyqtgraph.graphicsItems as pgg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import imageio
import glob
import cv2
import os
import sh... | lebrat/Biolapse | tracking/GUI.py | GUI.py | py | 46,183 | python | en | code | 0 | github-code | 90 |
29439792833 | # Import necessary libraries
import yfinance as yf
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
from sklearn.metrics import mean_squared_error
from datetime import... | aidan-pantoya/TheTrack | refineLSTM.py | refineLSTM.py | py | 3,164 | python | en | code | 0 | github-code | 90 |
18353972049 | def resolve():
s = input()
t = input()
d = {}
for i, c in enumerate(list(s)):
d.setdefault(c, [])
d[c].append(i)
import bisect
nloops = 0
prev = -1
for c in list(t):
if c not in d:
print(-1)
return
# prevより後ろにあるcのうち、最も近いものの位置
... | Aasthaengg/IBMdataset | Python_codes/p02937/s057881639.py | s057881639.py | py | 710 | python | en | code | 0 | github-code | 90 |
37565916920 | """This module provides various BitRequests methods, including:
`BitTransferRequests`, `OnChainRequests`, and `ChannelRequests`. These objects
can be used to make 402-enabled, paid HTTP requests to servers that
support the 402-protocol and those specific payment methods.
"""
import time
import json
import codecs
import... | 21dotco/two1-python | two1/bitrequests/bitrequests.py | bitrequests.py | py | 18,360 | python | en | code | 366 | github-code | 90 |
72663369897 | import pandas as pd
import utils as u
import evaluate as evl
import math
from typing import List, Dict
from sklearn.preprocessing import PolynomialFeatures
from termcolor import cprint
def run_model_experiments(
model_obj,
model_name: str,
feat_train: pd.DataFrame,
target_train: pd.Series,
feature... | chhaviarora95/house-price-prediction | src/model_experiments.py | model_experiments.py | py | 2,945 | python | en | code | 0 | github-code | 90 |
18180835579 | import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
n = int(input())
s = input()
num = int(s, 2) # 元の2進数を数字に
opc = s.count('1') # 元の2進数のpopcount
# ±1したpopcountで余りを求めておく
if opc > 1:
num1 = num % (opc - 1)
else:
num1 = 0
num0 = num % (opc + 1)
for i in range(n):
if s[i] == '1':
if o... | Aasthaengg/IBMdataset | Python_codes/p02609/s532378622.py | s532378622.py | py | 699 | python | en | code | 0 | github-code | 90 |
7508580685 | from flask import Blueprint, request, jsonify, make_response, session
from sqlalchemy.orm import load_only
from ..student.models import *
from ..student.types import *
from ..student import util
staff = Blueprint("staff", __name__)
# API: staff-profile dashboard page
@staff.route("<variable>", methods=["GET"])
@util... | AnishTiwari/Attendance | attendancesystembackend/attendancesystem/attendancesystem/attendancesystem/staff/views.py | views.py | py | 1,802 | python | en | code | 0 | github-code | 90 |
72115927978 | import pygame
from pygame.locals import *
import math
import random
pygame.init()
default_font = pygame.font.get_default_font()
font16 = pygame.font.Font(default_font, 16)
clock = pygame.time.Clock()
screen_width = 800
screen_height = 600
class Player(pygame.sprite.Sprite):
def __init__(self):
# self... | BrandtRobert/PythonCrashCourse | Asteroids/asteroids.py | asteroids.py | py | 7,122 | python | en | code | 0 | github-code | 90 |
5599272334 | import sys
def circle_area():
# inputs
N = int(sys.stdin.readline())
points = [None] * (2 * N)
for i in range(N):
center, radius = list(map(int, sys.stdin.readline().split()))
points[2*i] = (center - radius, 'l') # left point
points[2*i+1] = (center + radius, 'r') ... | jinhyung-noh/algorithm-ps | BaekJoon/10000_원영역.py | 10000_원영역.py | py | 1,597 | python | ko | code | 0 | github-code | 90 |
13090908955 | def isPossible(limit, nDays, mChapters, times):
dayCount = 1
allocation = 0
for t in times:
if t > limit:
return False
if allocation + t > limit:
dayCount += 1
allocation = t
else:
allocation += t
if dayCount > nDays:
return... | magdumsuraj07/data-structures-algorithms | questions/striever_SDE_sheet/67_allocate_minimum_number_of_pages.py | 67_allocate_minimum_number_of_pages.py | py | 624 | python | en | code | 0 | github-code | 90 |
9688161173 | from typing import Sequence
from dataclasses import dataclass
from datetime import datetime
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from utils.db_api.base import Base
from utils.db_api.... | KarimovMurodilla/about-me-bot | utils/db_api/connection.py | connection.py | py | 2,258 | python | en | code | 0 | github-code | 90 |
43193187255 | import pandas as pd
import numpy as np
def annotate(chr_, start, end):
result = []
for i in range(0, len(chrom)):
if str(chr_) == str(chrom[i]):
if start <= float(s_[i]) and end >= float(e_[i]):
result.append(name[i])
return result, len(result)
df = pd.read_csv('real/A... | Androstane/NestedBD | scripts_plots/annotate_gene.py | annotate_gene.py | py | 1,937 | python | en | code | 4 | github-code | 90 |
17937105439 | import bisect
n, *lst = map(int, open(0).read().split())
alst = sorted(lst[:n])
blst = lst[n:2*n]
clst = sorted(lst[2*n:])
res = 0
for i in blst:
a = bisect.bisect_left(alst, i)
c = n - bisect.bisect_right(clst, i)
res += a * c
print(res) | Aasthaengg/IBMdataset | Python_codes/p03559/s636243077.py | s636243077.py | py | 245 | python | en | code | 0 | github-code | 90 |
42267550104 | # 문제: 켜져 있는 전구의 밝기 최댓값 구하기
# 조건: 1) 1 <= N <= 200000
# 2) 전구는 꺼져있거나(0) 켜져있거나(1)
# 3) 1 <= 전구의 밝기 <= 5000
# 4) 연속한 전구를 한 개 이상 선택해서 뒤집을 수 있는데 딱 한번만 가능
# 방법: 1) 누적합 방식을 통해서 최대갑 구하기
# 2) 누적된 값이 음수가 되면 0으로 초기화
# 3) maxB가 0일 경우 모든 전구를 안 뒤집는 것이 최대값이기에 가장 작은 값을 뒤집어서 조건 충족
# 4) maxB가 존재할 경우 기존의 값... | junhong625/TIL | Algorithm/Baekjoon/Gold/[25634번] 전구 상태 뒤집기.py | [25634번] 전구 상태 뒤집기.py | py | 1,135 | python | ko | code | 2 | github-code | 90 |
44123381190 | #!/usr/bin/python
#----------------- For Part 2 ---------------------
# Function to return an array of summed numbers
def three_meas_window(input):
three_meas = []
for i in range(len(input)-2):
three_meas.append(input[i] + input[i+1] + input[i+2])
return three_meas
#----------------- For Part 1 -... | Dowscope/Advent-Of-Code | 2021/Day1/day1.py | day1.py | py | 1,140 | python | en | code | 0 | github-code | 90 |
34120220755 | """Overview plots of transcet"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
from os.path import join
from src import Config
plt.ion()
cf = Config()
savedir = 'reports/jasa/figures'
inputed = np.load('data/processed/inputed_decomp.npz')
lvls = inputed['filled_lvls']
stabl... | nedlrichards/tau_decomp | notebooks/isopycnals.py | isopycnals.py | py | 1,891 | python | en | code | 0 | github-code | 90 |
1249407832 | import scrapy
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateparser
from urllib.parse import urlparse
from tpdb.BasePerformerScraper import BasePerformerScraper
class BellaPassnPerformerSpider(BasePerformerScraper):
selector_map = {
'name': '//div[@cla... | SFTEAM/scrapers | performers/networkBellaPassPerformer.py | networkBellaPassPerformer.py | py | 6,541 | python | en | code | null | github-code | 90 |
27092636028 | from spack import *
class Openscenegraph(CMakePackage):
"""OpenSceneGraph is an open source, high performance 3D graphics toolkit
that's used in a variety of visual simulation applications."""
homepage = "http://www.openscenegraph.org"
url = "http://trac.openscenegraph.org/downloads/developer... | matzke1/spack | var/spack/repos/builtin/packages/openscenegraph/package.py | package.py | py | 1,599 | python | en | code | 2 | github-code | 90 |
3967803474 | ###########################################################################
#
#Author:Manali Milind Kulkarni
#Date:28th March 2021
#About: Implementing Decision Tree on Demo Dataset
#Note: This is sytematic code which uses main function,a machine Learning function and starter code
#
#############################... | ManaliKulkarni30/MachineLearning_CaseStudues | Balls3.py | Balls3.py | py | 1,843 | python | en | code | 0 | github-code | 90 |
5544477032 | # 치즈
# 복습 횟수:1, 01:00:00, 복습필요O
from collections import deque
import sys
si = sys.stdin.readline
dx = [-1,1,0,0]
dy = [0,0,-1,1]
N, M = map(int, si().split())
graph = [list(map(int, si().split())) for _ in range(N)]
time = 0
answer = []
def find_air():
cnt = 0
visited = [[0 for _ in range(M)] for _ in range(... | SteadyKim/Algorism | language_PYTHON/백준/BJ2636.py | BJ2636.py | py | 1,109 | python | en | code | 0 | github-code | 90 |
1973900226 | import sys
N,M=map(int,sys.stdin.readline().split()) #N:세로, M:가로
c_rule=["BWBWBWBW","WBWBWBWB"]
chess=[0 for i in range(N)]
result=64
for i in range(N):
M_line=sys.stdin.readline().replace('\n','')
chess[i]=(M_line)
for j in range(M-7):
for i in range(N-7):
b_cnt=0
w_cnt=0
cnt=0
... | seminss/algorithm-study | solvedac/브루트포스 알고리즘/1018 체스판 다시 칠하기.py3 | 1018 체스판 다시 칠하기.py3 | py3 | 669 | python | en | code | 0 | github-code | 90 |
29737648465 | import pytest
from bach import SeriesDict
from bach.expression import Expression
from sql_models.util import DatabaseNotSupportedException, is_bigquery, is_postgres
from tests.unit.bach.util import get_fake_df_test_data
def test_db_not_supported_error_on_not_supported_db(dialect):
df = get_fake_df_test_data(dial... | massimo1220/objectiv-analytics-main | bach/tests/unit/bach/test_series_dict.py | test_series_dict.py | py | 1,971 | python | en | code | 5 | github-code | 90 |
74038016297 | #!/usr/bin/python
import setuptools
with open("requirements.txt") as f:
required = f.read().splitlines()
setuptools.setup(
name="brendon-useful",
version="1.0",
packages=setuptools.find_packages(),
install_requires=required,
entry_points={
"console_scripts": [
"useful_ren... | brendonmatos/useful | setup.py | setup.py | py | 483 | python | en | code | 0 | github-code | 90 |
22132292166 | # -*- coding: utf-8 -*-
from selenium import webdriver
class ImageElement(object):
def __init__(self, parent, x, y, width, height):
"""
Create a new ImageElement.
:Args:
- parent: The WebDriver.
- x: location of the element on the X axis.
- y: location of the el... | cle-b/niobium | niobium/image_element.py | image_element.py | py | 3,800 | python | en | code | 1 | github-code | 90 |
33071029295 |
#import model's script and set the output file
from DCNN_benchmark.models import *
filename = f'results/{datetag}_results_3_{HOST}.json'
# Output's set up
try:
df_gray = pd.read_json(filename)
except:
df_gray = pd.DataFrame([], columns=['model', 'perf', 'fps', 'time', 'label', 'i_label', 'i_image', 'filename'... | JNJER/2020-06-26_fast_and_curious | experiment_grayscale.py | experiment_grayscale.py | py | 2,266 | python | en | code | 0 | github-code | 90 |
70299171498 | import cocotb
from cocotb.triggers import Timer
from cocotb.triggers import FallingEdge
from cocotb.clock import Clock
from cocotb.handle import ModifiableObject
from cocotb.utils import get_sim_time
from cocotbnumpy.test import NumpyTest
from cocotbnumpy.signal import NumpySignal
import numpy as np
def model(inputs):... | jhugon/vhdl_libs | pulse_analysis/pulse_counter/test_pulse_counter.py | test_pulse_counter.py | py | 2,076 | python | en | code | 0 | github-code | 90 |
73411582697 | #!/usr/bin/env python3
# Author: Zhang Huangbin <zhb@iredmail.org>
# Purpose: add, delete, show whitelists/blacklists for specified local recipient.
import os
import sys
os.environ['LC_ALL'] = 'C'
rootdir = os.path.abspath(os.path.dirname(__file__)) + '/../'
sys.path.insert(0, rootdir)
import web
from libs import u... | iredmail/iRedAPD | tools/wblist_admin.py | wblist_admin.py | py | 8,580 | python | en | code | 42 | github-code | 90 |
71621079018 | #!/usr/bin/python3
import fbgui
if __name__ == '__main__':
config = fbgui.Settings()
config.msg_level = "DEBUG"
config.bg_color = fbgui.Color.LIGHTBLUE
config.fg_color = fbgui.Color.WHITE
config.font_size = 40
config.width = 320
config.height = 240
config.title = "Hello... | bablokb/pygame-fbgui | doc/helloworld2.py | helloworld2.py | py | 658 | python | en | code | 0 | github-code | 90 |
70772963817 | # homework 4
# goal: k-means clustering on vectors of TF-IDF values,
# normalized for every document.
# exports:
# student - a populated and instantiated cs525.Student object
# Clustering - a class which encapsulates the necessary logic for
# clustering a set of documents by tf-idf
# ###################... | connieGao0819/CS525-IR-Social-Web | HW4/HW4_Jiani_Gao.py | HW4_Jiani_Gao.py | py | 8,421 | python | en | code | 0 | github-code | 90 |
18431156219 | #!/usr/bin python3
# -*- coding: utf-8 -*-
from collections import Counter
def main():
mod = 10**9+7
N = int(input())
S = list(input())
S = Counter(S)
ret = 1
for i,c in S.items():
ret *= (c+1)
ret %= mod
print((ret-1)%mod)
if __name__ == '__main__':
main() | Aasthaengg/IBMdataset | Python_codes/p03095/s658487398.py | s658487398.py | py | 308 | python | en | code | 0 | github-code | 90 |
38033285671 | import numpy as np
import os
import sys
import ntpath
import time
from . import util
import imageio
from skimage import img_as_ubyte
if sys.version_info[0] == 2:
VisdomExceptionBase = Exception
else:
VisdomExceptionBase = ConnectionError
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width... | IBMEOX/UltrasoundVQA | utils/visualizer.py | visualizer.py | py | 4,079 | python | en | code | 0 | github-code | 90 |
72117568616 | from numpy import *
from pyproj import *
def loadPoints(file_text):
#Load points
uv = []
with open(file_text, 'r') as file:
for line in file:
ut, vt = line.strip().split()
u, v = float(ut), float(vt)
uv.append([u, v])
return array(uv)
def samplePoints(umin, ... | bayertom/mmk_2021_22 | cv_12.py | cv_12.py | py | 2,518 | python | en | code | 0 | github-code | 90 |
33405926228 | import logging
from abc import ABC
from typing import Optional, Tuple, Type
from pydantic import Field, root_validator, validator
from iso15118.shared.exceptions import V2GMessageValidationError
from iso15118.shared.messages import BaseModel
from iso15118.shared.messages.datatypes import (
DCEVSEChargeParameter,
... | sahabulh/switchev_iso15118 | iso15118/shared/messages/din_spec/body.py | body.py | py | 21,706 | python | en | code | 1 | github-code | 90 |
9991566360 | # -*- coding: UTF-8 -*-
from example import models
def demo_simple():
shop_info = models.Shop(
name='My Shop',
address='My Address'
)
shop_info.save()
def demo_partition():
from random import randint
shop_id = randint(1, 10)
shop_customer = models.ShopCustomer(
shop_i... | karla9/django_partition | demo_app/example/views.py | views.py | py | 454 | python | en | code | 1 | github-code | 90 |
12542974713 | import numpy as np
from scipy.spatial import distance
def get_closest_images(images, image_index_to_measure, num_results=5):
"""
Calculate the manhattan distance between the image of
image_index_to_measure and all other images. Return the indicies
of the closest images and their distances.
:param... | VanLifeInc/models | utils/image_similarity.py | image_similarity.py | py | 1,518 | python | en | code | 1 | github-code | 90 |
42271872866 | #!/usr/bin/env python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader
from robot_sim.srv import RobotAction
from robot_sim.srv import RobotActionRequest
from robot_sim.srv import RobotA... | Minglunt/RobotLearning | project3_ws/src/robot_sim/scripts/learn_dqn.py | learn_dqn.py | py | 7,973 | python | en | code | 1 | github-code | 90 |
10142830356 | import numpy as np
import matplotlib.pyplot as plt
def initPlot(N):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.axis([0, N, 0, 500])
return ax
class filterKalman(object):
def __init__(self):
self.optimal = False
def setModelStateTransition(self, modelStateTransition):
self.F = np.matrix(modelSt... | fgroes/statistics | kalman/main.py | main.py | py | 2,609 | python | en | code | 0 | github-code | 90 |
15772099290 | """Example module of celery tasks."""
import logging
import time
from annuaire.annuaire.database import populate_lawyers
from annuaire.annuaire.exception import AnnuaireException
from annuaire.annuaire.query import get_form_page, search
from annuaire.tasks import celery
log = logging.getLogger(__name__)
@celery.tas... | djacomy/lawer-annuaire | annuaire/tasks/add.py | add.py | py | 927 | python | en | code | 0 | github-code | 90 |
22357945435 | import argparse
import asyncio
import json
from marilyn_api.client import AsyncClient
async def main(
api_root: str, headers: dict, project_id: int, params: dict = None, save_to_file: bool = False
):
aclient = AsyncClient(api_root, headers)
data = []
async for page in aclient.iter_project_placements(... | pavelmaksimov/marilyn-api | Examples/project_placements.py | project_placements.py | py | 1,675 | python | en | code | 0 | github-code | 90 |
31256817977 | from collections import deque
import copy
def bfs2(visited3,target):
que = deque()
sum = 0
for i in range(N+1):
if not visited3[i] :
que.append([i,1])
visited3[i]=True
sum += nums[i-1]
while que :
now ,count= que.popleft()
... | sungwoo-me/Algorithm | 백준/SK_연습/그래프탐색/17471.py | 17471.py | py | 2,058 | python | en | code | 0 | github-code | 90 |
10225434876 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 10:31:26 2019
@author: eileenlu
"""
import os
import sys
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score
from sklearn.metrics import classification_report
from bert_sklearn import BertTokenClassifier, load_model
def flatten(l):
return... | MenglinLu/Chinese-clinical-NER | bert_sklearn_bioes/train_bert_sklearn.py | train_bert_sklearn.py | py | 2,809 | python | en | code | 331 | github-code | 90 |
9485039200 | def checkIfListsAreEqual(list1, list2):
for i in list1:
if i not in list2:
return False
return True
def checkIfListsAreEqual2(list1, list2):
isEqual = True
for i in list1:
if i not in list2:
isEqual = False
break
return isEqual
print(checkIfL... | kelvin-homann/refugeeks | python_1/probeklausur/aufgabe_5.py | aufgabe_5.py | py | 411 | python | en | code | 2 | github-code | 90 |
32300099357 | import json
import tensorflow as tf
import numpy as np
from optparse import OptionParser
from tensorflow.python.lib.io.file_io import FileIO
from utils import SamplesIterator
from trainer import SupervisedTrainer
parser = OptionParser()
parser.add_option('--data-dir', dest='data_dir')
parser.add_option('--job-dir', ... | marekgalovic/jamesbot | jamesbot/agent/train.py | train.py | py | 2,000 | python | en | code | 1 | github-code | 90 |
25855276303 | import logging
def add():
logging.info("OKA")
return "ok"
def main():
format_log = "%(asctime)s: %(levelname)s: %(funcName)s Line: %(lineno)d %(message)s"
logging.basicConfig(level=logging.DEBUG, filename="output.log", format=format_log)
logging.debug("DEBUG")
logging.info("INFO")
logging... | ccruz182/Python | logging/custom_logging.py | custom_logging.py | py | 448 | python | en | code | 0 | github-code | 90 |
30071980500 | from django.test.testcases import TestCase
from log.log_content.log_generator import LogConfig, AdditionalInfoBeforeDelete
class LogGenerator:
pass
class TestLogConfig(TestCase):
test_url_name = 'test-register'
def test_create_log_config(self):
log1 = LogConfig()
log2 = L... | liushiwen555/unified_management_platform_backend | log/tests/test_log_generator/test_log_config.py | test_log_config.py | py | 1,196 | python | en | code | 0 | github-code | 90 |
8673455441 | import os
import pandas as pd
import pickle
def read_scv_content(csv_path):
df = pd.read_csv(csv_path)
label_value_pairs = []
for index, row in df.iterrows():
key_value_pairs = {} # 创建一个空字典用于存放键值对
key = row[1] # 第二列作为键
# print(csv_path)
value = 1.0 / row[2] # 第三列作为值
... | anqing1953561931/Finding_related_table | offline_processing.py | offline_processing.py | py | 4,186 | python | en | code | 0 | github-code | 90 |
70188445097 | import requests
import time
from bs4 import BeautifulSoup
import smtplib
import tkinter as tk
import tkinter.messagebox as tkm
class Processor():
def __init__(self, p, d, m, age):
self.p = p
self.d = d
self.m = m
self.age = age
self.stop = 0
self.tracke... | ayan07-eng/VaccineTracker-main | VaccineTracker-main/main.py | main.py | py | 7,077 | python | en | code | 1 | github-code | 90 |
71661241256 | class Student:
'''Student details'''
def __init__(self, id_no, name, dept, subject_names):
self.id_no = id_no
self.name = name
self.subject_names = subject_names
self.dept = dept
def get_student_department(self):
return self.dept
def get_student_subjects(self)... | yogeshjean12/Thoughtworks-Python-Assignments | department_problem.py | department_problem.py | py | 3,725 | python | en | code | 0 | github-code | 90 |
40756109049 | from math import log
import operator
'''计算香农熵'''
def calShannon(dataSet):
numOfData = len(dataSet)
labelCounts = {}
for featV in dataSet:
currentLabel = featV[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
... | qzylalala/MachineLearning | Trees/trees.py | trees.py | py | 2,757 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.