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
af5af95fbfea057e453433f0f9349109f03177a9
hbinl/hbinl-scripts
/Python/C7 - RPN/Task3.py
3,827
3.78125
4
""" FIT1008 Prac 7 Task 3 Loh Hao Bin 25461257, Tan Wen Jie 25839063 @purpose: RPN Evaluator @created 20140913 @modified 20140914 """ from Task1 import Stack from Task2 import * def push_into_stack(splitted): """ @purpose: To evaluate the stack and print the workings for the calculation @complexit...
12ebdaa36d6721f0422067ea932fac4ac590605a
hbinl/hbinl-scripts
/Python/C11 - Heaps/Task2.py
3,851
3.875
4
""" FIT1008 Prac 11 Task 2 Loh Hao Bin 25461257, Kedryn Yeo 25250620 @purpose: Creating events for a coffee shop @created 20141020 @modified 20141020 """ import Task1 import random def create_arrival(pq, n): ''' @purpose: Creates 200 customer arrival events and insert them into the queue @...
bb6436da03dc14cbbcc2d40a6f3da907ef6ae892
hbinl/hbinl-scripts
/Python/P5 - Sorting and Edit Distance/Q4.py
1,511
3.703125
4
__author__ = 'HaoBin' import random def partition_bootstrap(lst, k): # Generalised version of Dutch National Flag algorithm # k-way partitioning # First partitioning into three sub partitions, # then recursively partition the 3rd partition return partition(lst, list(range(k))) def partition(lst,k...
bf77ae260f2a9f25a83be172d77c85e1948989a6
whoiskhairul/python
/lists hackerrank.py
604
3.625
4
n = int(input()) arr = [] for _ in range(n): count = 0 s = input() count = s.count(' ') if count == 2: s = s.split() s[1] = int(s[1]) s[2] = int(s[2]) arr.insert(s[1], s[2]) elif count == 1: s = s.split() s[1] = int(s[1]) if s[0] == 'append': ...
d5642660dc9021b6a56e2509b38f3d09f3210a6a
itsformalathi/Python-Practice
/Project-Euler/SmallestMultiple.py
614
3.75
4
#Project Euler - Problem 5 : Smallest Multiple """2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def gcd(a,b): """ returns gcd of a, b """ ...
6f5abd237c95b6590f222c0e5c2dbaf1c7243e99
itsformalathi/Python-Practice
/iteratingdictionery.py
473
4.78125
5
#No method is needed to iterate over a dictionary: d = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat'} for Key in d: print(Key) #But it's possible to use the method iterkeys(): for key in d.iterkeys(): print(key) #The method itervalues() is a convenient way for iterating directly over the values: f...
4eb6f0a8a281bbe4ab7798581d500103d4540d34
itsformalathi/Python-Practice
/Project-Euler/LatticePaths.py
913
3.796875
4
# Project Euler - Problem 15 - Lattice paths """ Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner How many such routes are there through a 20×20 grid?""" def factorial(n): """ n! = n*(n-1)*(n-2)....1 """ fact...
e15ebf49ad10dce1e26fe45ada3476a6dd1cd208
itsformalathi/Python-Practice
/Project-Euler/SumPrimes.py
635
3.9375
4
# Project Euler - Problem-10: "Summation of primes" """The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.""" def isPrime(num): """ checks whether a number is prime""" for i in range(2, (int(num ** 0.5) + 1)): if (num % i) == 0: retur...
61ff78a9501e36550ae19e5f7cc8dc99038719c4
juanframart2011/tutorial-python
/capturas-error.py
163
3.828125
4
#capturar errore try-except entero = input( "número entero" ) try: entero = int( entero ) except ValueError: print( "no es un entero" ) print( entero )
693927cd66799f61cf111284dea85238c73f5096
juanframart2011/tutorial-python
/sqlite3/insertar-datos.py
1,026
4
4
import sqlite3, datetime print( "*** Programas para insertar registros en la tabla test ***" ) cadena_texto = input( "Introduzca una cadena de texto" ) entero = input( "Introduzca un número entero" ) decimal = input( "Introduzca un número decimal" ) try: entero = int( entero ) except ValueError: print( ent...
5bbb350c01d4f2911b69dd6dee41472cc5b3aeb7
IanFinlayson/exploring-cs
/programs/4.3.py
132
4.03125
4
# program to print just the first letter of the user's input response = input("Enter a string: ") first = response[0] print(first)
e5e94bcabc68d483a142c9776ad8157ea455ffd6
IanFinlayson/exploring-cs
/programs/5.2.py
359
4.09375
4
temp = float(input("What temperature is it out? ")) if temp < 10: print("It's super cold, maybe stay home?") elif temp < 30: print("Wear a snowsuit") elif temp < 60: print("Wear a coat.") elif temp < 80: print("You should wear pants.") elif temp < 95: print("You should wear shorts.") else: prin...
c8a33595cfdd6f163dd4f9d3aa9722d89bc95806
edrandall-dev/python
/pong.py
2,971
3.765625
4
#!/usr/bin/python3 #Import & initialise pygame import pygame import time import sys pygame.init() #Window Title pygame.display.set_caption('The worst incarnation of pong that you\'ve ever seen!') print() print("Your score is: ", end='') #Set some variables WIDTH = 1000 HEIGHT = 600 BORDER = 20 VELOCITY = 10 S...
f33cf2c903c778089a1ebd2c5810fc99515085e5
kirubah18/guvi
/codekata/sqareofdigits.py
74
3.609375
4
so = input() sum1=0 for i in so: i=int(i) sum1=sum1+(i*i) print(sum1)
1d679b43b907e70fae208611145d113b64aa4cf5
kirubah18/guvi
/codekata/check3ptsarecollinear.py
253
3.515625
4
x11,y11=input().split() x11,y11=int(x11),int(y11) x22,y22=input().split() x22,y22=int(x22),int(y22) x33,y33=input().split() x33,y33=int(x33),int(y33) if (y11 - y22) * (x11 - x33) == (y11 - y33) * (x11 - x22): print ("yes") else: print ("no")
537a8ffbcb74a2272d8c42b19b8d7c1f2f3d2410
kirubah18/guvi
/codekata/nearevn.py
70
3.625
4
nu1=int(input()) if(nu1%2!=0): n2=nu1-1 print(n2) else: print(nu1)
b0526f1f45a80344b6517ff91301822b86eedd08
kirubah18/guvi
/codekata/weekendholiday.py
84
3.796875
4
si=input() if(si=='Sunday') or (si=='Saturday'): print("yes") else: print("no")
d39d33ba619b51e75aa623864e0f0b92275a9eb7
kirubah18/guvi
/codekata/sumofdgt.py
92
3.75
4
inpt=int(input()) sum=0 while(inpt>0): digit=inpt%10 inpt=inpt//10 sum+=digit print(sum)
3c77c7a8186d60428194c5132786c6a248354c59
Cuidecheng/PythonLearning
/Python_Basiclearning/Chapter_Eleven.py
1,501
3.5
4
# Author: Cui De Cheng # University: China University of Mining and Technology Beijing # Position: Student # Development time: 2021/8/14 15:48 # ----------------------------------------------------------------- # # bug异常的捕获 # try...except结构 try: a = int(input('输入第一个整数:')) b = int(input('输入第二个整数:')) result ...
33571f26c360a771ff870e2272f8dfd22794e017
echap1/CS550
/HW3-Basic-Operations/question3.py
930
3.59375
4
""" CS550 Homework: Basic Operations - Question 3 (Day of Week) Due September 14, 2018 @author: Ethan Chapman """ import os, sys, inspect sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))) from libs.commandLine import * def main(): cl = CommandLine(__...
d2f780ce239fe60252e8459a0836376b2c3c72e9
echap1/CS550
/HW9-Random-Walk/walk.py
6,169
3.828125
4
""" CS550 Homework: Random Walk Due January 11, 2019 @author: Ethan Chapman Part A: What is the longest walk you can take where you'll be within walking distance of home at least 50% of the time? This is a harder question than it seems. You can't just do random walks of length n, and calculate the percent tha...
8beb44bb1abf99b16cc7b4a05f3dca7b6b3f6c93
derekyang7/WSIB-Coding-Challenge
/code-obfuscation.py
811
4.15625
4
def myfunction(): num = input("Enter string:") a = "" b = num while len(b) > 0: if len(b) > 0: c = b[-1] b = b[:-1] a += c else: break if a == num: return True else: return False """Function that reverses the order ...
da689e5dbfc167bf61fb34255b671b4c53ab1f01
michaelremington2/Rosalind-and-bioinformatics-scripts
/bioinformatics_official_functions.py
4,300
3.703125
4
class bioinformatics_exploratory_analysis: def __init__(self,dna_sequence): self.dna_sequence = dna_sequence self.dna_sequence_list = list(dna_sequence) self.a_count = 0 self.t_count = 0 self.g_count = 0 self.c_count = 0 self.dna_nucleotide_count = se...
2adc6545b8d6dcc6760907fe667129c5002aca2a
jayrbolton/query_csv
/query_csv/utils.py
2,809
3.765625
4
import gzip import shutil import tempfile import csv import os from typing import Union, List, Generator # yielded by the CSV parsers below. Generator of lists of column values for # every row in a CSV Rows = Generator[List[str], None, None] def convert_col_type(val: str) -> Union[str, float, int]: """ Conve...
8e29110b9907c8f4f4a2c16345f975de9b6188da
bdaene/python-challenge-tools
/euclide.py
1,402
3.671875
4
"""Library about GCD Euclide's algorithms and applications""" def gcd(a, b): """Returns the greatest common divisor of a and b.""" # It is better to use math.gcd. while a: a, b = b % a, a return b def gcde(a, b): """Extended Euclide's GCD algorithm.""" # The equalities r = a*u+b*v an...
590a19e766c24398c6a71eda3e5e3a8e76279012
zpopovych/CompPhys
/04/rand1.py
662
3.640625
4
""" Random number generation using linear congruent method Lev Kaplan 2019 """ # rand1.py: experimenting with random numbers from pylab import * def drand48(): global rnd rnd = (0o273673163155 * rnd + 11) % 2**48 # 0o means octal notation return rnd/2**48 # return number between 0 and ...
b32a7bed03c4034235686335c0f10b904eb94f38
epfl-dlab/deplatforming_dataset
/scripts/link_google_id.py
1,348
3.546875
4
from __future__ import print_function import json import urllib def link_google_id(entity): ''' This method links the entity with its google id. To use this function, it is necessary to first generate an API key file with an associated google accounts (https://developers.google.com/knowledge-graph/prereqs). ...
899f1c3063264dd7bae129fcf0e5cebf622eb1bd
vsedov/Fun_Scripts
/chapter_1_5/chapter_2/palindromes.py
1,262
3.765625
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © Viv Sedov # # File Name: palindromes __author__ = "Viv Sedov" __email__ = "viv.sv@hotmail.com" import pyinspect as pi import load_dictionary # Might add this to be really quick depending on how i would code def question(question: str)...
b6616e4747cc6723d408388c98bf7f1f50b801fe
VanherpeDries/labo_BP
/lab_01/oefeningen basis week-01.py
1,224
3.640625
4
# labo_intro oef1 (steeds commentarieeren) #naam = "dries" #achternaam = "vanherpe" #print("hello world,",naam,achternaam) basis= float(input("wat is basis?")) hoogte =float(input("wat is de hoogte?")) opp = (basis*hoogte)/2 print("de totale oppervlakte van de driehoek is {0:.2f}".format(opp)) # ^oefening vijf bereke...
99d0208314e4325ed63a965e5ccde27e94e178ae
clintreyes/num_model
/average_1_to_N.py
150
3.984375
4
def average_integer(N): sum = 0 for i in range(0,N+1): sum += i return sum N = int(input("input an integer: ")) print(average_integer(N))
d7862850e091aec35184ed124cda3f052ebd8a8d
clintreyes/num_model
/ch3/trapezoidal_alt1.py
436
3.609375
4
from math import exp a = 0.0; b = 1.0 n = int(input('n: ')) dt = float(b-a) / n # Integral by trapezoidal method numerical = 0.5*3*(a**2)*exp(a**3) + 0.5*3*(b**2)*exp(b**3) for i in range(1,n): numerical += 3*((a+i*dt)**2)*exp((a+i*dt)**3) numerical *= dt exact_value = exp(1**3) - exp(0**3) error = abs...
bedeca05898170a494c99114626316e46244480f
clintreyes/num_model
/function_area_rectangle.py
160
3.890625
4
def area_rectangle(b,c): b = float(input("Input value of b: ")) c = float(input("Input value of c: ")) A = b*c return(A) print(area_rectangle(2,3))
a086ad53f58f18ede70ba9eff3eb6d474ec49457
hrd005/lab3_inf
/lab_03_01.py
1,142
4.375
4
''' Кортежи ''' # создание кортежа a1 = tuple() a2 = 1, 2, 3, "abc" a3 = (1, 2, 3, "abc") print("Tuple a1 = ", a1) print("Tuple a2 = ", a2) print("Tuple a3 = ", a3) # создание кортежа из других структур данных l = [1, 2, 3, "abc"] # из списка a4 = tuple(l) print("Tuple a4 from list l = ",...
8361aeaa503adfa3d5a6aa9166f2628522d588e6
paramsingh/cp
/src/long/jun15/prob.py
2,864
3.546875
4
def area_trap(side1, side2, normal): return 0.5 * (side1 + side2) * normal def area_triangle(normal, base): return 0.5 * normal * base cases = int(raw_input()) for term in range(cases): # flag1, flag2 = False, False timex, timey, waitx, waity = map(float, raw_input().split()) # boundary rectang...
ba2448e91d750c2cf920f63fae0d08dc8e189b1c
paramsingh/cp
/src/practice/snape.py
288
3.578125
4
# http://www.codechef.com/problems/SNAPE def maximum(ls, b): return ((ls**2) + (b**2))**0.5 def minimum(ls, b): return ((ls**2) - (b**2))**0.5 t = int(raw_input()) while t: line = raw_input().split() b = int(line[0]) ls = int(line[1]) print minimum(ls, b), maximum(ls, b) t -= 1
2c240bd4da4dc9a27bf5f5fa07a16646271aeb90
paramsingh/cp
/src/recreation/infinity.gauntlet.py
445
3.515625
4
color = { 'purple': 'Power', 'green': 'Time', 'blue': 'Space', 'orange': 'Soul', 'red': 'Reality', 'yellow': 'Mind', } if __name__ == '__main__': n = int(input()) gems = [] for _ in range(n): gems.append(input()) cnt = 0 ans = [] for gem in color: if gem ...
8bcef3fbff8e70167fbf8c37d6dd4f74dd2769f4
ryantupo/christos---the-prisoner-dilemma
/christos.py
1,901
3.953125
4
#if we both keep quiet 1 year each // if both speak 2 years each // if only one you get 0 other gets 3 // import random #percentage chance both keep quiet? --- #percentage chance both talks? --- class prisoner: def __init__(self, name, decisions,safe, c_decision): self.name = name self.decisions...
0dcbc7574b6ac381e61252dfa5c99a8a5b866a0f
tvrt0001/CodeWars-Python
/challenges_7kyu/linked_lists_push_build_one_two_three.py
1,008
3.90625
4
##################################################################################### # # # NAME: Linked Lists - Push & BuildOneTwoThree # # RANK: 7kyu ...
79e1a4aa7f2c2f43b375af231db3e7ca7ae3f63b
tvrt0001/CodeWars-Python
/SolutionsByTobi/challenges_5kyu/exractDomainName.py
812
3.609375
4
##################################################################################### # # # NAME: Extract the domain name from a URL # # RANK: 5kyu ...
3beb8c97a7ec7ff89cc9f163d4a37538c45b01de
tvrt0001/CodeWars-Python
/challenges_4kyu/sudoku_solution_validator.py
2,047
3.859375
4
############################################################################### # # # NAME: Sudoku Solution Validator # # RANK: 4kyu # ...
ed220d48bd76b8c5beb8ee969e072be5b64d6872
tvrt0001/CodeWars-Python
/challenges_6kyu/highest_rank_number_in_an_array_2.py
1,237
3.6875
4
##################################################################################### # # # NAME: Highest Rank Number in an Array # # RANK: 6kyu ...
6fd271c5a9306bbd737e223d2d0236547ba033a2
tvrt0001/CodeWars-Python
/SolutionsByTobi/challenges_6kyu/tribonacci.py
846
4.15625
4
##################################################################################### # # # NAME: Tribonacci Sequence # # RANK: 6kyu ...
97299a55c8decec90677a4433bc2c0c274e684f4
yeongbin08/20200114.txt
/total.py
273
3.625
4
#기간의 전체 날짜의 수를 찾는 것과 5일 후의 날짜 찾기 한 것입니다. from datetime import datetime, timedelta t1=datetime(2019,12,10,9,00,1) t2=datetime(2020,5,20,17,40,1) t3=datetime.now() totalDay=t2-t1 print(t2-t1) print(t1+ timedelta(days=5))
5cfaa23ee0db02760d140480d7f07828b85f9e8f
nivekranjith/COS4861
/Assigment 1/Question3.2.py
1,703
3.84375
4
def CalculateMinEditDistance(str1,str2, insertWeight, deleteWeight, substituteWeight, showMatrix): str1length = len(str1) + 1 str2length = len(str2) + 1 matrix = [[0 for col in range(str1length)] for row in range(str2length)] for col in range(str1length): matrix[0][col] = col for row in r...
c69134bea13eea50381866e77ab1d7c833899d72
palka-michal/aoc2020
/task1.py
542
3.609375
4
# Part 1 import numpy as np A = np.loadtxt(fname="task1") from itertools import combinations from math import prod def rSubset(arr, r): return list(combinations(arr, r)) for x in rSubset(A, 2): if sum(x) == 2020: print(x) print(prod(x)) # Part 2 import numpy as np A = np.loadtxt...
b1e254e649b83072a1ea2a09f3e40d5a7f6b5a5d
siggij91/TileTraveller
/tile_traveller.py
2,353
4.1875
4
##Project 5 Tile Traveler https://github.com/siggij91/TileTraveller #Create tile structure and label it #Append allowable moves to file structure #N = +1 in second index and S = -1 #E = +1 in first index and W = -1 #Once in new tile, show the allowable moves #Once player enters 3, 1 show them that they win. def can...
4a578dd7fcd9cc12e0a6e28051f5641d2a9c22fe
vijaypal89/algolib
/ds/linkedlist/intro2.py
593
4.125
4
#!/usr/bin/python import sys class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp: print temp.data, temp = temp.next ...
af5e7f0fdcaba36ad0ea05711d7e9bf6153537ea
udox/learningpy
/vans.py
2,129
4
4
import urllib from BeautifulSoup import BeautifulSoup """ TASK Write a function that uses BeautifulSoup to get titles and summaries of posts on vans.com's news search: http://www.vans.com/news/search/?search_keywords=KEYWORDHERE Try http://www.vans.com/news/search/?search_keywords=rowley and you'll ge...
870c7d89dc0f9d6a6edbc11dd29bb00cc5c22905
swetharajaraman/Design-3
/Problem1_FlattenNestedListIterator.py
870
3.9375
4
# Time Complexity: O(n), where n - number of integers in the list # Space Complexity: O(n) class NestedIterator: def __init__(self, nestedList: [NestedInteger]): self.stack = [] self.nextElement = None # Append the nestedList as an iterator into the stack self.stack.append(iter(nest...
bd41821baf51406cc0c723aef66da6606c5888e2
aKondratyuk/Python-Enchantress
/homework/inheritance.py
1,263
3.8125
4
class Animal: def __init__(self, animal_type, speed): self.animal_type = animal_type self.speed = speed def run(self): return self.animal_type + " has speed of running " + self.speed class Dog(Animal): def __init__(self, animal_type, speed): super().__init__(animal_type, s...
a2e346b0dd0fc2607f07bbd92b912d2d56228dee
Vitalyfromby/Sorts
/sortApp/sort_engine.py
3,682
3.9375
4
def time_counter(func): import time def wrapped(*args): start_time = time.clock() return_value = func(*args) run_time = float(round((time.clock() - start_time), 9)) print(run_time) return return_value, run_time return wrapped class Algorithms: def __init__(se...
4811b51911e65942b13b6cbc14c4097896991cd9
skillsapphire/Url-Shortner
/test.py
835
3.515625
4
import sqlite3 cn = sqlite3.connect('urls.db') conn = cn.cursor() # check what data is present z = conn.execute(''' SELECT * FROM urls ''') print(z.fetchall()) # insert some data original_url = 'http://zetcode.com/db/sqlitepythontutorial/' url2 = 'https://github.com/narenaryan?tab=repositories' # insert same data...
af7924d8d914c4ddac82a9296d4b62dc03aa0276
LParker7/Practicals
/prac_04/lottery_ticket_generator.py
579
3.890625
4
import random def main(): number_of_rows = int(input("How many quick picks? ")) for row in range(number_of_rows): quick_pick = get_quick_pick() quick_pick_string = ' '.join(str(number) for number in quick_pick) print(quick_pick_string) def get_quick_pick(): quick_pick = [] fo...
6ba58a6be194bc36876e94994997a1efe6a6ed1d
jiangnandekafuka/python
/chepter9_bird_chaoleigouzao.py
441
3.671875
4
__metaclass__=type class Bird: def __init__(self): self.hugry=True def eat(self): if self.hugry: print 'Aaaah...' self.hugry=False else: print 'No,thanks!' class SongBird(Bird): def __init__(self): Bird.__init__(self) self.sound='...
5a5e2cc1cff4d8c69cdc0e034a8bb36a4eae7dc3
RALaFrance222/HaikuBot
/haikubot.py
3,758
3.53125
4
#Andrew LaFrance 2014 #HaikuBot - Program to randomly create haikus for the MSU StreetCar Journal #Word Lists provided by ashley-bovan.co.uk #import makehaiku #print(makehaiku.haiku) #print("By RAL") import random nouns1 = [line.strip() for line in open('dictionary\\nouns\\1syllablenouns.txt')] nouns2 = [line.stri...
e92c13988f42d00cd34eb375fd66731690be7377
labvit/student_manager
/db_adapter.py
1,918
3.9375
4
import sqlite3 class settings: ''' store db settings ''' db_file = 'student.db' class db: def connect(self): return sqlite3.connect(settings.db_file) def insert_student(self, student): with self.connect() as connect: try: cursor = connect.cursor() ...
5c7b58d61fb3df1bad1dbc775aac69fad7d5121d
Hestogpony/ETH_NLU_2017
/Task1/lstm.py
4,269
3.8125
4
''' Implementation of the LSTM cell and network. The cell is defined as follows: * An 'input' which computes a candidate value to introduce in the cell. * A 'modulate' gate which creates a mask for the candidate value, indicating how much it should be suppressed. * A 'forget' gate which creates a mask ...
9114541f1b9aa4b177fafd0ac50ef8b81ce76da0
AlreadyTakenJonas/pythonBootCamp2021
/easyExercise_12_regression/easyExercise_12_regression.py
2,208
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 14 17:20:35 2021 @author: jonas """ # IMPORT MODULES # Handling linear regression from sklearn.linear_model import LinearRegression # Handling exponential regression from scipy.optimize import curve_fit # Handling numbers and arrays import numpy as...
b3720f9f71f286e8b5b78cedcfa016537355fb13
AlreadyTakenJonas/pythonBootCamp2021
/easyExercise_06_readingFiles/easyExercise_06_readingFiles.py
1,205
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 27 20:30:12 2021 @author: jonas """ """ This program reads the alphabet and the numbers from 0 to 9 from a bunch of files and combines prints the information to the screen. """ # IMPORT MODULES # # Handling files and paths from p...
60590f560bd5e80e354a69a3d15a3c7bbc4fc74b
missweetcxx/fragments
/leetcode/subsets.py
702
3.796875
4
# # Create on 4/23/2018 # # Author: Sylvia # """ 78. Subsets Given a set of distinct integers, nums, return all possible subsets (the power set). """ class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [[]] f...
bdd47c34c975d5e2cad8f23503894dd6081e77e6
missweetcxx/fragments
/leetcode/self_dividing_nums.py
1,322
3.90625
4
# # Create on 5/18/2018 # # Author: Sylvia # """ 728. Self Dividing Numbers A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. """ class Solution(object): @staticmethod def self_di...
6555fc9f01be948961f32b3f7a955c654e074c32
missweetcxx/fragments
/leetcode/sum_of_square_nums.py
812
3.78125
4
# # Create on 5/2/2018 # # Author: Sylvia # """ 633. Sum of Square Numbers Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. """ import math class Solution(object): @staticmethod def judge_square_sum(c): """ :type c: int ...
051ef3dac4e40e5c2512b4cce9b5328222da06fe
missweetcxx/fragments
/leetcode/add_digits.py
1,063
4.03125
4
# # Create on 4/17/2018 # # Author: Sylvia # """ 258. Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. """ from functools import reduce clas...
9560b14628282f160b3581867cab32b781d8b5b3
missweetcxx/fragments
/leetcode/merge_two_binary_trees.py
1,950
4.0625
4
# # Create on 4/23/2018 # # Author: Sylvia # """ 617. Merge Two Binary Trees Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes over...
d9bb554f9b9c9b7d13e0ac28f39d3d5367e92280
missweetcxx/fragments
/fragments/triangle.py
826
4.0625
4
# # Create on 2/5/2018 # # Author: Sylvia # """ Triangle Given a triangle, find the minimun path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For Example, given the following triangle: [ [2], [3],[4], [6],[5],[7], [4],[1],[8],[3] ] """ class Triangle: def...
339114be5ed48f6052a21b6ec9f260e385c686c5
missweetcxx/fragments
/segments/sorting/g_shell_sort.py
1,120
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from segments.sorting.d_insert_sort import InsertSort class ShellSort: @staticmethod def solution(my_list): length = len(my_list) step = length // 2 while step > 0: for i in range(step): list = [my_list[x] for x ...
d9f5ed830b39528cb67c10bdb83fabcc1292286c
missweetcxx/fragments
/fragments/max_subarray.py
1,365
3.984375
4
""" 53. Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. """ def max_cross_subarray(arr, mid, low, high): now_left = arr[mid] left = arr[mid] for i in range(mid - 1, low - 1, -1): now_left = no...
130d68404004f4f07a239ae97dec645ec77022ce
missweetcxx/fragments
/leetcode/reverse_linked_list.py
1,487
4.0625
4
# # Create on 4/16/2018 # # Author: Sylvia # """ 206. Reverse Linked List Reverse a singly linked list. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): ...
7736bd8f305be6ea6e633d1fd34a7fe4e3ec33e3
missweetcxx/fragments
/segments/sorting/d_insert_sort.py
2,061
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class InsertSort: """ Insert Sort divide list into two lists: sorted one and unsorted one; each time insert an element from unsorted list into sorted one at correct position; Complexity: O(n^2) in worst case Memory: O(1) """ @staticmethod...
25d5e2d5f13b3580b96f8a8496ba1377b28171a6
missweetcxx/fragments
/segments/binary_tree/binary_tree.py
1,895
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from segments.binary_tree.node import Node class BinaryTree(object): """ generate binary tree """ def __init__(self): self.root = None pass # create a binary tree with nodes def _add_node(self, val): # create root node of...
2473cc61a41c0adc77ab127533ed5c83503d9f97
GabrielTovar91/SentimentalNetwork
/toolsNet/neuralNet.py
4,858
3.875
4
""" IMPLEMENTING A NEURAL NETWORK Following https://www.youtube.com/watch?v=XqRUHEeiyCs&list=PLRyu4ecIE9tibdzuhJr94uQeKnOFkkbq6 """ # Imports import numpy as np # Transfer functions def sgm(x, Derivate = False): if not Derivate: return 1 / (1+np.exp(-x)) else: out = sgm(x) return out * (1.0 - out) def linea...
c6028097760cbb32a3c9a52d82dd94d8fd23dccc
tunnelview/Sandbox
/Prac_03/password_check.py
729
4.1875
4
def main(): MINIMUM_LENGTH = 16 get_password(MINIMUM_LENGTH) def get_password(MINIMUM_LENGTH): get_password = input("Enter Password of at least {} characters: ".format(MINIMUM_LENGTH)) while len(get_password) < MINIMUM_LENGTH: print(f"please enter password of {MINIMUM_LENGTH} characters") ...
98b83b4682cd437da333665f77882118c2c77bd6
kennygao/adventofcode2020
/08.py
1,090
3.65625
4
with open("input/08.txt") as f: lines = [line.rstrip("\n") for line in f] def parse(line): operation, argument, *_ = line.split() return operation, int(argument) code = [parse(line) for line in lines] def run(program): seen = set() pc = 0 accumulator = 0 while pc not in seen: i...
6779b061c38dfb54b977a2bee0f34ca70a86ddc7
qadaidi/tp01-qadaidi-python
/tp01_ex1.py
1,697
4.15625
4
""" Programme permettant de convertir une quantité en plusieurs unités d'énergie. 1J = 0.738 ft-lb = 0.239 cal = 6.24*10^18 eV Unités : joule, calorie, Ft-lb et eV Données : Une valeur et une unité Indications: Selon l'unité entrée par l'utilisateur, afficher la conversion dans les 3 autres ...
d081b2b0c64a40844c133913ae944f05f57b7ec5
koiralaa/PythonScripts
/fibonacci.py
1,093
3.96875
4
import time def fib(n): if n == 0: print("Error : ", end="") return 0 if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) def fib_memo(n, memo): if (memo[n] != 0): return memo[n] if n == 1 or n == 2: result = 1 else: result = fib_memo(...
cd17396359380caf10f63ed41ce756d757f48da2
aliasthomas/Perfect_numbers
/Perfect_numbers.py
600
4
4
# Python program to print perfect number # function definition for perfect def perfect(n): s=0 for i in range(1,n+1 // 2): # n+1 is to count the last number. if n % i ==0: s = s + i return(s) # function definition to print perfect number ...
636b7b09d8210bc5df36f70677b1863409f0b016
chloebecker/extract
/extract.py
3,486
3.734375
4
from random import randint #our stack will just be a list- .append() = push, .pop() = pop! stack = [] extract = ["pour", "pull", "filter", "scoop", "grind", "brew", "(|)", "stir", "price", "lightRoast", "darkRoast", "makeLatte", "roast", "new"] def GetText(fileName) : #opens file with name of "sample.txt" fil...
c3412388a0116b1f4d02d973498c674c0844e371
catarcatar/cursopython
/ejercicio08.py
511
3.875
4
''' Escribe una función llamada raiz_cuadrada que reciba un parámetro num y retorne la raíz cuadrada de num. Nota: Usa el operador exponente ** para calcular la raíz cuadrada. # escribe la función raiz_cuadrada acá # código de prueba print(raiz_cuadrada(25)) # 5.0 print(raiz_cuadrada(5476)) # 74.0 print(raiz_cuadrad...
f3dd8be637e4f4523587e54784400c88cf8a5f02
catarcatar/cursopython
/dia04.py
3,073
3.96875
4
''' ##Listas alturas = ([1.9, 1.7, 1.5, 1.2, 1.3]) #floats o integers nombres = ["Ana", "Andrea", "Juan", "Pedro", "Julian"] #strings mix = [12, "Juan", True] #numeros, strings o booleans lista_lista = [["Ana", 1.6]] lista_vacia = [] print(alturas) print(nombres) print() print(lista_vacia) lista_vacia.append(1) #llen...
d238ca151039d1ef380bd4ea71ba2d6eab10afdb
catarcatar/cursopython
/ejercicio07.py
493
4.46875
4
''' Ejercicio 7 Escribe una función llamada hola que reciba un parámetro (una cadena de texto) y retorne "Hola " seguido del argumento y un signo de exclamación. # escribe la función hola acá # código de prueba print(hola("Pedro")) # "Hola Pedro!" print(hola("Juan")) # "Hola Juan!" print(hola("")) # "Hola !" ''' def...
3db4db9c93004441a249355b1a923a8439e78aa8
jgerity/talks
/2016/computing_workgroup/intro-to-python/firstclassfunctions_example.py
1,431
4.59375
5
#!/usr/bin/env python def makeAddFunction(x): """ This function represents breaking the operation x+y into two steps, by returning a function F(y) that "knows" what value of x to use. In more specific terms, the value of x is stored in the "closure" of the function that is created. """ de...
94d56dd7221b002806984dc29e05402093bef1da
bributler927/Recommender
/BookReader.py
961
3.515625
4
''' BookReader.py''' import os '''def getdata(): file = open("data/books.txt", 'r') bookrates = {} books = [] for line in file: newline = line.split(',') student = newline[0] for book in newline[1::2]: if book not in books: books.append(book) ...
e9373bd61c1d550dc9254f484065b83df9150d35
Sact3rnlang3l/Module-4-Assesment
/process.py
689
3.515625
4
log_file = open("um-server-01.txt") #opens and logs the entire um-server-01 file in console def sales_reports(log_file): # creates a function called sales_reports using the parameter of log_file for line in log_file: #let's make the parameter into a loop line = line.rstrip() #line strips anything extra in ...
3efd34ad76ac8bc585692de0f0868b0a8c124001
Lguo0128/helloPython
/practice/chapter4/ex04_02.py
622
4.5
4
# 4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用 for 循环将每种动物的名称都打印出来。 #  修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。 #  在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子 animals = ['cat','dog','rabbit','bird'] for animal in animals: print('A ' + animal + ' would make a gre...
a14e9a6d2e0e0d51e1c28ca022c8e11743f78b7c
Lguo0128/helloPython
/practice/chapter3/ex03_05.py
695
3.96875
4
# 3-5 修改嘉宾名单:你刚得知有位嘉宾无法赴约,因此需要另外邀请一位嘉宾。 # 3-4 时编写的程序为基础,在程序末尾添加一条 print 语句,指出哪位嘉宾无法赴约。 # 修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。 # 再次打印一系列消息,向名单中的每位嘉宾发出邀请。。 invites= ['alan liu','betty Liang','carl tan','derk ma','eric chen','fancy Ou'] for person in invites: print( person.title() + ',do you have time?') print('\n\t'+i...
5eaddbb780c7bbb9a569a7e491bbb58a36b7e435
L200190168/praktikum6
/kegiatan4.py
1,694
3.671875
4
>>> Nama = 'Imawan Luthfi Pambudi' >>> NIM = 168 >>> Tinggi = 1.70 >>> Berat = 55 >>> TahunLahir = 2000 >>> Aku = (TahunLahir, Berat, Tinggi, NIM, Nama) >>> Data = [TahunLahir, Berat, Tinggi, NIM, Nama] >>> type(Aku) <class 'tuple'> >>> # data "Aku" merupakan type data "tuple" >>> Aku[0] 2000 >>> # objek pe...
fd129d7fb6c77ede03874c71e12868e3e10401a1
chandulal/python-basic
/forloop.py
67
3.5625
4
fruits = ["apple", "banana", "orange"] for x in fruits: print(x)
aa41ff5a557b6dd197863669657f09012679d7c1
pringlesLion/mycs231n
/assignment2/cs231n/classifiers/convnet.py
10,372
3.65625
4
import numpy as np from cs231n.layers import * from cs231n.fast_layers import * from cs231n.layer_utils import * class ConvNet(object): """ A three-layer convolutional network with the following architecture: {conv -[spatial norm]- relu - 2x2 max pool} x N - {affine - [batch norm] - relu - [dropout]} x M - ...
ae2f5d50fc524f1b69a6ff78ec5b677bf8b9612b
linbofeng/learn-code
/penghaicheng/html/python/hello-world.py
158
3.921875
4
from datetime import datetime, timedelta # 注释:打印教程 print(datetime.today()) days = 6 before = datetime.today() + timedelta(+days) print(before)
63e7f3303c53473a445e23534e2dde107cd416dc
johan530/Challenge-Juego-de-carros-por-consola
/carro.py
783
3.578125
4
# -*- coding: utf-8 -*- """ Created on Jul 2021 Versión 1.0 @author: Johan Toloza """ class carro: def __init__(self, nombre, color): self.nombre = nombre self.color = color self.distancia=0 self.victorias=0 def getNombre(self): return self.nom...
385aeb4c3cb35d11039200c5134d2979ded38400
minmyatthu1/Test
/Pawn/Gold price calculator.py
690
3.609375
4
# 1 kyat = 16pel = 128yway price = int(input("Enter current gold price: ")) kyat = int(input("enter kyat: ")) pel = int(input("enter pel: ")) yway = int(input("enter yway: ")) yway_subtraction = int(input("Enter yway_subtraction: ")) # pel_addition: float = 0 # kyat_addition: float = 0 def cal(): if yway > 8:...
b2b25a52acd36f0321a94596067c80a573978084
rohith19113038/python.py
/Simple Python programs using Looping and Loop Control statements
383
4
4
our_pass="pass123" my_pass="" no_of_try=0 no_of_Max_try=3 Max_try="not reached" while my_pass!=our_pass and Max_try!="reached": if no_of_try<no_of_Max_try: my_pass=input("enter the password:") no_of_try no_of_try=no_of_try+1 else: Max_try="reached" if Max_try=="reached": ...
833156079963cb098f356e0fd7765d16ac7f02d9
simonenicf/Escape-from-Narlilia
/src/main.py
58,989
3.828125
4
import sys import time import random from menu import Menu from game_engine import Console, Player console = Console() player = Player() start = True basement_suprise = ["demon", "open", "closed", "bear"] sus_building = ["enemy_trap", "human_traffic", "smuggler"] boat_stuff = ["tip over", "fight", "safe"] truck_surviv...
434e454f2c98287d54e16e3ac63f68e86108c168
dangduylan/dangduylan-homework-c4e30
/session02/factorialcal.py
112
4.21875
4
n = int(input('Enter number:')) f = 1 for i in range(1,n+1): f = f*i print("Factorial of the number is:",f)
4c2bee59067985a8ac243c0c3a68ba6ad340c183
dangduylan/dangduylan-homework-c4e30
/session05/turtle_ex_05.py
208
3.96875
4
from turtle import * shape('turtle') def draw_star(x,y,length): penup() setposition(x,y) pendown() for i in range(5): forward(length) right(144) draw_star(10,20,100) mainloop()
1c1e52c4a9424408bbb16830ab4c000c92097d06
dangduylan/dangduylan-homework-c4e30
/session01/ptmanycircles.py
107
3.734375
4
from turtle import * shape('turtle') speed(0.5) for i in range(36): circle(100) left(10) mainloop()
f8b2a7f02b73ce360ab01d4ccdcc86032a96da96
n-faria/Tetris_Game
/tetris.py
36,280
3.546875
4
#Tetris #Nicholas Faria #Jan 25, 2018 #Recreation of the famous game tetris import pygame, random, time #Import the modules needed pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() #Call this function so the pygame library can initialize itself screen_width = 800 screen_height = 800 #Create variab...
ae6cc4196b2993dbb351c1bc6a2e8ff8fb5575d7
crackcrash/LearnNotes_Unimport
/LearnPython/Samples/classEx.py
1,927
3.859375
4
class classEx(object): """description of class""" pass class Person(): '''Person description''' def __init__(self): pass #看这个实例 class Person2(): """Person2 description""" #静态变量 staticVar = 1 def __init__(self, name): self.name1 = name #实例变量 @classmethod def c...
6ee846545dc411a346b3f810ffbe1fd99aa9b5d7
TezDmitry/Lesson
/number_game.py
1,502
3.859375
4
import random number = random.randint(1, 100) user_number = None count = 0 levels = {1: 10, 2: 5, 3: 3} # создаём уровни сложности и количество попыток в них level = int(input('Выберите уровень сложности от 1 до 3: ')) # предлагаем пользователю выбрать уровень сложности max_count = levels[level] user_count = int(i...
f15bacf358ecc967ff5fabc2644ab353b1541ef2
whiteblue0/Algorithm
/05_Stack_02/postfix notation.py
285
3.703125
4
data = ['2','+','3','*','4','/','5'] fixlst = [] stack = [] for i in range(len(data)): if data[i] == '+' or data[i] == '-' or data[i] == '*' or data[i] == '/': stack.append(data[i]) else: print(data[i],end='') while len(stack): print(stack.pop(),end='')