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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
2408166089 | import autograd.numpy as np
import numpy.testing as np_testing
import pytest
import pymanopt
from pymanopt.manifolds import Euclidean, Grassmann, Product, Sphere
class TestProductManifold:
@pytest.fixture(autouse=True)
def setup(self):
self.m = m = 100
self.n = n = 50
self.euclidean =... | pymanopt/pymanopt | tests/manifolds/test_product.py | test_product.py | py | 2,956 | python | en | code | 651 | github-code | 1 |
16070565974 | #!/usr/bin/env python3.8
# -*- coding: utf-8 -*-
"""
https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
Answer... | vikasmunshi/euler | projecteuler/041_pandigital_prime.py | 041_pandigital_prime.py | py | 1,083 | python | en | code | 0 | github-code | 1 |
39695926581 | import datetime as dt
import pandas as pd
import os
import smtplib
import json
from dotenv import load_dotenv
def fetch_planner():
TIME_PERIOD = int(os.environ["TIME_PERIOD"])
ORG_PLANNER_PATH = os.environ["ORG_PLANNER_PATH"]
ORG_PLANNER_SHEET_NAME = os.environ["ORG_PLANNER_SHEET_NAME"]
ORG_PLANNER_HE... | adrian-bjorling/daily-digest | app.py | app.py | py | 3,019 | python | en | code | 0 | github-code | 1 |
71757273633 | import config
import csv
import datetime
import main
import multiprocessing
import psycopg2
import time
sp = main.sp
cur = main.cur
lock = main.lock
def available_genres():
try:
print('Available genres for recommendation was requested!')
results = sp.recommendation_genre_seeds()['genres']
... | 0x01h/individual-symphony | tools/functions.py | functions.py | py | 18,474 | python | en | code | 6 | github-code | 1 |
2067953896 | import cv2
from datetime import datetime
from app.ml.yolo_v3 import YoloV3
import kivy
kivy.require('1.0.6')
from kivy.core.window import Window
from kivymd.app import MDApp
from kivy.clock import Clock
from kivymd.uix.screen import MDScreen
from kivymd.uix.button.button import MDIconButton
from kivymd.uix.label.labe... | nellymin/WildlifeCameraTrap | app/main.py | main.py | py | 7,267 | python | en | code | 0 | github-code | 1 |
39151193505 | # Driving linear regression algo
# y = mx+b
# m = mean(x)mean(y)-mean(xy)/mean(x)square-((x)square)mean
# b = mean(y) - m(mean(x))
# ^ _
# y = 1-SE(y)/SE(y)
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import random
style.use('fivethirtyeig... | Manukhurana97/Machine-Learning1 | 2 Linear Regression :drive(Best fit).py | 2 Linear Regression :drive(Best fit).py | py | 2,265 | python | en | code | 1 | github-code | 1 |
35423265171 | # Author: Xinyi Wang
# Date: 2021/10/05
import scipy.io as io
import numpy as np
def getCsf(mat_file, video_num):
video_num = int(video_num)
X_mat = io.loadmat(mat_file)
X3 = np.asarray(X_mat['feats_mat'], dtype=np.float)
# print(X3)
# print(type(X3))
cnnsa_feats = X3[video_num]
io.savema... | xinyiW915/RVS-resize | src/func/get_cnnsafeats.py | get_cnnsafeats.py | py | 642 | python | en | code | 0 | github-code | 1 |
24670068265 | from decimal import *
from django import template
from core.models import *
from pos.models import *
register = template.Library()
import datetime
@register.filter
def getBrand(value, salesLine):
product = Product.objects.filter(id=salesLine.item_id)
brand = Brand.objects.filter(id=product[0].brand_id)
ret... | hashirharis/DjangoERP | brutils/templatetags/reportTags.py | reportTags.py | py | 9,771 | python | en | code | 1 | github-code | 1 |
8231532069 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
wsPort = 81
BLINKER_BLE = 0
BLINKER_WIFI = 1
BLINKER_MQTT = 2
W_BUTTON = 0
W_SLIDER = 1
W_TOGGLE = 2
W_RGB ... | jjRen-xd/IOT_Access_Control_System_Based_on_Biometric_Recongnition | Release_version/BLINKER/lib/Blinker/BlinkerConfig.py | BlinkerConfig.py | py | 3,360 | python | en | code | 1 | github-code | 1 |
191886024 | #!/usr/bin/env python
"""Sample script of word embedding model.
This code implements skip-gram model and continuous-bow model.
Use ../ptb/download.py to download 'ptb.train.txt'.
"""
import argparse
import collections
import time
import numpy as np
import six.moves.cPickle as pickle
import chainer
from chainer impor... | jem0101/BigSwag-SQA2022-AUBURN | TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/jamieoglindsey0@chainer/examples/word2vec/train_word2vec.py | train_word2vec.py | py | 5,390 | python | en | code | 2 | github-code | 1 |
4197548801 | import matplotlib.pyplot as plt #import matplotlib yang digunakan sebagai visualisasi gambar
#matplotlib inline
import cv2 #mengimport atau memanggil cv2 dari opencv untuk pengolahan citra serta pembacaan gambar
from skimage import data #import data dari skimage sbagai acuan atau contoh
from skimage.io import imread#i... | farhanromd/Tugas-7 | Filter Batas.py | Filter Batas.py | py | 5,431 | python | id | code | 0 | github-code | 1 |
24181921860 | import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
import heapq
nltk.download('stopwords')
from nltk.corpus import stopwords
def nltk_summarizer(raw_text):
stopWords = set(stopwords.words("english"))
word_frequency={}
for word in nltk.word_tokenize(raw_text):
if word not... | ShrutiNathavani/Text_Summarization | nltk_1.py | nltk_1.py | py | 1,189 | python | en | code | 0 | github-code | 1 |
10650487581 | import maya.cmds as cmds
import pymel.core as pm
class UI(object):
def __init__(self):
title = 'curvyEdges'
version = '1.01'
self.ceObj = spline(self)
if pm.window('curvyEdgesWin', exists=True):
pm.deleteUI('curvyEdgesWin')
with pm.window('curvy... | cmcpasserby/curvyEdges | scripts/curvyEdges.py | curvyEdges.py | py | 5,573 | python | en | code | 9 | github-code | 1 |
27359979494 | from pymatgen.core import Element
from collections import OrderedDict
import numpy as np
from typing import Union, List
from pymatgen.core.composition import Composition
import pandas as pd
from numpy.typing import ArrayLike
class ElementOneHotRepresentation:
def __init__(self, one_hot: ArrayLike, element_dict: O... | nim-hrkn/ToyCompositionDescriptor | ToyCompositionDescriptor/composition_onehot.py | composition_onehot.py | py | 7,095 | python | en | code | 0 | github-code | 1 |
28244631646 | import typing as t
import typer
import json
import git
import sys
import os
import pathlib
import subprocess
fuam_path: pathlib.Path = pathlib.Path(os.path.dirname(os.path.abspath(sys.argv[0])))
cli: typer.Typer = typer.Typer()
@cli.command()
def configure() -> None:
print("fuam configure 0.1\n")
... | OkiStuff/fuam | fuam.py | fuam.py | py | 3,120 | python | en | code | 0 | github-code | 1 |
4721991109 | """AdventOfCode Day18."""
import re
test_input_1 = """1 + 2 * 3 + 4 * 5 + 6"""
test_input_2 = """1 + (2 * 3) + (4 * (5 + 6))"""
test_input_3 = """5 + (8 * 3 + 9 + 3 * 4 * 3)"""
test_input_4 = """5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"""
test_input_5 = """((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"""
test_input... | jneo8/AdventOfCode | 2020/day18.py | day18.py | py | 2,480 | python | en | code | 0 | github-code | 1 |
33256158133 | from transformers import BertTokenizer,GPT2LMHeadModel, AutoModelForCausalLM
hf_model_path = 'IDEA-CCNL/Wenzhong2.0-GPT2-110M-BertTokenizer-chinese'
tokenizer = BertTokenizer.from_pretrained(hf_model_path)
# model = GPT2LMHeadModel.from_pretrained(hf_model_path)
model = AutoModelForCausalLM.from_pretrained(hf_model... | taishan1994/chinese_llm_pretrained | test_model.py | test_model.py | py | 1,212 | python | en | code | 2 | github-code | 1 |
30894550551 | """
height means from top to this position, there are how many '1'
left means at current position, what is the index of left bound of the rectangle with height[j]. 0 means at this position, no rectangle.
right means the right bound index of this rectangle. 'n' means no rectangle.
"""
def maximalRectangle(matrix):
... | MinhVuong2000/Practising | QuestionsWithMatrixInterview/maxRectangleSubMatrix.py | maxRectangleSubMatrix.py | py | 1,537 | python | en | code | 0 | github-code | 1 |
9808834906 | import numpy as np
import matplotlib.pyplot as plt
import math
def count(arr):
tally = dict()
for ele in arr:
if ele not in tally.keys():
tally[ele] = 0
tally[ele] += 1
return tally
def save_plot(x, y, name):
plt.plot(x, y, 'o-')
plt.xlim((0, 100))
plt.savefig(nam... | yiyanw/Performance-Characterisation-of-Binarised-Neural-Networks-in-Traffic-Fingerprinting | TheromEncoder.py | TheromEncoder.py | py | 3,713 | python | en | code | 0 | github-code | 1 |
2736658133 | '''
https://www.codewars.com/kata/58f5c63f1e26ecda7e000029/python
In this simple Kata your task is to create a function that turns a string into a Mexican Wave.
You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up.
'''
def wave(people):
content... | SzybkiRabarbar/CodeWars | 2022-03/2022-03-22Mexican Wave.py | 2022-03-22Mexican Wave.py | py | 748 | python | en | code | 0 | github-code | 1 |
26593170611 | """Functions for deriving indices"""
import xarray as xr
import numpy as np
def effective_temp(T):
"""Compute effective temperature
Effective Temp = (1/2)*(yesterday's effective temp) + (1/2)*(today's actual temp)
To make sense of the expansion, today's ET is consist of a portion of the actual temperatur... | cal-adapt/climakitae | climakitae/tools/indices.py | indices.py | py | 7,473 | python | en | code | 11 | github-code | 1 |
16439319074 | import sys
sys.stdin=open('../input.txt', 'r')
def size(n):
q=[n]
cnt=0
while q:
cnt+=1
a=q.pop()
q.extend(V1[a])
return cnt
for t in range(1, int(input())+1):
v, e, n1, n2 = map(int, input().split())
n3=9**9
V1 = [[] for _ in range(v+1)]
V2 = [[] for _ in range... | ttppggnnss/CodingNote | 2005/0529/swea 1248.py | swea 1248.py | py | 619 | python | en | code | 0 | github-code | 1 |
39551925504 | from pyrogram import filters,Client
import wikipedia
wikipedia.set_lang("it")
cprefix="/"
@Client.on_message(filters.command("wiki",cprefix))
async def my_handler(client, message):
send = await message.reply_text("Cercando...")
try:
await send.edit_text(str(wikipedia.summary(message.text.split(" ",1)[1... | pentecoste/bot-telegram-5l | caldatobot-telegram/comandi/wikipedia.py | wikipedia.py | py | 698 | python | en | code | 0 | github-code | 1 |
22826864043 | GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2
def gravitational_law(
force, mass_1, mass_2, distance):
product_of_mass = mass_1 * mass_2
if (force, mass_1, mass_2, distance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if force < 0:
r... | py3-coder/Hacktober_Repo_22 | Python/newton_gravitational_law.py | newton_gravitational_law.py | py | 1,532 | python | en | code | 103 | github-code | 1 |
23669146088 | from django.shortcuts import render
from django.views.generic import TemplateView, ListView
import django_tables2
import books.models
import books.filters
import books.tables
class FilteredSingleTableView(django_tables2.SingleTableView):
filter_class = None
def get_table_data(self):
data = super(Filt... | spapas/django_table_filtering | books/views.py | views.py | py | 1,962 | python | en | code | 6 | github-code | 1 |
11510356842 | # Released under the MIT License. See LICENSE for details.
#
"""Defines AppDelegate class for handling high level app functionality."""
from __future__ import annotations
from typing import TYPE_CHECKING
import babase
if TYPE_CHECKING:
from typing import Callable
import bascenev1
class AppDelegate:
"""... | efroemling/ballistica | src/assets/ba_data/python/baclassic/_appdelegate.py | _appdelegate.py | py | 1,336 | python | en | code | 468 | github-code | 1 |
72355993314 | import pygame
import snake as s
import animal as a
import config as cfg
import random
import util as u
from game import Game
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
)
class SnakeGame(Game):
def init(self):
self.snake = s.Snake((cfg.BLOCK_SIZE, cfg.BLOCK_SIZE))
se... | BinaryCat17/snake | play_snake.py | play_snake.py | py | 2,302 | python | en | code | 0 | github-code | 1 |
28169435385 | from stix2 import MemoryStore, Filter
from itertools import chain
def get_related(thesrc, src_type, rel_type, target_type, reverse=False):
relationships = thesrc.query([
Filter('type', '=', 'relationship'),
Filter('relationship_type', '=', rel_type),
Filter('revoked', '=', False),
... | ilf0rz/MITRE-ATTACK-heatmap-gen | relationships.py | relationships.py | py | 5,814 | python | en | code | 0 | github-code | 1 |
70888270435 | # 피보나치 수열에서 특정 숫자를 입력할때
# 정석적인 피보나치 수열 계산에서 특정 숫자번째의 피보나치 수열은
# 피보나치 수열의 0 번째와 1번째를 총 몇 번 방문하게 되는지 출력
test = int(input())
# 다이나믹 프로그래밍을 이용했다.
dict = {}
dict[0] = [1,0]
dict[1] = [0,1]
for t in range(test):
n = int(input())
if n == 0:
print(dict[0][0],dict[0][1])
elif n == 1:
print(dict[1]... | rhkddud3917/Algorithm-Practice | BOJ/1003-피보나치 함수.py | 1003-피보나치 함수.py | py | 740 | python | ko | code | 0 | github-code | 1 |
33519355882 | import base64
from .platform import JYTHON, PY2
def compress_text(text):
result = base64.b64encode(_compress(text.encode('UTF-8')))
return result if PY2 else result.decode('ASCII')
if not JYTHON:
import zlib
def _compress(text):
return zlib.compress(text, 9)
else:
# Custom compress ... | robotframework/RIDE | src/robotide/lib/robot/utils/compress.py | compress.py | py | 958 | python | en | code | 910 | github-code | 1 |
21174566509 | from tkinter import messagebox, Tk, Frame, TOP, X, NW, Canvas, Image, Button
from PIL import ImageTk, Image
from models.Users import checkLoggedUserRole, checkLoggedUserIsBlocked
from classes.Navbar import NavbarWidget
from views.Manage import ManageView
from views.Recipes.RecipesCategory import RecipesCategoryView
d... | pedromst2000/Tkinter-Recipes-manage-App | views/Home.py | Home.py | py | 6,757 | python | en | code | 0 | github-code | 1 |
19792334224 | import torch
import torch.nn as nn
import torch.nn.functional as F
from easydict import EasyDict as edict
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/mod... | GAIMJKP/summer_work | model_util.py | model_util.py | py | 12,858 | python | en | code | 0 | github-code | 1 |
41597137875 | import sys, os, logging
import random
import pysam
import pandas as pd
vcf_file = sys.argv[1]
pre_file = sys.argv[2]
luad = sys.argv[3]
out = sys.argv[4]
rand = sys.argv[5]
logging.basicConfig(filename = "{}/ExtractReads.{}.log".format(out,luad),
filemode = "a",
fo... | ShomronLab/SomaticSerum | SomaticExtract/src/ExtractSNVs.py | ExtractSNVs.py | py | 3,899 | python | en | code | 0 | github-code | 1 |
6407461716 | #
# Credit to:
# Troy Fawkes for his primer on using queues with Multithreading
# > https://www.troyfawkes.com/learn-python-multithreading-queues-basics/
#
# The Python3 queue documentation
# > https://docs.python.org/3/library/queue.html#queue.Empty
#
import threading
import socket
import datetime
from queue import Q... | RikJonAtk/multiThreadedDNS | dns_v3.py | dns_v3.py | py | 1,869 | python | en | code | 2 | github-code | 1 |
75201422432 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Created on 2017/11/12
__author__ = "Jianguo Jin (jinjianguosky@hotmail.com)"
"""
Description:
"""
import sec34_module_test.script_test as st
if __name__ == '__main__':
print("自己的功能模块测试")
st.test_login()
print("------")
st.test_operation(... | skyaiolos/SeleniumWithPython | sec34_module_test/other.py | other.py | py | 381 | python | en | code | 1 | github-code | 1 |
27537503353 | import numpy as np
from torchtext import data
from torchtext import datasets
from gensim.models import KeyedVectors
def getVectors(args, data):
vectors = []
if args.mode != 'rand':
word2vec = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)
for i in range(l... | UVa-NLP/HEDGE | cnn/load_data.py | load_data.py | py | 1,480 | python | en | code | 30 | github-code | 1 |
382041952 | #!/usr/bin/env python3
import theory
class String():
def __init__(self, name):
self.name = name
self.notes = Fretboard.t.get_note_sequence(name, Fretboard.UP_TO_FRET)
class Fretboard():
""" Abstraction of a guitar fretboard """
UP_TO_FRET = 13
TUNINGS = {
'standard': [ 'E2', '... | alpozcan/pyfretboard | guitar.py | guitar.py | py | 1,235 | python | en | code | 0 | github-code | 1 |
70800238115 | # # 1行目の英大文字 X から、2行目の英大文字 Y の範囲に3行目のアルファベット C
# が含まれていれば"true", そうでなければ"false"と出力してください。
# # X が Y よりもアルファベット順で後ろになる場合(X = 'G', Y = 'F'のときなど)も
# "false"と出力してください。
# x1 - c3 - y2 : true
## inputx - inputc - inputy
# A - y -x,c : false
# x - y - c : false
##解答
alpha = []
[alpha.append(chr(i)) for i in range(65, 65+26... | emerada18/paiza_python3_skillup | final_search_alphabet.py | final_search_alphabet.py | py | 1,376 | python | ja | code | 0 | github-code | 1 |
70960347233 | # 画图找规律一下就出来了
# 1e18 肯定是二分处理
import sys
sys.stdin = open("cowcode.in", "r")
sys.stdout = open("cowcode.out", "w")
s, n = input().split()
n = int(n)
k = len(s)
while k*2<n:
k *= 2
while n > len(s):
if k+1 != n:
n -= k + 1
else:
n = k # “cowwcoo” oo处理不太一样
while k >= n:
k //= 2
... | cola0405/usaco | silver_pythonxxxxxxx/17-1/3.py | 3.py | py | 385 | python | en | code | 0 | github-code | 1 |
10095731570 |
def test_error():
from wkd import Error
assert(issubclass(Error, Exception))
error = Error('message')
assert(error.message == 'message')
def test_usage_error():
from wkd import Error, UsageError
assert(issubclass(UsageError, Error))
error = UsageError('messa... | esoma/wkd | test/test_error.py | test_error.py | py | 836 | python | en | code | 0 | github-code | 1 |
73352842273 | from decimal import *
ABS = 0
ORD = 1
class Polyline(object):
def __init__(self, filename):
self.filename = filename
self.shapes = 0
self.polyVertex = []
self.ruleTab = []
def __str__(self):
out = "Polyline: " + str(self.shapes) + "\n"
i = 0
while i < ... | ethanquix/scott_parser | polyline.py | polyline.py | py | 2,333 | python | en | code | 0 | github-code | 1 |
35407265058 | """
We want the longest substring without repeating characters
- use sliding window that expands each interation and stores all elements and their frequencies in a dict
- shorten the window while (len(dict) > fast - slow + 1)
- keep track of max length and return
a b c a b c b b
s f
cur_freq = {
a : 1,
... | Rahul-Mewada/leetcode-grind | 3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.py | 3-longest-substring-without-repeating-characters.py | py | 1,004 | python | en | code | 0 | github-code | 1 |
6585765676 | from UM.Job import Job
from UM.Logger import Logger
from .avr_isp import ispBase
from .avr_isp.stk500v2 import Stk500v2
from time import time, sleep
from serial import Serial, SerialException
# An async job that attempts to find the correct baud rate for a USB printer.
# It tries a pre-set list of baud rates. A... | Ultimaker/Cura | plugins/USBPrinting/AutoDetectBaudJob.py | AutoDetectBaudJob.py | py | 3,836 | python | en | code | 5,387 | github-code | 1 |
43368661765 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DFOIL: Directional introgression testing a five-taxon phylogeny
pre-dfoil - site count checking testt
James B. Pease
http://www.github.com/jbpease/dfoil
"""
from __future__ import print_function, unicode_literals
_LICENSE = """
If you use this software please cite:
Pe... | jbpease/dfoil | precheck.py | precheck.py | py | 5,664 | python | en | code | 26 | github-code | 1 |
40926531737 | import argparse
import subprocess
import os
from qsub import q_sub
import shutil
def main():
# arguments
parser = argparse.ArgumentParser()
parser.add_argument('-block_info', help='CSV of homeoblock coords', required=True)
parser.add_argument('-key', help='CSV of chromosome names and corresponding re... | henryjuho/sal_enhancers | homeoblock_alignments/do_all_pairwise.py | do_all_pairwise.py | py | 2,708 | python | en | code | 1 | github-code | 1 |
27070215388 | import json
import os
from flask import url_for
from flask_babel import _
from slugify import slugify
with open(
os.path.join(os.path.dirname(__file__), "countries.json"), encoding="utf8"
) as a:
COUNTRIES = sorted(json.load(a)["countries"], key=lambda k: k["name"])
COUNTRIES = [c for c in COUNTRIES if c[... | drkane/ngo-explorer | ngo_explorer/utils/countries.py | countries.py | py | 23,990 | python | en | code | 4 | github-code | 1 |
24351569490 | import requests
from main import Position
url = 'http://127.0.0.1:8000/positions/'
def test_positions():
positions = [Position(cm=100, gp=20), Position(cm=100, gp=80)]
positions = [p.dict() for p in positions]
response = requests.post(url, json=positions)
assert response.json() == [{'cp': 50.0, 'cm'... | LuisIllig/savings-balancer | test_positions.py | test_positions.py | py | 466 | python | en | code | 0 | github-code | 1 |
70576316194 | import numpy as np
import easysim
import os
import torch
class YCB:
CLASSES = {
1: "002_master_chef_can",
2: "003_cracker_box",
3: "004_sugar_box",
4: "005_tomato_soup_can",
5: "006_mustard_bottle",
6: "007_tuna_fish_can",
7: "008_pudding_box",
8: "0... | NVlabs/handover-sim | handover/ycb.py | ycb.py | py | 5,389 | python | en | code | 66 | github-code | 1 |
18781634052 | def prime(n):
if n==1:
return False
for i in range(2,1+int((n**0.5))):
if n%i==0:
return False
return True
def pal(n):
return str(n)== "".join(reversed(str(n)))
a=int(input())
while 1:
a+=1
if prime(a) and pal(a):
print(a)
break | Jashprachodai/codemind-python | Program_to_find_out_the_next_prime_palindrome_number.py | Program_to_find_out_the_next_prime_palindrome_number.py | py | 296 | python | ru | code | 0 | github-code | 1 |
17702010446 | from django.urls import path
# -- Importar todas las vistas de mi_tienda
from . import views
# -- Aquí se definen las URLs de nuestra tienda
# -- Metemos de momento sólo la principal (índice)
urlpatterns = [
# -- Vista pricipal (índice)
path('', views.index, name='index'),
path('panaderia.html/', views.p... | martaquintana/2019-2020-LTAW-Practicas | P2/mi_tienda_web/mi_panaderia/urls.py | urls.py | py | 701 | python | es | code | 0 | github-code | 1 |
33093921448 | import solution
from collections import defaultdict
from sortedcontainers import SortedList
class Solution(solution.Solution):
def solve(self, test_input=None):
ops, vals = test_input
n, entries = vals[0]
# Your MovieRentingSystem object will be instantiated and called as such:
obj... | QuBenhao/LeetCode | problems/1912/solution.py | solution.py | py | 2,076 | python | en | code | 8 | github-code | 1 |
37978950788 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by H.Turbé, March 2020.
"""
import argparse
import os
import shutil
import sys
import time
from pyspark import SparkFiles
from pyspark.sql import SparkSession
CWD = os.getcwd()
FILEPATH = os.path.dirname(os.path.realpath(__file__))
ROOTPA... | hturbe/InterpretTime | src/operations/__exec_generate_data.py | __exec_generate_data.py | py | 2,775 | python | en | code | 23 | github-code | 1 |
29135976593 | ######################################
#### Resampling
#####################################
freq = 100000
angle = np.pi
data_x_2 = np.linspace(0, d/sample_rate, d)
clock =0.45*np.cos((2*np.pi*freq*data_x_2+angle-0.5))
huffman_sync = []
for i in range (d-27820,d-1):
if (clock[i] > clock[i-1] and clock[i] > clock... | MaazHKhan/ESC_Practicals_2020 | Practical 3/Python_scripts/trellis.py | trellis.py | py | 821 | python | en | code | 0 | github-code | 1 |
71386683875 | import redis
import requests
from bs4 import BeautifulSoup
from celery import shared_task
from products.models import Product
from core.telegram_notification import telegram_notify
MARKETPLACE_URL = 'https://ozon.ru/seller/1/products'
redis_client = redis.StrictRedis(
host='redis',
port=6379,
db=0
)
d... | mxstrv/mxstrv-test-o-parser | ozon_parser/core/tasks.py | tasks.py | py | 5,591 | python | ru | code | 0 | github-code | 1 |
10418138913 | S = input('Ent. Sth. : ')
S1 = S.split()
S2 = dict()
for i in S1:
if i not in S2.keys():
S2[i] = 0
S2[i] = S2[i] + 1
print(S2)
y = '((Ali Akbar Gholami))'
z = y.center(67,'0')
print(z) | ali3006/AliAkbar-Gholami | Exc_3_Data_Mining.py | Exc_3_Data_Mining.py | py | 218 | python | en | code | 0 | github-code | 1 |
36176895571 | #----------------------------------------------------------------------
# A dataset wrapper for pluto simulations
#
# Author : Thomas Rometsch (thomas.rometsch@uni-tuebingen.de)
# Date : 2018-07-12
#----------------------------------------------------------------------
from cast.dataset import *
from . impor... | rometsch/cast | cast/pluto.py | pluto.py | py | 12,451 | python | en | code | 0 | github-code | 1 |
40306360382 | """
Dialog to ask user to choose an item from a list.
C-Python TCL-TK Implementation
To test type in a console:
from rmh.dialogs import chooseFromList_cpy
chooseFromList_cpy.test()
"""
# -------------------------------- #
from ttk import Tkinter as tk
import ttk
try:
import connect as rsl
except:
p... | icrphysics/Script-Dialogs | chooseFromList_cpy.py | chooseFromList_cpy.py | py | 5,981 | python | en | code | 1 | github-code | 1 |
34552883298 | import gradio as gr
from spellchecker import SpellChecker
from itertools import permutations
def Anagram(words):
"""
A function that returns an anagram after filtering out the incorrect words.
It also returns the given word passed to the function whether anagaram is
generated or not.
"""
rand... | Jonaben1/Anagram | main.py | main.py | py | 1,427 | python | en | code | 0 | github-code | 1 |
2316243589 | from __future__ import division, print_function, absolute_import
import numpy
from scipy.linalg.lapack import get_lapack_funcs
from scipy.linalg.misc import LinAlgError
__all__ = ['qrp', 'qlp', 'tri_inv']
# Duplicate from scipy.linalg.misc
def _datacopied(arr, original):
"""
Strict check for `arr` not shari... | Sabrina85/odemis | src/odemis/util/linalg.py | linalg.py | py | 3,299 | python | en | code | null | github-code | 1 |
24639727756 | import datetime
import time
from datetime import datetime
from typing import Optional
import holidays
import numpy as np
import pandas as pd
from gluonts.time_feature.holiday import (
BLACK_FRIDAY,
CHRISTMAS_DAY,
CHRISTMAS_EVE,
COLUMBUS_DAY,
CYBER_MONDAY,
EASTER_MONDAY,
EASTER_SUNDAY,
G... | aleksei-mashlakov/m6_competition | src/time_features.py | time_features.py | py | 5,570 | python | en | code | 2 | github-code | 1 |
16386299264 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 26 18:09:24 2021
@author: user
"""
def medidas_hoja_A(N):
"""
Devuelve el ancho y el largo de la hoja A(N), por recursión.
Pre: N debe ser mayor o igual a 0.
Pos: devuelve un tupla con el ancho y el largo de la hoja.
"""
if N == 0:
res = (... | MarcosMartilotta/Curso_Python_UNSAM | Entrega_clase_10/hojas_ISO.py | hojas_ISO.py | py | 484 | python | es | code | 0 | github-code | 1 |
24217475763 | import faiss
import pandas as pd
import wandb
import time
import sys
wandb_name = sys.argv[1]
wandb.login(key='188ce11fc669c7ea709e957bece5360053daabe8')
wandb.init(id = id, project='faiss_clustering', entity='emilymuller1991')
n_clusters = 20
# prefix for hpc
# prefix = '/rds/general/user/emuller/home'
prefix = '/r... | emilymuller1991/thesis | chapter4clustering/faiss_clustering.py | faiss_clustering.py | py | 2,586 | python | en | code | 0 | github-code | 1 |
20271684058 | from .settings import *
# DEBUG=False 不会用自带的 server 去 server js/css 等静态文件
# 需要用 nginx 之类的去做静态文件的 server.
DEBUG = True
INTERNAL_IPS = ['127.0.0.1']
ALLOWED_HOSTS += INTERNAL_IPS
ALLOWED_HOSTS.append('localhost')
# 重置 setting 里的 STATIC_ROOT 配置
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.pa... | CoinLQ/cutrect | cutrect/settingsdev.py | settingsdev.py | py | 1,267 | python | zh | code | 1 | github-code | 1 |
43346740956 | import json
from pprint import pprint
from time import ctime
def lambda_response(status_code, message, **kwargs) -> dict:
'''Presents the custom OleTalk API Gateway/server responses in standard HTTP format, for all communications sent
from the API to the client. \n
Parameters:
----------- ... | Gallatin-Engineering/oletalk_response | python/api_response.py | api_response.py | py | 3,907 | python | en | code | 0 | github-code | 1 |
21578935466 | from fastapi.testclient import TestClient
import pytest
from app.main import app
from app.db import Base, engine
from app.cache import Cache
cache = Cache()
client = TestClient(app)
@pytest.fixture(autouse=True)
def cleanup_db():
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
y... | csornyei/url-shortener | app/test_main.py | test_main.py | py | 4,650 | python | en | code | 0 | github-code | 1 |
25846418713 | #!/usr/bin/python3
import discord
from discord.ext import commands
from spam_modules import meme
class MemeBot(commands.Cog):
def __init__(self,client):
self.client=client
@commands.command(name='help')
async def help(self,ctx):
h=discord.Embed(title='Help',description='Help for Disco Mem... | himanshudas75/Spam | spam_cogs/meteor.py | meteor.py | py | 863 | python | en | code | 0 | github-code | 1 |
40654443610 | import unittest
from datetime import datetime
from batteries.nubbin_battery import NubbinBattery
from batteries.spindler_battery import SpindlerBattery
class TestNubbin(unittest.TestCase):
def setUp(self) -> None:
self.current_date: datetime = datetime.today().date()
self.last_service_date: datet... | manucho254/forage-lyft-app | test/test_battries.py | test_battries.py | py | 1,956 | python | en | code | 0 | github-code | 1 |
41977630402 | # %%
import os
import glob
import numpy as np
import torch
from PIL import Image, ImageDraw
from skimage import draw
from skimage.io import imread
from matplotlib import pyplot as plt
from scipy.ndimage.filters import gaussian_filter
from torch.utils.data import Dataset, DataLoader
from torchvision import tr... | NataliePolach/Bachelor-thessis | utils.py | utils.py | py | 3,034 | python | en | code | 0 | github-code | 1 |
16098447748 | from tkinter import *
root = Tk()
root.title("Compliment Color Calculator")
root.configure(background="#b3c9c3")
root.geometry('450x450')
# person will type in Hexcode for which color they want to compliment
""" Compliment colors will be calculated in this function by subtracting the input Hex code value from #FFFFF... | RafaelGutz444/ComplimentColorCalculator | main.py | main.py | py | 3,563 | python | en | code | 0 | github-code | 1 |
43983644009 | #!/usr/bin/env python
import time
import rospy
import rosnode
import rostopic
from trucky_custom_msgs.msg import ActuatorsState
from ackermann_msgs.msg import AckermannDrive
op_mode = "None"
def actuatorsCmdCb(data):
global op_mode
motor_pwm = data.motor_pwm_high_time
servo_pwm = data.servo_pwm_high_tim... | AldoAguilar/TruckyAVProject | ros/workspaces/trucky_ws/src/trucky_arduino/scripts/arduino_logger.py | arduino_logger.py | py | 3,746 | python | en | code | 1 | github-code | 1 |
13414995206 | if __name__ == '__main__':
with open('d1.csv', 'r') as d1:
with open('d1_cleaned.csv', 'w') as d1_cleaned:
d1_cleaned.write(d1.readline().strip() + '\n')
line = d1.readline()
while line is not '':
line = line.strip().split(',')
if line[-1] ... | NiramayVaidya/Differential_Privacy_Hemodialysis_SBP_Prediction | clean_d1.py | clean_d1.py | py | 600 | python | en | code | 2 | github-code | 1 |
27037262888 | from ByteArray import *
__all__ = ["parse"]
keyList = (0xd1, 0x73, 0x52, 0xf6, 0xd2, 0x9a, 0xcb, 0x27, 0x3e, 0xaf, 0x59, 0x31, 0x37, 0xb3, 0xe7, 0xa2)
def decode(fileData):
if fileData[:3] != b"BMD":
return (None, -1)
if fileData[3] == 0x0A:
return fileData, 4
if fileData[3] == 0x0C:
memory = by... | snjdck/Aladdin | src/_tools/model/CopyMuFilesToUnity.py | CopyMuFilesToUnity.py | py | 6,533 | python | en | code | 1 | github-code | 1 |
11562018372 | # 2016-02-09 282 tests, 236 ms
# see https://leetcode.com/discuss/54724/python-140ms-beats-100%25-and-works-for-n-sum-n-2 for a faster solution
# from http://cs.stackexchange.com/questions/2973/generalised-3sum-k-sum-problem
#k-SUM can be solved more quickly as follows.
# For even k: Compute a sorted list S of all s... | chaor/LeetCode_Python_Accepted | 18_4Sum.py | 18_4Sum.py | py | 2,153 | python | en | code | 49 | github-code | 1 |
26768362338 |
# coding: utf-8
# In[ ]:
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import numpy as np
from tkinter import *
from tkinter import filedialog
from tkinter i... | zuhaalfaraj/DSP | Signals Display with Flask/Tkinterapp.py | Tkinterapp.py | py | 2,088 | python | en | code | 1 | github-code | 1 |
15818104013 | from models.calendar_model import CalendarItem
from dotenv import load_dotenv
import os
# id: int
# subject: str
# location: str
# starttime: str
# endtime: str
# categorycolor: str
# Load Secret Items
load_dotenv()
connection_string = os.getenv("ConnectionString")
# MongoDB Driver
import motor.motor_asyncio
client ... | DerenB/FARM-Stack-Dashboard | backend/db_functions/calendar_db_functions.py | calendar_db_functions.py | py | 1,586 | python | en | code | 0 | github-code | 1 |
6612162646 | #!/usr/bin/env python
import unittest
import numpy as np
from mtuq.wavelet import\
Gaussian,\
Triangle,\
Trapezoid,\
EarthquakeTrapezoid
EPSVAL = 1.e-3
def _is_close(a, b):
if abs(a-b) < EPSVAL:
return True
else:
print('Error:', abs(a-b))
return False
class TestWa... | uafgeotools/mtuq | tests/unittest_wavelet.py | unittest_wavelet.py | py | 1,372 | python | en | code | 57 | github-code | 1 |
40134649435 | from sys import stdin
from heapq import heappush, heappop
input = stdin.readline
''' 출력초과
if __name__ == '__main__':
num = []
n = int(input())
for _ in range(n):
num.append(int(input()))
num.sort()
cache = num[0] + num[1]
result = num[0] + num[1]
for _ in range(2, n):
result ... | Woojun-Yoon/YOONJOON | 1715 카드 정렬하기.py | 1715 카드 정렬하기.py | py | 785 | python | en | code | 1 | github-code | 1 |
22525694413 | import logging
import hydra
from omegaconf import DictConfig
logger = logging.getLogger(__name__)
class BiencoderDatasetsCfg(object):
def __init__(self, cfg: DictConfig):
datasets = cfg.datasets
self.train_datasets_names = cfg.train_datasets
logger.info("train_datasets: %s", self.train_d... | microsoft/LMOps | uprise/DPR/dpr/utils/conf_utils.py | conf_utils.py | py | 986 | python | en | code | 2,623 | github-code | 1 |
5250226508 | __author__ = "Severi Jääskeläinen \n Samuel Kaiponen \n Heta Rekilä \n" \
"Sinikka Siironen \n Juhani Sundell"
__version__ = "2.0"
import platform
import subprocess
import shlex
import glob
from . import general_functions as gf
from .beam import Beam
from .detector import Detector
from .target import Ta... | ilardinho/ePotku_public | server/potku/modules/get_espe.py | get_espe.py | py | 6,789 | python | en | code | 0 | github-code | 1 |
2325343679 | #!/usr/bin/env python
# HOUSE ROBBER
#
# - given list of values
# - return highest total value you can get by adding values - but none of the indexes can be touching
#
# NOTES
#
# - introduces RECURRANCE RELATIONSHIP which is a way to break up DYNAMIC PROGRAMMING problems
# - trick is to break the problem into subsets... | scorzo/python_algorithms | 13_1d_dyanmic_programming/03_house_robber.py | 03_house_robber.py | py | 1,424 | python | en | code | 0 | github-code | 1 |
19844910180 | #!/usr/bin/env python
# coding=utf-8
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
import numpy as np
from geometry_msgs.msg import Twist
rospy.init_node('line_follower')
cmd_vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
cv_bridge = CvBridge()
... | PARC-2023-Team-Mali/Line-followers-parc | parc_line_follower.py | parc_line_follower.py | py | 2,305 | python | fr | code | 0 | github-code | 1 |
11807018018 | from typing import List
import pandas as pd
from graphysio.dialogs import askUserValue
from graphysio.plotwidgets import PlotWidget
from graphysio.plotwidgets.curves import CurveItemWithPOI
from graphysio.structures import Parameter, PlotData
def get_perfusion_index(plotwidget: PlotWidget) -> List[CurveItemWithPOI]:... | jaj42/GraPhysio | graphysio/transformations/perfusion_index.py | perfusion_index.py | py | 1,512 | python | en | code | 4 | github-code | 1 |
42581376596 | from tkinter import Tk, filedialog
import json
import os
Tk().withdraw() # prevents extra window
with filedialog.askopenfile(initialdir='~') as input_file:
base_name = os.path.basename(input_file.name)
if base_name.split('.')[-1] != 'ipynb':
raise ValueError("Expected file extension '.ipynb'")
in... | maxTarlov/interview-bot-source | utils/nb-remove-text.py | nb-remove-text.py | py | 811 | python | en | code | 0 | github-code | 1 |
22710793236 | import pygame
import random
# creation de la class monstre
class Monster(pygame.sprite.Sprite):
def __init__(self, game):
super().__init__()
self.game = game
self.health = 100
self.max_health = 100
self.attack = 0.3
self.image = pygame.image.load('assets/bart.png')... | YvanMackowiak/SimpsonPython | monster.py | monster.py | py | 1,998 | python | fr | code | 0 | github-code | 1 |
70888601635 | import csv
from io import StringIO
import json
import os
import requests
import sys
import unittest
from unittest.mock import patch
from etl.run import run_cmd_line
from etl.setup import ETLEnv
import pdb
REAL_GET = requests.get
def get_test_data_paths(format_, num_calls):
"Returns list of possible paths to t... | rhizomes-project/rhizomes-etl | etl/tests/test_tools.py | test_tools.py | py | 4,114 | python | en | code | 1 | github-code | 1 |
27273086943 | import numpy as np
import scipy.stats as sts
import matplotlib.pyplot as plt
import functools as ft
#mu = 0
#std = 1
N = 10000
n_means = 2000
def Chi2_i(prediction_i, label_dist, population_variance=None, population_mean=None):
#Cowan p. 104
# The quantity (y_i - f(x_i, w)) / s_i is a measure of deviation b... | CLEANit/EGSnrc | egs_home/scatter-learn/misc/chi2_goodness_fit/chi2_demo.py | chi2_demo.py | py | 3,677 | python | en | code | 0 | github-code | 1 |
41209016704 | import threading, time
import multiprocessing
import socket
import json
import os
from kafka import KafkaConsumer, KafkaProducer, TopicPartition
from kafka.common import LeaderNotAvailableError
from kafka.errors import KafkaError
'''
KAFKA BASICS
describe a topic
/usr/local/kafka/bin/kafka-topics.sh -... | kartikra/dattasa | dattasa/kafka_system.py | kafka_system.py | py | 8,807 | python | en | code | 4 | github-code | 1 |
73910114914 | __author__ = 'Victor Olaya'
__date__ = 'October 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsDataSourceURI, QgsVectorLayerImport
from processing.core.GeoA... | nextgis/nextgisqgis | python/plugins/processing/algs/qgis/ImportIntoPostGIS.py | ImportIntoPostGIS.py | py | 5,852 | python | en | code | 27 | github-code | 1 |
19322875332 | import sys
import heapq
input = sys.stdin.readline
n = int(input())
data = []
q = []
for _ in range(n):
s, t = map(int, input().split())
data.append((s, t))
data.sort(key=lambda x: x[0])
heapq.heappush(q, data[0][1])
for c in data[1:]:
if c[0] >= q[0]:
heapq.heappop(q)
heapq.heappush(q, c[1])
... | hanameee/Algorithm | KUCC_Algorithm_Study/week2/11000.py | 11000.py | py | 334 | python | en | code | 2 | github-code | 1 |
72019823395 | from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse,
compat_urllib_request,
compat_urlparse,
)
from ..utils import (
ExtractorError,
int_or_none,
parse_duration,
)
class PluralsightIE(InfoE... | builder07/ytdl | youtube_dl/extractor/pluralsight.py | pluralsight.py | py | 7,598 | python | en | code | 0 | github-code | 1 |
12021443393 | import discord
import asyncio
import sys
from datetime import datetime
import feedparser
import re
import time
import random
import os
client = discord.Client()
latestNum = 0
currentNum = 0
link = 'blank'
title = 'blank'
last = open("/last.txt", "r") #This file stores the last thread number so if the bot closes it ... | swmpdg/discord-mybb-thread-poster | bot.py | bot.py | py | 2,189 | python | en | code | 0 | github-code | 1 |
10338740792 | from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QLabel
from menu_window import MenuWindow
class GUI(QtWidgets.QMainWindow):
"""
This is the base window where all the child widgets are placed.
All the child widgets act as seperate window.
This also holds all the variables shared... | jonirajala/ImgAnnotator | src/ui/gui.py | gui.py | py | 1,340 | python | en | code | 0 | github-code | 1 |
71036138274 | import random
import tensorflow as tf
from dqn.agent import Agent
from dqn.environment import GymEnvironment
from config import get_config
flags = tf.app.flags
flags.DEFINE_string('env_name', 'Breakout-v0', 'The name of gym environment to use')
flags.DEFINE_boolean('display', False, 'Whether to do display the game ... | gutobortolozzo/reinforcement-learning-atari | main.py | main.py | py | 750 | python | en | code | 0 | github-code | 1 |
11910453993 | from flask import jsonify, request
from app.models import Manufacturer, Token
from app import db
def deleteManufacturer(id):
'''delete manufacturer record'''
token = request.headers['TOKEN']
t=Token.query.filter_by(token=token).first()
is_expired=t.status
if id is n... | the1Prince/drug_repo | app/deletes/deleteManufacturer.py | deleteManufacturer.py | py | 964 | python | en | code | 0 | github-code | 1 |
9257928467 | from tkinter import *
from random import choice
import pandas
# -------------------- CONSTANTS -------------------- #
BACKGROUND_COLOR = "#B1DDC6"
LANG_FONT = ("Arial", 40, "italic")
WORD_FONT = ("Arial", 60, "bold")
try:
word_data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
word_dat... | terryszhou/100-days-of-code-python | 31/flashcards.py | flashcards.py | py | 2,335 | python | en | code | 0 | github-code | 1 |
34842351600 | # Trapping Rain Water: https://leetcode.com/problems/trapping-rain-water/
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
# In this problem we can utilize a stack to append the left barrier as we move across the array wh... | KevinKnott/Coding-Review | Month 02/Week 02/Day 06/a.py | a.py | py | 3,949 | python | en | code | 0 | github-code | 1 |
33770943344 | month_english = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
month_chinese = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
week_english = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
week_chinese = ["一", "二",... | xungeer203/calendar | htmlmod.py | htmlmod.py | py | 1,155 | python | en | code | 0 | github-code | 1 |
35329125934 | #!/usr/bin/env python3
import os
import sys
import json
import re
from argparse import ArgumentParser
import hashlib
import copy
import subprocess
import uuid
import datetime
def get_app_info(wf_name, data_type):
app_info = {
"sanger-wxs": {
"snv": ["CaVEMan"],
"indel": ["Pindel"]... | icgc-argo-workflows/data-processing-utility-tools | tools/payload-generation/payload-generation.py | payload-generation.py | py | 12,859 | python | en | code | 0 | github-code | 1 |
25074566253 | ## 题目类型:数组
'''
Hashtable
一次遍历:time complexity: O(N)
**【字典中存放的是什么,return什么。有两种情况不要搞混了】**
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
## 01. 存放 target-num / 余数对应的序号,判断当前数num是否在字典中
d = dict()
for i, num in enumerate(nums):
if num in d:
... | jty-cu/LeetCode | Algorithms/001-twoSum.py | 001-twoSum.py | py | 788 | python | zh | code | 0 | github-code | 1 |
43064481866 | def triplets():
for i in range(1, 998):
a = i
for j in range(a+1, 999-a):
b = j
c = 1000 - a - b
if (a**2) + (b**2) == (c**2):
return a, b, c
if b >= c:
break
triplet = triplets()
print(triplet)
product = triplet[0] * t... | Hellheym/Euler-s-project | Problems/Special_Pythagorean_triplet.py | Special_Pythagorean_triplet.py | py | 357 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.