blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f560d757d75fece285f6b78fff49632ead9f1782
lopezpdvn/pysweng
/pysweng/recursion/__init__.py
1,056
3.671875
4
def get_path0(maze): if not maze or not len(maze): return None path = [] if _get_path0(maze, len(maze) - 1, len(maze[0]) - 1, path): return path return path def _get_path0(maze, row, col, path): if col < 0 or row < 0 or not maze[row][col]: return False is_at_origin = not row an...
f2fe7d12570272946b585ac28826525539f085ec
igorsorokin66/Crossword
/Crossword.py
968
3.625
4
class Letter: def __init__(self, character): self.character = character self.adjacentLetters = [] def addAdjacentLetter(self, letterObj): self.adjacentLetters.append(letterObj) cross1 = [i.strip() for i in open('crossword1.csv')] alphabet = [] for letter in range(97,123): alphabet...
4b08ec71c16ceece3a94403064febba2d1560df4
Sniedes722/pyRelations
/pyrecords/__init__.py
400
3.578125
4
import os class Table: def __init__(self,columns): self.columns = columns self.records = [] self.primary = None self.table = [] def insert(self,record): if len(record) == len(self.columns): self.records.append(record) else: p...
95d919d6ed44f276810f13bb6a1d7d44728d9038
zzxzzg/python
/test1/iter_generator.py
865
3.96875
4
#! /usr/bin/env python3 import sys #迭代器,和java c++ 原理基本差不多 list = ["1","2","3","4"] it = iter(list) print(next(it)) #yield 的函数被称为生成器 #在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回yield的值。并在下一次执行 next()方法时从当前位置继续运行。 def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n):...
8fbcb251349fe18342d92c4d91433b7ab6ca9d53
gsaikarthik/python-assignment7
/assignment7_sum_and_average_of_n_numbers.py
330
4.21875
4
print("Input some integers to calculate their sum and average. Input 0 to exit.") count = 0 sum = 0.0 number = 1 while number != 0: number = int(input("")) sum = sum + number count += 1 if count == 0: print("Input some numbers") else: print("Average and Sum of the above numbers are: ", sum / (coun...
06764edfde37af020afdfb2c2ee75cac798d3083
cian-gmit-da2020/PandS-Project
/analysis.py
3,613
3.59375
4
# Cian Hogan # Final project, Programming and Scripting Module # Write a program called analysis.py that: # • outputs a summary of each variable to a single text file, # • saves a histogram of each variable to png files, and # • outputs a scatter plot of each pair of variables. # import needed libraries import pandas ...
0ad90ea2a092eca0198ff361ff1702cbdce5e66e
RegisteDjessou/L3-Informatique-
/exercice1_atelier1.py
1,181
4
4
""" #Auteur: Watt_Registe #Date: 07/09/20 #Version: 1 #Description: Calcul de salaire """ def salaire(salaire_horaire: float, nombre_heures:float)-> float : #attention, pour tout l'atelier 1 on ne devait pas mettre de return ni de paramètres dans nos fonctions """Calcul de salaire en fontion du nom...
6480c120be7596126b2a0c24975d2a177070e75c
petefitton/python-classroom-lab
/classroom.py
3,610
3.765625
4
class Assignment(): def __init__(self, name, github_url): self.name = name self.github_url = github_url self.completed = False self.grade = None def mark_done(self, grade): self.grade = grade self.completed = True class Student(): def __init__(self, name): ...
5f1d80463b49fa43c00a4727ed44fd82911d8acc
gytHW/leetcode
/algorithm/python/575-DistributeCandies.py
442
3.859375
4
#思路:这题很简单,看看糖果总共多少种,少于一般就获取全部种类,最多获取一半 class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ uniqueCandies = set(candies) num = len(list(uniqueCandies)) half = len(candies) // 2 if num <= half: ...
2db7639f696c1098a81cfda6b8913e0f19f37c04
gytHW/leetcode
/algorithm/python/441-ArrangingCoins.py
266
3.546875
4
class Solution(object): def arrangeCoins(self, n): """ :type n: int :rtype: int """ line = 0 num = 0 while( num <= n): num += line + 1 line += 1 return line - 1 #完整行数
8cef1514eb83fc45b06cbb930e82d3879d946e50
gytHW/leetcode
/algorithm/python/202-HappyNumber.py
734
3.765625
4
#思路:这道题的核心是拆分数字和判断怎么算无限循环 class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ seen = set() #用set保存已经出现过的数字,如果再次出现,则说明无限循环了,不是快乐数 while True: seen.add(n) n = self.sumSquare(n) if n == 1: return Tr...
665229ecdb780338cc809ec74e7b5cdf5cc1ea9a
gytHW/leetcode
/algorithm/python/724-FindPivotIndex.py
1,485
3.5625
4
#思路:本题颇费了一番时间,主要是因为提交总是timeout超时,参见注释为第一版写法.分析应该是因为太多sum()函数的调用导致超时 # 经过参考和思考,绝对使用累加和累减来获取每次的左右子数组之和,这种方式比每次都sum好得多,整体只需要sum一次,如此 # 更改之后便不再超时,需多多借鉴此种写法 #基本思路:遍历数组,对每个元素做中心索引时的左右元素之和作比较,如果相同则返回index class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: ...
f3b00fa586009bb5d7fe7cc2a874f187e1e44e57
kaspergroenbek98/first-first-year-project
/split_date_and_time.py
200
3.578125
4
n = int(input()) d = [] print(d) for i in range(n): d.append(input().split()) date = [] for i in range(n): temp = d[i].pop(1) date.append([temp]) print(n,d, date) print(len(d[0]))
441e0267399a7b249f264efc6e85892bd506d9fe
tsrsubbulxmi/Python-Practice
/Assessment3/q7.py
136
3.53125
4
a=input() a=a.split(' ') b=input() b=b.split(' ') l=[] for i in a: for j in b: t=(i,j) l.append(t) print(l)
dd07d52ced12038d32e299ecc32adbcd64ae6d44
tsrsubbulxmi/Python-Practice
/Assignment 2 Types of method and access specifiers.py
3,628
3.6875
4
#========================= Implementation of instanca,class,static methods and access specifiers============ class Company: #Parent class Company __count=0 #private count variable @classmethod def disp_cnt(cls): #class method for calculat...
8ef6194fae25fe8b4d3ebd304cf94553712b156f
w00sung/Algorithm
/Programmers/2020KAKAO_bracket.py
1,458
3.53125
4
from collections import deque # 2단계, 분리 & u가 올바른가 올바르지 않은가 def split_bracket(p): if p == "": return is_right = True u = [] v = deque(p) cnt = 0 for i in range(len(p)): if p[i] == "(": cnt += 1 elif p[i] == ")": cnt -= 1 u.appe...
1508aaa7164ae1f8e1534913346c327ce9e12df2
w00sung/Algorithm
/Search/binary_search_recur.py
479
3.671875
4
def binary_search_recur(data, find, strt, end): if strt > end: return None mid = (strt + end) // 2 if data[mid] == find: # 위치 반환 return mid elif data[mid] < find: # 찾고자 하는게 더 크다 -- 범위를 우측으로 binary_search_recur(data,find,mid+1,end) else:...
6a6644419352d7b58691e9d0ceed12373ca273f3
w00sung/Algorithm
/BOJ/11049_Chained Matrix Multiplication.py
1,105
3.59375
4
import sys read = sys.stdin.readline # 행렬 개수 N = int(read()) matrix = [] # N+1 x N+1 테이블 생성 # table[i][j] = 행렬(i) 에서 행렬(j)까지 곱할 때 최적값 table = [[0] * (N) for _ in range(N)] for _ in range(N): row, col = map(int,read().rstrip().split()) matrix.append((row,col)) def put_table(): # for i in range(N): #...
67e51a6978995d528ec59309486eee05c12ab8cd
shenhangke/FlaskLearn
/main.py
5,944
4.15625
4
# 装饰器相当于在函数外面包一层函数,扩展原来函数的功能,只只不过通过python提供了一种语法糖,来简单的调用这个函数 """ #装饰器 def debug(func): def wrapper(): print("[DEBUG]: enter {}()".format(func.__name__)) return func() return wrapper def say_hello(): print("hello!") say = debug(say_hello) # 添加功能并保持原函数名不变 #say() #其实这里调用的是wrapper函数,在wrap...
73c4703ef79a5cbcbd402fc1b9dc03fcc9011eb4
jinhli/Object_program
/object_practice/class_object/Polymorphism_1.py
661
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Bonnie Li" # Email: bonnie922713@126.com # Date: 5/31/18 # import abc # class Animal(metaclass=abc.ABCMeta): #同一类事物:动物 # @abc.abstractmethod # def talk(self): # pass # # class People(Animal): #动物的形态之一:人 # def talk(self): # prin...
4df924d88455016db2db2672067dc48ff80a8f74
jbadelino/Fractal-Lattices---Koch-curve
/Koch_curve.py
1,530
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 12 12:33:12 2018 @author: jbadelino """ #import turtle graphics for an easier drawing environment import turtle #define a function for constucting a Koch curve def Koch_curve1(length, iteration): if iteration > 0: for theta in [-60, 120, -6...
571d55ec0fd7cf5a87af0eb76a00080e62e181cd
GunikhanSonowal/SmiDCA
/Pos_nltk.py
1,356
3.921875
4
########################## # Part of speech #Here we see that and is CC, a coordinating conjunction; now and completely are RB, or adverbs; for is IN, a preposition; something is NN, a noun; and different is JJ, an adjective. ######################## import nltk import enchant import sys reload(sys) sys.setdefaulte...
e765dcda95e4b54164e636164d17ff477b58169b
macaoleaf/Udacity
/Nanodeg_ML_basic/Math/exercises/sinCos.py
1,106
3.859375
4
# QUIZ # # Fill in the for loop below to set # the x, y1, and y2 arrays to the # following values: # # - The x array should contain # num_points many points evenly # spaced between 0 and 2*pi. # 0 and 2*pi should be included. # # - The y1 array should contain # the corresponding sine values # of the va...
163c74e039d5ef389b48ab2941260107f5264c4b
lemon1995/lemon1994
/hw13/guess1.py
176
3.6875
4
guess_me=7 start=1 while guess_me>start: print('too low') start+=1 if guess_me==start: print('found it') start+=1 if guess_me<start: print('oops')
13ad9d79b3025635df3f98d4a822dd8f6d9db81b
odydasa/phyton
/factorial.py
247
3.5
4
import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") print(parser.parse_args()) #text = parser.parse_args().echo #def recur_factorial(n): # if n == 1: # return n # else: # return n*recur_factorial(n-1)
4731e40b41f073544f2edf67fb02b6d93396cd7b
hbomb222/ICTPRG-Python
/week3q4 new.py
819
4.40625
4
username = input("enter username ") # ask user for username user_dict = {"bob":"password1234", "fred":"happypass122", "lock":"passwithlock144"} # create dictionary of username password pairs if (username == "bob" or username == "fred" or username == "lock"): # check if the entered username matches any of the known val...
d82ffa573c4820eebbed9924b0a2b9952265dcf3
RameshAditya/algorithm-implementations
/Kadane's-algorithm.py
870
3.609375
4
def kadane(A): currentsum=0 maxsum=0 startindex=0 currentstartindex=0 endindex=0 for i in range(len(A)): currentsum+=A[i] if currentsum>maxsum: startindex=currentstartindex maxsum=currentsum endindex=i if currentsum<0: ...
3999de839ac1355b752e9ce404294380fa042413
BrodayWalker/5143-OS-Walker
/Assignments/client_server_game/DbHelpers.py
8,856
3.609375
4
#!/usr/bin/env python3 """Api.py """ from pymongo import MongoClient import pprint import json import datetime def logg(message): """ Simple log function to log errors to a file. """ f = open("logfile.log","a") f.write(message+"\n") f.close() class Api(object): def __init__(self,db,request):...
74ae158c920252195aab047d016eb8b12fac8ebb
BrodayWalker/5143-OS-Walker
/Assignments/client_server_game/guessingGame2.6.3.0.14b.py
6,083
3.75
4
import random import sys import math from datetime import datetime # seed value random.seed(datetime.now()) # Max value MAX = (2**53) -1 # Always guess max so I can cut down 50% of the set of possibilities # everytime it's higher guess = MAX # Create a range, and pick a random number from within it L = random.randi...
2836d22ed1ccb4e610ce35cce508bacfef869f13
yuyatabata/python_practice
/tdd/fizzbuzz/fizzbuzz.py
395
3.703125
4
class FizzBuzz: def convert(self, num): # return 'Fizz' #仮実装 # if num == 3: # return 'Fizz' # if num % 15 == 0: return 'FizzBuzz' if num % 3 == 0: return 'Fizz' if num % 5 == 0: return 'Buzz' return num fizzbuzz =...
09ee2a1e7f2c0d0d237e969a60849c36b40e67f2
PyQuantSharp/FinQuant
/finquant/quants.py
3,936
3.8125
4
"""The module provides functions to compute quantities relevant to financial portfolios, e.g. a weighted average, which is the expected value/return, a weighted standard deviation (volatility), and the Sharpe ratio. """ import numpy as np import pandas as pd def weighted_mean(means, weights): """Computes the we...
bc18c5a99b9a4fde561442991bca1e9d589c7412
mrwen00/MachineLearning-TH1-Clustering
/BT1.py
601
3.609375
4
# 14521097 # Trieu Trang Vinh # BT1 Thuc hien thuat toan Kmean. Du lieu duoc sinh ngau nghien gom 2 gaussian. Visualize ket qua import numpy as np import matplotlib.pyplot as plt from random import randint from sklearn.cluster import KMeans from sklearn.datasets import make_blobs plt.figure(figsize=(12, 12)) n_samp...
f14e0d5a091c82dc562492708d7a24ab3dfe9b2e
furkankykc/Numericalillustrations
/RungeKuttaMethod.py
6,841
4.3125
4
# Mfile name # mtl_int_sim_RK2ndmethod.m # Revised: # March 7, 2008 # # Authors # Nathan Collier, Autar Kaw # Department of Mechanical Engineering # University of South Florida # Tampa, Fl 33620 # Contact: kaw@eng.usf.edu | http://numericalmethods.eng.usf.edu/contact.html # T...
6397958304ca8d126e9e21d6103560d7abf79053
JeevanLiang/goodgoodstudydaydayup
/q3.py
272
3.546875
4
# -*- coding: utf-8 -*- s=input() ss=s.split(' ') if(len(ss)==0): print(0) else: i=range(len(ss)) x=0 for j in reversed(i): if(ss[j]!=''): print(len(ss[j])) x=1 break; if(x==0) : print(0)
5e3d41c1d7e1d49566416dced623ae593b58c079
nickwerner-hub/WhirlwindTourOfPython
/Scripting/03_RangeFunctionExample.py
270
4.34375
4
#RangeFunctionExample.py # This example demonstrates the range function for generating # a sequence of values that can be used in a for loop. pi = 3.1415 for r in range(0,100,20): area = (r ** 2) * pi print "The area of a circle with radius ", r, "is ", area
313925e1c6edb9d16bc921aff0c8897ee1d2bdf5
nickwerner-hub/WhirlwindTourOfPython
/Scripting/07_WriteDataExample.py
1,620
4.34375
4
#WriteDataExample.py # This script demonstrates how a file object is used to both write to a new text file and # append to an existing text file.In it we will read the contents of the EnoNearDurham.txt # file and write selected data records to the output file. # First, create some variables. "dataFileName" will po...
1fc51bc3ec116ee0663399bffae6825020d33801
abdbaddude/codeval
/python/jolly_jumper.py3
2,166
4.1875
4
#!/usr/bin/env python3 """ JOLLY JUMPERS CHALLENGE DESCRIPTION: Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences between successive elements take on all possible values 1 through n - 1. eg. 1 4...
119045ce054d7412483e4d920569edb2790caf8b
jamesros/PythonProject
/newproject/animals.py
177
3.875
4
pets = ['dogs', 'cats', 'goldfish'] statement_pet = " make really good pets." for pet in pets: print(pet + statement_pet) print("Any of these animals would make great pets")
487e9a44adffb9f315868cb6498e70508f33878d
jamesros/PythonProject
/newproject/seeing_the_world.py
665
3.640625
4
fav_places = ['ireland', 'japan', 'italy', 'alaska', 'hawaii'] print("This is the original list of the places I would like to visit:") print(fav_places) print("\nThis is the same list in alphabetical Order:") print(sorted(fav_places)) print("\nThis is the original list again:") print(fav_places) print("\nThis is the...
3544d246fd4cd0090eaa387b13fce3c4fac7e842
sakurazz/Hero-Villain-Victim
/extractBySoup.py
981
3.578125
4
##need to install: # pip install beautifulsoup4 # pip install lxml # pip install requests # pip install html5lib # work to do - ## currently can extract from a url ##I currently have the texts print to the terminal ## stored as strings in list ## I could try to make it store into csv if that's easier for other people...
ebe6c12088508637a7bb0587b8f88b8d1f7f4dad
hpcll/test
/class.py
344
3.671875
4
class Dog: kind = "canine"#类变量 tricks = [] def __init__(self,name,age): self.name = name#实例变量 在类初始化时才有意义 self.age = age @classmethod def add_trick(cls,trick): cls.tricks.append(trick) d = Dog('FIDO',14) E = Dog('BUDDY',13) # print(d.name) print(Dog.add_trick(1))
87c2fcfcaa140e8971926f8da3098c5abe781271
Nadeem-Doc/210CT-Labsheet
/Labsheet 5 - Task 2.py
1,542
4.21875
4
class Node(): def __init__(self, value): self.value=value self.next=None # node pointing to next self.prev=None # node pointing to prev class List(): def __init__(self): self.head=None self.tail=None def insert(self,n,x): #Not actually perfe...
b60860e96ff12af3101393ef27afa7760fc3835e
kanebrogan/takeaway-ai
/playta.py
13,800
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[6]: import time class Node: def __init__(self, chips, turnp, children=[]): self.chips = chips self.turnp = turnp self.children = children self.mmv = None class Player: def __init__(self, value): self.value = value class A...
7532e19196a638583a391e2294a1cd2e0500a319
MrLTJ19941003/Python_projectExample
/learn04/md5login.py
1,542
3.59375
4
import hashlib,getpass db={ #'michael': 'e10adc3949ba59abbe56e057f20f883e', #'bob': '878ef96e86145580c38c87f0410ad153', #'alice': '99b1c2188db85afee403b1536010c2c9' } MD5='the-Salt' class userlib(object): def get_md5(self,password): md5 = hashlib.md5() md5.update(password.encode('utf-8')...
9912df4fb52c56f99641242d3caa90c930729498
abelmagnag0/ppsi-python
/operadores-aritmeticos-16-08-21/ex3.py
206
3.796875
4
chuva = float(input("Quantidade de chuva:")) print("Calculando o equivalente em milímetros..") print("...") print("..") print(".") chuva_milimetros = round(chuva * 25.4, 2) print(chuva_milimetros, "mL")
f063aa8969b9543d3fef2736b853592030acaeda
hyqLeonardo/Alfred
/voice.py
994
3.578125
4
import speech_recognition as sr # audio to text def listen(): # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Listening") audio = r.listen(source) # recognize speech using Microsoft Bing Voice Recognition BING_KEY = "72c9268836d5478980d267984273358a" # Microsoft...
d93e11b6d95ea35379059ae05cf7ddea4501617a
FHomewood/ScientificComputing
/ExamPrep/Shit Comp/Python Code/PythonShit(UpToRoots)/Polyfit(leastsquaresfit).py
953
3.984375
4
#polyFit (least squares fit) (example assesment 1 Q3 part c) #creates a least squares polynomial fit ''' c = polyFit(xData,yData,m). Returns coefficients of the polynomial P=polyFit(x,y,m) #uses least squares fit to create a polynomial P of m degrees yu=P[0]+P[1]*(xu)+P[2]*(xu)**2 #can use coefficients of the ...
5071fc88c18d7c82e3e8e44090b5de235d0a030b
FHomewood/ScientificComputing
/ExamPrep/Shit Comp/Python Code/Interpolation/Barycentricinterpolate.py
753
4
4
#barycentric interpolate (example assesment 1 Q3 part a) from scipy import interpolate from scipy.interpolate import barycentric_interpolate as bi import numpy as np #when you are given an array of x and corresponding y values you can use them to estimate a value y value at a value of x you have not been given (let t...
d8cf1183d12a49d32c5944fc51b3a29599314398
tortoise1992/ahui-python
/l1/1.py
940
3.578125
4
# classMates=['ahui','xiaozhang','shanshan'] # print(len(classMates)) # classMates.append('admn') # # classMates.pop() # classMates.insert(1,'周青会') # classMates.pop(0) # print(classMates) # def add(): # # # return 'hello' # import copy # a=[1,'ahui',[1,2]] # b=copy.deepcopy(a) # b[2][1]='test' # print(a) # def print_...
e414258bd22447a2f5f874a6d5c2c342f18b82b2
mp4096/dla
/dla/slicing.py
1,357
4
4
"""Routines for slicing, i.e. distributing the problem Ax = b onto agents.""" def standard_slices(problem_size, num_agents, overlap=0): """Create standard slices for a problem. We assume that the problem size is exactly divisible by the number of agents; hence all agents have exactly the same subproblem ...
e830814919556e4ba216c429e39f82ab3aea659c
theOriginalPerson/body-fat-calculator
/main.py
1,767
3.625
4
maleOrFemale = input("are you a male or female? (m/f) ") tWeight = float(input("what's your total weight? ")) waist = float(input("what's your waist measurement? ")) wrist = float(input("what's your wrist measurement? (press 0 if male) ")) forearm = float(input("what's your forearm measurement? (press 0 if m...
6de70cc0c9f0b84e00203e8c323e164b5a9e77a7
joepetrini/dayuntil
/app/scripts/holidays.py
17,312
3.75
4
from datetime import datetime, timedelta, date from dateutil.easter import easter import calendar [MON, TUE, WED, THU, FRI, SAT, SUN] = range(0, 7) [JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC] = range(1, 13) HAVE_30_DAYS = (APR, JUN, SEP, NOV) HAVE_31_DAYS = (JAN, MAR, MAY, JUL, AUG, OCT, DEC) def ge...
48ef70bfc287abac22666cdedd531776c4653fcb
nkzxw/dirtysalt.github.io
/codes/contest/leetcode/largest-rectangle-in-histogram.py
913
3.625
4
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ ps = [] hs = [] res = 0 for i in range(len(heights)): h = heights[i]...
191080c15faa60d787d4e78c023b75b7fc6bc002
nkzxw/dirtysalt.github.io
/codes/contest/leetcode/insert-interval.py
1,112
3.984375
4
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e import functools def cmp(x, y): if x < y: return -1 if x > y: return 1 return 0 class Solution(object): de...
619a39621be31f894d67cfc3efe6343de8b0da8a
Abdullah3553/algorithms_visualizer
/selection_sort.py
3,771
3.703125
4
from tkinter import * from tkinter import messagebox import shared_functions def main(arr, maxm_num): main_window = Tk() lop1 = 0 lop2 = 1 is_sorted = False cur_op = 1 text = True def swap_lbls(element1, element2): # a function to swap 2 labels :) return element2['text'], element...
56b7bee1f753d3c1f26b716a39d3d09ab1a60387
glifchits/KlonSolve
/mcts.py
7,099
3.640625
4
""" A minimal implementation of Monte Carlo tree search (MCTS) in Python 3 Luke Harold Miles, July 2019, Public Domain Dedication See also https://en.wikipedia.org/wiki/Monte_Carlo_tree_search https://gist.github.com/qpwo/c538c6f73727e254fdc7fab81024f6e1 """ from abc import ABC, abstractmethod from collections import d...
3de4112b3967759bc3839dbbd22f7674ab8e070d
hgkang9/TIL
/algo/josephus.py
455
3.59375
4
class Node: def __init__(self,data,link=None): self.data=data self.link=link def Enque(item): global head, p newnode=Node(item) if head==None: head=newnode else: p=head while p.link: p=p.link p.link=newnode # while : head=None for i in...
f0664f2b9a826598dc873e8c27d53b6623f67b5b
Vanagand/Data-Structures
/queue/queue.py
1,520
4.21875
4
#>>> Check <PASS> """ A queue is a data structure whose primary purpose is to store and return elements in First In First Out order. 1. Implement the Queue class using an array as the underlying storage structure. Make sure the Queue tests pass. 2. Re-implement the Queue class, this time using the linked list imp...
6f1fbad0e294f9d9c800c84b72e915938b7a1c33
javicercasi/um-programacion-i-2020
/58004-Cercasi-Javier/tp1/Orientado a Objetos/Ejercicio2OPP.py
1,471
4.5625
5
'''La pizzería Bella Napoli ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación. * Ingredientes vegetarianos: Pimiento y tofu. * Ingredientes no vegetarianos: Peperoni, Jamón y Salmón. Escribir un programa que pregunte al usuario si quiere una pi...
019384e954ebf8474fbadd4dfbba8c6a0212658b
javicercasi/um-programacion-i-2020
/58004-Cercasi-Javier/tp1/Ejercicio10.py
485
4.0625
4
'''Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes.''' def logica(): Meses = ["ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NO...
0315fda0cd48fab78e9d0a1bbe35217f78029f5a
javicercasi/um-programacion-i-2020
/58004-Cercasi-Javier/tp1/Orientado a Objetos/Ejercicio15OPP.py
1,557
4
4
'''Crear un programa que lea un archivo de lista que va a contener datos de una venta y mostrarlo por pantalla. El formato será: Nombre y apellido, monto de la venta, descripción, forma de pago (contado o tarjeta). El archivo contendrá una línea por cada venta, y podrá contener múltiples ventas.''' class EntradaSalid...
43029ca4a4a757e2c1aa177b9addca9c7c3157f0
Amrut-17/python_programs
/Selection_Sort.py
620
4.15625
4
def selection_sort(n): for i in range (n): min = i for j in range(i+1 , n): if (a[j] < a[min]): min = j temp = a[i] a[i] = a[min] a[min] = temp print('\nAFTER sorting') for i in range(n): print (a[i], end = " ") ...
b22b53d54c08df688fb5f575775148f4e9bf073e
Amrut-17/python_programs
/factorial_inbuildFunction.py
125
4.03125
4
import math n = int (input ('enter number :- ')) result = math.factorial(n) print ('factorial of' , n ,'is :- ' , result)
e2c64efb46caca711cc31691bf711f6d2fc05354
ThomasGjerde/knowit-jul-2020
/luke13.py
348
3.6875
4
import string input_list = list(open('input/luke13.txt', 'r').read().strip()) for letter in string.ascii_lowercase: indices = [i for i, x in enumerate(input_list) if x == letter] for idx in reversed(indices): if indices.index(idx) != string.ascii_lowercase.index(letter): del input_list[idx]...
d0cf7e65dc90e95b6109d51c65468e4fc62e97e5
18s005073/Algorithm_sort
/maopao.py
723
4.03125
4
# 冒泡排序,从小到大 ''' 1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。 2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 3.针对所有的元素重复以上的步骤,除了最后一个。 4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较 ''' def bubbleSort(arr): for i in range(1, len(arr)): for j in range(0, len(arr)-i): if arr[j] > arr[j+1]: arr[j], arr[j+...
84b45ff2e971fdb1646165c28d01fd7331290cef
shantanu609/Array-8
/Minimum_word_distance_ii.py
1,144
3.953125
4
# Time Complexity : O() # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach # https://leetcode.com/problems/shortest-word-distance-ii/ class WordDistance: # Tc = O(n), where n are th...
da0f41dddff8195580409893e093966529722d92
sachindra149/covid19-tracker
/projects/api/api.py
2,042
3.796875
4
# import the flask library and its underlying objects, making the code available to the rest of the application. from flask import Flask, jsonify import requests # Then initialise a new Flask object to a variable called app. Every Flask application must create an application instance. The web server will pass all the...
4506f5995b4f4837ccbef830f41e2dbe58bc5112
EntangledLabs/LazyMeeting
/event.py
1,055
3.734375
4
import datetime class event(): def __init__(self, ident, time, action, tz, *args): self.ident = ident self.tz = tz self.time = self.make_time(time) self.action = action self.args = args[0] # print("Event object created with time {}".format(self.time)) # Takes in an hour and a minute and returns a time ...
de5f1ae3bae6d0744cd18ded1ec0631d48fbb559
TanvirKaur17/Greedy-4
/shortestwayToFormString.py
912
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 29 08:30:10 2019 @author: tanvirkaur implemented on spyder Time Complexity = O(m*n) Space Complexity = O(1) we maintain two pointers one for source and one for target Then we compare the first element of source with the target If we iterate through ...
8de845a6d439308e772f0c8c91909f4a6f27d79b
lakshmic6/CSEE5590-490-Python-and-Deep-Learning-Programming
/Assignment 3/source/4.py
1,053
3.625
4
from sklearn.model_selection import train_test_split from sklearn import datasets, metrics from sklearn.neighbors import KNeighborsClassifier #Loading the dataset irsdataset=datasets.load_iris() #getting the data and response of the dataset L=irsdataset.data M=irsdataset.target a_train, a_test, b_train, b_test=train_...
06085edf02ff92ddb5b1937b2b85800c646c328a
N03/arithmetic_text_coding
/ar_coding.py
2,024
3.796875
4
# arithmetic coding for text implementation # Université de Fribourg, Suisse # AUTHOR: Noé Zufferey - noe.zufferey@gmail.com # CREATION: april 2018 # USAGE: python3 ar_coding.py '<string to encode>' # OUTPUT: an interval of floating value and a binary code import sys from decimal import * """this function compute th...
96c09ac183899ecd13a818fa810033fe831510f4
avigail-oron/sandbox
/src/ex/exercises.py
3,162
3.578125
4
''' Created on Mar 16, 2017 @author: maint ''' from __builtin__ import str """ Exercise 4 """ from random import random def divisors(): num = int(input("Enter a number to find its divisors: ")) potentials = range(1, num+1) answer = [] for x in potentials: if num % x == 0: answer.a...
acad69f122951867c805bd57090bc689ad311d62
ahmedhussein89/CarND-Advanced-Lane-Lines
/binary_thresholding.py
2,609
3.625
4
import cv2 import numpy as np import matplotlib.pyplot as plt def abs_sobel_thresh(gray_image, orient='x', sobel_kernel=3, thresh=(0, 255)): # Apply the following steps to img # 1) Take the derivative in x or y given orient = 'x' or 'y' if(orient == 'x'): orient_image = cv2.Sobel(gray_ima...
5c5d5bba02099515b9b00b7bc92ad7e232dfd165
eadgarchen/python_excrise
/Threads.py
1,142
3.921875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading, time #The balance variable. balance = 0 #Add lock for more than one threads to access the global resource. lock = threading.Lock() def loop(): print('thread %s is running...' %threading.current_thread().name) n = 0 while n < 5: print('thread %s >>>...
d09de5d88ab0f332ed7fcadfdbc1b110006ce92c
RostyslavOleniuk/sorted.py
/sorted.py
416
3.953125
4
choose=str(input('Choose a or b:')) if choose == 'a': text=str(input("Enter text: ")) SplitString=text.split() x="" for i in sorted(SplitString): x=x+" " +i print(x) d={} for char in set(text): d[char]=text.count(char) print(d) elif choose == 'b': text1=str(input("Enter text: ")) S...
ba09980b888ff1ce4c3135738ffcf6cb517213f5
Nuwisha/nuwisha_hackerrank
/python/03_strings/string_validators.py
3,730
4.28125
4
link = "https://www.hackerrank.com/challenges/string-validators" # ---=== SOLUTION ===--- data = input() print(any([c.isalnum() for c in data])) print(any([c.isalpha() for c in data])) print(any([c.isdigit() for c in data])) print(any([c.islower() for c in data])) print(any([c.isupper() for c in data])) # ---=== ONEL...
16528fcce9606843a3eb4ebdfe3a6c6009673a68
mzhinf/pat
/1015. Reversible Primes (20).py
612
3.96875
4
#素数测试 O(√n) def is_prime(num): if num < 2: return False i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True #十进制数num按照radix进制倒转 def reversible(num, radix): res = 0 while num > 0: res = res * radix + num % radix num ...
9b966892f276f71678b15bec9bceb9058e09d163
sqyu/Vocab
/Help_funs.py
1,382
3.53125
4
import unidecode class QuitException(Exception): pass def quitOrInput(prompt=None): if prompt: print(prompt) s = input() if s.upper() == "EXIT": quit() elif s.upper() == "QUIT": raise QuitException else: return s def isInt(s): """ isInt(s): Returns True if s can be converted to int, or False oth...
a5a4405908a824a0462c82ee2754790e6aa95c4f
weekend37/TOL1A18
/syniklasi_ur_daematima_17_10_2018.py
1,895
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 17 11:09:50 2018 @author: helgi """ class Islendingur: # smiðurinn okkar def __init__(self, n='', h=0, m=0): # eiginleikar skilgreindir inni í smiðnum: self.nafn = n self.haed = h self.thyngd = m ...
d496a52f395f709cbe71396cbc7d7f4de9dd19a6
CSEKU160212/GraphicsLab
/LineDrawing/DDAlgoWithMouse.py
2,031
3.859375
4
import tkinter as tk root = tk.Tk() root.title("DDA") canvas = tk.Canvas(root, bg="white", width=600, height=400) canvas.pack() coords = {"x1":0,"y1":0,"x2":0,"y2":0} #lines = [] def click(e): # define start point for line canvas.delete("all") coords["x1"] = e.x coords["y1"] = e.y canvas.create...
38bf0b44f7b0860343f4a84f2b4a538b9264f74e
tikilite/google_challenges
/google2.py
2,152
3.6875
4
""" To help yourself get to and from your bunk every day, write a function called answer(src, dest) which takes in two parameters: the source square, on which you start, and the destination square, which is where you need to land to solve the puzzle. The function should return an integer representing the smallest nu...
aecb0f9c92740ee7fef65404f30e067a0d9f9760
Shaifali10/start
/test.py
97
3.546875
4
#!/usr/bin/env python print("Hello World!") for a in [1,2]: for b in ['a','b']: print(a,b)
9b3fe519719c1dddaf2dde9211a02c582e542050
junghwayang/problemsolving
/Algorithms/2. Implementation/29 - Find Digits.py
94
3.703125
4
def findDigits(n): return sum(n % int(digit) == 0 and int(digit) != 0 for digit in str(n))
8d9ce0abb800aea0237379ff88625af1f08dfd61
nkarnik/euler
/4_/1sol.py
556
3.578125
4
def isPalindrome(num): s = str(num) spl = [i for i in s] size = len(spl) middle = size / 2 opp = 0 if size % 2 == 0: opp = middle - 1 else: middle += 1 opp = middle - 2 pal = False while middle < size: if spl[middle] == spl[opp]: middle += 1 opp -= 1 else: re...
42a48b5c66c9aa6c792f638b030c350d4f5a949d
oucb/Exercises_and_notes_LPTHW
/ex18.py
676
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed May 21 08:32:04 2014 @author: oucb """ #!C:\Python27\python # Filename:ex18.py # this one is like your scripts with argv def print_two(*args): arg1,arg2 = args print "arg1: %r, arg2: %r" % (arg1,arg2) # ok, that *args is actually pointless, we can ju...
4235a6ec7be2669d421460219b58d5cfb0c9de4e
oucb/Exercises_and_notes_LPTHW
/ex36.py
1,097
3.71875
4
__author__ = 'oucb' def work_time(): print "the time what you get at the workplace determin whether you lot or not." w_time = raw_input("> ") if w_time < 510: good_time() else: bad_time() def work_bus(): print "the time bus get at the station." b_time = raw_input("> ") while ...
0d68942bb98e0af70e03b5b12f6470da21d41e68
AlxMancia/Curso_Python
/if,for,while.py
498
4.03125
4
## if sintaxis a = 4 if a == 5: print("Es correcto") else: print("No es correcto") ##else if es elif resultado2 = "aprobado" if resultado2 == "aprobado": print("Felicidades") elif resultado2 == "pendiente": print("Aún no hay resultado") elif resultado2 == "reprobado": print("Intentalo nuevamente") ...
0f8df2bb7f0ca56f34737d85faa3aeb5d4c8a300
emmanuelagubata/Wheel-of-Fortune
/student_starter/main.py
1,188
4.15625
4
# Rules print('Guess one letter at a time. If you want to buy a vowel, you must have at least $500, otherwise, you cannot buy a vowel. If you think you know the word or phrase, type \'guess\' to guess the word or phrase. You will earn each letter at a set amount and vowels will not cost anything.') from random import ...
dab2d704ba42a007e64e34436e20fad5244fc05d
larisse13/oo-python
/jogo.py
1,858
4.03125
4
class Robo: def __init__(self, x, y): self.x = x self.y = y def subir(self): self.y += 10 return self.x, self.y def descer(self): if self.y >= 10: self.y -= 10 return self.x, self.y else: print('Ops, comando ...
2ad417f3d2154594ee138512ab13d3459f72e0cf
thanhtrung123/face_rec
/timecheck.py
194
3.953125
4
import time start = time.time() while True: print("start: {}".format(start)) end = time.time() print("end: {}".format(end)) if end - start >= 3: break print(end - start)
355df5e645f38513d4581c5f3f08ed41568c59e2
zaincbs/PYTECH
/reverseOfString.py
375
4.375
4
#!/usr/bin/env python """ Define a function reverse, that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I". """ def reverse(s): k= "" for i in range (len(s)-1, -1, -1): k = k + s[i] return k def main(): v = reverse("This is testing...
af771a30f93a4382dacfb04e423ad01dd96b3160
zaincbs/PYTECH
/filter_long_words_using_filter.py
561
4.25
4
#!/usr/bin/env python """ Using the higher order function filter(), define a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n. """ def filter_long_words(l,n): return filter(lambda word: len(word) > n, l) def main(): list_with_len_of...
528bb5e90b48a7b741e96c7df0ffe0905534df39
zaincbs/PYTECH
/readlines.py
1,420
4.125
4
#!/usr/bin/env python """ I am making a function that prints file in reverse order and then reverses the order of the words """ import sys def readFile(filename): rorder = '' opposed = '' finale= '' inline = '' #reading file line by line #with open(filename) as f: # lines = f.readline...
cddf97c1866cda863176a775e141a2ce53cbcbff
zaincbs/PYTECH
/palindrome_recog.py
2,595
4.3125
4
#!/usr/bin/env python """ Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tire...
4b18b23b90f4538445ec6c6bf53c3cb2c1d73aef
zaincbs/PYTECH
/99_Bottles_of_Beer.py
12,695
4.21875
4
#!/usr/bin/env python """99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows: 99 bottles of beer on the wall, 99 bottles...
ffb8469f1e0b85926bd9e60c1a7f0306247ff9f6
eodnjs467/python
/BOJ/최대공약수와 최소공배수.py
238
3.65625
4
# https://www.acmicpc.net/problem/2609 def gcd(a, b): if b==0: return a else: return gcd(b, a%b) def lcm(a, b): g = gcd(a, b) return g * (a//g) * (b//g) a, b = map(int, input().split()) print(gcd(a, b)) print(lcm(a, b))
004c4a6647887420c61c80e62adf9faebd9ef6d6
eodnjs467/python
/python_basic/python_5day(2).py
1,555
3.984375
4
##제어문(while) ##while 조건문 : ## 수행할 문장1 ## 수행할 문장2 ## ... ##열 번 찍어 안 넘어가는 나무 없다 treeHit = 0 while treeHit < 10 : treeHit = treeHit + 1 print("나무를 %d번 찍었습니다." %treeHit) if treeHit == 10 : print("나무 넘어갑니다.") prompt = """ 1. Add 2. Del 3. List 4. Quit ... Enter number: """ nu...
b719faf4109a297687b0c2df13cb72337500b488
eodnjs467/python
/Algorithm/그룹단어체커(keyfind).py
458
3.84375
4
# https://www.acmicpc.net/problem/1316 # sorted(a, key=a.find) # key = a.find 는 a ㅇ요소중 들어온 순서대로 정렬함 ex abbbba 들어오면 a가 첫번째로 들어와서 a를 나열 후 b나열 # ex gabbwa 하면 g 나열 후 a 나열 후 b 나열 후 w나열 들어온 순서대로 정렬 후 반환 N = int(input()) ans = 0 for i in range(N): word = input() if list(word) == sorted(word, key=word.find): ...
753458738a4a416f55bb9539575dc509ec0e2b32
ramaramayadeepika/guvi11
/odd&even.py
84
4.15625
4
num =int(input ("enter a number:") if (num % 2) ==0 print("even") else print("odd")
c7f2eb3beccc8791ed85d0e0b08873505e546d84
ramaramayadeepika/guvi11
/palindrome.py
190
3.96875
4
n =int(input("enter number:")) temp = n rev = 0 whihle(n>0) dig = n%10 rev =rev * 10+dig n = n/10 if(temp==rev): print("the number is palindrome!") else print("the number is a palindrome!")