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
3b8439cb24283afaac9cd9d6b8af0e6f466cf341
heyheycel/advent-of-code
/2017/code_day3.py
2,566
3.875
4
num=265149 current=1 level=0 while current<num: level+=1 current=current+level*8 print("Given number: "+str(num)) print("Number of cells: "+str(current)) print("Number of shells in the square: "+str(level)) distance=current-num print("Distance from the last cell to the given cell: "+str(distance)) """ side one (la...
947e4659acd5a8ce781fb0767774b8d105075d3f
heyheycel/advent-of-code
/2017/code_day2.py
702
3.59375
4
instructions = [] differences=[] with open('day2_input.txt') as f: for line in f: instructions.append([int(i) for i in line.split()]) def smaller(lista): tmp=lista[0] for i in range(1,len(lista)): if tmp>lista[i]: tmp=lista[i] return tmp def bigger(lista): tmp=lista[0] for i in range(1,len(lista))...
6304872ca1e9c995ab206c0caa47ea67aaa9200b
x1ah/python-snippets
/sort/insert_sort.py
371
3.921875
4
# coding: utf-8 """ 直接插入排序: 最好:已经有序,O(n) 最坏:逆序,O(n^2) 平均: O(n^2) 稳定排序 """ def insert_sort(lst): length = len(lst) for i in range(length): j, key = i, lst[i] while j > 0 and lst[j-1] > key: lst[j] = lst[j-1] j -= 1 lst[j] = key return lst
52d3f448d88ac46ec4eadaaba64bd247ec5bec55
wangyonge1/study
/exercise9.py
3,979
3.8125
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import os,pickle def commentfile(): 'exercise 9-1' try: f=open('read1.txt','r') f1=open('write.txt','w') for i in f: i=i.strip() index=i.find('#') if index==-1 : f1.write('%s%s' %(i,os.linese...
20477e4fe534a36995cbd28567c584b0174e410f
wangyonge1/study
/num-exe.py
1,741
4.0625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ ''' 数字类型练习 ''' def mul(num1,num2): if isinstance(num1,(int,long,float)) and \ isinstance(num2,(int,long,float)): return num1*num2 else: print "num1 or num2 type error" def score(num): if isinstance(num,int): if 90<=num<=100: ...
4983ccc6c182c1088d348d0e9e823ee8b7394a8d
Jtkolich/PythonProjects
/RealLab7.py
1,972
3.59375
4
# CS1210 Lab7 # # I certify that the entirety of this file contains only my own work # and/or that of my assigned partner. I also certify that my partner # and I have not shared the contents of this file with anyone in any form. ###################################################################### # Edit the followi...
6543e730cf5790b4864379a9213fb76310ef2e54
Jek08/alay-word-generator
/alay_generator.py
1,120
3.71875
4
def alayGenerator(sentence_input): # fungsi untuk mengubah kata biasa ke alay # dictionary huruf alay huruf_alay = { 'a': '4', 'i': '1', 'e': '3', 'g': '6', 'j': 'jh', 'o': '0', 's': '5', 'u': 'uw', 'c': 'ch', 'f': 'v', ...
320fba2a5627ea67e99b54abfae6315115e5c74b
Jamieleb/python
/challenges/prime_checker.py
685
4.34375
4
import math def is_prime(num): ''' Checks if the number given as an argument is prime. ''' #first checks that the number is not even, 1 or 0 (or negative). if num < 2 or num > 2 and not num % 2: return False #checks if all odd numbers up to the sqrt of num are a factor of num for x in range(3, int(math.sq...
682db942edb416b08128a9bddbc28c76dcbb9789
Cbkhare/Codes
/LeetCode_LCA_in_BST.py
751
3.53125
4
class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root in (None,p,q): return root ans= None p,q = sorted([p,q]) if q.val...
e6cc21aee9ca12010f323c8965028fc29b8ec679
Cbkhare/Codes
/LeetCode_Longest_Palindormic_Substring.py
589
3.546875
4
from sys import stdin as si class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ return self.bazinga(s,0, len(s)-1) def bazinga(self, s,b,e): if b==e: pass if s[b] == s[e]: self.bazinga(s, b+1, e-1) ...
68d09f41e576e938d3153f66c2b9239a20200898
Cbkhare/Codes
/LeetCode_Minimum_Path_sum.py
812
3.59375
4
class Solution: def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ self.grid = grid self.d = {} def sum(self,m,n): if (m,n) in self.d: return self.d.get((m,n)) if m==0 and n==0: return self.grid[0][0] ...
ada36adecdc412d652012d9626df8668715358ea
Cbkhare/Codes
/IB_BS_Square_Root_of_Int.py
648
3.5625
4
from sys import stdin as si class Solution: # @param A : integer # @return an integer def sqrt(self, A): if A<=1: return A i=1 j=A//2 while i<=j: mid = i+(j-i)//2 if mid*mid<=A<(mid+1)*(mid+1): return mid elif A<mid*mid...
1166a5d08b5ae2675ca67330d06145925afc3910
Cbkhare/Codes
/Try_Sorting.py
496
3.78125
4
from sys import stdin as si class Sort: def __init__(self): pass def insertion_sort(self,A): for i in range(1,len(A)): j = i-1 while j>0 and A[j]>A[i]: A[j],A[i]= A[i],A[j] j-=1 i-=1 return A if __name__=="__ma...
a7a5beacedfb4227d551b8ee18051beed8274af6
Cbkhare/Codes
/HackerRank_Sherlock_and_Anagrams.py
1,124
3.65625
4
from sys import stdin as si from math import factorial as f global d def nCr(n,r): return f(n) / f(r) / f(n-r) def bazinga(S, l, i): if i==l-1: d[S[i]] = 1 return [S[i]] else: lst = bazinga(S, l, i+1) c = S[i] new_lst = [c] d[c] = 1 if c not in d else d[c] ...
77739ec2f6bebf3227ed3602b7abe0b836eb6d74
Cbkhare/Codes
/LeetCode_PowerOfTwo.py
205
3.875
4
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ return bool(n!=0 and ((n-1) & (n) ==0)) # return if a number is power of two or not
eaf27df7b5181460d116f4f8c66fd6719d253826
TMsosa/MTEC-2280
/Guess.py
292
3.96875
4
import random answer = random.randint(1, 10) while True: guess = int(input("Take your guess: ")) if guess < answer: print("wah! too low") elif guess > answer: print ("nah son too high") elif guess == answer: break print("You got it correct!")
01420a2b9f0cfc199eadcf1a9f94051f88c02b5d
mshasan/Python-Computing
/Linear algebra/solve by LU decomposition.py
4,704
3.609375
4
#------------------------------------------------------------------------------------------------------------------- #################################################################################################################### """some libraries to perform our desired calculations""" import math ...
b1195edcbe5420622554a64020bb994431807993
mshasan/Python-Computing
/Linear algebra/cholesky decomposition.py
4,381
3.609375
4
#------------------------------------------------------------------------------------------------------------------- #################################################################################################################### """some libraries to perform our desired calculations""" import math ...
b1892e71560d9d0083678b55639d68a3032f6ca3
mshasan/Python-Computing
/Optimization/Naive Quasi-newton method.py
3,427
3.90625
4
import math # used to perform mathematical calculation import random # used to generate random number from math import exp,sin,cos,log,floor # to use math modules ###################################################################################################################...
61b02379efc60cd0023e7e4e833db44ccbd3deea
IILuisII/Projects
/03-Python/Solution/PyBank.py
2,711
3.765625
4
import csv # Path FilePath = r"C:\Users\Maxi\Desktop\smu-homework\03-Python\Solution\budget_data.csv" #Couldn't get relative path. #Function def PL_Bank(data): # Variables Months_Amount = 0 Profit = 0 Months = [] Total_Profit = 0 Difference = 0 Total_Difference = [] # Loop ...
70a4ebdcee05a5be49879d3391f3713d7e75c71a
snowflying/algorithm-in-python
/sort/select.py
1,315
3.5625
4
''' mbinary ######################################################################### # File : select.py # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.xyz # Github: https://github.com/mbinary # Created Time: 2018-07-06 17:13 # Description: #######################################################...
98db7f274361ea7dc91b9fa4f9c79b7f6597da5f
snowflying/algorithm-in-python
/math/numericalAnalysis/iteration.py
3,397
3.703125
4
''' mbinary ######################################################################### # File : iteration.py # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.xyz # Github: https://github.com/mbinary # Created Time: 2018-10-02 21:14 # Description: ####################################################...
a3f3d06cc253d68a1bc7def0aeb7d2efa1f94df7
2ptO/code-garage
/icake/q23.py
845
4.03125
4
# Write a function contains_cycle() that takes the first node in a singly-linked list # and returns a boolean indicating whether the list contains a cycle. # Skipped Q22 which was a simple question on link list. # class LinkedListNode: """ Simple linked list class """ def __init__(self, value, next_node...
001fdec153f06057706080a2b1b7f0a842aa0c6c
2ptO/code-garage
/icake/test_q43.py
1,530
3.5
4
import unittest import heapq import random import q43 class TestQ43(unittest.TestCase): def test_merge_of_empty_lists(self): self.assertListEqual(q43.merge_sorted_lists([], []), []) def test_merge_of_one_empty_list(self): left = [1, 3, 5, 6] right = [] self.assertEqual(q43.merg...
df979d40806a9acbdbec1a3165e3b846df611031
2ptO/code-garage
/icake/q31.py
848
4.09375
4
# Write a recursive function for generating all permutations of an input string. # Return them as a set. # Don't worry about time or space complexity—if we wanted efficiency # we'd write an iterative version. # To start, assume every character in the input string is unique. # Your function can have loops—it just ne...
3b3003c21cef527680b8a35472500e96a4367f46
2ptO/code-garage
/icake/q34.py
3,081
4.09375
4
# Write code that takes a long string and builds its word cloud data in a dictionary, # where the keys are words and the values are the number of times the words occurred. # Think about capitalized words. For example, look at these sentences: # 'After beating the eggs, Dana read the next step:' # 'Add milk and eg...
d0d8113e63c4038434a7c2782d6177268adb919f
2ptO/code-garage
/binary_search_tree/bst.py
8,494
4.1875
4
class Node: # Is object really needed? What is the significance? def __init__(self, value, parent = None, leftChild = None, rightChild = None): self.value = value self.left = leftChild self.right = rightChild self.parent = parent def has_left_child(self): return self...
80ae08b7bf04d23b557a34f0dcd409c04b7e942a
2ptO/code-garage
/icake/q26.py
541
4.59375
5
# Write a function to reverse a string in-place # Python strings are immutable. So convert string # into list of characters and join them back after # reversing. def reverse_text(text): """ Reverse a string in place """ if not text: raise ValueError("Text is empty or None") start = 0 ...
721baf5c444e86203662a9e8fdd0a6bcc9f20e14
fand/euler
/007.py
322
3.609375
4
primes = [2,3] i = 6 while i < 2000000: l = i - 1 r = i + 1 lp = True rp = True for p in primes: if l % p == 0: lp = False if r % p == 0: rp = False if lp: primes.append(l) if rp: primes.append(r) i += 6 print sum(primes...
c8da53102f47b130ca9a47615231d326f0bc746b
fand/euler
/036.py
637
3.8125
4
def is_palindrome(num): if is_palindrome_dec(num) and is_palindrome_bin(num): return True return False def is_palindrome_dec(num): s = str(num) lim = len(s)/2 # Note: digit at center doesn't need inspection. for i in range(lim): if s[i] != s[-1-i]: return False ...
908b37ef23e23156396a33582721faa92f816ddc
Akshaypokley/PYCHAMP
/src/SetConcepts.py
2,816
4.25
4
"""Set A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.""" setex={'java','python',True,False,45,2.3} print(setex) """Access Items You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through ...
dbc64b6d5bc7c6c11b84f2727236c9ff56b68f6f
Akshaypokley/PYCHAMP
/src/BooleansConcept.py
451
4
4
print(3>0) #True print(5<3)# False #Bool function we used Identityfi state of variable or value x=90; print(bool(x))#True print(bool('akshay10'))#True print(bool())#false #Python also has many built-in functions that returns a boolean value, like the isinstance() function, which can be used to determine if an objec...
84d13c65e3b036f0887da9a009a67d65385b17e0
aadroher/pingpong
/pingpong/models/calendar.py
1,089
4.125
4
from datetime import datetime """ Este módulo representa el calendario general para la aplicación. Puesto que es único y no hay que guardar ninguna información sobre el mismo, se representa de esta forma y no mediante una clase. """ def current_year(): """ :return: El año en el que nos encontramos. """ ...
509d9c3fa6b9b56fddf7ba986b8ea75c4dcfaa23
tinnan/10daysstat
/day4_geometric_distribution_2.py
569
3.921875
4
""" The probability that a machine produces a defective product is 1/3. What is the probability that the 1st defect is found during the first 5 inspections? """ # Formula success rate a.k.a product defective rate p = 1/3 # Formula failure rate q = 1 - p # Total number of binomial experiment n = 5 # List contains num...
b7c9deb2e1fd40b3b79343e8afd5f1978ffcb0ae
ayoblvck/Startng-Backend
/Python task 1.py
225
4.5625
5
# a Python program to find the Area of a Circle using its radius import math radius = float(input('Please enter the radius of the circle: ')) area = math.pi * radius * radius print ("Area of the circle is:%.2f= " %area)
c734bcecefebc305e5eb81b84d3bc326327947d5
MichaelLLi/Text_Normalization
/Prediction/prediction64/digit.py
918
3.515625
4
import re from num2words import num2words import numpy as np def digit(a): # output= np.empty(shape=(len(a),1),dtype=object) output=['AAAis is wrong!'] * len(a) for i in range(len(a)): try: word=str(a[i]) word=re.sub('[^0-9]+', '', word) output_temp="" ...
b8f9fae8a934ae0b35851750806bc1a3dfbc7ff5
MichaelLLi/Text_Normalization
/Prediction/prediction64/ordinal.py
2,112
3.53125
4
from num2words import num2words import numpy as np import pandas as pd import re numerals = [ {'letter': 'M', 'value': 1000}, {'letter': 'D', 'value': 500}, {'letter': 'C', 'value': 100}, {'letter': 'L', 'value': 50}, {'letter': 'X', 'value': 10}, {'letter': 'V', 'value'...
c46e9a78a12b5406a529b211a211701a4345bf9c
kowaraj/SLAM_for_mBed
/robot.py
951
3.640625
4
from math import * class Robot(): def __init__(self, ): self.adir = 0 # angle [degrees] self.meas = 0 self.move = 0 # lenght [in the dir of 'adir'] self.moves = [] # logging only (history?) self.coords = [0,0] #current coords self.radius = 10 self.arrow = 20...
2affa63631c780fa5b82278d31f6df1dc2441e1c
RashaMou/code-challenges
/Problems/majority-element.py
536
3.84375
4
# given an array of size n, find the majority element(element that appears more than n/2 times). # populate hashmap with counts of each of the numbers in the input list # look through hashmap to see which number has a value > n// 2 def majorityElement(nums): counts = {} for n in nums: if n in counts...
42fbdc36fe956f7d4704ee1dafb29fc684e9e5b6
GooS69/internship
/task9.py
726
3.640625
4
def connect_dicts(dict1, dict2): dict3 = {} list = [dict1, dict2] if sum(dict2.values()) < sum(dict1.values()): list[0], list[1] = list[1], list[0] for i in list: for j in i.items(): if j[1] >= 10: dict3[j[0]] = j[1] sorted_dict = {} sorted_keys = sor...
cd21fb69dd96c6dc5270d7fca3c86e197a2a92fc
coolqiyu/tensorflow-exercise
/experiments/tf_example.py
3,014
3.890625
4
""" TF的基本使用 图:计算的过程 节点:操作,如add 边:数据=tensor 会话:执行计算 """ import tensorflow as tf class Example(object): # 第一个是最基本的例子 @staticmethod def Example1(): # tf.constant:创建常量的op matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.], [2.]]) # tf.matmul:矩阵乘法的op,以matrix1和ma...
b6dd55f61795983858f76cbd06978865722c9850
isolis1210/HW2-Python
/calculator.py
1,487
4.5
4
def calculator(): #These lines take inputed values from the user and store them in variables number_1 = float(float(input('Please enter the first number: '))) number_2 = float(float(input('Please enter the second number: '))) operation = input('Please type in the math operation you would like to complet...
528d5952bab7e3b3885003783e95ce48b344a401
agustinaguero97/Sudoku-finale
/Sudoku/antiguo-no-mirar/test_api.py
793
3.5
4
import unittest from api import get_board_from_api class Test_api(unittest.TestCase): def test_board_size_9(self): board = get_board_from_api(9) self.assertEqual(len(board), 9) for column in range(9): self.assertEqual(len(board[column]), 9) def test_board_size_4(self): ...
ff31d9b4c51affcf254b6fbf02bd2d79c0e42812
manju-dev/leetcode-workspace
/Arrays/problem-286.py
1,439
3.65625
4
# 283. Move Zeroes class Solution: # Approach 1 def moveZeroes1(self, nums) -> None: """ Do not return anything, modify nums in-place instead. """ i = 0 j = 0 while i < (len(nums)-(1+j)): if nums[i] == 0: nums[i:] = nums[i+1:] ...
ddeabbe89a5cb39c6e2b3a07f71e0e6eac0bcf75
manju-dev/leetcode-workspace
/Strings/problem-344.py
558
3.890625
4
# 344. Reverse String class Solution: def reverseString1(self, s): """ Do not return anything, modify s in-place instead. """ for i in range(len(s)//2): s[i], s[~i] = s[~i], s[i] def reverseString(self, s): """ Do not return anything, modify s in-plac...
ff6d0cbf3a962ed4c811dcafdd97e9feca1a6291
ccc96360/Algorithm
/BOJ/Bronze IV/BOJ1297.py
217
3.578125
4
import math def main(): d,h,w = map(int, input().split(' ')) rw = math.sqrt((w**2 * d**2)/(w**2 + h**2)) rh = rw*h/w print(math.floor(rh), math.floor(rw)) if __name__ == "__main__": main()
b1be0fa3b5ebcf4e5ff20af38311cb090833e747
ccc96360/Algorithm
/BOJ/Bronze II/BOJ1076.py
534
3.5
4
VALUE = 0 MUL = 1 info = {"black" : ("0", 1), "brown" : ("1", 10), "red" : ("2", 100), "orange" : ("3", 1000), "yellow" : ("4", 10000), "green" : ("5", 100000), "blue" : ("6", 1000000), "violet" : ("7", 10000000), "grey" : ("8", 100000000), "white"...
0679f502eef7c82da82e6a8e8337cd2aac1acaf3
YuliethVelandia/dplyr-pandas
/pandas/05_query_rows.py
1,809
4.03125
4
# # Returning a subset of rows from a pandas DataFrame # Import modules and read games data import numpy as np import pandas as pd games = pd.read_table('data/games/games.csv', sep=',') games # Use the DataFrame method `query` to return the subset # of rows that satisfy some conditions # The argument to `query` is ...
6c1464eb178d5dccce4eee4efde8c6bb946c2f3f
dosentmatter/elements-of-programming-interviews
/epi/utils/itertoolsextra.py
6,869
4.59375
5
def range_length(*args): """ Return the number of iterations of a Python range() mathematically. The parameters are the same as the Python range() - either (stop) or (start, stop[, step]). You can actually just use len(range(stop)) or len(range(start, stop[, step])). This function turns out to b...
f62df09bb023e5b070f5e919edcad814a00b41f6
dosentmatter/elements-of-programming-interviews
/epi/epi4.py
1,477
3.96875
4
from epi.utils import itertoolsextra class P1_MaxDiff: """ Compute the max difference in a list, L. """ @staticmethod def brute_force(L): """ Return max difference by using brute force. Checks all possible differences and finds the max. """ max_diff = -flo...
856d99562d8d7163b1f130e8032d6eef3f49cf9a
dhu758/python_algorithm
/gugudan.py
111
3.5
4
num=int(input('구구단을 출력할 숫자를 입력하세요(2~9):')) for i in range(1,10): print(num*i)
e955856f3e8ce9c5224a42c82be51f829ab50c4d
AriaTZY/SketchGeneration
/image2pencil/csv_parser.py
1,949
3.8125
4
# This file contains some files about writing and parsing csv file import csv import os class CsvManager(object): def __init__(self, file_name='test.csv'): self.index = [] self.name = [] self.quali = [] # quality self.compli = [] # complicity self.resume_index = 0 ...
464b965116516cd499d591285d85d3847b894cb5
a1sabau/spiking-p-system
/main.py
634
3.578125
4
"""Some examples using spiking neural p systems""" from sps.SNPSystem import SNPSystem def compute_fig2(k): snps = SNPSystem(max_delay=5, max_steps=100) snps.construct_scenario_fig2(k=k) snps.start() print(snps.history) #output is 3k+2 print("input: ", k, "result", snps.result()) ...
6e564dd9c65e3ccdc9b34aed8c2b06c0828cea24
borraborra/Resume-Keyword-Search
/resume.py
1,727
3.984375
4
fname = input("Enter file name: ") import csv abc = input('Enter keywords: ') wxy = abc.upper() ghi = [wxy] for row in csv.reader(ghi, delimiter=" "): count = 0 count_1 = 0 count_2 = 0 count_3 = 0 f = open(fname) lines = f.readlines() f.close() for line in lines: line = line.strip().up...
501500018db10d5483342eca79fb6fcf65c45ee0
Bhaskara20/Dice-Rolling-Simulator-Python-Project-
/main.py
1,409
3.8125
4
import random import sys print("=======================================================\n\n") print(" SELAMAT DATANG DI SIMULASI KOCOK DADU\n\n") print("=======================================================") decide=input("Apa yang akan anda lakukan? >>") while decide=="roll": num=random.randint(1,6) ...
7d413a31dc9f5f728c75335446e4ab1c608d5856
DaveGraff/SudokuSolver
/SudokuBoard.py
3,207
3.734375
4
import numpy as np from time import sleep import pyautogui as inter class Cell: """A single cell in a Sudoku game""" def __init__(self, value, given, x, y, pos=None): self.value = value #Integer 1-9 self.given = given #Whether or not this was a given self.x = x self.y = y self.pos = pos #Position onscr...
4e86ef5f2a8176f9d39e5a54b1fa9db32cf2477d
thai321/machine-learning
/Regression/Polynomial Regression/polynomial_regression.py
2,482
3.9375
4
# Polynominal Regression # Predict the salary at level 10 # Importing the libararies import numpy as np import matplotlib.pyplot as plt import pandas as pd #np.set_printoptions(threshold = np.nan) # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values # consider to be...
32a429bae97a0678517dff15dbce80bbd25ee46a
NSNCareers/DataScience
/Dir_OOP/classVariables.py
1,374
4.3125
4
# Class variables are those shared by all instances of a class class Employee: raise_amount = 10.04 gmail = '@gmail.com' yahoo = '@yahoo.com' num_of_employees = 0 def __init__( self, fistName, lastName, gender, pay): self.first = fistName self.last = lastName self.ge...
2575ab7be1ce14fcb840456fe5827beffeac2762
TheLissandra1/PythonDemos_Primary
/1.py
450
3.859375
4
def isprime(num): i = 2 while(i<num): if num%i==0: return False i += 1 return True def goldbachresolve(num): for i in range(2,num): if isprime(i) and isprime(num-i): print(num,'=',i,'+',num-i) return True return False times=10000 i=4 while(goldbachresolve(i) and i<times): i += 2 ...
b6f6ef8259cec6d548e78c79642da640cbebbac8
guillaumethomas/reference
/python_algo/insertion_sort.py
455
3.8125
4
''' Insertion sort algo O(n2) In Place (no need for extra storage) ''' def insertion_sort(lst): i = 1 # looping with position while i < len(lst): j = i while all([j > 0, lst[j - 1] > lst[j]]): lst[j], lst[j - 1] = lst[j - 1], lst[j] j -= 1 i += 1 return...
eed491e7aa143a7422b062f14b1b91f62053e999
guillaumethomas/reference
/python_algo/dijkstra_g.py
7,674
3.640625
4
from math import inf import random import string from graphviz import Digraph class Vertex(): def __init__(self, name): self._name = name self.adjacent = {} # these attribute are specific to find the shortest of a graph self._dist_dij = inf self._visited_dij = False ...
fa3515d7f6ef27088049e611a4301d1cfff8c259
Devrim-Celik/nature_inspired_algorithms
/Task4/python/de_functions.py
9,683
3.71875
4
""" Module containing Differential Evolution Methods """ import random import matplotlib.pyplot as plt import numpy as np # POPULATION MATRIX WITH FORM: (NR_MEMBERS x NR_COMPONENTS) # STANDARD POPULATION IS CALLED: TARGET POPULATION/VECTOR # MUTATION POPULATION IS CALLED: DONOR POPULATION/VECTOR # RECOMBINED P...
35f986cbbaa78e96e01bdfda14379a96b9b20e42
avanishsingh07/Tree-level-Order-Traversal
/level_Order_traversal.py
301
3.828125
4
from collections import deque def levelOrder(root): #Write your code here q = deque([root]) while len(q): root = q.popleft() print(root, end = " ") if root.left: q.append(root.left) if root.right: q.append(root.right)
9062b5641fedda154d12e0027b737e0bb9459261
sudhirgamit/Python-Learning
/Main8.py
1,295
4.0625
4
# Functions def add_multi(a,b): sum = a + b multi = a * b sub = a - b div = a / b mod = a % b return sum,multi,sub,div,mod #print("Arithmetic Oparetion : ",add_multi(10,2)) add,multi,sub,div,mod=add_multi(10,4) print("Sum : ",add,"\t Multi : ",multi,"\t Sub : ",sub,"\t Div : ",div,...
3876d4c2374932ca9e2122bd0c39a29a77b34566
ryosuzuki/hint-pilot
/data/001.py
241
3.8125
4
def repeated(f, n): if n==1: return f(args) else: i = 1 g = f while i<n: g = compose1(f, g) i += 1 return g def main(): """ repeated(square, 0)(5) => 5 """ print(repeated(square, 0)(5)) #=> 25
48ae0414a30abe3420c3e73a78ea9b54a756f555
jsacane/ProjectEuler
/Problem_10/Problem10.py
367
3.765625
4
""" Problem 10: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from math import ceil, sqrt def isPrime(x): upperBound = ceil(sqrt(x)) + 1 return (n > 1) and (all(x % i for i in range(2, upperBound))) n = 3 sum = 2 while n < 2000000: if isPri...
304e2b328590a5c4a2dca3013b078fb4ce538cce
tinhtn1508/problem-solving
/leetcode/tree/populating_next_right_pointer.py
957
3.625
4
from common import Node class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None q = [] q.append(root) while len(q) != 0: size = len(q) prev = None for _ in range(size): tmp = q.pop(0) ...
0d5f27067f2fda20b94a30b2cbe48445d3517b6b
tinhtn1508/problem-solving
/leetcode/collect/largest_k.py
339
3.71875
4
def solution(arr): arr = sorted(arr) i = 0 j = len(arr) - 1 while i < j: if arr[i] + arr[j] == 0: return arr[j] elif abs(arr[i]) > arr[j]: i += 1 elif abs(arr[i]) < arr[j]: j -= 1 return 0 if __name__ == "__main__": print(solution([3, ...
8e60bc1c6a91dbf7fc49f5ff9c5542c0a11bba67
tinhtn1508/problem-solving
/search/binary_sreach.py
542
4.0625
4
def binary_search(arr:list, left: int, right: int, x: int) -> int: if right >= left: mid = left + int((right - left) / 2) if arr[mid] == x: return mid if arr[mid] > x: return binary_search(arr, left, mid - 1, x) return binary_search(arr, mid + 1, right, x) ...
216c1d39f5fa6fac747d6f67665bbf418dbe1a5c
Harsimran29120/MARRtino
/MARRtino-obstacle-avoidance.py
387
3.765625
4
import random begin() while marrtino_ok(): if (obstacle_distance(0)) > 1: forward(1) else: if (random.randint(0,1)) == 0: right(1) else: left(1) end() import random begin() while marrtino_ok(): if (obstacle_distance(0)) > 3: forward(0.5) else: turn((r...
7b8794a9d7c41e81421e27ae21648369b876ffaa
bgonzalo/progcomp
/bgonzalo_prob1001.py
629
4.0625
4
#http://acm.timus.ru/help.aspx?topic=python import sys, math nums = [] #crea una lista vacia llamada nums for line in sys.stdin: #a cada elemento en la lista introducida atravez de stdin for word in line.split(): #los separa en cada espacio y a acada elemento de las nuevas ...
0880e54a0034c9513dba726c12ade904ca796f07
luphord/nelson_siegel_svensson
/nelson_siegel_svensson/ns.py
2,393
3.75
4
# -*- coding: utf-8 -*- """Implementation of a Nelson-Siegel interest rate curve model. See `NelsonSiegelCurve` class for details. """ from numbers import Real from dataclasses import dataclass from typing import Union, Tuple import numpy as np from numpy import exp EPS = np.finfo(float).eps @dataclass class Nels...
e69539f58ab8f159c826d552d852c08cd79a022f
Developirv/PythonLab1
/exercise-5.py
512
4.25
4
# DELIVERABLE LAB 03/05/2019 5/6 # exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. f = 1 current = 1 former = 0 for term in range (50): if term == 0: print(f"term: {term} / number: 0") elif term == 1: prin...
91bcd6886a825494f0013eb115ee3f8ac5871ec8
LialinMaxim/Toweya
/league_table.py
2,866
4.21875
4
""" The LeagueTable class tracks the score of each player in a league. After each game, the player records their score with the record_result function. The player's rank in the league is calculated using the following logic: * The player with the highest score is ranked first (rank 1). The player with the lowest score...
cd64ce4c424c5fc80a256884b0c259ad05fa1186
anlaganlag/Processing
/畫圖解決函數.pyde
1,028
3.640625
4
from math import sin,cos,tan xmin=-10 xmax=10 ymin=-10 ymax=10 rangex = xmax - xmin rangey = ymax - ymin def setup(): global xscl,yscl size(600,600) xscl = width/rangex yscl = -height/rangey def draw(): global xscl,yscl#tell py not creating new var use the global background(255)#set backgro...
3b2f759429ded75e6fb81ee96af6f50f23874987
smartronx/PythonBrasil-exercicios
/01_estrutura_sequencial/11_inteiros_real.py
601
3.828125
4
#Usei a versão do Python 3.6.7 para fazer o exercício. #Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: # a-o produto do dobro do primeiro com metade do segundo . # b-a soma do triplo do primeiro com o terceiro. # c-o terceiro elevado ao cubo. #Resposta: print(' * Resposta exercício ...
4a65f4a10d87961ec118e172ad65f46e992dd756
Omarfos/Algorithms
/69.sqrtx.py
1,527
4
4
# # @lc app=leetcode id=69 lang=python3 # # [69] Sqrt(x) # # https://leetcode.com/problems/sqrtx/description/ # # algorithms # Easy (33.54%) # Likes: 1257 # Dislikes: 1853 # Total Accepted: 537.7K # Total Submissions: 1.6M # Testcase Example: '4' # # Implement int sqrt(int x). # # Compute and return the square ...
03da43cd9836b7a76540e0f0c32087ed378ba108
Omarfos/Algorithms
/54.spiral-matrix.py
2,158
3.8125
4
# # @lc app=leetcode id=54 lang=python3 # # [54] Spiral Matrix # # https://leetcode.com/problems/spiral-matrix/description/ # # algorithms # Medium (33.55%) # Likes: 2205 # Dislikes: 556 # Total Accepted: 356.8K # Total Submissions: 1.1M # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' # # Given a matrix of m x n...
ddf97790fe7e127b179e98bf3154a427f1531d78
Omarfos/Algorithms
/17.letter-combinations-of-a-phone-number.py
1,538
3.640625
4
# # @lc app=leetcode id=17 lang=python3 # # [17] Letter Combinations of a Phone Number # # https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ # # algorithms # Medium (46.10%) # Likes: 3738 # Dislikes: 401 # Total Accepted: 593.4K # Total Submissions: 1.3M # Testcase Example: '"23"' ...
745fbad66d859ca9bb3f04b5a402a53eca80260b
Omarfos/Algorithms
/20.valid-parentheses.py
1,716
3.8125
4
# # @lc app=leetcode id=20 lang=python3 # # [20] Valid Parentheses # # https://leetcode.com/problems/valid-parentheses/description/ # # algorithms # Easy (38.64%) # Likes: 4869 # Dislikes: 214 # Total Accepted: 986.8K # Total Submissions: 2.6M # Testcase Example: '"()"' # # Given a string containing just the cha...
131a774145f8578a603a2a13b8684ee4ff46a4ae
BWatson019/AboutMe
/Test2Pt2b.py
180
3.59375
4
""" <Description: Part B> """ def checkIfPrime(numberToCheck): for x in range(2, numberToCheck): if (numberToCheck%x == 0): return False return True
15ea8626a86ac8b3e9741b1fd224ceca5b840063
leon740gk/ml_algo_sandbox
/algorithms_adn_data_structures/data_structures/my_stack.py
943
4.0625
4
# Custom implementation of stack # List and Deque from collections import deque class StackList: def __init__(self): self.__stack = [] def push(self, x): self.__stack.append(x) def pop(self): if self.is_empty(): raise ValueError("Stack is empty") return self._...
0f6c09cbac76f5be9acd37ea10861117c31304ea
leon740gk/ml_algo_sandbox
/algorithms_adn_data_structures/algorithms/KMP_Search.py
1,444
3.796875
4
def compute_lps_array(pattern, m, lps): length = 0 i = 1 lps[0] = 0 while i < m: if pattern[i] == pattern[length]: lps[i] = length + 1 length += 1 i += 1 else: if length != 0: length = lps[length - 1] else: ...
db3e2167de73afac5b4c8a2559139f96fd8f1a2d
sbuteryd/break_time
/rename_file.py
427
3.53125
4
import os import string def rename_files(): #(1)get file names from a folder file_list = os.listdir(r"/Users/lihangen/PycharmProjects/untitled2/prank") #(2) for each file , rename filename saved_path = os.getcwd() os.chdir(r'/Users/lihangen/PycharmProjects/untitled2/prank') for file_name in file...
ea2caf1bf6aca74273cb69b0cb9dc7d9322abd42
wuqingze/leetcode
/0599-Minimum-Index-Sum-of-Two-Lists/Solution.py
822
3.578125
4
class Solution: def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ ans = [] n1 = len(list1) n2 = len(list2) m1 = {} mn = 0x7fffffff jj = {} for i ...
4b965a2602df824182bc96f13c4463c6ea90cac1
wuqingze/leetcode
/0015-3Sum/verify_00.py
333
3.578125
4
## 好像第一个写的程序不仅耗时,而且得到的结果要少一些 ## Solution.cc能够得到正确的结果和更快的速度 f = open('tt') s = [] for line in f: t = line.strip().split(" ") t = sorted(t) ts = str(t) if ts in s: print(ts) else: ## print("--", ts) s.append(ts)
de536a57738d64fad75eddabae1bc3f3c587772c
wuqingze/leetcode
/0893-Groups-of-Special-Equivalent-strings/Solution.py
426
3.546875
4
class Solution(object): def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ s = set() for i in range(len(A)): if len(A[i]) <= 2: s.add(A[i]) else: s.add(str(sorted(A[i]))) ...
cc4d18e8f26dbeac1a848257051f2dc247989550
wuqingze/leetcode
/0092-Reverse-Linked-List-II/Solution.py
1,328
3.75
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head, m, n): if head == None or head.next == None or m>n or m<1 or m == n: return head pre = None cur = head nxt = head.next preTail...
932d171cb11bdcb0728ee70f587ab5595be7d4bb
wuqingze/leetcode
/0002-Add-Two-Numbers/2_add_two_numbers.py
3,727
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def addTwoNumbers(l1, l2): return addTwoNumbers1(l1, l2, 0) def num_reverse(num): if num == 0: return None else: snum = str(num) index = len(snum) - 1 result = ListNode(snum[index]) ...
9bf72527d8fd16c45e1522f7f72264199cf56a0b
wuqingze/leetcode
/0073-Set-Matrix-Zeroes/Solution.py
857
3.515625
4
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) m = len(matrix[0]) rows = [-1]*n cols = [-1]*m for i in range(n): for j in r...
46e42928cbeac210bf63fdf116fde319ccc2ab1d
cyberdefense-club/cdc2017-summer
/lessonbatch_03/bmi.py
3,241
4.0625
4
def convert_feet_to_meters(feet, inches=0): # per Google: return (feet + inches/12.0) * 0.3048 def convert_pounds_to_kilos(pounds, ounces=0): return (pounds + ounces/16.0) / 2.2 def get_int_input(prompt, min_int, max_int): while True: instring = input(prompt) if instring.isdigit():...
38a07eb07203cb6cfe3734dd4dbc58b3b484c8dd
alexforcode/py_arcadegames_craven
/ch12/12.2.2.py
634
3.828125
4
# I '''class Cat(): name = '' color = '' weight = 0 def meow(self): print(self.name, 'says: "Meow!!!"') # II snowflake = Cat() snowflake.name = 'Snowflake' snowflake.color = 'white' snowflake.weight = 9.5 snowflake.meow()''' # III '''class Monster(): name = '' health = 0 def decr...
ef124f241c2f739e667f2361c86eaadef94d9f01
alexforcode/py_arcadegames_craven
/ch17/17.4.2.py
430
3.765625
4
# X '''num_list = [55, 41, 52, 68, 45, 27, 40, 25, 37, 26] temp = num_list[6] num_list[6] = num_list[7] num_list[7] = temp print(num_list)''' # XI '''num_list = [27, 32, 18, 2, 11, 57, 14, 38, 19, 91] temp = num_list[0] num_list[0] = num_list[3] num_list[3] = temp print(num_list)''' # XII '''num_list = [70, 32, 98, ...
b6bcc9292962d86034ef8912696965042e2d9658
alexforcode/py_arcadegames_craven
/ch7/7.6.py
227
3.828125
4
months="JanFebMarAprMayJunJulAugSepOctNovDec" try: n = int(input("Enter a month number: ")) if (n > 12 or n < 0): print('Not in range!') else: print(months[(n*3-3):(n*3)]) except: print('Error!')
789ff6363631b1128873263b5d4b5d12213192e0
alexforcode/py_arcadegames_craven
/ch12/12.4.1.py
846
3.984375
4
'''# I class Animal(): name = '' def __init__(self, name): self.name = name print('Animal is born!') def eat(self): print('Om nom!') def makeNoise(self): print(self.name, 'says: "GRRR!!!"') # II class Cat(Animal): def __init__(self, name): Animal.__init__(...
7a7d25bbaac1d4ef7cf5a94e5b6709468cf84463
BenPHaley/GoogleTraining
/Foundations/Interpret/interpret.py
280
3.734375
4
def interpret(value, commands, args): i = 0 length = len(commands); while (i < length): if ("+" == commands[i]): value += args[i] elif ("-" == commands[i]): value -= args[i] elif ("*" == commands[i]): value *= args[i] else: return -1 i+=1; return value;
914b695823c75d94d037962b8802adf5e9dbee42
jvejar1/quizzes_sw_design
/quizz5.py
229
3.78125
4
def add(numbers_str, delimiter = ','): str_numbers = numbers_str.split(delimiter) sum = 0 for str_number in str_numbers: number = int(str_number) if number > 0: sum += number return sum
2f2019a903fbdd4da02973c7d55471da33b28b9d
s-nc/100-days-of-code
/Day21-Snake-Game/food.py
508
3.984375
4
# In this file, we define food objects. from turtle import Turtle import random class Food(Turtle): def __init__(self): super().__init__() self.shape("circle") self.penup() self.shapesize(stretch_wid=0.5, stretch_len=0.5) self.color("orange") self.speed(...
485f1ba0a4fc4f744ba96e668eb64ab5cc4e7a7f
s-nc/100-days-of-code
/Day21-Snake-Game/main.py
1,262
3.734375
4
from turtle import Screen, Turtle from snake import Snake from food import Food from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) snake = Snake(3) food = Food() scoreboard = Scoreboar...
be761a2226b6741db8da1d50face2d4a4269bcb1
thinkSharp/Interviews
/addition_without_add.py
434
3.59375
4
def add(v1, v2): def xor_carry(b1,b2): xor_bs = b1 ^ b2 and_bs = (b1 & b2) << 1 if and_bs == 0: return xor_bs else: return xor_carry(xor_bs, and_bs) return xor_carry(v1, v2) def test_add(): result = add(3,5) print(result) result = add(13,5)...