blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
0ef405a933a049278c1e1cee4daca7b4cbc80dda | Python | radomirbrkovic/algorithms | /dynamic-programming/exercises/tiling-problem.py | UTF-8 | 241 | 4.0625 | 4 | [] | no_license | # Tiling Problem https://www.geeksforgeeks.org/tiling-problem/
def getNoOfWays(n):
if n >= 0 and n <= 1:
return n
return getNoOfWays(n-1) + getNoOfWays(n - 2)
print(getNoOfWays(4)) #3
print(getNoOfWays(3)) #2 | true |
d3b98d8c5e0d8d79282ca30379cf8b9c341f86b7 | Python | soic1/lear_python_and_ethical_hacking_from_scratch | /Network_scanner/network_scanner.py | UTF-8 | 1,147 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python
import scapy.all as scapy
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--ip", dest="ip", help="IP address to be scanned")
options = parser.parse_args()
if not options.ip:
parser.error("Please enter a valid IP address")
... | true |
be50ead68a75680f96bd09ed4408515da1dc20e0 | Python | Harvus/CodaAcademy_Python_Code | /CodeAcademy_Code_Test01.py3 | UTF-8 | 4,269 | 4.1875 | 4 | [] | no_license | print("-------------------Turn up the Temperature-------------------")
print("")
#define the function called f_to_c
def f_to_c(f_temp):
return (f_temp - 32) * 5/9
print("Converting 70 Fahrenheit to celsius: ")
print(f_to_c(70))
print()
print()
#Define the var f100_in_celsius and set it equal to the value of f_to_c... | true |
e040257089538c0612e00974c0c136801e776602 | Python | Snooker4Real/Python_files | /Remplissage d'un cotour.py | UTF-8 | 4,093 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 13:51:56 2017
@author: jonathancindanomwamba
"""
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def F1(x,y):
norme = np.sqrt(x**2+y**2)
tx, ty = x/norme, y/norme
nx, ny = -y/norme, x/norme
return nx, ny,... | true |
9af9c28ab880b7c5e64d30e44b2582a756f21587 | Python | L1nwatch/leetcode-python | /717.1-比特与-2-比特字符.py | UTF-8 | 493 | 2.890625 | 3 | [] | no_license | #
# @lc app=leetcode.cn id=717 lang=python3
#
# [717] 1比特与2比特字符
#
# @lc code=start
class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
index = 0
length = len(bits)
while index < length:
if bits[index] == 1:
index += 2
continue
... | true |
954bfb7cca4800744eff56dbf504d2e96c360103 | Python | AnteDujic/pands-problem-sheet | /weekday.py | UTF-8 | 836 | 4.4375 | 4 | [] | no_license | # Program that outputs a different message depending if today is weekday or weekend
# Author: Ante Dujic
# Importing module datetime to work with dates as date objects
import datetime as dt
# Setting variable for current day
today = dt.datetime.now()
# Comparing current day (1-7)... | true |
b8a8d5b8110b0a1c9496699c3e0c62a10c52b1b4 | Python | lfdyf20/Leetcode | /Self Dividing Numbers.py | UTF-8 | 523 | 3.34375 | 3 | [] | no_license | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for num in range(left, right + 1):
snum = str( num )
if '0' in snum:
continue
if all( m... | true |
abb20e01bfcd82f5d8c0c37b0f9a08ca45dfb1ec | Python | dpasacrita/server_manager | /combat.py | UTF-8 | 3,681 | 3.96875 | 4 | [] | no_license | #!/usr/bin/python3.5
import random
# Globals
BASE_DAMAGE = 1
UNARMED_DAMAGE = 1
CRITICAL_MULTIPLIER = 2
def calculate_weapon_damage(char1):
"""
Calculate the damage that char1 will do against something
This is determined by rolling for how much damage char1 does based on their weapon.
:param char1: ... | true |
3d4555eb57d6e411797ecccb8e00326f650239f0 | Python | Hiroki39/CS-UY-1134 | /DataStructure/MeanQueue.py | UTF-8 | 785 | 3.578125 | 4 | [] | no_license | from ArrayQueue import ArrayQueue
class MeanQueue:
def __init__(self):
self.data = ArrayQueue()
self.curr_sum = 0
def __len__(self):
return len(self.data)
def is_empty(self):
return self.data.is_empty()
def enqueue(self, e):
if not isinstance(e, (int, float))... | true |
506f053a5695a697513ed9599f28d76c70069869 | Python | abhiunix/python-programming-basics. | /enumerate.py | UTF-8 | 745 | 4.78125 | 5 | [] | no_license | #Enumerate
#enumerate is a built in function that returns an iterator of tuples containing indices and values of
#a list. You'll often use this when you want the index along with each element of an iterable in a loop.
letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
#Quiz:... | true |
d25a4542b5c985f6f25236e6a73614b4dbbe26bc | Python | wolfhardfehre/olli-simulation | /app/app/routing/booking.py | UTF-8 | 1,265 | 2.828125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | class Booking:
counter = 1000
@classmethod
def get_counter(cls):
cls.counter += 1
return cls.counter
def __init__(self, start_node, end_node, earliest_departure, latest_arrival):
self.start_node = start_node
self.end_node = end_node
self.earliest_departure = ear... | true |
eade6654f0b57fda51ef76d0e7d1682a0b5f2a80 | Python | jianmink/geoip2dataloader | /src/e164cc.py | UTF-8 | 2,020 | 2.515625 | 3 | [] | no_license |
import time
import unittest
e164ccList=[]
def load():
with open("./result_e164cc2mcc.csv_ready4use",'r') as f:
for record in f:
fields = record.split(',')
e164ccList.append(fields[0].strip())
#print e164ccList
def e164cc(vlrnum):
cc = ""
for e... | true |
ee551a5d173107f4a1b8442a7c67db1a01ab010a | Python | Aasthaengg/IBMdataset | /Python_codes/p02802/s411687593.py | UTF-8 | 351 | 2.75 | 3 | [] | no_license | N, M = map(int, input().split())
Q = [list(map(str, input().split())) for _ in range(M)]
ans = [0] * N
AC = 0
WA = 0
for P in Q:
p = int(P[0])
S = P[1]
if ans[p - 1] == "END":
continue
if S == "WA":
ans[p - 1] += 1
if S == "AC":
WA += ans[p - 1]
AC += 1
ans[... | true |
597c9464fd5e75ea66273fb08ef59bf335524952 | Python | fall-2018-csc-226/t04-master | /t04_refactored.py | UTF-8 | 46,535 | 3.953125 | 4 | [
"MIT"
] | permissive | ######################################################################
# Author: The Fall 2018 226 Class!
#
# Assignment: T04: Adventure in Gitland
#
# Purpose: To recreate a choose-your-own-adventure style game
# by refactoring T01.
#
# Each "twist" in the story is from a different group. The resulting story
# will ei... | true |
26be0f6fb3c405cafb11dc0cc6c6ba1494140a29 | Python | han8909227/data-structures | /src/test_graph_1.py | UTF-8 | 8,220 | 3.546875 | 4 | [
"MIT"
] | permissive | """Test for Graph_1."""
import pytest
from graph_1 import Graph
@pytest.fixture(scope='function')
def graph_1():
"""Making one empty graph instance per test."""
return Graph()
@pytest.fixture(scope='function')
def graph_5():
"""Making one graph instance with len of 5 per test."""
g = Graph()
g.a... | true |
6d94a187fa3532c4329b573c8da0f527f2dfaa29 | Python | Yuchen-Yan/movie-recommender-anna | /endpoint/api.py | UTF-8 | 13,275 | 2.765625 | 3 | [] | no_license | import difflib
import json
import re
import itertools
import ast
from functools import wraps
import pandas as pd
from flask import Flask
from flask import request
from flask_restplus import Resource, Api
from flask_restplus import abort
from flask_restplus import fields
from flask_restplus import inputs
from flask_res... | true |
20d6a7a57ef3db70b48986750eac1bd298b6945d | Python | hebe3456/algorithm010 | /Week01/9.回文数.py | UTF-8 | 640 | 3.78125 | 4 | [] | no_license | #
# @lc app=leetcode.cn id=9 lang=python3
#
# [9] 回文数
#
# @lc code=start
class Solution:
def isPalindrome(self, x: int) -> bool:
# 暴力法:
# 如果是负数,return False
# 如果是正数,列表或字符串切片
# str:80ms, 80.33%
# list:100ms, 35.03%
if x < 0: return False
if len(str(x)) < 2: re... | true |
11c2d514eb3e354b938c9968ca74496bd5ebb6b8 | Python | TheVinhLee/Python | /learning/Advanced_Python/Functions/variable_argument_lists_start.py | UTF-8 | 831 | 4.28125 | 4 | [] | no_license | # Demonstrate the use of variable argument lists
# TODO: define a function that takes variable arguments
def addition(*args):
"""
addition(*args) : sum of all input argument with unknown number of arguments
and it is only has 1 list param rather than (base, *args)
if (base, *args), first param will be ... | true |
226b16c46edad14f9b24a357a7e58b3a23e827b1 | Python | musabbirsaeed/usaspending | /analysis2020Oct18-2.py | UTF-8 | 1,721 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 12:37:00 2020
@author: Mohammed kamal
[Read the csv files from /data/backups/.spyder-py3/data_noflt/*.csv
and create table name ends withh _Cnt and append for all agencies]
1. Populate “allagency1” table based on allaward and filteredaward
... | true |
428c39601b2c3827808e7cc46fe54ad144cdb001 | Python | ys0823/python-100examples | /100 examples/93.py | UTF-8 | 623 | 3.09375 | 3 | [] | no_license | #---------------------------------------------------
#题目:使用python把每隔一分钟访问200次的IP,加到黑名单。
#要求:每隔一分钟读区一下日志文件,把统计到的Ip添加到黑名单。
#2018-9-4
#---------------------------------------------------
import time
pin = 0
while True:
ips = []
fr = open(r'kms10.log')
fr.seek(pin)
for line in fr:
ip = line.split()[... | true |
1feaf761a25db9a5dbc2ce509510dd2fac97bd50 | Python | GG-yuki/bugs | /python/ijcai_spider/test.py | UTF-8 | 264 | 3.078125 | 3 | [] | no_license | import re
with open("test_links.txt", "r") as f: # 打开文件读取信息
for line in f.readlines():
# line = line.strip('\n') # 去掉列表中每一个元素的换行符
print(re.findall(r'https://www.google.com/search\?q=(.*)', line)[0]) | true |
0ca355e41e70b8419c2056d93f49be00af3b731c | Python | xb-chang/SCT | /src/SCT/models/fs_model.py | UTF-8 | 959 | 2.84375 | 3 | [] | no_license | import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
from yacs.config import CfgNode
class Fs(nn.Module):
"""
Fs(Z)
"""
# noinspection PyPep8Naming
def forward(self, Z: Tensor, T: int) -> Tensor:
"""
Predicts the temporal action probabilities S using the i... | true |
79dd49e554c6f8b9f98c2cd117ea470486038f89 | Python | MarkErickson02/Reddit-Submission-Stream | /PRAW_Stream_Bot.py | UTF-8 | 4,758 | 2.828125 | 3 | [] | no_license | from praw.exceptions import PRAWException
import DictionaryUtility
import UserStatistics
import config
import praw
import time
class StreamBot:
def __init__(self):
self._utility = DictionaryUtility.DictionaryUtility()
self._user_stats = UserStatistics.UserStatistics()
self._reddit = None
... | true |
7b11fa584de0e712694706759da3f2dd73740853 | Python | scxr/eco-dcbot | /cogs/rain.py | UTF-8 | 1,741 | 2.84375 | 3 | [] | no_license | from discord.ext import commands
import random, json, discord
class Rain(commands.Cog):
"""Rain is a cog for the bot to make it rain."""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.guild)
async def rain(self, ctx... | true |
adff3cb191a4a471eab05421921e1d68254a69b6 | Python | sbavington/Graphing | /JmeterPerfmonGraphs.py | UTF-8 | 2,261 | 2.515625 | 3 | [] | no_license | from matplotlib import pyplot as plt
from matplotlib import style
import datetime
data_noopt = open("./NoOpt.csv", "r")
data_t4 = open("./Opt.csv", "r")
data_crypt = open("./Crypt.csv", "r")
cpu_percent_noopt = []
cpu_percent_t4 = []
cpu_percent_crypt = []
mem_noopt = []
mem_t4 = []
mem_crypt = []
for line in data_n... | true |
2f9979c9c223cf53e18bb3a613e91b0d76afc127 | Python | Yhatoh/ProgramacionCompetitivaUSM | /soluciones/RPC/2020-6/E_Auteams.py | UTF-8 | 824 | 3.296875 | 3 | [
"MIT"
] | permissive | rima=input().strip().split()
n=int(input())
niños=[]
equipo1=[]
equipo2=[]
for i in range (0,n):
temp=input()
niños.append(temp)
while (len(niños)>0):
if len(niños)>n//2:
if(len(rima)<=len(niños)):
equipo1.append(niños[len(rima)-1])
niños.pop(len(rima)-1)
... | true |
21d92cf2e0027b977d30c7f7af3383d0331e1ed0 | Python | baejinsoo/TIL | /4th/파이썬/python_programming_stu/Practice/prac_2.py | UTF-8 | 577 | 4 | 4 | [] | no_license | # # 일반적인 함수 정의
# def add(x, y):
# return x + y
#
#
# print(add(10, 20))
#
# # 람다식 사용
# my_add = lambda x, y: x + y
# print(my_add(10, 34))
#
# square = lambda x: x ** 2
# print(square(4))
#
# multi = lambda x, y: x * y
# print(multi(40, 3))
#
# division = lambda x, y: x / y
# print(division(50, 5))
my_arr = [1, 2... | true |
cb91e549164dc95e60134918b70a3fc4fe3a3ab0 | Python | PieterVDMerwe/Project | /Project/Code/untitled0.py | UTF-8 | 314 | 2.5625 | 3 | [] | no_license | import scipy.integrate as scii
import scipy.constants as scic
import math as mt
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as scio
from scipy.special import hyp2f1
def f(x):
return 1.0*x - 1.0/x;
x = np.arange(0.0,10.0,0.001);
plt.plot(x,f(x));
plt.ylim(-30.0,30.0);
plt.show(); | true |
a9f8c00c778ed0e92b6abf7dbeeb1135e3424603 | Python | amirocha/doktorat | /uv/serpens/profiles/divide_fluxes.py | UTF-8 | 3,916 | 2.828125 | 3 | [] | no_license | '''Divide fluxes (total/wings)'''
def read_data():
total = []
wings = []
file1 = open('fluxes_profiles_wings.txt','r')
lines = file1.readlines()
for i in range(1,len(lines)):
if i%3 == 1:
total.append(float(lines[i].split()[3]))
elif i%3 == 2:
wing = float(lines[i].split()[3])
else:
wings.append... | true |
c25d8314c067ed17bd3201837e5b7966408062a7 | Python | KylinHuang7/Account | /bin/add_type.py | UTF-8 | 879 | 2.75 | 3 | [] | no_license | #!/usr/local/bin/python2.6
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import sys
import MySQLdb
def showhelp():
print("Usage: $0 type")
def add_type(title):
conn = MySQLdb.connect(read_default_file='/var/www/accounts/conf/my.cnf', read_default_group="mysql")
cursor = conn.cur... | true |
29aae9a2e1e53d6e699498af333af569020390ce | Python | exmakhina/xm_rst | /xm_rst_log.py | UTF-8 | 3,045 | 2.515625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 vi:noet
# Log writing utilities
import sys, os, io, subprocess, time, datetime, uuid, hashlib, base64, struct, binascii
def printf(x):
sys.stdout.write(x)
sys.stdout.flush()
def log_echo(txt):
cmd = "xclip -selection clipboard".split()
proc = subprocess.Popen(cmd, stdin... | true |
14942cd28af655814c60542f51cf8274f79f36d0 | Python | beebopkim/spartan_algorithm | /week_2/homework/02_is_available_to_order.py | UTF-8 | 394 | 3.484375 | 3 | [] | no_license | shop_menus = ["만두", "떡볶이", "오뎅", "사이다", "콜라"]
shop_orders = ["오뎅", "콜라", "만두"]
def is_available_to_order(menus, orders):
order_possible = True
for order in orders:
if not (order in menus):
order_possible = False
break
return order_possible
result = is_available_to_order(... | true |
85ed991610112e3c1f9a6f4cf6407caa8cf42d8e | Python | amezysk/aoc2020 | /day6.py | UTF-8 | 344 | 2.875 | 3 | [] | no_license | #!/usr/bin/env python3
lines=[]
with open('tmp') as f:
lines = f.readlines()
first=1
total=0
for l in lines:
if first==1:
q=set(l)
first=0
elif l!="\n":
q=q.intersection(set(l))
else:
q.discard("\n")
first=1
total=total+len(q)
q.clear()
total=to... | true |
3c7e6f534e16befa1c3344718e1e4ffadc36c97e | Python | fredrb/advent-of-code-2020 | /23/part1.py | UTF-8 | 2,295 | 3.46875 | 3 | [] | no_license | example = [3, 8, 9, 1, 2, 5, 4, 6, 7]
puzzle = [9, 2, 5, 1, 7, 6, 8, 3, 4]
class Node():
def __init__(self, value, n=None):
self.next = n
self.value = value
class CircularLinkedList():
def __init__(self, initializer):
self.head = Node(initializer[0], None)
cn = self.head
for v in reversed(init... | true |
118808d89269f85d8c6586a58d1ee5e74320ed37 | Python | ferpoletto/Estudos-Python | /CursoEmVideo/ex053 - Palindromos.py | UTF-8 | 443 | 3.75 | 4 | [] | no_license | frase = input("Digite uma frase: ").strip().upper()
print(f'Você digitou a frase {frase}')
palavras = frase.split()
print(palavras)
semespaco = ''.join(palavras)
print(semespaco)
inverso = ''
for i in range(len(semespaco)-1, -1, -1):
inverso += semespaco[i]
if frase == inverso:
print(f'A frase digitada é um... | true |
80d6b14558f51f19d47b16dc91c8f0ecc7b0ffee | Python | phac-nml/irida-galaxy-importer | /irida_import/sample_pair.py | UTF-8 | 1,163 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | """
Copyright Government of Canada 2015-2020
Written by: National Microbiology Laboratory, Public Health Agency of Canada
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License at:
http://www.apache.org/lic... | true |
f9261c1844cc629c91043d1221d0b76f6e22fef6 | Python | ningyuuu/test-gsheets | /gsheets.py | UTF-8 | 2,345 | 2.671875 | 3 | [] | no_license | import os.path as path
from googleapiclient.discovery import build
from google.oauth2 import service_account
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1FSMATLJUNCbV8... | true |
6695532eef823ae3eec77cc8e9cc49fd5f275ef1 | Python | koblas/thistle | /py/thistle/safestring.py | UTF-8 | 5,315 | 3.171875 | 3 | [] | no_license | """
Functions for working with "safe strings": strings that can be displayed safely
without further escaping in HTML. Marking something as a "safe string" means
that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
d... | true |
93ccac9aa75c1b30f717333e48bb14cd41493d8f | Python | matthewdeanmartin/json_kata | /python/simple_calls/time_it_class.py | UTF-8 | 1,480 | 3.828125 | 4 | [
"MIT"
] | permissive | """
Basic utility code to show perf.
Could also have been implemented as a decorator.
usage
with time_it():
do_something_slow()
More elaborate usages
with time_it(show=False) as clock:
for _ in range(0, 10):
single()
print("Average %s" % clock.format_time(clock.elapsed() / 10))
"""
import math
... | true |
1c6158f1c18ae6302b9adef01c7c75d46a6a27c2 | Python | MauVlad/Mytest | /ev3dev/texto/F/funcion.py | UTF-8 | 152 | 2.90625 | 3 | [] | no_license | def fun():
x = raw_input("escribe algo: ")
if x == 'hola':
print (x + 'hola')
elif x == 'adios':
print (x + 'hola')
else:
print x
fun()
| true |
188de9456c7ba51a481bced7f47eccc723720369 | Python | lewsn2008/learning_examples | /gensim/text_classification/sense_classifier.py | UTF-8 | 7,505 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python
#coding=utf8
from __future__ import print_function
import argparse
import logging
import re
import sys
from gensim.corpora import Dictionary
from scipy.sparse import csr_matrix
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection im... | true |
6b8c7a87ba0c0479bc4916ca0503038447db6acd | Python | FreddyLimachi/rest-api-user-auth | /app/app_users/validators.py | UTF-8 | 1,615 | 3.1875 | 3 | [] | no_license | import re
def validate(username, email, password, confirm_pass, user, verify_email):
if len(username) < 5 or len(username) > 15:
return {'value': False, 'msg': 'El username debe contener entre a 5 a 15 carácteres'}
elif re.match("^[a-zA-Z0-9_-]+$", username) is None:
return {'value': False, ... | true |
e2fb788d0c8a32487e5bd751c855b501d577b5fa | Python | eeshadutta/SMAI-Assignments | /Class Assignments/HW8/3.py | UTF-8 | 828 | 3.078125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
x = np.array([[0,0],[3,0],[4,2],[1,2]])
parallelogram = np.array([[0,0],[3,0],[4,2],[1,2],[0,0]])
mu = np.array([np.mean(x[:,0]),np.mean(x[:,1])])
print('mean = ',mu)
sigma = np.cov(x.T)
print('Covariance = \n', sigma)
eigvals, eigvecs = np.linalg.eig(sig... | true |
2f0823a779326a597ca585ddc9773b06d3cc629f | Python | zzz136454872/leetcode | /numberOfMatches.py | UTF-8 | 154 | 2.875 | 3 | [] | no_license | from typing import List
class Solution:
def numberOfMatches(self, n: int) -> int:
return n - 1
n = 7
print(Solution().numberOfMatches(n))
| true |
a86c1e5c7bc563209e47ae55c5bc13c3a1224366 | Python | toguchi-taichi/study-03-desktop-01-master | /search.py | UTF-8 | 700 | 2.9375 | 3 | [] | no_license | import pandas as pd
import eel
### デスクトップアプリ作成課題
def kimetsu_search(word, csv_save):
# 検索対象取得
df=pd.read_csv("./{}".format(csv_save))
source=list(df["name"])
# 検索
if word in source:
print("『{}』はあります".format(word))
return "『{}』はあります".format(word)
else:
print("『{}』はありません。... | true |
8f34ede92589f487793efc2054f738e26cb8c28a | Python | erikkrasner/Project-Euler | /prob3_solution.py | UTF-8 | 300 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
# 6857
# 0.402 s
import sys
from prime_gen import *
def largest_prime_factor(n):
for p in primes():
while not n % p:
n /= p
if n == 1:
return p
if p * p > n:
return n
print largest_prime_factor(int(sys.argv[1]) if sys.argv[1:] else 600851475143)
| true |
ca1b30ccbc289ab34fab825ff0236793b6366c4a | Python | martinleeq/python-100 | /day-09/question-076.py | UTF-8 | 266 | 3.265625 | 3 | [] | no_license | """
问题75
运用zlib包对"hello world!hello world!hello world!hello world!"进行压缩和解压
"""
import zlib
s = 'hello world!hello world!hello world!hello world!'
out = zlib.compress(bytes(s, 'utf-8'))
print(out)
plain = zlib.decompress(out)
print(plain) | true |
82d641bdd168200c286719934e85de50ea3dfcca | Python | Greenwicher/Competitive-Programming | /CodeForces/Python3/598C.py | UTF-8 | 1,626 | 3.359375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 20:47:21 2016
@author: liuweizhi
"""
#%% Version 1
from math import *
# stores counterclockwise angle between vector (1,0) and each vector in a
a = []
n = int(input())
for _ in range(n):
x,y = map(int,input().split())
# calculate counterclockwise angle between... | true |
ae193cdaf57f6ff979b4eae3a956a62541bc9050 | Python | neurord/moose_nerp | /moose_nerp/prototypes/logutil.py | UTF-8 | 1,374 | 2.5625 | 3 | [] | no_license | import inspect
import logging
class Message(object):
def __init__(self, fmt, args):
self.fmt = fmt
self.args = args
def __str__(self):
return self.fmt.format(*self.args)
class StyleAdapter(logging.LoggerAdapter):
def __init__(self, logger, extra=None):
super(StyleAdapter, ... | true |
7792e82d54c4d091af54cd35cfe9b304d871d575 | Python | tectronics/wepoco-web | /mpe_tools/process/map_tiles_mpe.py | UTF-8 | 3,841 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python
# Michael Saunby. For Wepoco.
# $Date$
#
# The last MPE (grib) file of the day will trigger the creation of a PNG
# image.
# For each of the reporojection LUT files in lutdir this
# script will generate a map tile for use with Google Maps.
##############################################################... | true |
d52bc47431b63e6ba17a10836f16d321f1f0ca14 | Python | j4velin/photobooth | /trigger.py | UTF-8 | 1,815 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import socket
import sys
import time
import RPi.GPIO as GPIO
import os
import fcntl
import struct
from functools import partial
from multiprocessing import Pool
PORT = 5555
GPIO_TRIGGER_PIN = 4
TAKE_PHOTO_CMD = "TAKE_PHOTO\n"
SCANNER_WORKERS = 10
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socke... | true |
2f336cfa8b738a8fc9b756afd71870c7fb6282ce | Python | EstelleDutheil/Bronkhorst_flux_afficheur | /convertisseur_string_chr_en_n_hexaDecimal.py | UTF-8 | 341 | 2.625 | 3 | [] | no_license | from convertisseur_1int_1byte import conversion_1int_1byte
def conversion_string_chr_en_n_hexaDecimal(chaine_chr):
hexaDecimal=b''
for bla in range(0,(len(chaine_chr))):
caractere=chaine_chr[bla]
caractere=ord(caractere)
caractere=conversion_1int_1byte(caractere)
hexaDecimal=hexaDecimal+caractere
... | true |
215a65925829c83877f23339ed67e8abfa658383 | Python | Percygu/algorithm | /leetcode/compare1.py | UTF-8 | 593 | 3.140625 | 3 | [] | no_license | if len(self.hashmap) == self.capacity:
# 去掉哈希表对应项
self.hashmap.pop(self.head.next.key)
# 去掉最久没有被访问过的节点,即头节点之后的节点
self.head.next = self.head.next.next
self.head.next.prev = self.head
# 如果不在的话就插入到尾节点前
new = Node(key, v... | true |
a40d2615c71e90cc59f66435915fdf0ce839b0ae | Python | GoncharovVS/GBlearn | /hw03_easy.py | UTF-8 | 2,332 | 4.15625 | 4 | [] | no_license | __author__ = "Гончаров Всеволод Сергеевич"
while True:
print("Введи номер задачи (1-2) или 0 для выхода")
key = int(input())
# Задание-1:
# Напишите функцию, округляющую полученное произвольное десятичное число
# до кол-ва знаков (кол-во знаков передается вторым аргументом).
# Округление должн... | true |
7ed8299433df092aeb60b4592d32790f7d74eb0a | Python | Hiking-Apprentice/python_spider | /scrapy携带cookies爬取拉勾网职位/LGW/LGW/spiders/lgw.py | UTF-8 | 1,246 | 2.546875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
import re
from ..items import LgwItem
class LgwSpider(CrawlSpider):
name = 'lgw'
allowed_domains = ['lagou.com']
start_urls = ['https://www.lagou.com/jobs/6877483.html']
ru... | true |
4ff25e436aa6f8086adaa1a5ffd709994c35fa71 | Python | bielskin/NoStop | /NoStop.py | UTF-8 | 1,617 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 16:20:16 2021
@author: NVB
"""
import argparse
parser = argparse.ArgumentParser(description='NOSTOP: Removes stop codons from a codon aligned fasta formatted nucleotide file and replaces with gaps')
requiredNamed = parser.add_argument_group('re... | true |
f95f03e909635277015eb5e0f64e9a84e853c0cf | Python | vanisatish/API_SeleniumPython | /GET_Request/FetchUserData.py | UTF-8 | 659 | 3.296875 | 3 | [] | no_license | import requests
import json
import jsonpath
url = "https://reqres.in/api/users?page=2" # API URL
# Send GET request
response = requests.get(url)
print(response)
# display response content
print(response.content)
print(response.json())
print(response.headers)
# another way to print response data usin... | true |
751ec1918ceca0584afe160504d543db39441af9 | Python | tlherr/PythonChallenge | /Question1.py | UTF-8 | 62 | 2.5625 | 3 | [] | no_license | import url
number = (2 ** 38)
# Question 1
url.format(number) | true |
23425f83b531e0bf945b51c5b02a5c071e8edfb8 | Python | seamustuohy/dockerfiles | /cyobstract/get_indicators_from_url.py | UTF-8 | 2,700 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © 2018 seamus tuohy, <code@seamustuohy.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at... | true |
0cc9504f313a89df5c2949649b100ed9fd40ab2e | Python | kabilankarunakaran/FakeLabVideo | /inference_video.py | UTF-8 | 3,293 | 2.625 | 3 | [] | no_license | import numpy as np
import torch
from model import create_model
from utils import get_face_crop, parse_vid, predict_with_model, get_front_face_detector
import shutil
import os
import uuid
import datetime
from mysqlhelper import *
from PredictionInfo import *
import cv2
def pred_test(v_path, start_frame=0, end_frame=15... | true |
626e225caf22bcc0d953f5f250a5ade7db845ad7 | Python | changhengliou/ECE-GY-9123-DL-final | /Paper2PPT/baselines/LexRank/example.py | UTF-8 | 2,849 | 2.578125 | 3 | [] | no_license | from lexrank import STOPWORDS, LexRank
from path import Path
documents = []
documents_dir = Path('bbc/politics')
for file_path in documents_dir.files('*.txt'):
with file_path.open(mode='rt', encoding='utf-8') as fp:
documents.append(fp.readlines())
lxr = LexRank(documents, stopwords=STOPWORDS['en'])
sen... | true |
303afc4bd70cc10b7286dc1077ec10f40cda2b2a | Python | jsawatzky/ICS3UI | /src/Unit 4 Arrays/Assignment/sky.py | UTF-8 | 1,548 | 2.96875 | 3 | [] | no_license | '''
Created on Nov 8, 2014
@author: Jacob
'''
from utilities import *
class Sky():
def __init__(self, queue):
self.queue = queue
colors = {}
colors['sunrise'] = "#FFC012"
colors['sunset'] = "#DE8501"
colors['day'] = "#3AA0FF"
colors['night'] = "#121C43"
... | true |
065c64bfa8463ea62ae0c1b099d848c0065b8ad4 | Python | squadran2003/build_a_soccer_league | /league_builder.py | UTF-8 | 4,554 | 3.515625 | 4 | [
"MIT"
] | permissive | import csv,sys,datetime
num_of_teams = 3
# assign 3 teams Raptors,Sharks,Dragons
Raptors = [] # team1
Sharks = [] # team2
Dragons = [] # team3
exp_and_non_exp_players_count = 0 # hold on to the count for exp and non exp players
experienced_players=[]# will hold all exp players
non_experienced_players=[]#... | true |
d6a72ee4bc4cd43a6f63d8b3ae80751cceb5ca18 | Python | ktritz/fdp | /fdp/methods/fft.py | UTF-8 | 1,863 | 2.671875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 8 16:28:32 2016
@author: drsmith
"""
from warnings import warn
import matplotlib.pyplot as plt
from fdp.classes.utilities import isSignal, isContainer
from fdp.classes.fdp_globals import FdpWarning
from fdp.classes.fft import Fft
from . import utilities as UT
def fft... | true |
ab18e50c659df0f08f94d96c7ad9530519ebbc7b | Python | vivekbarsagadey/accent | /accent-poc/src/recommender.py | UTF-8 | 2,148 | 3.28125 | 3 | [
"MIT"
] | permissive | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
import numpy
texts = ["This first text talks about houses and dogs",
"This is about airplanes and airlines",
"This is about dogs and houses too, but also about ... | true |
c7219d38fc264d9ee9553fe1958485c2fc64fd0e | Python | Aatish-Dhami/AD_Leetcode | /_1281.py | UTF-8 | 317 | 3.15625 | 3 | [] | no_license | class Solution:
def subtractProductAndSum(self, n: int) -> int:
sum = 0
product = 1
while n > 0:
sum = sum + (n % 10)
product = product * (n % 10)
n //= 10
return (product - sum)
n = 4421
c1 = Solution()
x = c1.subtractProductAndSum(n)
print(x) | true |
e3b50bf3ccf72dcc9c35a715cca4c3c877c57102 | Python | nailbiter/panoptic-submission | /py/image_analyzer.py | UTF-8 | 1,080 | 2.84375 | 3 | [] | no_license | import sys;
import cv2;
import argparse;
#procedures
def parseArgs():
parser = argparse.ArgumentParser();
parser.add_argument('--mode',type=str,default='COUNTPIXELS',help='');
parser.add_argument('files',type=str,nargs='+');
args = parser.parse_args();
return vars(args);
def countPixels(filename,a... | true |
d163b0d227a72608eb83ed04fa43c87fd610dc83 | Python | zx1989031/pytest | /layNumber.py | UTF-8 | 80 | 2.6875 | 3 | [] | no_license | #coding:utf8
strnum = {}
for x in range(0,12,1):
strnum[x]=x+1
print strnum | true |
c62213f45798ce4647c55c1efaf0c773cfa105df | Python | TPei/Base-Converter | /Python/decode.py | UTF-8 | 570 | 4.25 | 4 | [] | no_license | '''
decode a number from any base to base 10
'''
def decode(number, source_base):
result = 0
number_of_digits = len(number)
for index in range (0, number_of_digits):
digit = number[index]
result = result + int(digit) * pow(source_base, index)
return result
if __name__ == '__main__':
print 'Encoding a number... | true |
c90d623de4138ad7720a409ffa454bc79f07bd9d | Python | maumruiz/BasicAgents | /PartiallyObservableEnvironment.py | UTF-8 | 1,634 | 3.09375 | 3 | [] | no_license | import numpy as np
from FullyObservableEnvironment import FullyObservableEnvironment
from ModelBasedAgent import ModelBasedAgent
from agents import *
from Objects import *
'''
This class is a representation of a Partially Observable Environment
where some of the information required for optimal decision maki... | true |
6616f3fe79952179209f75a0eae475d9fa391ffe | Python | destinyu/Python_Crash_Crouse | /traceback_practise_10.py | UTF-8 | 577 | 4.15625 | 4 | [] | no_license | #10——6
print("Give me two numbers,and i'll plus them.")
print("Enter 'q' to quit.")
while True:
first_number=input("\nFirst number: ")
if first_number=='q':
break
second_number=input("\nSecond number: ")
try:
answer=int(first_number)+int(second_number)
except ValueError:
pri... | true |
1254fa3256bf5bc4fbcb494cee21c51c45265c75 | Python | Statistical-model-in-R-and-Python/python-data-science-indrani-sen2003 | /hello_test.py | UTF-8 | 88 | 2.515625 | 3 | [] | no_license | import pandas as pd;
df=pd.read_csv("Walmart2.csv");
df.dtypes
df.head(15)
df.tail(15)
| true |
631316cfc067232103503a5696be32c7df73dd98 | Python | Jigar710/Python_Programs | /networking/client3.py | UTF-8 | 275 | 2.796875 | 3 | [] | no_license | import socket
ip = socket.gethostname()
port = 1600
s = socket.socket()
s.connect((ip,port))
while True:
msg = s.recv(1024).decode()
print("server says :",msg)
if msg=='bye':
break;
msg = input("Enter msg : ")
s.send(msg.encode())
if msg=='bye':
break; | true |
454ab20a3eb0cb13da1248ae1f1690f792efd0e6 | Python | Zer0xPoint/Algorithms4_python | /1.Fundamentals/3.Bag Queue And Stack/44.py | UTF-8 | 880 | 3.625 | 4 | [] | no_license | import random
from algs4.Stack import Stack
class Buffer:
def __init__(self):
self.__right = Stack()
self.__left = Stack()
self.__N = 0
def insert(self, c):
self.__right.push(c)
self.__N += 1
def delete(self):
self.__N -= 1
return self.__right.pop... | true |
0d6fee50cea3d9e1898079b37846a6748f42aa3c | Python | imrivera/TuentiChallenge2013 | /18 - Energy will be infinities/18-energy_will_be_infinities.py | UTF-8 | 3,930 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env pypy
# -*- coding: utf-8 -*-
# Tuenti Challenge 3
#
# Challenge 18 - Energy will be infinities
# To infinity and beyond!
import sys
# First find the strongly connected components of the graph with Tarjan's algorithm
# and then apply the Bellman-Ford in each of the components to find positive cycles
... | true |
243c48d3e28d41d0c18072f52da223e3d8a75d24 | Python | Devin6Tam/python_example | /ting89_vocal_story/vocal_story_example01.py | UTF-8 | 2,046 | 2.53125 | 3 | [] | no_license | """
============================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/9 15:00
# @Author : tanxw
# @Desc : 幻听网-有声小说
============================
"""
from urllib.parse import urljoin
from lxml import etree
import re
import requests
def downs(url):
headers = {
'User-Agent' : '... | true |
3bf47f159ef311013ffc18fe6f9ce8cd0707b435 | Python | ShadowElf37/ProjectMercury | /lib/server/response.py | UTF-8 | 10,658 | 2.515625 | 3 | [] | no_license | """
response.py
Project Mercury
Yovel Key-Cohen and Alwinfy
"""
ENCODING = 'UTF-8'
from os.path import dirname, realpath
from re import split
from urllib.parse import unquote
def create_navbar(active, logged_in):
"""kwargs should be 'Home="home.html"'; active should be "home.html" """
navbar = []
pages =... | true |
a14971229dd10bbf9c7dfd17279968e09c032f17 | Python | olesmith/SmtC | /Display/Body.py | UTF-8 | 1,710 | 3.0625 | 3 | [
"CC0-1.0"
] | permissive |
class Display_Body():
##!
##! Generates HTML BODY.
##!
def Display_Body(self):
html=[]
html=html+[ self.XML_Tag_Start("BODY") ]
args={
"width": "100%",
"border": "1",
}
html=html+[ self.XML_Tag_Start("TABLE",... | true |
33914735ea94144c7b60c53804da26414f7f9154 | Python | uwescience/raco | /raco/myrial/keywords.py | UTF-8 | 825 | 2.625 | 3 | [] | no_license | """Emit all Myrial/SQL keywords as lowercase strings."""
from raco.myrial.scanner import (builtins, keywords,
types, comprehension_keywords,
word_operators)
from raco.expression.expressions_library import EXPRESSIONS
def get_keywords():
"""Return ... | true |
cf7da661b542146c48e735dc600f69aa99c547ca | Python | sunminky/algorythmStudy | /알고리즘 스터디/3차/16주차/GasStation.py | UTF-8 | 971 | 3.171875 | 3 | [] | no_license | # https://www.acmicpc.net/problem/13305
import sys
if __name__ == '__main__':
n_gasStation = int(sys.stdin.readline())
distance = list(map(int, reversed(sys.stdin.readline().split())))
cost_dict = dict() #기름가격별 도착지에서 가장 먼 노드 저장
max_distance = 0 #출발지에서 도착지의 거리
cur_loc = 0
answer = 0
fo... | true |
62843076f2c47d90996122d6ff4a742809818b9e | Python | 10qpal/kfq_python | /flask/flaskjinja/app.py | UTF-8 | 1,206 | 2.640625 | 3 | [] | no_license | from flask import Flask, request, render_template, send_from_directory, redirect, url_for
import os
UPLOAD_DIRECTORY = os.path.dirname(__file__)+'/files'
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.ht... | true |
49dd082a63132526c9b78b502e7cb2365ab34f2d | Python | kharddie/is-pepsi-okay | /IsPepsiOkay/database/better_pop.py | UTF-8 | 1,109 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
import os
import MySQLdb
import sys
import re
from bs4 import BeautifulSoup
def check_type(column_names):
"""
column_names: (list of strings) MySQL column names)
"""
t = {}
def build_query(filename, table_name, column_names, column_numbers,
type_convert, offset=0):
"""
... | true |
4c55e96bec6501d9885a232b587c4d63a1ec79d6 | Python | Hygens/hackerearth_hackerrank_solutions | /python_problems_competitive/LittleShinoandFibonacci_2.py | UTF-8 | 702 | 2.875 | 3 | [] | no_license | from decimal import Decimal,getcontext
import sys
sys.setrecursionlimit(10000000)
getcontext().prec=10**1000
M = 1000000007
def fibSum2(n):
v1, v2, v3 = Decimal(1), Decimal(1), Decimal(0)
if n==0 or n==1: return 0
elif n==2: return 1
else:
n+=1
for rec in bin(n)[3:]:
cal... | true |
f0d6283f9b1f79247ff70268cdf983228cd0c3f6 | Python | HectorZetino/PythonPractices | /Problems/Update a list/task.py | UTF-8 | 58 | 3.109375 | 3 | [] | no_license | numbers = [4, 1, 0, 3, 2, 5]
numbers.sort()
print(numbers) | true |
e7594334c9993e0fe65f5fd758e78d402ca66698 | Python | devmittal/EID-Final-Project | /mic.py | UTF-8 | 3,676 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python3
import pyaudio
import wave
import logging
import boto3
import time
from botocore.exceptions import ClientError
import json
import requests
form_1 = pyaudio.paInt16 # 16-bit resolution
chans = 1 # 1 channel
samp_rate = 44100 # 44.1kHz sampling rate
chunk = 4096 # 2^12 samples for buffer
record_s... | true |
7604750c6e0996b5e624c23947d1bc277e6caf4e | Python | zy31415/blackjack | /blackjack/game.py | UTF-8 | 2,981 | 3.109375 | 3 | [] | no_license | import random
from .player import Player, Dealer
class Game(object):
def __init__(self, player=None):
self.dealer = None
self.player = Player() if player is None else player
self.dealer = Dealer()
self.verbose = True
self.faceup = None
@staticmethod
def draw():
... | true |
33ced9682d05a054df234f452505ba56708eef60 | Python | almirms/adventofcode | /day5/trampolines.py | UTF-8 | 1,191 | 3.390625 | 3 | [] | no_license | import os
import input_file
def jump(current_position, jumps):
jump_size = int(jumps[current_position])
jumps[current_position] = int(jumps[current_position]) + 1
current_position += jump_size
return current_position, jumps
def jump_part2(current_position, jumps):
jump_size = int(jumps[current... | true |
2c10674189b5af01750b90e15403f3c7ccb02369 | Python | lazyjek/MachineLearning-Course | /homework3/src/main.py | UTF-8 | 1,036 | 2.734375 | 3 | [] | no_license | import sys
from data_provider import data_provider
from cv import CrossValidate
from perceptron import Perceptron
if __name__ == '__main__':
try:
trainFileName = sys.argv[1]
nfolds = int(sys.argv[2])
learningRate = float(sys.argv[3])
epochNum = int(sys.argv[4])
except:
p... | true |
1ff2b9c520599d5db980113cb62b55c99830f741 | Python | sdvinay/lounge_trivia_bot | /lounge_parser.py | UTF-8 | 1,459 | 3.078125 | 3 | [] | no_license | from bs4 import BeautifulSoup
class LoungePost:
""" A lounge post"""
def get_lounge_posts(fp):
soup = BeautifulSoup(fp, features="lxml")
for post in soup('div', 'post'): # <div class="post">
response = LoungePost()
response.text = post.text
response.soup = post.parent.parent.par... | true |
3acad0a89d8d597ca24495d9f5b600060a00bbd5 | Python | bruno5182/coronavirus-analysis | /coronavirus/python_scripts/us_data_cleaner.py | UTF-8 | 4,268 | 3.34375 | 3 | [
"MIT"
] | permissive | """
US data format was changed in the JHU data.
This class should help handle standardizing it.
"""
# pylint: disable=invalid-name, line-too-long
import os
from datetime import datetime
import pandas as pd
class USDataCleanUp:
"""
Take in a dataset, clean up the US data that has changed format,
and then a... | true |
9c698f8299e24a71a0c2ba95cea9a4cba4ba48c2 | Python | BBackJK/2020tech | /python/200520/06_ifElseExample1.py | UTF-8 | 318 | 2.703125 | 3 | [] | no_license | # 교재 p.122 영화 조조 할인 판정
from time import localtime
hour = localtime().tm_hour
mnt = localtime().tm_min
if hour < 10:
print("현재 시각: %d시 %d분, 조조 할인 가능합니다." %(hour, mnt))
else:
print("현재 시각: %d시 %d분, 조조 할인 불가능합니다." %(hour, mnt)) | true |
ca3dfa8ab29b55e526f2e96eec063458790051b4 | Python | 448Watanabe/python_random_test | /classMethodTest.py | UTF-8 | 1,495 | 3.875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
class Boku(object):
# これはクラス変数
subject = "ぼくは"
name = "ドラえもん"
def __init__(self, nickname):
self.nickname = nickname # これはインスタンス変数
# これはインスタンスメソッド
def get_name_instance(self, class_var=False):
if class_var:
return Boku.subject + Bo... | true |
0178ddcd952db5929eeab96a6b3499e45b69c5ac | Python | Luolingwei/LeetCode | /OA/Amazon/QAmazon_Closest Two Sum.py | UTF-8 | 610 | 3.796875 | 4 | [] | no_license | # Intput: [1,6,4,2], 7
# Output: 6,2
# 思路: 先排序,然后two pointers寻找closest pair
class Solution:
def closest_two(self,nums,target):
nums.sort()
l,r=0,len(nums)-1
mingap=float('inf')
n1,n2=-1,-1
while l<r:
v=nums[l]+nums[r]
if v>target:
r-=... | true |
2cb71fd378e7b42eb99ba4452a4f6c2f6bc73271 | Python | brianchun16/PythonPractices | /Review/quiz2-1.py | UTF-8 | 440 | 3.796875 | 4 | [] | no_license | import sys
x = int(raw_input("Enter a number: "))
y = int(raw_input("Enter a number: "))
z = int(raw_input("Enter a number: "))
has_odd = False
odd_max = -sys.maxint - 1
if x % 2 == 1:
has_odd = True
if x > odd_max:
odd_max = x
if y % 2 == 1:
has_odd = True
if y > odd_max:
odd_max = y
if z % 2 == 1:
has... | true |
70b01183a0a7e2d760264f17937853e343d165d7 | Python | elliothevel/trep_collisions | /examples/basic/simplenc.py | UTF-8 | 1,204 | 2.8125 | 3 | [] | no_license | """
In this example, we have two pendula that can contact one another (basically newton's cradle
with only two masses).
"""
import trep
from trep import ty, tz, rx
from trep.visual import *
import numpy as np
import trep_collisions as tc
# Define the system. We include gravity and damping.
frames = [ty(0.0), [rx('the... | true |
81c2c58491b35d69ba0e145db56d0f2794a42192 | Python | paro87/Machine-Learning-with-Python | /ML3/sheet3.py | UTF-8 | 13,710 | 3.1875 | 3 | [] | no_license | from typing import Dict, List, Tuple, Optional
from unittest import TestCase
import numpy as np
import matplotlib.pyplot as plt
from utils import train_test_idxs
t = TestCase()
from minified import max_allowed_loops, no_imports
from IPython.display import Markdown as md
from ML3.minified import max_allowed_loops, n... | true |
92573afaa8fa079da762900ef6842e09557919ab | Python | VismantasD/tic_tac_toe | /deepTic.py | UTF-8 | 20,735 | 3.59375 | 4 | [] | no_license | import random
import pickle
from pprint import pprint
class Symmetries():
"""Class for finding invariant states of the tic tac toe board.
Given a state will return an invariant state based on 8 symmetries
Attributes:
multiplier: multipliers for different positions on the board
... | true |
83b3f7df6a45332006b32fbe6c199995b4358fb9 | Python | Neethu-nr/aa203_project | /RF/RunAgent.py | UTF-8 | 3,799 | 3.125 | 3 | [] | no_license | #From https://github.com/the-deep-learners/TensorFlow-LiveLessons/
#modified by Albin
import os
import gym
import numpy as np
from DQNAgent import DQNAgent
from Airplane import Airplane_Env
def train():
agent = DQNAgent(state_size, action_size) # initialise agent
#choice = raw_input("Name weight: ")
#fil... | true |
0bd4d72f75838ccef71c9f7781373de9031f8fef | Python | AaronYang2333/CSCI_570 | /records/09-05/brackets.py | UTF-8 | 793 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '9/5/2020 4:06 AM'
class Solution:
def getHouses(self, t, xa):
# write code here
arr = []
for i in range(0, len(xa), 2):
left = xa[i] - xa[i + 1] // 2
right = xa[i] + xa[i + 1] // 2
arr... | true |
f4b84748fa2362dcee63d31e7712221b3818a6d6 | Python | kmcginn/advent-of-code | /2021/day02/dive2.py | UTF-8 | 2,386 | 4.3125 | 4 | [
"MIT"
] | permissive | #! python3
"""
--- Part Two ---
Based on your calculations, the planned course doesn't seem to make any sense. You find the
submarine manual and discover that the process is actually slightly more complicated.
In addition to horizontal position and depth, you'll also need to track a third value, aim, which
also starts... | true |