blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4b8e404e0fc4580832250c0d10935cc754bba69e
rjorth/Algorithms-and-Data-Structures
/searchInsert.py
344
3.875
4
def searchInsert(nums, target): # my solution.... for i in range(len(nums)): if nums[i] >= target: return i return i+1 #if last value in list def SearchInsertFast(nums, target): #leetcode faster python3 solution return(sorted(nums + [target]).index(target)) print(searchInsert([1,2,3,4], 5)) print(SearchI...
7503cce3945d518c26aec3c4a8bfef38eb10594c
rjorth/Algorithms-and-Data-Structures
/isSameTree.py
245
3.5
4
def isSameTree(p, q): if not p and not q: return True elif not p or not q: return False elif p.val != q.val: return False else: return isSameTree(p.left, q.left) and isSameTree(p.right, q.right) print(isSameTree([1,2,3], [1,2,3]))
ea7070310a27bd2331b6a27960d70b2428259447
rjorth/Algorithms-and-Data-Structures
/mergeTwoBinaryTreesAgain.py
366
3.765625
4
def merge(t1,t2): #add vals of trees #if both have values then : if t1 and t2: #combine vals as long as both have vals available t1.val += t2.val t1.left = merge(t1.left, t2.left) t1.right = merge(l2.right, t2,right) #obviously interchangeable #we default to t1. if t1 is not, then go for t2. but mostly ...
2b4dfd4763eea4be731c98b281edd8bd38e61b50
rjorth/Algorithms-and-Data-Structures
/stairs.py
260
3.84375
4
def climbStairs(n): # a is the number of ways to reach the first step # b is the number of ways to reach the next step # after a step, b becomes a, and is reassinged a + b a = b = 1 for _ in range(n): a, b = b, a + b return a print(climbStairs(5))
0443c4c129fb47ebea24e145131a0fd494e321bb
rjorth/Algorithms-and-Data-Structures
/LHS.py
340
3.890625
4
import collections def findLHS(nums): #counter counts the number of times that an element appears in the list #you constantly confuse this with enumerate count = collections.Counter(nums) #store result arr = 0 for i in count: if i+1 in count: arr = max(arr, count[i] + count[i+1]) return arr print(findL...
f329f4c4c0e3f052a61362b83ff6e07e06d42fb9
rjorth/Algorithms-and-Data-Structures
/moveZeroes.py
232
3.640625
4
def moveZeroes(nums): #iterate backwards! for i in range(len(nums))[::-1]: if nums[i] == 0: #pop where i is zero. does this count as in place? nums.pop(i) nums.append(0) return nums print(moveZeroes([1,2,1,0,0,3]))
d5b77816f96be6462ad6f1aac57de51683ceccb6
rjorth/Algorithms-and-Data-Structures
/TIQ/125-validPalindromeStr.py
202
3.8125
4
def valid(s): s = s.lower() s = s.strip().split(' ') s = "".join(char for char in s if char.isalnum()) return s == s[::-1] print(valid("Race car")) print(valid("fat")) print(valid(":racecar"))
07037e21c88da8084cc80dbafcd3c769a08dc96d
deesaw/PythonD-03
/Data Structures/references.py
195
3.53125
4
a=[4,5,6] b=a[:] # make a copy of a c=a #add a reference print id(a) print id(b) print id(b) d={4:5} e=d #add a reference f=d.copy() # make a copy of d print id(d) print id(e) print id(f)
c78ddd4b6f982e547c2fad03dcf129a8171369fe
deesaw/PythonD-03
/Databases/mysqlConnector/db3.py
546
3.765625
4
"""this program shows how to connect to a MySQL database and fetch multiple rows of data using fetchall""" from mysql.connector import connection mydb = connection.MySQLConnection(user='root', password='hello123',host='127.0.0.1', database='fkdemo') # connect to database mycursor=mydb.c...
a3b784e8335187847470972a0e23adbe68bd961a
deesaw/PythonD-03
/Databases/mysqlEx/db4.py
589
3.53125
4
"""this program shows how to connect to a MySQL database and fetch multiple rows of data using fetchone""" import sys import MySQLdb try: mydb = MySQLdb.connect("localhost","root","root","pytho" ) # connect to database except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) print "Check your connecti...
9516fbd1b0e41dcf6679ce5445241734848c1714
winlp4ever/algos
/remove-duplicate-letters.py
1,023
3.6875
4
import collections class Solution: def removeDuplicateLetters(self, s: str) -> str: if not s: return s # keep track of occurances of each character in the original string counter = collections.Counter(s) # keep track of which characters have already been used us...
f088e333f8bbe131a340ba9434a479dd6c88f3c4
winlp4ever/algos
/longestrepeatingcharacterreplacement.py
961
3.515625
4
''' Problem: link: https://leetcode.com/problems/longest-repeating-character-replacement/ ''' def foo(l, k: int) -> int: # longest contiguous subseq whose sum infe or equal to k i = 0 j = 0 lg = 0 sm = 0 n = len(l) while j < n: sm += l[j] while sm > k: sm...
377d0f3e4215b0a121ef398cd5bcc06d2e564c5f
winlp4ever/algos
/house-robber-iii.py
1,556
3.796875
4
''' search for problem on leetcode the nature is: given a binary tree with weighted vertices. find out the set of vertices with maximum weight sum where no 2 vertices are adjacent. ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution:...
7254ed2f7bdbf7f4016718be6de8c22fe9c704e9
winlp4ever/algos
/implement-queue-using-stacks.py
1,032
4.25
4
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.in_ = [] self.out_ = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.in_.append(x) def pop(self) -> in...
6e644756ecb2ff6a0d6cf987125ffc5296e6ca31
winlp4ever/algos
/queuereconstructionbyheight.py
548
3.921875
4
from typing import List class Solution: ''' Link to problem:https://leetcode.com/problems/queue-reconstruction-by-height/ Complexity: O(n^2) If u can find an array-based data structure that allows insert in O(1) then the complexity become O(nlogn) ''' def reconstructQueue(self, people: List[Lis...
7bc0954a1012d781c23a2b9dd391529ab96e1d40
winlp4ever/algos
/codeforces/r638/science.py
801
3.578125
4
t = int(input()) def ord2(k): i = 0 while k: k //= 2 i += 1 return i def binsearch(nums, val, l, h): if nums[h] <= val: return h if nums[0] > val: return -1 if l + 1 >= h: return l m = (l+h)//2 if val >= nums[m]: return binsearch(nums, va...
d23237b3bdf047a6cbb21128c71d0522e213301f
winlp4ever/algos
/largestdivisiblesubset.py
845
3.984375
4
''' Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1: Input: [1,2,3] Output: [1,2] (of course, [1,3] will also be ok) Example 2: In...
72f68418308f3a26044b2dff0108267ffd7a3465
ngomankone/JoinMapReducePy
/REDUCER.py
3,004
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 10 21:40:59 2019 @author: PERSO """ #!/usr/bin/env python import sys # maps words to their counts foundKey = "" foundValue = "" isFirst = 1 currentCount = 0 currentCountry2digit = "-1" currentCountryName = "-1" isCountryMappingLine = False # input comes from STDI...
2a230685bdb7375d19441e48625aada3936f43e1
phamvubinh/working_space
/python/pygame/pygame_course/snake_game/tut7_moving_rectangle.py
828
3.796875
4
"""https://www.pygame.org/docs/ref/event.html""" import pygame pygame.init() white = (255,255,255) black = (0,0,0) head = [400, 300, 20, 20] tail = [200, 200, 20, 100] gameDisplay = pygame.display.set_mode((800,600)) #surface pygame.display.set_caption('Slither') #pygame.display.flip() pygame.display.update(...
f07210eb4aa6efa636f033ff92bfb868f4a8c74e
phamvubinh/working_space
/python/python_basic/input/input.py
228
3.796875
4
#!/usr/bin/python import sys str = raw_input("Enter raw_input: ") print "raw_input is: ", str try: str = input("Enter expression input: ") print "result is: ", str except NameError: print "No valid expression" sys.exit()
ba00a52aa2e7be7f7369bc6316553792f065baff
phamvubinh/working_space
/python/pygame/pygame_course/snake_game/tut13_fixing_the_hardcoding.py
1,452
3.71875
4
"""https://www.pygame.org/docs/ref/event.html""" import pygame pygame.init() white = (255,255,255) black = (0,0,0) display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Slither') lead_x = display_width/2 lead_y = display_height/2...
ff29292e839be9465a9005916c320ce325bb1ddf
medhapanuganti/EDUYEAR-PYTHON-20
/Day4.py
725
3.8125
4
#numbers which are divisible by 5 and 7 n,m=map(int,input("enter the range:").split()) for i in range(n,m+1): if i%5==0 and i%7==0: print(i,end=" ") #sum of the series (2+22+222+...) a='2' terms=int(input("enter no. of terms:") count=0 for i in range(1,terms+1): count+=int(a*i)...
efefac8442e0c1f290bc1dd976210ff4a8d73eb1
drapert/Final_appliedP
/Instructor.py
1,846
3.75
4
from Individual import * import sqlite3 db = sqlite3.connect('assignment2.db') cursor = db.cursor() class Instructor(Individual): '''Contains functions for use of an instructor or professor''' def __init__(self): pass def print_class_roster(self): roster = input("Enter the c...
419f09c1e02d56c60ccf58e7fb763c6c2b5b4b4c
nolll77/ml_tutor
/ml_tutor/classification/knn.py
15,308
3.734375
4
from ml_tutor.model import BaseModelClassification from sklearn.decomposition import PCA import random import numpy as np import matplotlib.pyplot as plt class KNeighbourClassifier(BaseModelClassification): def __init__(self, n_neighbors=5, visual_training=True, number_of_visual_steps=-1): """ Create the K-Nea...
db5d2c302893eb4b72a82849226609326c9ad9c8
JoshCornell/My_first_doodle
/backupgen.py
1,408
4.15625
4
# This program will run over a log file and create an identical copy in a text file. # The text file will be created automatically if it does not already exist. If the File already exists, data will be appended to the existing file. datadumpvar = [] todaydate = input("Enter Today's date, (format YYYYMMDD): ") ...
c3d0ee7709097f55f66bc310f8e76ec462b93ca7
meghalrag/pythonExample
/commonPgm/divisibleby5and6.py
423
4.15625
4
num=input("enter anumber:") temp=False if num%5==0 and num%6==0: temp=True else: temp=False print"Is divisible by 5 and 6?",temp if num%5==0 or num%6==0: temp=True else: temp=False print"Is divisible by 5 or 6?",temp if num%5==0 or num%6==0: if num%5==0 and num%6==0: temp=False...
87e403be2ed3a367f28ec449b53f4b90a5d1d729
meghalrag/pythonExample
/loop/revstring.py
106
4.15625
4
str=raw_input("enter the string:") print"reverse=", for i in range(len(str)-1,-1,-1): print str[i],
85c98279d559b02603fd2382f92b1700a4d5298b
meghalrag/pythonExample
/loop/sumof10.py
149
3.9375
4
limit=input("enter the limit:") print "enter",limit," numbers:" sum=0; for i in range(limit): num=input() sum=sum+num; print "sum=",sum
55ec195892e55ad77496b20f18c1f0e9a41039fe
BDT-02/katas
/Gab0x/classexercises-2.py
1,216
3.90625
4
#var = input() #if ( var == 100 ): # print("Value of expression is %d" % (var)) # print("That is all!!") #some_value = 1 #if some_value: # print("Got a true expression value") # print(some_value) #else: # print("Got a false expression value") # print(some_value) #var = 200 #if var == 200: # print("...
434215a5110549d709f5cd0dd2d345f04daa3247
foundling/CS-Courses
/data_structures/week_1/assignments/2_tree_height.py
1,179
4.03125
4
# python 2 ''' Alex Ramsdell Coursera Data Structures Week 1 Programming Assignment, Problem #2 Compute Tree Height Input: first line, N, number of vertices in the tree. Second line, a space-delimited list of integers, L, from L[0] to L[n-1], where the index represents a node, and the value at that index represents ...
bd7b9e4b8f24b7112876e263f901f676c25a53c5
MarcoASV/casa-
/main.py
1,873
3.515625
4
from gpiozero import LED from time import sleep from gpiozero import Button luzSala = LED(2) luzCocina = LED(3) button_1 = Button(17) button_2 = Button(27) button_3 = Button(22) motora = LED(10) motorb = LED(9) motora.off() motorb.off() luzCocina.on() luzSala.on() name = input("ingresa tu nombre de usuario: ") cont...
3ba882e880086cc81c093ca5d943059d1984829c
amosricky/LeetCode_Practice
/UnFinished/LeetCode_026_Remove Duplicates from Sorted Array.py
394
3.53125
4
class Solution: def removeDuplicates(self, nums: 'List[int]') -> 'int': if not nums: return 0 i = 0 for j in range(1, len(nums)): if (nums[i] != nums[j]): i += 1 nums[i] = nums[j] return i+1 myClass = Solution(...
b4106958fefea099d819457e1634e7d1bc917f7d
amosricky/LeetCode_Practice
/Problems/LeetCode_079_Word Search/LeetCode_79_Word Search_1.py
1,480
3.609375
4
class Solution: def exist(self, board: "List[List[str]]", word: "str") -> "bool": for index_Row, _ in enumerate(board): for index_Column, _ in enumerate(board[index_Row]): chk = self.backTracking([index_Row, index_Column], board, word, 0) if chk: ...
97fbe7f4d890427e737026ab1cbc611088287393
amosricky/LeetCode_Practice
/Problems/LeetCode_079_Word Search/LeetCode_79_Word Search_2.py
1,741
3.78125
4
class Solution: def exist(self, board: "List[List[str]]", word: "str") -> "bool": for index_Row, _ in enumerate(board): for index_Column, _ in enumerate(board[index_Row]): # Check up if self.backTracking([index_Row, index_Column], board, word, 0, [-1, 0]): ...
4c6a49c72b6aac5988a4711df5f3ef8bb6428502
amosricky/LeetCode_Practice
/Problems/LeetCode_535_Encode and Decode TinyURL/LeetCode_535_Encode and Decode TinyURL_1.py
871
3.65625
4
import hashlib class Codec: def __init__(self): self.baseUrl = "http://tinyurl.com/" self.urls = {} def encode(self, longUrl: 'str') -> 'str': """Encodes a URL to a shortened URL. """ m = hashlib.md5() m.update(longUrl.encode("utf8")) enCode = m.hexdig...
bebabb1d49fe213ce23db9c6ba16f986cb90bf7d
amosricky/LeetCode_Practice
/Problems/LeetCode_053_Maximum Subarray/LeetCode_053_Maximum Subarray_3.py
910
3.5625
4
class Solution: def maxSubArray(self, nums): def divide_and_conquer(nums, start, end): if start == end - 1: return nums[start], nums[start], nums[start], nums[start] mid = (start + end) // 2 subStart_l, mid_l, subEnd_l, subSum_l = divide_and_conquer(nums,...
2d75ceadeb7a2bf958758aa2c00dd8f0d2ea751b
amosricky/LeetCode_Practice
/Problems/LeetCode_046_Permutations/LeetCode_046_Permutations_1.py
666
3.59375
4
class Solution: def __init__(self): self.res = [] def permute(self, nums: 'List[int]') -> 'List[List[int]]': if not nums: return self.res self.find(nums, []) return self.res def find(self, remainingNums: 'List[int]', tempANS: 'List[int]'): for index, val...
c68e9b28f27f0954b74e72fdaf65041a0ab3c094
amosricky/LeetCode_Practice
/UnFinished/LeetCode_069_Sqrt(x).py
826
3.875
4
# Binary Search class Solution: def mySqrt(self, x: 'int') -> 'int': if x == 1 or x == 0: return x left, right = 0, x while left <= right: mid = left + (right - left) // 2 if mid * mid > x: right = mid - 1 elif mid * mid < x: ...
7ab39ce01ad89af7be8a2250b4a07ba4b3bb37a3
amosricky/LeetCode_Practice
/UnFinished/LeetCode_035_Search Insert Position.py
580
3.828125
4
class Solution: def searchInsert(self, nums: 'List[int]', target: 'int') -> 'int': for idx, val in enumerate(nums): if (val == target) or (val > target): return idx return len(nums) # 效能差很多 # class Solution: # def searchInsert(self, nums: 'List[int]', target: 'int')...
16fd2ea7e4480ae7858d1ecd78cb1e78d47499cf
Nasreen98/codekata98
/pgg2.py
116
3.84375
4
ns=int(raw_input()) if(ns<0): print("invalid") elif(ns%2==0): print("Even") elif(ns%2==1): print("Odd")
8ffc08ef9aa1f211a054e9e4f2488c6c4ee28cab
lorenzokuo/python_fundamentals
/functionIntermediate2.py
3,795
3.84375
4
# 1 x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] # How wou...
27c59c9134fc3e2d5d18651058601fff883b9b66
lorenzokuo/python_fundamentals
/for_loop_basic1.py
1,334
3.96875
4
# 1. Basic - Print all the numbers/integers from 0 to 150. for count in range(0,151): print(count) # 2. Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000. # solution 1 # count = 1 # while count < 1000000: # print(count*5) # count += 1 # solution 2 for count in range(1,1000001): print(count*5) ...
27221b8014f94e5b6fd876730d068d42bf58429d
jake-billings/edu-csci2511
/check-prime/check_prime.py
1,635
3.828125
4
""" Name: Jake Billings Date: 10/26/2017 Class: CSCI 2511 Discrete Structures Desc: Implementation of a prime-checking algorithm for problem 4.3.1 of the midterm review """ # Import time so that we can benchmark the algorithm from time import time # Check if i is prime using the simplest algorithm I could thin...
7e6de4ecbaac54f7b803c94a925994a1a7f2fba4
AstroHeyang/-offer
/039-平衡二叉树/is_balanced_tree.py
391
3.875
4
def is_balanced_tree(pRoot): def height_of_tree(node): if not node: return 0 height_left = height_of_tree(node.left) height_right = height_of_tree(node.right) if height_left == -1: return -1 if height_right == -1: return -1 if abs(height_left - height_right) > 1: return -1 else: return 1 ...
65d33a4e62afed4a37b1fd390bb7746bf744afbc
AstroHeyang/-offer
/050-数组中重复的数字/duplicate.py
420
3.875
4
def duplicate(numbers, duplication): if not numbers: return False for num in numbers: if num < 0 or num > len(numbers)-1: return False for i, num in enumerate(numbers): while i != numbers[i]: num = numbers[i] if numbers[i] == numbers[num]: duplication[0] = num ...
3ef8ee770bc95bb0ab93f89111dc0d3527b98cc0
AstroHeyang/-offer
/052-正则表达式匹配/match.py
538
3.828125
4
def match(self, s, pattern): # write code here if not s and not pattern: return True if s and not pattern: return False if len(pattern) >= 2 and pattern[1] == '*': if s and (pattern[0] == s[0] or pattern[0] == '.'): return (self.match(s,pattern[2:]) or self.match( s[1:],patte...
b23f8cf9775a15ff7c98e2c8bcc14d2c5673cc22
AstroHeyang/-offer
/001-二维数组中查找/find.py
347
3.84375
4
def find(target: int, array: list) -> bool: if not target or not array: return False row, col = 0, len(array[0])-1 while row < len(array) and col >= 0: if array[row][col] == target: return True elif array[row][col] > target: col -= 1 else: ...
6c83e033402eae5f29b17f1dc429df8ce0ac2cd4
AstroHeyang/-offer
/040-数组中只出现一次的数字/find_number_appear_once.py
556
3.5
4
def find_number_appear_once(array): if not array: return None f = lambda x,y:x^y pivot = reduce(f, array) def isBit1(num,index): while index > 0: num >>= 1 index -= 1 return (num & 1) def getBit1Index(num): index = 0 while not (num & 1): num >>= 1 index += 1 return index ...
bbb5b227eb65ba76922babe9e2f6071d7f27e4c9
AstroHeyang/-offer
/008-跳台阶/jumpFloor.py
242
3.625
4
def jumpFloor(n: int): if n == 0: return 0 if n == 1: return 1 if n == 2: return 2 first, second = 1, 2 while n > 2: first, second = second, first + second n -= 1 return second
4caf589fdedf7ad522e1a95ea65ddb250358a4fb
AstroHeyang/-offer
/019-顺时针打印矩阵/print_matrix.py
867
3.71875
4
res = [] def print_matrix(matrix): if not matrix: return start = 0 while len(matrix) > 2*start and len(matrix[0]) > 2*start: print_circle(matrix, len(matrix), len(matrix[0]), start) start += 1 return res def print_circle(matrix, nRow, nCol, start): if not nRow or not nCol...
c2b0f624711a476d31562c73aa69401b3aa0906d
bev-a-tron/TeaHouse2
/inventory.py
422
3.5625
4
#inventory.py """ This will keep track of inventory for the tea shoppe. """ class tea: type = 'none' stock = 0 price = 0 def buy(self,num): self.stock = self.stock + num def sell(self,num): self.stock = self.stock - num oolong = tea() oolong.type = 'black' oolong.stock = 10 oolong...
8547850f81831f868fc9fb2dccc542bd5f99ab3c
abhigna15/Vending-Machine
/vm.py
10,602
3.515625
4
import tkinter as tk from tkinter import * import sqlite3 # Abhigna KV r = tk.Tk() r.resizable(0,0) r.title("Vending Machine") Label(r, text="VENDING MACHINE", bg="pink", font=('arial', 15, "bold")).pack(pady=10) Label(r, text="MENU", font=('arial', 12, "bold")).pack(pady=10) Label(r, text="1.Coke Rs 20/-\n2.L...
d00302d9b0895a9db04a6a3ea0fed25765bd9e2c
Legoeggolas/amiable-ariadne
/util/graph.py
294
3.828125
4
# A simple node # Stores the position as a tuple of abscissa and ordinate # Also stores other neighbouring Nodes in an ordered list class Node: def __init__(self, position: tuple): self.position = position self.neighbours = [None, None, None, None] # Up, Down, Left, Right
c2c03ca3117ebbd9dcf709768eb9c566b0a41f56
pranjitbharali/Compiler-Design
/reg2dfa.py
5,195
3.625
4
class node: count=0; def __init__(self, typ): self.typ=typ def print_tree(root,values): if(hasattr(root,'left')): print_tree(root.left,values) if(hasattr(root,'down')): print_tree(root.down,values) print("type = ",root.typ,"\t\talphabet : ",values[root.index],"\t\t nullable...
5d52ef0edff9164e7d14fe9f5d222f51d45c01b0
hillc4456/CTI110
/Hill_M5HW2.py
226
4
4
#Camron Hill #11/3/17 #M5HW2 def main(): num=0 total=0 while num >-1: num=int(input("Enter a Number: ")) theSum=num +1 total +=theSum else: print(total) main()
7fac116ec2f8c991701c775144eb5edb5f1a7861
hillc4456/CTI110
/M5LAB.py
715
3.71875
4
#Camron Hill #10/23/17 #M5_Lab def main(): import turtle import random wn = turtle.Screen() elsa = turtle.Turtle() wn.bgcolor("White") colours = ["red", "blue", "orange", "white"] elsa.penup() elsa.forward(90) elsa.left(45) elsa.pendown() def branc...
6333407221a591a502643a132df1f047c1f2461b
ram0ngar/Metodos-numericos
/MetodosNumericos/SegundoParcial/SeNewtonRaphson/SeNewtonRaphson.py
4,136
3.78125
4
#Ejemplo #x^2+y^2=10 u #x^-y^2=1 v def createMatrix(m,n,v): C=[] for i in range(m): C.append([]) for j in range(n): C[i].append(v) return C def getDimensions(A): return(len(A),len(A[0])) def copyMatrix(B): m,n=getDimensions(B) A=createM...
e3fe47c744ba1c0dbbc2a24d2694cd6c3898dbd8
YTRodi/Curso_Python
/Listas/binary_search.py
1,112
4.0625
4
# --------------------------------------------------- FUNCIONES def binary_search(numbers,number_to_find,low,high): # Si el index bajo es mas grande que el alto, el número no existe. if low > high: return False mid = (low + high) / 2 mid = round(mid) if numbers[mid] == number_to_find: ...
8bbf2bc8632857b9172eafbf87a09991b3c01dd3
KirtiGautam/spotflix-backend
/Music_Recommendation file/fma_metadata/Music Recommendation System (Data Processing and Analysis).py
12,256
3.5
4
#!/usr/bin/env python # coding: utf-8 # ## Music Recommendation System (Data Processing and Analysis) # ### Framing the Problem # This project is aimed upon building a music recommendation system that gives the user recommendations on music based on his music taste by analysing his previously heard music and playlis...
5cd72fd8ddcbb7767e3c3a2c10e8aeb6d50c7cfc
PawanPatil19/CS50--Introduction-to-Computer-Science
/pset6/mario.py
305
3.796875
4
from cs50 import get_int l=0 while (l>8 or l<1): l=get_int("Height: ") for i in range(l): for j in range(l,i+1,-1): print(" ",end="") for p in range(0,i+1,1): print("#",end="") print(" ",end="") for q in range(0,i+1,1): print("#",end="") print()
fdfcc559574f532ba0993b73836834ab53b89710
harvey345/drive-lisence
/drive.py
395
3.828125
4
country=input("請輸入國家 : ") age=int(input("請輸入年齡 : ")) if country=="美國": if age>=16: print("你可以開車") else: print("你還不能開車") elif country=="臺灣": if age>=18: print("你可以開車") else: print("你還不能開車") else: print("只能輸入 臺灣 和 美國")
0e9dc42f2c8c2403bc0cdd9920f2afd10c5733c6
CHADBUCK13/AI_Climate_Crisis_2021
/AI_Launch_Lab_2021/honeyTransform.py
2,294
3.5625
4
# read csv using relative path import pandas as pd # Method to perform transformation of collected data into usable format # Computes price per lb def honeyTransform(): try: hn = pd.read_csv('HoneyData/Detailed US Honey Data_clean.csv') print(hn.head()) except IOError: print("File not a...
4f849b330d6fdb0b6d5a6accb2db9d0dd9100cd7
Patrick5455/jetbrains-python-academy
/Hangman/hangman.py
2,101
3.953125
4
import random WORDS = ['python', 'java', 'kotlin', 'javascript'] def menu(): opt = get_option() while opt != "exit": print("H A N G M A N") play() print("") opt = get_option() def get_option(): opt = '' while not (opt == 'exit' or opt == 'play'): opt = input(...
4852a1701cf4671d2b65d1ded0bed3f403d40c54
Patrick5455/jetbrains-python-academy
/Tic-Tac-Toe/tictactoe.py
3,704
4.0625
4
# write your code here from itertools import count game = [ ["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"] ] def print_board(board): print("---------") for row in board: print("| " + " ".join(row) + " |") print("---------") def valid_play(cells): if len(cells) != 9: p...
e61b3dde4c492e8b79f5645f20dcd8664a7da848
jkeohane/physics_220
/ball_angle.py
150
3.640625
4
from math import * x = 10 # Horizontal position y = 10 # Vertical position angle = atan(y/x) print((angle/pi)*180)
03c36fa8f7512de9cf16f356954ad1c08b345410
jkeohane/physics_220
/ball_position_xy.py
411
3.734375
4
def y(v0y, t): g = 9.81 # Acceleration of gravity return v0y*t - 0.5*g*t**2 def x(v0x, t): return v0x*t initial_velocity_x = 2.0 initial_velocity_y = 5.0 time = 0.6 # Just pick one point in time print(x(initial_velocity_x, time), y(initial_velocity_y, time)) time = 0.9 # ... ...
5039ddbdef64c5ea4c47d9153b95a1d2fcac3598
mauzeh/formation-flight
/lib/geo/point.py
3,853
3.796875
4
import math from lib.debug import print_line as p class Earth(object): # 6371.00 in km, 3440.07 in NM # always make sure this is a float!!! R = 3440.07 class Point(object): """Represents a point on earth. Lat/lon in decimal degrees.""" def __init__(self, lat, lon, name = 'Point'): self....
e4c187fdf02fcb6ace2e2ceb89c93829251d2a77
mauzeh/formation-flight
/lib/sim.py
2,430
3.8125
4
"""A discrete event simulation framework.""" import debug, config class Event(object): """An occurrence initiated from within the simulation.""" def __init__(self, label, sender, bubble_time = 0): assert bubble_time >= time self.label = label self.sender = sender self.time =...
0b089b3a2811601a37e0df2bbc4c476c3547bf4e
usernamesarehard15/rpg
/enemy.py
3,570
3.8125
4
import random class enemy(): """ base enemy class to be inherted Arugments name -- enemy name desc -- enemy description shown on encounter death -- message played on enemy death health -- the max health of the enemy damage -- the damage dealt on attack specialChance -- number between ...
8d2a6a1caa1075eb085c142043b408b1179aff9f
Tyler-Applegate/python-exercises
/function_exercises.py
8,170
4.28125
4
# Exercises # Create a file named function_exercises.py for this exercise. After creating each function specified below, write the necessary code in order to test your function. # 1. Define a function named is_two. It should accept one input and return True if the passed # input is either the number or the string 2, F...
1d3848489dbd64d86c16ea04ce93186da763dc11
brycefarnsworth/tictactoe
/tictactoe/tictactoe.py
3,973
3.625
4
PLAYER = ["X", "O"] class Game(object): def __init__(self): self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] self.player = 0 self.choice = None def reset(self): self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] ...
4007f6dd2132a4b7795d5caad977ac03ec0fb614
N-911/chess
/FEN - ASCII.py
2,294
3.546875
4
""" Дано расположение шахматных фигур на доске в FEN-нотации. Вывести её в текстовом ASCII формате по образцу. На диаграмме должно присутствовать: рамка вокруг позиции, буквы a-h снизу, цифры 1-8 слева, точки на пустых полях, фигуры на своих местах Начальные данные: строка символов - позиция в FEN н...
24491c96beda752bbf0dad3fe5e96887a09d3a35
KenDesrosiers/CS-2223
/Project 1/finalcode.py
22,834
4.125
4
###################################################################################### # # # Name: Kenneth Desrosiers # Date: 3/25/18 # # This project compares the implementation of a Priority Queue using two different # data structures, a heap and an unsorted list. It then measures each module (by time) #...
ed1a0f27f504e4671fbf2691a7210817db5b4ecd
cabirerguven/Class4-PythonModule-Week4
/W4_Q2_LCM.py
1,312
3.8125
4
#C@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@1 # PyCoder Coding Class:4 @ # Cabir Erguven @ # Week : 4 @ # Question : 2 @ # Date: 30.01.2021 @ #C@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@1 # # Calculate the least common multiple (L.C.M.) of f...
190d581eb5f476393cbe78634dedfa68c614ba26
greenca/exercism-python
/queen-attack/queen_attack.py
1,016
3.75
4
def board(pos1, pos2): check_positions(pos1, pos2) board = [] for i in range(8): row = 8*['_'] if i == pos1[0]: row[pos1[1]] = 'W' if i == pos2[0]: row[pos2[1]] = 'B' board.append(''.join(row)) return board def can_attack(pos1, pos2): chec...
d960b4d0d72b3cf09ca7e3a0aee3557d2e6db9bc
vdpham326/python-data-structures
/sets/unique_words.py
239
3.953125
4
''' Write a function named count_unique_letters(word) that accepts a string argument and returns the number of unique letters (characters) in the word. ''' def count_unique_letters(word): set_word = set(word) return len(set_word)
28e478f3a68cc9133614c952388e6d6309fc1968
vdpham326/python-data-structures
/sets/pawn_moves.py
557
3.9375
4
def next_position(current_position, move): x, y = current_position # untuck the tuple into x and y variables if move == 'down': return (x, y - 1) if move == 'up': return (x, y + 1) if move == 'left': return (x - 1, y) if move == 'right': return (x + 1, y) print(next...
828743255b3e61f78a18dd82a4e51772d8062317
vdpham326/python-data-structures
/nested_list/gameboard.py
966
4.65625
5
''' Create a function named is_board_correct(input_board) that accepts a game board in the format shown in the template code. The function should count the number of obstacles on the board (represented by 'x') and return True if there are exactly three obstacles. If there is any other number of obstacles, the functio...
1d42c8ce06f70d05052e2171fa806a8fa3de33be
vdpham326/python-data-structures
/nested_list/gameboard2.py
630
4.125
4
''' Implement another version of the hero_move_right(board) function. This time, when the hero stands in the rightmost column and wants to move right, put him in the leftmost column of the same row. hero_move ''' def hero_move_right(board): for i in range(len(board)): for j in range(len(board[i]) - 1): i...
411f0b7bc1cf9da1122f66c64ddce1e7fd71dbc5
vdpham326/python-data-structures
/sets/sports_cost2.py
1,083
4.21875
4
''' Create an all_players set and a new_players set. Then, count the number of elements in these sets and print: There are {} players using the hall, {} of which are new players. ''' volleyball_players = {'John Williams', 'Tom Jones', 'Jessica White', 'James Moore', 'Anne Davis', 'Lara Taylor', 'Conrad Anderson', 'R...
36afb935682d5e1d2cc95de8159bda1deb5cbbdb
revv-tech/GeneticBees
/abejas.py
8,969
3.734375
4
#ABEJAS import math import random """ Estructura del DNA Constaran de 26 bits 0-1-2: COLOR -> Color en RGB 3...12: DIRECCION -> Punto Cardinal 13...16: ANGULO -> Por ahora lo tendremos en 31 para tener 3 bits 17...23: DISTANCIA -> El maximo es 63 por lo que se utilizan 6 bits 24...26: TIPO DE RECORRIDO -> Hay tres ti...
9fae9f7cf148ef4a0363eba4d461c84f3428c463
kondurisaisanthosh/python-projects
/DFS-BFS-UCS/ucs_undirected_adj_mat.py
2,792
3.578125
4
import queue # import queue def mat_to_queue(pair,adj_mat,start): # method which returns states expanded visited_vertex=[start] path=[start] while path: node=path.pop(0) current_ele=0 for key,value in pair.items(): ...
eeb5823594bc644e924808cd7e7e79d8185d2d71
kondurisaisanthosh/python-projects
/DFS-BFS-UCS/Depth_FS_recursion_undirected_adj_matrix.py
2,439
3.609375
4
def DFS_adjacencymatrix_Using_Recursion(begin, dest,path,visited): #called method which returns shortest path node = path[-1] #assigns node variable with last element of the path visited.append(node) if node == dest: print("Path=",...
87b8ba78e2e61e6322b184c508a78ecaa71dc63a
Gochim/AdventOfCode
/2019/Python/day01_02.py
593
3.6875
4
import math def positive(value): return 0 if value < 0 else value # Task - https://adventofcode.com/2019/day/1 def main(): data = open("day01_01.txt", 'r') final = 0 for mass in data: module_fuel = 0 iteration_fuel = mass while True: iteration_fuel = positive(math...
c3b1896aa1376aaeef581142ea7ba5be48d7dd45
Ayushi-gupta1225/hello-world
/04_add n multipy.py
223
4.03125
4
a=int(input("enter the first number")) b=int(input("enter the second number")) c=int(input("enter the third number")) x=(a+b)*c if x>100: print("greater than 100 ") else : print("less than 100")
cad119c4db044abbb183f8b8088982c577efe834
smooth-dasilva/Smoothstack-Workload
/DailyAssingments/Week1/Day3AssingmentsDoc8.py
1,714
3.84375
4
#doc8 #1 def printHelloWorld(): print("Hello world") printHelloWorld() #2 def printName(name): print(f"Hello, my name is {name}") printName("Google") #3 def printCondition(x, y, z): if bool(z): return x else: return y ans=printCondition("This is true","This is false", []) print(f"The ch...
54357a39fec296eb647dc03708a414fc3d2e971d
smooth-dasilva/Smoothstack-Workload
/DailyAssingments/Week2/Day2Assignment.py
2,840
3.546875
4
import numpy as np import pandas as pd def ConvertString(cell): try : return str(cell) except: return 'NA' def ConvertFloat(cell): try: return float(cell) except: return 0.0 # data read without converters, set low memory otherwise interpreter complains # df = pd. re...
83a9117104c424030adaa5baede9feaa694c4574
Charles5533/Passwrord-Gererator-Python
/lab4.py
2,726
4.125
4
import numpy as np import re first=np.zeros((3,3)) second=np.zeros((3,3)) def addition(first,second): print("you selected addition. the results are") return np.add(first,second) def substraction(first,second): print("you selected substraction. the results are") return np.sub(first,second) def mult...
8b29dacc069e200f3221247d905d36fda64645d1
nmduc99/LabPythonC17
/Lab 3/Strings.py
290
3.828125
4
hello = 'hello' world = "world" print(hello) print(len(hello)) hw = hello + ' ' + world print(hw) hw12 = '%s %s %d' % (hello, world, 12) print(hw12) s = "hello" print(s.capitalze()) print(s.upper()) print(s.rjust(7)) print(s.center(7)) print(s.replace('1', '(ell)')) print(' world' strip())
815e0f22c59f4a22a5facc38ee5ad62c90c4ef46
fits/try_samples
/python/itertools/groupby_sample.py
158
3.53125
4
from itertools import groupby vlist = ["A", "B", "B", "C", "B", "A"] for k, g in groupby(sorted(vlist)): print "key = %s, count = %d" % (k, len(list(g)))
8cf5221b5a8f818f82242b596d9a52eec124947b
Enigmamemory/submissions
/6/regexp/eric-eric/filterName.py
2,845
3.703125
4
import re import csv def getNames(s): names = re.findall(r"[A-Z][a-z'-]+ [A-Z][a-zA-Z'-]+", s) return names def getSurnames(s): names = re.findall(r"M[a-z]{1,2}\. ([A-Z][a-zA-z'-]+)", s) return names def deleteDuplicates(names): """Deletes Duplicates and return a Dictionary of names to frequen...
536570be0a421ab55fdaaef1cc26875b615ed9bd
Enigmamemory/submissions
/5/regexp/leon_nathaniel/NameFind.py
963
3.5625
4
import re re.M #Mr Ms Mrs Dr Jr Sr Prof Sir Lady Lord search = "(([A-Z][a-z]*|Mr.|Mrs.|Ms.|Dr.|Lady|Lord|Professor|Prof.)\s([A-Z][a-z]*\s?)+)" #prepping the book x = open("Elizabeth.txt", "r") splitBook = x.read().split() book = " ".join(splitBook) #fixes weird book formatting #prepping the name/notName list y =...
b8def69dc1a6e43ad5eb68700ec3126a341525d6
Enigmamemory/submissions
/7/regexp/claire_dennis/dictionary.py
584
3.65625
4
import re firstname_file = open("firstnames.csv") firstname_text = firstname_file.read() firstname_file.close() firstnames = re.findall('[A-Z][A-Z]+',firstname_text,flags=0) lastname_file = open("lastnames.csv") lastname_text = lastname_file.read() lastname_file.close() lastnames = re.findall('[A-Z][A-Z]+',lastname...
cd62e2ea9e3428a960a198a66029f90ed110bc78
Enigmamemory/submissions
/6/intro-proj1/justin-mark/data.py
1,670
3.71875
4
FILENAME = 'School_Attendance_and_Enrollment_Statistics_by_District__2010-11_.csv' def read_attendance_data(): return read_data(FILENAME) def read_data(filename): data = [] for line in open(filename).readlines(): values = line.strip().split(",") data.append(values) data.pop(0) ...
1629334dd0b9a10d65f2c27c9df7fdc8c4ac2a08
Enigmamemory/submissions
/6/regexp/sadman-michael/regex.py
574
3.8125
4
import re str = "There was a boy named Billy. John Joe likes cake. The dog likes food. George brings the dog his food. Googles Ceo owns the company" strbook = open("tale.txt", "r") strbook1 = strbook.read() strbook.close() ex=open("title.txt","r") ex1=ex.readlines() ex.close() results = re.findall("([A-Z][a-z]+)\...
ecb58f852bf8f87dc22d8ca046434ab3a1439022
Enigmamemory/submissions
/7/regexp/barak-kyler/regexp.py
944
3.875
4
import re text_file = open("NameList", "r") raw_text = text_file.read() text_file.close() spaceless_text = raw_text.split(); #this is the list of names to be checked with name_list = [x for x in spaceless_text if not x[0].isdigit()] #Takes a file name and returns a dictionary of names that are found in name_list and...
976f638ace65314d24f98274f8c03ffe67ac5c34
yehnet/SQL---Python
/schedule.py
3,770
3.59375
4
import sqlite3 import os import sys def main(args): databaseexisted = os.path.isfile('schedule.db') if not databaseexisted: print("schedule.db not found") return #the database file does not exist dbcon = sqlite3.connect('schedule.db') with dbcon: cursor = dbcon.cursor() ...
81ce737af5f76412803b9c2cf2db4a33eb94e6f3
Mauro-CVO/Python_Programs
/Python_POO/complejidad_algoritmica.py
648
3.78125
4
import time import sys #Factorial, implementación iterativa def factorial(n): ans = 1 while n > 1: ans *= n n -= 1 return ans #Factorial, implementación recursiva def factorial_r(n): if n == 1: return 1 return n * factorial_r(n - 1) def recus_lim(lim = 5000): sys.s...
7826d2ad0dd84f0384d99e5a33f6d814c7eb65af
Mauro-CVO/Python_Programs
/hackerrank/Migratory_birds.py
824
3.546875
4
import math import os import random import re import sys # Complete the migratoryBirds function below. def migratoryBirds(arr): list_max = [0,] count_1 = 0 count_2 = 0 count_3 = 0 count_4 = 0 count_5 = 0 for x in arr: if x == 1: count_1 += 1 elif x == 2: ...
42ff60de78b9450293b6bb9e3c16b9949c0b9eaf
Mauro-CVO/Python_Programs
/Python_Basico/palindromo_check.py
539
4.0625
4
## Funciones def palindromo(palabra): palabra = palabra.replace(" ","") #Elimina espacios palabra = palabra.lower() #deja todas las letras en minus palindromo = palabra[::-1] #Voltea la palabra if palabra == palindromo: return True else: return False def run(): palabra = input("...