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
bf90010d0cdce556867524453c439db5e5b0bbd8
btrif/Python_dev_repo
/Maths/Polynomials_Functions/Taylor_polynomials_partial_sums.py
798
3.515625
4
#!/usr/bin/env python # Jonathan Senning <jonathan.senning@gordon.edu> # Gordon College # January 1999 # Revised August 2000 # Revised April 27, 2006 to update graphing commands # Converted to Python May 2008 # # This python program does essentially the same thing as the sequence # of MatLab commands given on page 25 ...
2dbae09466384658d5906425b8aeb6095495ac1a
btrif/Python_dev_repo
/BASE SCRIPTS/searching.py
1,535
4.75
5
# ### Python: Searching for a string within a list – List comprehension # The simple way to search for a string in a list is just to use ‘if string in list’. eg: list = ['a cat','a dog','a yacht'] string='a cat' if string in list: print ('found a cat!') # But what if you need to search for just ‘cat’ or some oth...
1833ffe13ec5e12a351380518671ddccd79991f9
btrif/Python_dev_repo
/BASE SCRIPTS/OOP/class_Worker_example.py
558
3.734375
4
# A first Python script class class Worker: def __init__(self, name, pay): # Initialize when created self.name = name # self is the new object self.pay = pay def lastName(self): return self.name.split()[-1] # Split string on blanks def giveRaise(self, percent): self.pay *= (1.0 + percent) # Update pay...
e08b3350dbfe2a82abfc7f9f804192c6708fa458
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/test-ComplyAdvantage/pb03.py
1,334
3.765625
4
def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f): self.f = f def __call__(self, *args): return self[args] def __missing__(self, key): ret = self[key] = self.f(*key) ...
b6f7cc9d969e3cdb4a2d59664e4e285ea06b2880
btrif/Python_dev_repo
/Algorithms/Recursion/partition.py
1,085
3.734375
4
# Created by Bogdan Trif on 09-09-2017 , 9:34 PM. def partition(number): ''' :Description: partition a number into a custom set of integers ''' answer = set() answer.add((number, )) for x in range(1, number): for y in partition(number - x): answer.add(tuple(sorted((x, ) + y))) ...
42882aa525e0bc86cdd1bfded6aaca1dc2013d9a
btrif/Python_dev_repo
/plots exercises/05_ellipse_03_working.py
1,259
3.703125
4
from numpy import linspace from scipy import pi, sin, cos def ellipse(ra , rb , ang , x0 , y0 , Nb=500): '''ra - major axis length rb - minor axis length ang - angle x0,y0 - position of centre of ellipse Nb - No. of points that make an ellipse based on matlab code ellipse.m written by D.G. Long, ...
0df9971ca88550d72efbbbea7ba9ad99ac5adba5
btrif/Python_dev_repo
/plots exercises/05_ellipse_03_original.py
1,061
3.75
4
from numpy import linspace from scipy import pi,sin,cos def ellipse(ra,rb,ang,x0,y0,Nb=50): '''ra - major axis length rb - minor axis length ang - angle x0,y0 - position of centre of ellipse Nb - No. of points that make an ellipse based on matlab code ellipse.m written by D.G. Long, Brigham Y...
6becbf5541e11d80a5ce48dd454d837816bbbfec
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/PYTHON 3 - Scientific Training/interactive input.py
66
3.625
4
x = input('Enter name: ') print('Hey ' + x) input('Press<enter>')
f9a1940dc62eb85a85441c7b6d564440505d9441
btrif/Python_dev_repo
/BASE SCRIPTS/input_control_while_guess number.py
2,306
3.984375
4
x=100 h=100 l=0 y=0 print ("Please think of a number between 0 and 100!") while True: if y!='c': print ("Is your secret number " + str(int((h+l)/2)) +"?") y=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") ...
77f890063b506c0840a89a9c89aa7be3e2db61a8
btrif/Python_dev_repo
/BASE SCRIPTS/module_operator.py
1,090
3.6875
4
import operator # My answer is a little late, but I hope that maybe it will be helpful for the future. # Yes, you are right. The problem with the translation from Python 2 --> Python 3 # is the fact that lambdas in Python 3 do not accept tuples as arguments. # However, there is a solution and this is done by having th...
2b95f260c276576a1305aa5cc877ab2a14b257f0
btrif/Python_dev_repo
/BASE SCRIPTS/OOP/slots.py
3,273
4.5625
5
# Created by Bogdan Trif on 19-07-2018 , 6:59 PM. # https://www.python-course.eu/python3_slots.php ''' === Slots === == Avoiding Dynamically Created Attributes The attributes of objects are stored in a dictionary "__dict__". ...
15705a89c31afbb086c3f166ae551352f6725885
btrif/Python_dev_repo
/Algorithms/Recursion/tst01.py
921
3.875
4
# Created by Bogdan Trif on 30-06-2018 , 3:16 PM. import turtle myTurtle = turtle.Turtle() myWin = turtle.Screen() myTurtle.speed(10) def drawTriangle( points , color , myTurtle ): myTurtle.fillcolor(color) myTurtle.up() myTurtle.goto(points[0][0],points[0][1]) # ( -100, -50 ) myTurtle.down...
82cb8a02ea63a13f19ac018b76d56d770dab7d9b
btrif/Python_dev_repo
/NumPy-Tutorial/numpy_tutorial_Using_array-generating_functions.py
1,497
3.890625
4
# Using array-generating functions from numpy import * '''For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in numpy that generates arrays of different forms. Some of the more common are:''' # arange...
19841920929365b29c6a87d626860a7893f5a086
btrif/Python_dev_repo
/Algorithms/subset/stackoverflow.py
930
3.59375
4
''' http://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number ''' def stackoverflow(x_list, target): memo = dict() result, _ = g(x_list, x_list, target, memo) return (sum(result), result) def g(v, w, S, memo): subset = [] id_subset = [] f...
a42127989a11eabe0a112f58ec1e6ca0a4be9bcd
btrif/Python_dev_repo
/BASE SCRIPTS/OOP/static_variables.py
2,037
4.5
4
# Created by Bogdan Trif on 17-07-2018 , 3:34 PM. # I noticed that in Python, people initialize their class attributes in two different ways. # The first way is like this: class MyClass: __element1 = 123 # static element, it means, they belong to the class __element2 = "this is Africa"...
0b4eae1855d2a62e6152419526c4f49d08c1085d
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/EDX - MIT - Introduction to Comp Science I/bank_credit_account.py
844
4.65625
5
''' It simulates a credit bank account. Suppose you have a credit. You pay each month a monthlyPaymentRate and each month an annualInterestRate is calculated for the remaining money resulting in a remaining balance each month. ''' balance = 5000 # Balance monthlyPaymentRate = 2/100 # Monthly payment rate...
864c98a7bf4d7f5d6906772f40e991b32630c18f
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/EDX - MIT - Introduction to Comp Science I/final EXAM - Longest Run - Monotonic List.py
5,267
4.03125
4
# Problem 4 # Made by Bogdan Trif @ 2016-10-31, 00:01 ''' Problem 4 - 20 points possible (graded) You are given the following definitions: A run of monotonically increasing numbers means that a number at position k+1 in the sequence is greater than or equal to the number at position k in the sequence...
216fb3c4cc98fdba728393f42a8726bc9e5a1564
btrif/Python_dev_repo
/Maths/gauss_quad.py
2,082
3.640625
4
from grule import grule def gauss_quad( f, a, b, n ): """ Estimate the integral of f(x) from a to b using Gaussian Quadrature. USAGE: y = gauss_quad( f, a, b, n ) INPUT: f - function to integrate [a, b] - interval of integration n - number of nodes (points to ...
e2807945fed7a30a261c243c6c0be817dbebb3f7
btrif/Python_dev_repo
/Algorithms/sets_subsets algorithms.py
1,956
4.03125
4
# What is the recursive solution for finding all subsets of a given array? def subsets( nums ): # Returns all the subsets of the main set if nums is None: return None subsets_ = [[]] next = [] for n in nums: for s in subsets_ : next.append(s + [n]) subsets_ += next ...
aad8d4a2fde87af3cf0873d29bc341da23b69676
btrif/Python_dev_repo
/BASE SCRIPTS/base_conversion.py
1,806
3.984375
4
# Converting an Integer to a String in Any Base def toStr(n, base ): # Recursion Solution '''Very elegant. Works Fine. 2017-10-16 - Has problems for huge numbers > 500 digits. Because of the sys.getrecursionlimit() . I tried o increase it to sys.setrecursionlimit(10000000) and when dealing with 2000...
73804de88c230bc4e822e3a197b81049ab1ef440
btrif/Python_dev_repo
/Algorithms/fractal algorithms.py
4,147
3.890625
4
############ DRAGON HEIGHWAY def dragonpos(n) : c = [0,1] length = 1 while length < n : c = [ c[0] + c[1], c[1] - c[0] ] length*=2 if length == n : return c m = length-n c2 = dragonpos(m) c2 = [ -c2[1], c2[0] ] print(c, length, n, m) return [ c[0]+c2[0], ...
d8cd80845a11d5a6c9f469729cc42f3cf6f5a978
btrif/Python_dev_repo
/BASE SCRIPTS/object_types_conversion.py
2,527
4.125
4
print('----------'*13) print('........................Function which transforms a string into a list: ....................') def string_to_list(strng): if (type(strng) == str): lst = list(strng) print(lst) print('The type of ',lst, 'is : ',type(lst)) return lst else: print('Not a stri...
54db2fd56f5495d75f8d7902bc2ed271bf3b1016
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/Lynda - Python 3 Essential Training/15 Files/files - two operations at once.py
346
4
4
# Use words.txt as the file name fname = input("Enter file name: ") fh = open(fname) # FIRST METHOD for line in fh: upper=line.upper() print(upper.rstrip()) print('-----'*10) # SECOND METHOD - BETTER ! for xx in fh: xx = xx.rstrip().upper() # that's how you do more operations on a str...
3aa0285361aff1997fcc2775fe35c69ab2fc4165
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/machine learning examples/test.py
1,524
3.84375
4
#Number of training samples from numpy import loadtxt, zeros, ones, array, linspace, logspace from pylab import scatter, show, title, xlabel, ylabel, plot, contour #Plot the data #Load the dataset data = loadtxt('ex1data1.txt', delimiter=',') X = data[:, 0] y = data[:, 1] m = y.size it = ones(shape=(m, 2)) it[:,...
53958a00677713402c549640639d87442b94d9d2
btrif/Python_dev_repo
/plots exercises/line_animation.py
1,087
4.40625
4
__author__ = 'trifb' #2014-12-19 import numpy as np from matplotlib import pyplot as plt from matplotlib import animation # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() #defining the figure ax = plt.axes(xlim=(0, 10), ylim=(-8, 8)) # x-axes limit...
266ad757802b72a50c4e93eb5224c855a79a4286
btrif/Python_dev_repo
/BASE SCRIPTS/ADT/sequential_search.py
3,569
4.3125
4
# Created by Bogdan Trif on 02-08-2018 , 6:13 PM. # http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSequentialSearch.html ''' === 5.3. The Sequential Search === When data items are stored in a collection such as a list, we say that they have a lin...
cbdb444d3416052310e28557e7455cc7f40ee860
btrif/Python_dev_repo
/Algorithms/sieve_build_admissible_numbers.py
870
3.515625
4
######### SMART WAY TO BUILD A SIEVE OF ADMISSIBLE NUMBERS ####### # This code build numbers like powers of consecutive primes ONLY : [2**i, 3**j, 5**k, 7**l, ..... ] # 2,4,6,8,12, 16, 18, 24, 30 ,... # There were some mistakes in the algorithm as it does not add 30. I corrected it !!!! limit = 10 ** 2 adm = [] prim...
d35be6e290fbde052cf6d762071c5f42dacf6a10
btrif/Python_dev_repo
/Courses, Trainings, Books & Exams/PYTHON 3 - Scientific Training/transform function to class 02.py
1,999
3.875
4
import math import turtle class FLOWER: def toRadians(self, degrees): return (degrees / 180.0) * math.pi def polar_to_X(self, theta, r): x = r * math.cos(theta) return x def polar_to_Y(self, theta, r): y = r * math.sin(theta) return y def drawPeta...
02426aae35dc6cd41d798b4bffc9534c72f9f0ad
btrif/Python_dev_repo
/turtles/turtle_zig_zag2.py
971
3.875
4
# made by Bogdan Trif @ 2014-10-06 14:00 import turtle window = turtle.Screen() def simpleLoop(a, b, c): for i in range(a, b, c): print (i) simpleLoop(4, 400, 44) turtle.setpos(-40, -30) def ZigZag(turtle, z, ya, x, yb, w, u, color, t): for i in range(z): turtle.speed(u) turtle....
34fa135f187a458ab824f0dba01ce4c9998bf613
andythewhale/machineComponents
/modelCreation/preceptronTwoInputs.py
1,925
3.984375
4
#Good perceptron example with 2 inputs that another user showed. class TwoStepFun(object): def __init__(self, threshold=0.5): self.threshold = threshold def __call__(self, value): if value < self.threshold: return 0 else: return 1 class Perceptron(object): ...
931eabdaeefb15f18b76a5fcaafd5a4d50e9dfcd
andythewhale/machineComponents
/algorithms/dijkstra.py
1,124
4.03125
4
#This is a basic implementation of Dijkstra's Algorithm #Andy Miller #2017/5/18 #This might not make sense to anyone but me. #Use 3 dictionaries. Parents, Weights, Total #First we need something to determine cost: def find_lowest_cost_node(costs): lowest_cost = float('inf') lowest_cost_node = None for node in cost...
933cf5b5fe75e3d653a94b7d20f047300a9fcd0b
andythewhale/machineComponents
/modelCreation/twoDimLinearRegression.py
441
3.640625
4
#This is a basic component for 2 dimensional linear regression. ###comp block start import pandas as pd import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt #import your data data = pd.read('file') #label variables x = data[['x']] y = data[['y']] #training model reg = linear_model.L...
c309ef551a6c22be95befaadc88820aafc1e87f6
zzznavarrete/introduccion_al_pensamiento_computacional_python
/clases/epsilon.py
920
3.96875
4
# Preguntar si se quiere activar el debug debug = '' while debug.upper() != 'Y' and debug.upper() != 'N': debug = input('Quieres activar el debug? [Y/n]: ') # Implementando algoritmo EPSILON, para aproximaciones objetivo = int(input('Escoge un número: ')) dificultad = 0 while dificultad != 1 and dificultad != 2...
ec91bd0fb25bc87452bd55b4c2b08eef3dec27f8
zzznavarrete/introduccion_al_pensamiento_computacional_python
/clases/optional_parameter_function.py
477
3.53125
4
def nombre_completo(nombre, apellido, inverso=False): if inverso: return apellido + ', ' + nombre else: return nombre + ', ' + apellido var_nombre = 'Nicolás' var_apellido = 'Neira' #Sin pasarle el valor opcional print(nombre_completo(var_nombre, var_apellido)) #Pasándole el valor opcional p...
594fe8367d06949cba40e35fad63bbcf69fa7d3f
nick-walkden/DivertorInverter
/read_movie.py
4,559
3.671875
4
#!/usr/bin/env python from __future__ import print_function import cv2 import numpy as np from frame_history import frame_history from movie_reader import ipx_reader,mraw_reader,imstack_reader import logging def read_movie(filename,Nframes=None,stride=1,startpos=0,endpos=-1,verbose=True,startframe=None,endframe=None,s...
b3c7e3a249eb2fc083ebfc442ac970735066bb83
nmandal/interview_prep
/recursion/medium/permutations/permutations_in_place.py
424
3.5625
4
# O(n*n!) time | O(n*n!) space def permutations(arr): perms = [] _permutations(0, arr, perms) return perms def _permutations(i, arr, perms): if i == len(arr) - 1: perms.append(arr) else: for j in range(i, len(arr)): swap(arr, i, j) _permutations(i+1, arr, per...
d3ee36a6f0f094eb3650dd86a7e715158217f1c9
nmandal/interview_prep
/sorting/very_hard/merge_sort/merge_sort.py
1,022
3.890625
4
# Best: O(n log n) time | O(n) space # Average: O(n log n) time | O(n) space # Worst: O(n log n) time | O(n) space def merge_sort(array): if len(array) <= 1: return array aux_array = array[:] _merge_sort(array, 0, len(array) - 1, aux_array) return array def _merge_sort(array, start, end, aux_...
a0a9dc6f4885468949f54ddc5cc567b62c63acad
nmandal/interview_prep
/elements_of_programming_interviews/greedy_algorithms_and_invariants/3-sum_problem/three_sum_problem.py
436
4.03125
4
def three_sum(A, t): def has_two_sum(array, target): i, j = 0, len(array) - 1 while i <= j: if array[i] + array[j] == target: return True elif array[i] + array[j] < target: i += 1 else: j -= 1 return False ...
f358b4ab27bf654cb761e599a62928a26679c972
nmandal/interview_prep
/leetcode/medium/173_binary_search_tree_iterator/binary_search_tree_iterator.py
449
3.578125
4
class BSTIterator: def __init__(self, root): self.stack = [] self.add_left_to_stack(root) def has_next(self): return True if self.stack else False def next(self): curr = self.stack.pop() self.add_left_to_stack(curr.right) return curr.value d...
cfded2a30b14f6d55dbc8078f0ca3cd50e4d6d46
nmandal/interview_prep
/sorting/easy/bubble_sort/bubble_sort.py
455
3.890625
4
# Best: O(n) time | O(1) space # Average: O(n^2) time | O(1) space # Worst: O(n^2) time | O(1) space def bubble_sort(arr): is_sorted = False counter = 0 while not is_sorted: is_sorted = True for i in range(len(arr) - 1 - counter): if arr[i] > arr[i+1]: swap(i, i+1...
a5bead7b068b968686b72e6eab0ce28cff5acfa9
nmandal/interview_prep
/binary_trees/medium/invert_binary_tree/invert_binary_tree_iterative.py
351
3.921875
4
# O(N) time | O(N) space def invert_binary_tree(tree): queue = [tree] while(len(queue)): curr = queue.pop() if curr is None: continue swap_left_and_right(curr) queue.append(curr.left) queue.append(curr.right) def swap_left_and_right(tree): tree.left, tree...
9d7aec15a3231389ae5866d2508bf611a68e32e3
nmandal/interview_prep
/linked_lists/hard/find_loop/find_loop.py
278
3.578125
4
# O(n) time | O(1) space def find_loop(head): slow = head.next fast = head.next.next while slow != fast: slow = slow.next fast = fast.next.next slow = head while slow != fast: slow = slow.next fast = fast.next return slow
31e97c323d1154a0dc5f3075219ede50e3aeabba
mit1221/Stonehenge-Game
/stonehenge.py
13,452
4.15625
4
""" An implementation of the Stonehenge game and its state. """ from typing import Any, List, Union from game import Game from game_state import GameState class StonehengeGame(Game): """ The Stonehenge game. size - the side length of the board current_state - the current state of the game """ ...
ea9166892ac288a5be81164f2772d9857a5ad304
JoeyDeSmet/Algorithm-intro
/Exercises/Riemann.py
484
4
4
import math def f(x): return math.pow(x, 2) + 3 * x + 15 def riemannIntegral(interval, a): x = interval[0] step = (interval[1] - interval[0]) / a x1 = x + step integral = 0 for i in range (interval[0], a): width = x1 - x height = f(x1) integral += width * height ...
24e78bf77cad25af185baf4fd71d6953e86620c7
fransikaz/PIE_ASSIGNMENTS
/homework8.py
2,880
4.5
4
import os # import os.path from os import path ''' HOMEWORK #8: Create a note-taking program. When a user starts it up, it should prompt them for a filename. If they enter a file name that doesn't exist, it should prompt them to enter the text they want to write to the file. After they enter the text, it should ...
0f050bfc3594d1a7b8a65157483c51b89af4a064
ALOK8467100/snake-game
/snakegame.py
3,913
3.6875
4
import turtle import time import random delay = 0.1 #score score = 0 high_score = 0 #set up screen wn = turtle.Screen() wn.title("snake game") wn.bgcolor("black") wn.setup(width=600, height=600) wn.tracer(0)#turns off screen updates #snake head head = turtle.Turtle() head.speed(0) head.shape("square") head.color("r...
502fb5c79da031d8ba3a38f1b932f18ed2f9055d
asklasek/myleftarm
/myleftarm game.py
1,030
3.578125
4
# myleftarm game # 1,177 lines # written by speedymcgreedy import character import introoutro, rooms, altercations def main(): introoutro.intro() # Introduction to the game. name=input('What is your name? ') # Player enters their name player=character.Character(name) # create a Character from th...
d92eafeaafb9aacc1c13dd5e4040c516c85d1815
aishdharan/week2
/week2/problem5.py
937
3.640625
4
import os import sys import math """ Notes: - Please see the notes inline below """ def calculate(a, b, c): discriminant = b ** 2 - 4 * a * c if discriminant < 0: return None, None # real roots here x1 = complex((2 * c) / (- b + math.sqrt(discriminant))) x2 = complex((2 * c) / (- b - mat...
0434a072402f937accd80ffc1c121060996acfdd
insomnia33/USP_Coursera
/soma_elementos.py
127
3.5
4
def soma_elementos(l1): aux = 0 for i in l1: aux += i return aux lista = [1,2,3,4,5,6,7,8,9] print(soma_elementos(lista))
b1fe2e3e12b4f029657a92fb0b85da3e3630cf32
insomnia33/USP_Coursera
/conta_primos.py
346
3.75
4
def n_primos(num): if num == 2: return 1 elif num == 3: return 2 cont = 3 primos = -1 while cont <= num: cont2 = cont while cont2 >= 2: if cont%cont2 == 0: check = False else: check = True cont2 -= 1 if check: primos += 1 cont += 1 return primos n = int(input("Digite um númer...
ba122c8351d138ae4c903f75104a41ff881a17b0
insomnia33/USP_Coursera
/soma_digitos.py
101
3.96875
4
a = int(input("Digite um número: ")) soma = 0 while a > 0: soma = soma+a%10 a = a//10 print(soma)
68c7a69399e9dce833e0a5b60fcdd95d4816c0f3
insomnia33/USP_Coursera
/pontos.py
305
3.796875
4
import math xa = int(input("Digite a primeira coordenada: ")) ya = int(input("Digite a primeira coordenada: ")) xb = int(input("Digite a primeira coordenada: ")) yb = int(input("Digite a primeira coordenada: ")) dist = math.sqrt((xb-xa)**2+(yb-ya)**2) if dist >= 10: print("longe") else: print("perto")
f1ef92515648ab43fc04d054a4cf424953eef336
mohshabrez/shabrez
/mohprgm5.py
174
4.3125
4
#!/usr/bin/python3 for i=2 in range(0,20): if(i%2==0): print(i,"an even number") for i=3 in range(0,30): if(i%3==0): print(i,"an odd number")
e2ad5ac03aaa6ae557256b754294e0fff9ce2103
precious/kinopoisk_to_imdb
/imdb_find_movie.py
1,198
3.734375
4
#!/usr/bin/python import urllib # import urllib2 import sys import json import imdb_find_movie2 from romanization import romanize def get_movie_url(movie_data): url = 'http://www.deanclatworthy.com/imdb/' params_dict = {} data_list = movie_data.split('*') if len(data_list) < 3: raise ValueError('invalid movie ...
5325432f15e713d4ab200d3a9d612ed0bd8d4551
jakobgerstenlauer/CloudComputing
/Lab1/Lab1.guessnumber.py
663
3.984375
4
import random randomNumber = random.randrange(0,20) print("Random number between 0 and 20 has been generated") guessed = False while guessed==False: userNumber = int(input("Introduce your guess number: ")) if userNumber==randomNumber: guessed = True print("Yes, " + str(randomNumber) + " is correct!") ...
7041568ad96e36c3e483b3d90a9d7f7ad5db0ca5
marieke-thomas/sorting-hat-quiz
/app/models/model.py
2,357
3.609375
4
gryffinscore = 0 ravenscore = 0 hufflescore = 0 slytherscore = 0 def reset_score(): global gryffinscore global ravenscore global hufflescore global slytherscore gryffinscore = 0 ravenscore = 0 hufflescore = 0 slytherscore = 0 def add_points(question_response): global gryffinscore ...
10334f38d0b2bb934d4be79b6d614d6fc9c163f2
david-gang/project_euler
/src/ex41_60/ex47.py
516
3.5625
4
from sympy import primefactors import time def p_fact(n): return (n,len(primefactors(n))) def find_consecutive(n): arr = [p_fact(i) for i in range(2,2+n)] counter = 2+n-1 while True: if all(a[1]==n for a in arr): return arr[0][0] counter +=1 arr.pop(0) arr.ap...
d82146dab5b2ed86e0987f520355d722cef891b6
akuchotrani/ChromeExtensionPlugin
/DataTransformation/DataFileTransformation.py
925
3.625
4
import csv import os def LoadFile(file_path): print("Loading the file into memory...") global DataFile DataFile = open(os.path.expanduser(file_path)) def TransformDataFile(): ''' Creates a dictionary of unique words with emotions value as row. Converts all emotional data into a row of emotion...
40ccdc3b32395db4b58afb27d4f5cd2e68938003
lpchg1992/Python006-006
/week07/HomeWork/2.mymap.py
139
3.984375
4
def mymap(func, iterator): return (func(it) for it in iterator) def func(x): return x for i in mymap(func, [1,2,3]): print(i)
0c54727d814c8716a2ebffa02d281a3ef5896896
lpchg1992/Python006-006
/week07/class_code/p4_abc.py
1,141
3.96875
4
import numpy as np ''' 计算欧氏距离【也就是空间中两个点之间的距离】 ''' vector1 = np.array([1, 2, 3]) vector2 = np.array([4, 5, 6]) # 算出对应点的差的平方之和,对这个和求算数平方根。 op1 = np.sqrt(np.sum(np.square(vector1-vector2))) # 直接调用numpy的方法。 op2 = np.linalg.norm(vector1-vector2) print(op1, op2) from collections import namedtuple from math import sqrt P...
0096296f462ed5edcbe600608c7685341f55ca47
gitmagistere/notebook
/ac-amiens/7496/pytha.py
308
3.703125
4
# Créé par za, le 06/11/2020 en Python 3.7 from math import* #la bibliothèque lycee n'existe pas sur le notebook (en ligne) # nous vous conseillons de l'utiliser sur votre PC cote_1=15 cote_2=20 hyp_carre=cote_1**2+cote_2**2 hyp=sqrt(hyp_carre) print ("l'hypoténuse du triangle rectangle vaut", hyp)
379d8968482bf2d03f1b771012c94e7cc68b5ccc
gitmagistere/notebook
/ac-guadeloupe/5117/Calcul_d_une_fonction.py
83
3.75
4
x=0 x=float(input("Entrez une valeur ")) y=2*x**2-6*x+4 print("Le résultat est",y)
5b3934fff2cca772257fbe7c68200da59f97c59b
seungsu3579/Algorithm_Study
/programmers/dfs_bfs/타겟넘버.py
362
3.546875
4
# 타겟넘버 def recur(num, target, index): if index == len(num): if target == 0: return 1 else: return 0 a = num[index] return recur(num, target + a, index + 1) + recur(num, target - a, index + 1) def solution(numbers, target): answer = recur(number...
70182bf6582ada5774694111bfaf4fdad7d516f3
seungsu3579/Algorithm_Study
/programmers/2-level/폰켓몬.py
226
3.578125
4
# https://programmers.co.kr/learn/courses/30/lessons/1845 # 폰켓몬 def solution(nums): answer = 0 tmp = set(nums) answer = len(tmp) if len(tmp) <= len(nums) // 2 else len(nums) // 2 return answer
05f27a2103a1a860181a0c90cd63a12bef8dca98
MichaelKay09/Mjukvarutestning
/Transaction.py
1,470
3.640625
4
from datetime import date from Budget import Budget class Transaction(Budget): name, amount, date = "", "", "" transactions = [] trans_id = 0 budget = Budget() def Add_Transaction(self, name, amount, myDate): try: num = 0 self.name = name self.amount = ...
ee018e24e0c6a191447c59305a06988bb2cfac10
gbiebuyc/stuff
/cryptopals/set2/9.py
559
3.71875
4
#!/usr/bin/env python3 def padPKCS7(data, blocksize): n = blocksize - len(data) % blocksize return data + bytes([n] * n) def unpadPKCS7(data, blocksize): if len(data) % blocksize: raise ValueError('Input data is not padded') n = data[-1] if n == 0 or n > blocksize: raise ValueError...
c2e68bade1612544dc31c3065616294da8c34f7a
gbiebuyc/stuff
/adventofcode2020/d09.py
711
3.515625
4
numbers = [int(l) for l in open('input-09.txt')] preamble_len = 25 ans=0 for i in range(preamble_len, len(numbers)): valid=0 for j in range(i-preamble_len, i): if valid: break for k in range(j+1, i): if numbers[j]+numbers[k]==numbers[i]: valid=1 ...
fb4d5973fb7cef0e8d01fb7d0aca8d474c48a01c
gbiebuyc/stuff
/cscbe/crypto_a_pirates_life_for_me.py
1,047
3.625
4
#!/usr/bin/env python3 from base64 import b64decode, b64encode VALID_H = "3F34564B0A1FB3AFE3676911FF990B3127BEC0C2" SIGNATURE_SIZE = 256 ASN = b"0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14" # https://stackoverflow.com/questions/356090/how-to-compute-the-nth-root-of-a-very-big-integer def find_invpow(x,n): """...
aaae8e09055e34be9cf3718245fb9d4b077ed0c2
bringsyrup/Edge_Detection
/kernel.py
7,764
3.640625
4
#!/usr/bin/env python """ This module transforms a given image by a specified kernel or set of kernels. The module is self-contained and is controlled via a command-line interface. The goal is to apply any 3x3 kernel (including pairs of 3x3 kernels such as the sobel operator). Some ideas for "artsy filters": - con...
8f8e0e49b56d4ff0b1b057eaf48a3d91f6f46772
tatparya/HackerRank
/Algorithms - Greedy/Grid Challenge/solution-Tatparya’s MacBook Pro.py
472
3.6875
4
import os import math def getAnswer(): n = int( input() ) grid = [] for i in range( n ): row = ''.join( sorted( input() ) ) grid.append( row ) # for i in range( n ): # print( grid[i] ) # Check if horizontally sorted for i in range( n - 1 ): for j in range( n ): if grid[i][j] > grid[i+1][j]: prin...
52818fd0b75111951bf2890ba229b74ca37539e6
tatparya/HackerRank
/Contests/Number Voyage/Voyage/solution.py
628
3.859375
4
import os import math def getT( v, u, a ): t = ( v - u ) / a return t def getV( u, a, s ): v = math.sqrt( u * u + 2 * a * s ) return v def getS( u, a, t ): s = u * t + 1 / 2 * a * t * t return s def main(): totalDist = math.pow( 10, 20 ) s = totalDist / 3 a1 = 150 a2 = 0 a3 = -150 print( "Total dist ...
f2706e881184fb6d8f5d4abed81b0ef9b066ca56
tatparya/HackerRank
/Contests/Pythonist3/CompressTheString/solution.py
422
3.859375
4
import os def compressString( string ): i = 0 count = 1 current = string[0] while i < len( string ) - 1: current = string[i] if current == string[i + 1]: count += 1 else: # print print( (count, int(current) ), end=" " ) # reset count count = 1 i+=1 print( (count, int(string[len(string) ...
e2f998f70e016a1b11eb2bc51e7f384c2500cccf
kgrover/algorithmpractice
/mcp.py
1,197
3.65625
4
# Minimum Cost Path import numpy as np # defines the matrix ROWS = 5 COLS = 5 mat_shape = (ROWS, COLS) matrix = np.random.random_integers(0, 20, (5,5)) def get_min_cost_path (matrix, dest_col, dest_row): cost_matrix = np.zeros((5, 5)) cost_matrix[0, 0] = matrix[0, 0] for row in range(0, ROWS): ...
9393f452395547eb4611516c726bddb23e6eed89
angrySmeagol/data-structure-and-algorithm-python
/cnchess.py
17,212
3.765625
4
# -*- coding: utf-8 -*- class Board(object): def __init__(self): self.board = {} for i in xrange(1, 10): for j in xrange(-5, 6): if j != 0: self.board['{}|{}'.format(i, j)] = None class Piece(object): def __init__(self, col, row, army='red'): ...
93fbfd23700139abd99add1138df0d490d5423ee
ccchowww/python-knightly-kakapo
/turtle-presentation/M5_tuple_original.py
1,553
4.03125
4
import turtle turtle.setup(width = 800,height=800,startx = None, starty=None) turtle.penup() turtle.speed(20) turtle.setpos(-300.00,200.00) turtle.setpos(-310.00,220.00) turtle.write("Tuple \n" ,align="left",font=("Ariel",50,"bold")) turtle.penup() turtle.setpos(-370.00,20.00) turtle.write("A tuple is ...
a29212866789b6ca40f8187634d94930f16779e2
Prasanthdemigod/DataStructure_python
/BinarySearchTree/Bst.py
1,621
3.953125
4
class BST: class TreeNode: def __init__(self, ele): self.data=ele self.left=None self.right=None def __init__(self): self.root=None self.count=0 def is_empty(self): return self.count==0 def length(self): return self.count ...
d20f44d4150c21a96b178b3aac74b45e25c5fab1
AndersenDanmark/udacity
/test.py
2,516
4.5
4
def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ # YOUR CODE HERE if day+1>30: day=1 if month+1>12: month=1 year=year+1 else: month=month+...
90bb3b7adc9fd69add74482662eb1afe2a3d295a
xpunch/leetcode
/0056.merge-intervals/56.merge-intervals.py
625
3.5625
4
# # @lc app=leetcode id=56 lang=python3 # # [56] Merge Intervals # from typing import List # @lc code=start class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: n = len(intervals) if n <= 1: return intervals intervals.sort(key=lambda i: i[0]) ...
e9dd52c6b01105e84c073d9bceb43f4ccc5f9db7
xpunch/leetcode
/0002.add-two-numbers/2.add-two-numbers.py
974
3.609375
4
# # @lc app=leetcode.cn id=2 lang=python3 # # [2] add tow numbers # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: r, n, ...
e6a7f88af25ccf230672eb0ced3f47e63c248a3f
xpunch/leetcode
/1374.generate-a-string-with-characters-that-have-odd-counts/1374.generate-a-string-with-characters-that-have-odd-counts.py
789
3.53125
4
# # @lc app=leetcode id=1374 lang=python3 # # [1374] Generate a String With Characters That Have Odd Counts # # @lc code=start class Solution: def generateTheString(self, n: int) -> str: result, alphabets, cache = '', 'abcdefghijklmnopqrstuvwxyz', {} usedCharCount, usedCharIndex, charCount = len(...
47bdc4ac073ab6c23187dc34acf15d8af19b3837
sinchir0/2020_NLP100
/ch04/37/37.py
1,689
3.578125
4
# 37. 「猫」と共起頻度の高い上位10語 # 「猫」とよく共起する(共起頻度が高い)10語とその出現頻度をグラフ(例えば棒グラフなど)で表示せよ. import re import MeCab import collections import matplotlib.pyplot as plt import japanize_matplotlib from ipdb import set_trace as st def ngram(seq: list, n: int): return list(zip(*[seq[i:] for i in range(n)])) if __name__ == "__main_...
c5c9b2d4f9b12c16250c0361e9817dd40d50a710
sinchir0/2020_NLP100
/ch01/03/03.py
439
3.828125
4
# 03. 円周率 # “Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics." print([len(word.strip(",.")) for word in sentence.sp...
e465d455ec840a2b7fd3e0de111258524dbec7d5
sinchir0/2020_NLP100
/ch01/02/02.py
332
3.96875
4
# 02. 「パトカー」+「タクシー」=「パタトクカシーー」 # 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ. word1 = "パトカー" word2 = "タクシー" word = "".join([a + b for a, b in zip(word1, word2)]) print(word)
a6c215c68e5a7acc71c3aeb7b3a637ba8b8d8005
ansariamaan709/Python-
/python prac/captains_room.py
237
4.03125
4
from itertools import groupby n=int(input('How many Numbers')) N = [] for k in range(n): a=int(input("Enter the numbers")) N.append(a) N.sort() print([list(j) for i, j in groupby(N)]) print('Captain:',N[-1])
96d5631b66e034787f3b1a5e56e62944a09e3049
ansariamaan709/Python-
/python prac/birthday.py
182
3.84375
4
n= int(input("how many candles")) a=[] for i in range(n): b=int(input("Enter the size of candles")) a.append(b) c=a.count(max(a)) print("The candle blown is :" , c)
676e18f9367f618cc1dda326c905d1fa50591cb2
foowaa/py-patterns
/structural/proxy.py
755
3.59375
4
""" 代理模式是一种应用很广泛的结构型设计模式,而且变化形式非常多,常见的代理形式包括远程代理、保护代理、虚拟代理、缓冲代理、智能引用代理等。 代理模式定义如下: 代理模式:给某一个对象提供一个代理或占位符,并由代理对象来控制对原对象的访问。 Proxy Pattern: Provide a surrogate or placeholder for another object to control access to it. 代理模式是一种对象结构型模式。在代理模式中引入了一个新的代理对象,代理对象在客户端对象和目标对象之间起到中介的作用,它去掉客户不能看到的内容和服务或者增添客户需要的额外的新服务。 """ class...
c1c88c65c9bd996ac62fa6b51e90387956f25c58
foowaa/py-patterns
/behavioral/observer.py
2,276
3.609375
4
""" 观察者模式是使用频率最高的设计模式之一,它用于建立一种对象与对象之间的依赖关系,一个对象发生改变时将自动通知其他对象,其他对象将相应作出反应。在观察者模式中,"发生改变的对象称为观察目标,而被通知的对象称为观察者",一个观察目标可以对应多个观察者,而且这些观察者之间可以没有任何相互联系,可以根据需要增加和删除观察者,使得系统更易于扩展。 观察者模式定义如下: 观察者模式(Observer Pattern):定义对象之间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。观察者模式的别名包括发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-...
785500307aed2da26a40b40c3535637b84e3edab
Kacper20/Algorithmic-Tasks
/Hackerrank/queue/queue_two_stacks.py
592
3.921875
4
class MyQueue(object): def __init__(self): self.left = [] self.right = [] def peek(self): if len(self.left) == 0: self.right.reverse() self.left = self.right self.right = [] return self.left[-1] def pop(self): val_to_return = self.peek() del(self.left[-1]) return val_to_return def p...
4c6c58905cdb5c3d1b890081777baccbb2ed4627
supertailcat/small_semester
/Sender.py
1,660
3.5
4
############################################################################################# # # # 通过启动start_listen函数开始监听,在与客户端取得链接之后,发送两个字符串。客户端需要再转变一次格式 # # python和Java的字符串长度没有限制,所以可以一次传递。 ...
5b6194da5f03ac89c1e7cdb95fb263b395b4e0ce
supertailcat/small_semester
/GenerateJsonFile.py
897
3.5625
4
######################################################### # # # 调用csv_to_json函数生成json文件,传参为scv文件的文件名 # # 直接运行该文件则调用if函数 # # # #####################################################...
47fe969bf222c6fc436570151a9a5d277ec282b8
AgnesNM/Tic-Tac_Toe
/board4.py
7,633
3.765625
4
'''GLOBAL VARIABLES''' player = "x" or "o" #global ongoing_game ongoing_game = True #player 1 inputs player_1_input_lst = [] #player 1 input position player_1_pos_lst = set () #player 2 inputs player_2_input_lst = [] #player 2 input position player_2_pos_lst = set() class Game(): def __init__(self, pla...
f486929e45f63a5e94936b31796f7cca29bc834e
sridhar-s24/DSA-Python
/Day 6 assignment/StackPushPopFindMinimum.py
1,557
3.8125
4
import math top = -1 st = list() st2 = list() size = eval(input('Enter size of the stack: ')) mini = math.inf def push(data): global top, st, st2, size, mini if (top == size - 1): print ('Overflow') return top += 1 st.append(data) print ('Element ', data, 'added to the original sta...
917a58d3f5f9b6a8d895e3997ab2bc05c24f099b
daniilmir3105/mueller_project
/scoring_func.py
869
3.671875
4
from abc import * from decimal import Decimal class base_class(metaclass=ABCMeta): ''' This class will be base for our scoring class ''' @abstractmethod def rec(self, y=1, z=1): return 108 - ((815 - 1500 / z) / y) class scoring_class(base_class): ''' This is a class, that must s...
7adef8d9de1097de9783d21148fad88d3cd4df2d
skmahalakshmi/django_Example2
/food_delivery_project/database.py
447
3.8125
4
# connect to sqlite3 import sqlite3 db = sqlite3.connect('Registration') # created cursor from database registration rs = db.cursor() rs.execute('''create table register(name varchar(50),email varchar(100),phone varchar2(10),passwd varchar(10))''') rs.execute(''' insert into register values('kaha','@gmail.com','12345...
8e4531f38458192f039758c768732bc9863c90ff
SriDharshini31/sridharshini
/multiply.py
40
3.546875
4
num=5 for i in range(1,5): print(num*1)
1c57974ac49229db2db58a201876ba672b824d19
yunshiuan/tomnet-project
/models/working_model/commented_batch_generator.py
11,288
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ class BatchGenerator: The class for making batches. @author: Chuang, Yun-Shiuan """ import numpy as np class BatchGenerator: def __init__(self): pass def generate_train_batch(self, train_data_traj, train_labels_traj, train_data_query_state, train_labels_query...
85468d5fbba154fba5ac815b57674adeaa73a500
VishnuCR913/turboland
/answer_1.py
109
3.71875
4
start=input(list("enter the start list: ")) stop=input(list("enter the stop list: ")) for i in start:
15633c36a6cfc4d37a9cea6d18cd6564d1568806
daniilcao/pyton-geekbrains
/lesson2/dz4.py
184
3.796875
4
strName = input("set string separated by a space:") reList = strName.split() for k in range(len(reList)): s = reList[k] if len(s) > 10: s = s[:9] print(f"{k}:{s}")
dca5b8f079f6ca279623886fcd4d3e59b3c699b9
IsaacRodgz/Algorithms
/Linked Lists/removeKFromList.py
595
3.6875
4
# CodeFights # Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k. # @param l : Head node of linked list # @param k : integer to remove # @return l without nodes with value == k # Definition for singly-linked list: # class ListNode(object): # de...
8ae65ebf15112621aa34ec7e5fdba418ce5aaa60
Doblanko/sorting_visualization
/merge_sort.py
2,393
3.96875
4
import pygame, time import board sleep_time = 1 def merge_sort(bars, game_board): if len(bars) > 1: # show section being looked at color(game_board, bars, board.colors["green"]) time.sleep(sleep_time) middle = int(len(bars)/2) left_half = bars[:middle] right_half =...