blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5e843d9ca5658d34e3ff3b6be1b19f688182d36c
muhammadmuzzammil1998/CollegeStuff
/MCA/Machine Learning/is_prime.py
306
4.03125
4
from math import sqrt import sys def is_prime(n): if n <= 1: return False for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True if is_prime(int(sys.argv[1])): print("It is a prime number") else: print("It is not a prime number")
aaebaaf467df179c44413775fffd845736bbca10
L200170047/prak_asd_b
/MODUL3/no2.py
454
3.625
4
#2A def matriks(m, n): """Menggunakan dua input""" matrix = [[0 for x in range(m)] for i in range(n)] print(matrix) def matriks2(m): """Menggunakan satu input""" n = m matrix = [[0 for x in range(m)] for i in range(n)] print(matrix) #2B def buatIdentitas(m): n = m ma...
f4f5443a4d1eda5a4665a59b2eb72d0d868c5ea4
jxie0755/Learning_Python
/SimpleLearnings/CodeSnippets/fibonacci.py
5,605
4.46875
4
"""this is to learn different ways of creating fibonacci number/list""" # if only need to get one number # recursive way (recursion) # Time O(2^N) def fib_gen_r(i): """ Fibonacci function generator generate the fibonacci number at "i"th posistion """ if i == 0: return 0 elif i == 1: ...
fe9da9f1a5a464aa6d3ea7099048b47a9c2cd731
Wolfhan99/LeetCode-Javascript-Solution
/leetcode/31.下一个排列.py
2,278
3.71875
4
# # @lc app=leetcode.cn id=31 lang=python3 # # [31] 下一个排列 # # https://leetcode-cn.com/problems/next-permutation/description/ # # algorithms # Medium (37.33%) # Likes: 1323 # Dislikes: 0 # Total Accepted: 210.8K # Total Submissions: 564.8K # Testcase Example: '[1,2,3]' # # 实现获取 下一个排列 的函数,算法需要将给定数字序...
768f07c54823c9efb64f06dbf9d68fb11b9db3c2
Ivan-Malinin-IBM7968/mars-rover
/direction.py
1,015
3.953125
4
class Direction: """ N W E S """ def __eq__(self, other): if isinstance(other, Direction): return type(self) == type(other) else: return False def __repr__(self): return type(self).__name__ class North(Direction): """ W <- N...
88774fa20f94db522746a7b3863817d3098e8bad
sud1997ar/Web-Development
/To Do List(web development)/summa.py
635
3.703125
4
# items =['a','b'] # N= len(items) # for i in range(3**N): # bag1 = [] # bag2 = [] # for j in range(N): # print('i is ',i) # print('j is',j) # print('the answer for i // (3 ** j)%3 is',i // (3 ** j)%3) # if (i // (3 ** j)) % 3 == 1: # bag1.append(items[...
27d6e539faf2d8c7c5ae80e1647520343f37f084
kaydee0502/Data-Structure-and-Algorithms-using-Python
/DSA/Tree/bst.py
6,433
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 30 16:32:27 2020 @author: KayDee """ class Node(): def __init__(self,data): self.data = data self.left = None self.right = None class Tree(): def __init__(self): self.root = None self.parent = Non...
12ce50f5bd2557dc4f8ab95253acea7a8b7aec64
Jayaprakash1998/Python-practice-problems-set-2
/Speed Dating.py
1,270
3.734375
4
''' QUESTION: Speed Dating: A nationwide speed dating event is organised on 14th of February every year. Let’s say ‘N’ men and ‘M’ women attended the speed dating event in the year 2019. Each person attending the event will be given a special token. On each successful meet, the token has to be exchanged with t...
98523a801954ba41ff85e824b26c546a3131dc99
David-Archer-us/python
/threeCharacterUrlShortener.py
5,680
3.703125
4
""" This is an improved URL shortener It takes the 140000 characters of Unicode to encode original urls to short urls It can reduce the length of the urls to only 3 characters Author: David Zhang Version: 0.1 Date: October 20, 2020 """ # use the entire unicode data import unicodedata class urlShortener: # This is...
2a0b79d12192115c7448e78d7398e81b00917855
catdog001/leetcode_python
/Tree/leetcode_tree/easy/start_undone_101.py
1,222
4.25
4
""" 给定一个二叉树,检查它是否是镜像对称的。   例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3   但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/symmetric-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tre...
82c6b0e8ac985f562a562cfeac2d8a1d037dafd4
hancx1990/hancx
/code/python/demo/com/hcx/basedemo/list_demo.py
298
3.71875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print(list1[0]) print(list2[1:5]) list = [] list.append('google') list.append('runoob') print(list) print('before del value', list1) del list1[2] print('after del value', list1)
6e6456d10a481dc7737493a78213147adea19a03
HaoSungogogo/EECS495_Machine_Learning_Foundation
/HW3/4.3.py
2,885
3.734375
4
# This file is associated with the book # "Machine Learning Refined", Cambridge University Press, 2016. # by Jeremy Watt, Reza Borhani, and Aggelos Katsaggelos. import numpy as np import matplotlib.pyplot as plt import csv from math import * from pylab import * # sigmoid for softmax/logistic regression minimization...
c2cc2b3b2d0eefa43ecd3a8a54199ebd3855f880
KevinStigma/Leetcode
/Merge Two Sorted Lists.py
889
3.890625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def printList(head): ptr=head while ptr: print ptr.val ptr=ptr.next class Solution(object): def mergeTwoLists(self, l1, l2): if l1==None and l2==None: return None if l...
2a07a71dce73cc451df190b1b532204e6fb0e2c7
marmikreal/HOPP
/hybrid/layout/layout_tools.py
2,791
3.5625
4
from math import fabs from typing import ( Callable, Tuple, ) import numpy as np from shapely.geometry import Polygon def binary_search_float(objective: Callable[[float], any], minimum: float, maximum: float, max_iters: int = 32, ...
00807285b333242797248d6618b8be0a74bb46b0
Pietro-Tomelin/Calculadora
/src/teste.py
393
3.84375
4
def main(): hexadecimal = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] numero = int(input("Digite um número inteiro: ")) resultado = [] while numero > 0: resultado.append(hexadecimal[(numero % 16)]) numero = numero // 16 for r in range(len(resultado) - 1, -1, -1): ...
fbdc6e25092ae989d5ced040034e35ccb5362282
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2/gadet/solve.py
1,293
3.84375
4
import sys def pancake_flip(stack, i): '''Flips the stack at the given index, 0 is top, n-1 is bottom''' top = list(stack[:i+1]) top.reverse() # reverses the order of the flipped pancakes top = map(lambda p: '-' if p == '+' else '+', top) # flips the pancakes to the other side bottom = [stack[i+1:]...
01c2544d5d0223d0fbaf356baeb9004fc0d3e5d0
MurluKrishna4352/Python-Learning
/merging and sorting of list according to length of word - Copy.py
671
4.34375
4
# merging of list according to length of list = [] list_1 = [] user_input = int(input("how_many_elements_do_you_want_in_list_1: ")) user_input_2 = int(input("how_many_elements_do_you_want_in_list_2: ")) for i in range(1 , user_input + 1 ): no_elements = input("enter_element_" + str(i) + ": ") list...
d8069aba1675414b4892b57ab61826dec83acf74
amymareerobinson/cp1404practicals
/prac_01/broken_score.py
579
3.921875
4
""" CP1404 2020 - Practical 1 Student Name: Amy Robinson Program - Broken Score """ # Fix this! # score = float(input("Enter score: ")) # if score < 0: # print("Invalid score") # else: # if score > 100: # print("Invalid score") # if score > 50: # print("Passable") # if score > 90: # ...
2edd5652227c122d60f15272a2039c5cadcc7ead
junmadlab/Learn_to_compose_IDETC_2020
/GNN/visualization_tensor.py
29,334
3.65625
4
""" Visualize data and results of GNN (tensor version) Author: Jun Wang (jwang38@umd.edu) """ import math import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt def visualize(num, X_first, Y_first, X_next, Y_next, edge_feature, model, save_dir): ''' Visualize the results by compa...
f9e2114b66a955751bc8b441faeef184a28439ba
begor/CS212
/week4/bridge.py
8,092
3.625
4
def bsuccessors2(state): """Return a dict of {state:action} pairs. A state is a (here, there) tuple, where here and there are frozensets of people (indicated by their travel times) and/or the light.""" # your code here here, there = state l = 'light' if l in here: return {(here - fro...
66798d84297eed8f3ca71bff6ff80832a57ba651
optionalg/cracking-1
/02.Linked_Lists/01/with_dictionary.py
505
3.578125
4
from base import Node, print_nodes def remove_duplicates(root): n = root prev = None d = {} while n is not None: if n.data in d: prev.next = n.next else: d[n.data] = 1 prev = n n = n.next root = Node(4) root.append_to_tail(5) root.append_to_t...
3041c049f29c65d4ead3003d7104a426262b2828
maxleverage/math
/square_root_convergents.py
624
3.875
4
#!/usr/bin/env python import math as m import numpy as np import time start_time = time.time() numerator = 1; denominator = 2; counter = 0 for i in range(1, 1001): numerator += 2*denominator; new_numerator = denominator new_denominator = numerator; denominator = new_denominator; numerator = new_numerator if len(st...
d438c550c9232d51b6d3151a4f5873df4a5d58d9
Danielopes7/Grafos-ED2
/main.py
2,290
3.75
4
import utilitarios as ut arquivo=input("Qual o nome do arquivo ?") Grafo, classificacao = ut.OpenFile( arquivo) # pego o arquivo txt e passo para a variavel grafo e a classificacao do grafo para variavel classificacao string = Grafo.split() string2 = Grafo.split("\n") ListVertices = ut.vertices(string,...
521a00f0652d620bfcf2d6649835ca2121b84f56
st-pauls-school/bio
/2010/python/q1.py
555
3.5
4
def anagramNumbers(a): liA = list(str(a)) liA.sort() res = [] for i in range(2,10): b = i*a liB = list(str(b)) if len(liA) == len(liB): liB.sort() if liA == liB: res.append(str(i)) if len(res) == 0: return "NO" return ' '.join(res) print(anagramNumbers(123456789)) print(anagramNumbers(100)) ...
1ad6419d20859deaf657c97101bd43ff79ed0de1
jasujaayush/Random
/leetcode/split-linked-list-in-parts.py
839
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def splitListToParts(self, root, k): """ :type root: ListNode :type k: int :rtype: List[ListNode] """ ...
5339bb568c7ad6b53d58c1da35faa17130806e92
ChangRui-Yao/pygame
/每日任务/2019年11月13日/更强大的else.py
506
3.734375
4
#else 不止和if进行判断 还可以和while for配合使用 循环结束才能使用 #要么怎样 要么怎样 #干完了怎么样 干不完怎么样 #没有问题 那就干吧 def sushu(num): count = num // 2 while count > 1: if num % count == 0: print("%d的最大约数是%d" % (num,count)) break count -= 1 else: print("...
5d5d53ef132146f3d82b2e64dd6c8da7d8c1f876
JamesRoth/Unit3
/warmup6.py
167
3.625
4
#James Roth #2/16/18 #warmup6.py - for and while loop practice for i in range(1,11): print(i, "mississippi") i=1 while i<11: print(i, "mississippi") i+=1
e35253f57b9042d117d8e8cc972fb0c814d6407a
EnavHidekel/PythonTools
/CodeWarsProjects/isTriangle.py
204
3.578125
4
def is_triangle(a, b, c): msg = False if a + b > c: if a + c > b: if b + c > a: msg = True return msg if __name__ == "__is_triangle__": is_triangle()
1d164ca3cdea1e85b5b7f03d0fd5419db98d8e37
m4mayank/ComplexAlgos
/hotel_bookings_possible.py
1,495
4.0625
4
#!/usr/local/bin/python3.7 #A hotel manager has to process N advance bookings of rooms for the next season. His hotel has K rooms. Bookings contain an arrival date and a departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand. Write a program that solves this problem in t...
0c89cf3c77c52c7eabc076ff6d995a34543e83c4
llemoss/Files
/Python/URI/uri1074.py
358
3.515625
4
print "URI 1074" N = input() i = 0 f = range(N) while i < N: if i != N: f[i] = input() i = i + 1 i = 0 while i < N: if f[i] == 0: print "NULL" else: if f[i]%2 == 0: if f[i] > 0: print "EVEN POSITIVE" else: print "EVEN NEGATIVE" elif f[i]%2 == 1: if f[i] > 0: print "ODD POSITIVE" else...
c4e6fb7487f29eef2294aedda2660a34747f9712
rlanga/tenzo-coding-challenge
/unused.py
1,099
4.125
4
def get_total_time_period(start, end): """ Calculates the period elapsed between two time points :param start: The start of the time period in 24hr format. (e.g. '17.10') :type start: str :param end: The end of the time period in 24hr format. (e.g. '18.20') :type end: str :re...
a8e8cc4b0fa4a7834be1941c80414ecc544b7b9a
annikaslund/python_practice
/python-fundamentals/29-vowel_count/test.py
679
3.78125
4
import unittest # Click to add an import from vowel_count import vowel_count class UnitTests(unittest.TestCase): def test_input_1(self): # Failure message: # expected vowel_count('awesome') to equal {'a': 1, 'e': 2, 'o': 1} self.assertEqual(vowel_count('awesome'), {'a': 1, 'e': 2, 'o': 1...
dd280c1790cbdf804c73e5299a40d6e080352d83
melissayee/AIDI2004
/LAB #1/prime_finder.py
403
3.921875
4
""" Function Description: A function that determines whether a number is prime or not Inputs: n (int) Outputs: result (bool) Examples: prime(2) -> False prime(1) -> False prime(23) -> True """ def prime(n): result = True if n < 3: result = False else: for i in range(2, n): if ...
a6e3592b912612dedc84105e86ee8f349db487ce
cortelucas/curso-python
/Aula/aula-04.py
182
3.796875
4
nome = input('Qual é o Seu nome? ') idade = input('Quantos anos você tem ?') peso = input('Qual o seu peso? ') print(f'O seu nome é {nome}, tem {idade} anos e pesa {peso} kls! ')
1a1ab7ccca824250313fdb147f25accfff08b249
moyueating/learn_python_demo
/alien_invasion/settings.py
1,053
3.59375
4
class Settings(): """外星人所有的设置的类""" def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) # 飞船的设置 self.ship_limit = 3 # 子弹设置 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullet_allowed = 10 # 外星人设置 self.fleet...
ef532a180ca2db717033205d4556f6f6f7bbc8a7
Abdus-Salam/Python
/object_oriented_python.py
682
4.21875
4
""" Class =============================================== Numbers, String, Boolean : is class, but shopping card is not class or any type. So we need to create one type using class. List, Dictionaries : is also class Self : is refernce of current object """ class Point: def __init__(self, x: int, y: int): ...
666b6736a6a5d52d04c300edfc7d8ce022d1fb26
MMuttalib1326/Creating-Tree
/Creating Tree.py
726
3.78125
4
# Creating Tree class TreeNode: def __init__ (self,data,children=[]): self.data=data self.children=children def __str__(self,level=0): ret = " " * level+str(self.data) + "\n" for child in self.children: ret += child.__str__(level + 1) return ret ...
5c18d1b03945926dc119dfdd4e1c9370ddd8f091
denglert/computer-science-sandbox
/algorithms/dynamic_programming/examples/coin_change/minimum_number_of_coins/test.py
830
3.8125
4
#!/usr/bin/env python from algorithms import * amount = 12 coins = [1,3,5] print("Amount: {}".format(amount)) print("Coins: {}".format(coins)) ### --- Dynamic programming --- ### result = dp_algo(coins, amount) print("DP algo:") print_result(result) ### --- Recursive --- ### #result = recursive_algo_wrapper...
caa138063f27e958b28be2e4c0d4312ee1ca8606
LukasPol/URI_Online_Judge
/python/1165 - Número Primo.py
268
3.515625
4
N = int(input()) for i in range(N): A=True X = int(input()) for j in range(2,X): if X%j == 0: A = False break if A == False: print('{} nao eh primo'.format(X)) else: print('{} eh primo'.format(X))
4cf868dff83ff98681ac2b73fbd04d6a8431e7ad
Puzanovim/Lessons
/lesson_#2.py
402
4.40625
4
seconds_per_hours = 60 * 60 seconds_per_day = seconds_per_hours * 24 result = seconds_per_day / seconds_per_hours result_two = seconds_per_day // seconds_per_hours print(f'{seconds_per_hours} seconds per hour') print(f'{seconds_per_day} seconds per day') print(f'{result} if we divide seconds per day to seconds per hour...
97773d75aae85033dabbe104ca68be5520489674
aptleee/leetcode-python3
/59_spiral2.py
750
3.6875
4
class Solution: def generateMatrix(self, n: 'int') -> 'List[List[int]]': top, down, left, right = 0, n-1, 0, n-1 x, y, dx, dy = 0, -1, 0, 1 matrix = [[0 for _ in range(n)] for _ in range(n)] for i in range(n*n): x += dx y += dy matrix[x][y] = i+1 ...
57cb8d9b103062f45e243e5973f998812f5a1c85
willgoishi/CSCI_150_AG_Project
/src/employees.py
1,439
4.375
4
#employee python file #Employee - #1:Input employee information and is able to store this information into database #2:Employee information can be extracted #3:Employee's payroll and position standings are calculated and stored #4:Employees can be sorted based on precedence or ordered based on inform...
ec132b6e3f7f2ecee8e56bea21dd16e0ccbf44b9
rossdavidhunter/pands-problem-set
/solution3alt.py
255
4.03125
4
# Ross Hunter, 2019 Solution 3 alternative divisors # Import using numpy import numpy as np # create varaibale and use of range value=np.array(range(1000,10000)) # then say if value is divided by 6 == even number Newvalue=value[value%6==0] print(Newvalue)
cf0017e091fb6c068af73fe3713f52f9bc10c8cf
pkulkar/Algorithms
/Fast and Slow pointers/Linked List Cycle II.py
2,189
3.671875
4
""" Leetcode 142. Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of ...
2472100abefdcdb550f8da2382052af8ad90c2c9
github-mohsinalam/Python
/Sorting/sorted_letters.py
369
4.4375
4
#Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters. letters = "alwnfiwaksuezlaeiajsdl" sorted_letters = sorted(letters, reverse = True) #sorted function expects a sequence ,but we have passed a string ,so it will convert it into a list whose elements are character...
86a538a2cbddfc0082d73e632414d7dfd2bf9f02
VincentLa/draftkings
/src/get_draftkings_salaries.py
6,405
3.515625
4
""" Script to grab DraftKings Salaries To run, cd into the root level directory of this repo. For example, run: python -m src.get_draftkings_salaries --start_game_year=2019 --start_game_month=10 --start_game_day=22 --end_game_year=2020 --end_game_month=8 --end_game_day=7 To run a single day, set the start and end da...
877041825740160d794f1f54fa2519bee6a18bc9
urmuelle/DatastructuresWithPython
/HalloWelt.py
503
3.625
4
#!/usr/bin/python class myClass: def __init__(self, classi, name): self.name = name self.classi = classi def classFunction(self, variable): test = variable + 500 print(test) def myFunction(variable): test = variable + 5 print(test) n = input('Zahl...
18fde06614d143d92da2fd723a63e972be65431c
ploverpang/-RoutineTestCode
/pythonTest/pycharmTest/helloworld.py
226
3.546875
4
#!/usr/bin/env python print('hello world') def debugTest(): ll = [x+1 for x in range(10)] for idx, l in enumerate(ll): print("idx is %d, l is %s" %(idx, str(l))) if __name__ == '__main__': debugTest()
adc35f2370b58245ce8270fc9fba37338e184e38
anthoxo/python-skeleton
/q1.py
2,429
3.609375
4
# # ONLY EDIT FUNCTIONS MARKED CLEARLY FOR EDITING class BinaryTree: left = None right = None def __init__(self): _ = 0 def addNode(self, number): if (len(number) != 0): if (number[0] == 0): if (self.left == None): self.left = BinaryTree() self.left = self.left.add...
ef9137d385f2a5e6f72569a6ee4060d15ddbab55
royeectu/python-exercise
/dictionaries/07_square_of_keys.py
202
4.0625
4
''' Write a script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys ''' my_dict = { num: num **2 for num in range(16)} print(my_dict)
a4185fe61222a0421a8885eb3bc3c407027e8a8b
whizzkid-ox/neuron-image
/model.py
1,052
3.546875
4
from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop from keras.models import Sequential from keras.layers.core import Dense, Activation # Author: Ryo Segawa (whizznihil.kid@gmail.com) def ann(x_train,y_train,x_test,y_test,batch_size,epochs): # create mo...
57eddcbe2ace9384956695f634f5e2730cf67b95
RadchenkoVlada/tasks_book
/Linked_List/main.py
2,192
4
4
from Node import Node from Linked_List import LinkedList if __name__ == '__main__': """ help() The Python help function can be super helpful for easily pulling up documentation for classes and methods. We can call the help function on one of our classes, which will return some basic info about the me...
a8defc84abacfa0887d4cb05766cdcf67ed047e2
szepnapot/repo
/coursera_assignments_python/assignment_4_6.py
199
3.65625
4
def computepay(h,r): if h>40: return (h-40)*(1.5*r)+40*r else: return h*r h = float(raw_input("Enter Hours:")) r =float(raw_input("Enter Hours:")) p = computepay(h,r) print p
b5d19f98b7633a1b9297377ebd790edac18813d5
edwindethomas/PrograCompPython
/URI/URI1051.py
439
3.859375
4
salario = float(input()) if salario>0 and salario<=2000: print("Isento") elif(salario>2000 and salario<=3000): resto = salario-2000 result = resto*0.08 print(f"R$ {result:.2f}") elif(salario>3000 and salario<4500): resto = salario - 3000 result = (resto * 0.18) + (1000*0.08) print(f"R$ {result:....
8a59961961f0c9b885fc5b9f84c76d3d1f28ac59
RavinderSinghPB/data-structure-and-algorithm
/stack/insert.py
340
3.796875
4
def InsertInStack(n,arr): stack=[] for e in arr: stack.append(e) return stack if __name__=='__main__': tcs=int(input()) for _ in range(tcs): n=int(input()) arr=[int(x) for x in input().split()] stack=InsertInStack(n,arr) while stack: print(s...
282ca6b714015380e9bcd87572598d8314ace5b5
ufffshyam/python
/listit.py
195
3.953125
4
# array = [1,2,3,4,5,6,7,8,9,10] # print(array[2::2]) first is # print(array[5::-1]) #split msg = str(input('Enter the multiple name')) li = [] li += msg.split(); li.append('shyam') print(li)
75fd53c3b29e3ad7613cef62e21e27d84db1f79d
okebinda/algorithms.python
/graphs/directed/DirectedGraph.py
13,313
3.828125
4
"""Directed Graph: DirectedGraph A directed graph (digraph) is a graph (G) that contains a set of vertices (V) and a set of edges (E), where the first vertex in an edge tuple has a directed connection to the second vertex but not the other way around. For example, given the following digraph: 0 → 1 ↕ ↙ ↶ ...
3832018610262ac63c95935b8118f21dd81928ab
gaoisbest/Basic-Algorithms
/Sorting_algorithms/Counting_sort.py
502
3.734375
4
""" Time complexity: O(n + k) stable sorting algorithm The lower bound of comparison sorting algorithm is O(nlgn). """ def counting_sort(A, k): C = [0] * k B = [0] * len(A) for j in range(len(A)): C[A[j]] += 1 for i in range(1, k): C[i] += C[i-1] for j in range(len(A)-1, -1, -1...
590298cffc1d4de635ee963fc943ab7a26a4fb72
yiming1012/MyLeetCode
/LeetCode/贪心算法/堆/5556. 可以到达的最远建筑.py
2,150
4.03125
4
""" 给你一个整数数组 heights ,表示建筑物的高度。另有一些砖块 bricks 和梯子 ladders 。 你从建筑物 0 开始旅程,不断向后面的建筑物移动,期间可能会用到砖块或梯子。 当从建筑物 i 移动到建筑物 i+1(下标 从 0 开始 )时: 如果当前建筑物的高度 大于或等于 下一建筑物的高度,则不需要梯子或砖块 如果当前建筑的高度 小于 下一个建筑的高度,您可以使用 一架梯子 或 (h[i+1] - h[i]) 个砖块 如果以最佳方式使用给定的梯子和砖块,返回你可以到达的最远建筑物的下标(下标 从 0 开始 )。   示例 1: 输入:heights = [4,2,7,6,9,14,12], bric...
7ee4141dfc0c783700d085b33c4d8a1d25f6ffcc
againfo/The-Python-Workbook-Solutions
/Section 2/54.py
633
4.21875
4
wavelength = int(input("Enter a value for a wavelength of visible light in nanometers: ")) colour = "" if wavelength >= 350 and wavelength < 450: colour = "violet" elif wavelength >= 450 and wavelength < 495: colour = "blue" elif wavelength >= 495 and wavelength < 570: colour = "green" elif wavelength >= 570 and w...
68db6527f2b0d371f2d4c7de74a95ed716a12d2e
vinaykumar7686/Leetcode-Monthly_Challenges
/December/Week1/Spiral Matrix II.py
1,453
4
4
# Spiral Matrix II ''' Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 20 ''' class Solution: def generateMatrix(self, n: int) -...
540a9cda58c6790334ab0792337f05c1c9228242
mathvolcano/leetcode
/reorganizeString.py
1,204
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 22 15:15:26 2020 @author: mathvolcano https://leetcode.com/problems/reorganize-string/ 767. Reorganize String """ def reorganizeString(S): from collections import Counter from heapq import heapify, heappop counts = Counter(S) he...
4472875826fdb377772c1eaea3c4064c742bd835
mjweiper/python-challenge
/Pybank/main.py
2,596
4.1875
4
'Importing os module - Allows us to create file paths across operating systems' import os 'Importing csv module - Allows us to read csv files' import csv 'Determine csv path - use example python,3,1, Start in resources folder' budget_csv = os.path.join( "Resources", "budget_data.csv") 'open and read csv' with open(b...
34af14d9c62565a0e88fca722d06684457dabe3b
youxi0011983/python3
/python/excel/numpy/charindex.py
483
3.65625
4
#!/usr/bin/python3 import pandas as pd import numpy as np # Series是一种以为的数组型对象 a = pd.Series([9,8,7,6]) print (a) b = pd.Series([9,8,7,6], index=['a','b','c','d']) print (b,"\n",b.index,"\n",b.values) print("\n",b[1]) print("\n",b['b']) print("\n",b[['b','c','d',0]]) c = pd.Series(25, index=['a','b','c','d']) print(...
6a1b67babb6e96c15d8c5e33e204471670d1b5f2
MatthewGoff/CSC245
/Gorillas/ball.py
2,872
3.609375
4
# A simple 2D ball class # Author: Matthew Anderson, Kristina Striegnitz, John Rieffel # Winter 2017 import pygame, random, math from vector import Vector from bumper import Bumper def get_rand_color(): return pygame.color.Color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 255) def g...
17490dd63096a009864e3509dd2801b63bf5937f
1436006750/My_Study
/Python_Study/0.0_Python_All/3.0_Python_会使用到的库/argprase包/7.0_候选参数_choices.py
895
3.765625
4
# coding:utf-8 """ 表示该参数能接受的值只能来自某几个值候选值中,除此以外会报错,用choices参数即可。比如: parser.add_argument('filename', choices=['test1.txt', 'text2.txt']) """ import argparse parser = argparse.ArgumentParser(description="候选参数!!") parser.add_argument('filename', choices=['text1.txt', 'text2.txt']) args = parser.parse_args() print("...
71715f0decd678cba1618739c924c8f1f1848104
miniyk2012/leetcode
/interestings/sqlalchemy_study/engine_api.py
1,101
3.875
4
from sqlalchemy import create_engine, text def main(): engine = create_engine('sqlite:///:memory:', echo=True) connection = engine.connect() # 这里是从连接池取一个连接 connection.execute( """ CREATE TABLE users ( username VARCHAR PRIMARY KEY, password VARCHAR NOT NULL ...
a6ddac1b8025516cc9caa9e316a89ffb9c23c227
EmmanuelAlmonte/pythonfromscratch
/main_project/Chapter 3/Excercises.py
620
4.09375
4
# In the Spotlight Using if statement. """ Get the first test score Get the second test score Get the third test score Calculate the average Display the average If the average is greater than 95: Congratulate the user """ """ first_score = int(input("Enter your first test score: ")) second_score = int(input("Enter y...
37a2e040b64a214ceb6f0bcbae47610abfae73e2
UCDCoderDojo/Pygame-Tic-Tac-Toe
/solution/game.py
5,996
3.9375
4
import pygame from sys import exit BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) # set up pygame pygame.init() # build the window. 0 for height and width gives window same size as the current resolution surface = pygame.display.set_mode((400, 400)) TILE_WIDTH = 100 offset = (400 - (TILE_WIDTH * 3)) / 2...
8eeceed06a6a31652767e2ce78c3a6d003479b93
hagios2/Py-Tutorials
/ex7.py
1,693
4.375
4
def break_words(stuff): """This function will break up words for us""" #get the argv and split it into a list when ' ' is encountered words = stuff.split(' ') #return the words return words def sort_words(words): """Sorts the words""" #built in function for sorting a list return so...
9232dfe3e556c3274639be0fc4b3c527b50c9fe7
gitferry/data-structure-alg
/queue/circleQueueArray.py
1,288
3.671875
4
class CircleQueueArray: def __init__(self, capacity): assert(capacity > 1) self._data = [] self._count = 0 self._head = 0 self._tail = 0 self._n = capacity def enQueue(self, item): if (self._tail + 1) % self._n == self._head: pr...
0c9f07b4cd58d2aaaaf0701ec2cbafc606d384c3
brucekevinadams/Python
/RedRedBlack.py
795
3.796875
4
# Python 3 code # Bruce Adams # austingamestudios.com # ezaroth@gmail.com # Python program to find probability # There are urns labeled X, Y, and Z. # # Urn X contains 4 red balls and 3 black balls. # Urn Y contains 5 red balls and 4 black balls. # Urn Z contains 5 red balls and 4 black balls. # # One ball is...
3df5d119ad15507b3168ccd5d9ca4dbce2820ba2
AmbystomaMexicanum/pcc2e-exerc
/src/ch_04/e_4_10.py
280
3.9375
4
numlist = [val**2 for val in range(0, 10)] print(f'Popped element:\n{numlist.pop()}\n') print(f'List now:\n{numlist}\n') print(f'First three elements:\n{numlist[:3]}\n') print(f'Last three elements:\n{numlist[-3:]}\n') print(f'Elements in the middle:\n{numlist[3:-3]}\n')
ceb31e7fcffd1d0af73340a07d63904e83bfb449
finchnest/Python-prac-files
/_quiz3/messages encoded into strings.py
831
3.515625
4
def hidden(array): dic={"a" : 1 ,"b" : 2 ,"c" : 3 ,"d" : 4 ,"e": 5 ,"f": 6 ,"g" : 7 ,"h" : 8 ,"i" : 9 ,"j" : 10 ,"k" : 11 ,"l" : 12 ,"m" : 13 ,"n" : 14 ,"o" : 15 ,"p" : 16 ,"q" : 17 ,"r" : 18 ,"s" : 19 ,"t" : 20 ,"u" : 21 ,"v" : 22 ,"w" : 23 ,"x" : 24 ,"y" : 25 ,"z" : 26} for x in array:##for such expre...
617e552cf3598724a5c9754014588c94faf42f63
onkarj-98/Data_structures_and_Algorithms
/Array/array_rotation.py
373
3.984375
4
def leftRotate(arr,n,d): for _ in range(d): leftRotateByOne(arr,n) def leftRotateByOne(arr,n): temp = arr[0] for i in range(n-1): arr[i] = arr[i+1] arr[n-1] = temp def printArray(arr,n): for i in range(n): print("%d"% arr[i],end = " ") #driver program arr = [1,2,3,4,5,6,7...
e3697042b96d079f6f2a8008c5b1c7109b7319e4
ConnerLambdaAccount/AOC-2019
/day1/p2.py
323
3.71875
4
import math def main(): input = open('input.txt') line = input.readline() total = 0 while(line): mass = int(line) fuel = math.floor(mass / 3) - 2 while(fuel > 0): total += fuel fuel = math.floor(fuel / 3) - 2 line = input.readline() print("Total = " + str(int(total))) if __name__ == "__main__": main...
16c894a73708f2e85e342e4a68a5a817311b6926
jnj16180340/franklin
/transcripts/wellref_converter.py
7,122
3.609375
4
#!/usr/bin/python3 import itertools import string import math import argparse def num2let(arg): '''Converts integer [0...25] to character [A...Z]. Fails more noticeably than chr()!''' return dict(zip(range(26), string.ascii_uppercase))[arg] def let2num(arg): '''Converts character [A...Z] to integer [0...2...
eb303ba8583af85a74a3d5a12a332c11eb3ccd74
Rabona17/Implementation_of_ML_DL_Algorithm
/YOLO/iou.py
1,092
3.84375
4
def iou(box1, box2): """Implement the intersection over union (IoU) between box1 and box2 Arguments: box1 -- first box, list object with coordinates (x1, y1, x2, y2) box2 -- second box, list object with coordinates (x1, y1, x2, y2) """ # Calculate the (y1, x1, y2, x2) coordinates of the in...
7b902dc18281c510e2926275fcb847cdfb2ada3a
Udit-Waghulde/Basic-python
/car info (oop).py
1,149
4.15625
4
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): proper_name = str(self.year) + " " + self.make.title() + " " + self.model.title() return...
c5c1d7c041ce70d8d9ca2b5bc23fc01722e1d28d
brij2020/Ds-pythonic
/Queue/PriorityQueue.py
2,095
4.0625
4
""" PRIORITY QUEUE """ class Node(object): next = None data = None priority = None pass class PeriorityQueue(object): head = None def insert(self, data, priority): node = Node() node.data = data node.priority = priority node.next = self.head self.he...
1e6a8fd47d22dbb7ea488468685aa249cfc8c85d
ryfeus/lambda-packs
/Pdf_docx_pptx_xlsx_epub_png/source/pptx/compat/python2.py
1,234
3.9375
4
# encoding: utf-8 """ Provides Python 2 compatibility objects """ from StringIO import StringIO as BytesIO # noqa def is_integer(obj): """ Return True if *obj* is an integer (int, long), False otherwise. """ return isinstance(obj, (int, long)) def is_string(obj): """ Return True if *obj* ...
50d6496496531c365527290d9d12bcf4fb1f1c5f
DanilkaZanin/vsu_programming
/Time/Time.py
559
4.125
4
#Реализация класса Time (из 1 лекции этого года) class Time: def __init__(self, hours, minutes, seconds): self.hours = hours self.minutes = minutes self.seconds = seconds def time_input(self): self.hours = int(input('Hours: ')) self.minutes = int(input('Minutes...
1007e7a7a3445004549971e878e10a2ae57b5db0
LanJinUC/MyCodingChallenge
/AlgoExpert/Easy/PythonVer/binarySearch.py
356
3.875
4
# time O(log(N)) # space O(1) in place # the array needs to be sorted first def binarySearch(array, target): start = 0 end = len(array) -1 # // means floor dibision mid = 0 while start <= end: mid = (start + end)//2 if target == array[mid]: return mid elif target < array[mid]: end = mid - 1 els...
d48cd7f26444aab0556b4cff4acb0ed7725b2b29
Ivan-Dimitrov-bg/Python_100_Days_UdemyCourse
/12.Scope/12.guess_the_number.py
1,957
4.25
4
"""1. Ask for difficulty Easy - 10 attempts or Hard - 5 attempts 2. Computer random number bw 1 and 100 While 3. user_inpu = Ask the user to guess the number 4 print the ruels Make a guess: {user_input} Too hight/ Too low Guess again. You have {attempts} remaining to guess the number Make a guess: {us...
f5b8dd29f404729c976216ce1c2e697e4c97ab80
Garacc/LeetCode
/43. Multiply Strings.py
397
3.578125
4
class Solution: def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ n1, n2 = 0, 0 for i in range(len(num1)): n1 = n1 * 10 + int(num1[i]) for i in range(len(num2)): n2 = ...
c5eab5e9615994bc306bcd171dc76432818853f4
baralganesh/OOP-and-Functions
/Caluclate_Cylinder.py
661
4.125
4
class Cylinder: # height and radius set to 1 as default value def __init__(self, height=1, radius=1): self.height = height self.radius = radius def volume(self): return self.height *3.14 *(self.radius)**2 def surface_area(self): top = 3.14 * (self.radius**2) ret...
7746d3e395efd038f7ab22de23d57d2ffdd0c426
Zitelli-Devkek/Drones-con-Python
/Ejercicios practicos Drones/ej-de-codigo-python drones-listas.py
405
4.1875
4
usuarios = ["marta" , "jose" , "pepe" , "juana" , "luisa" , "marcos"] print (usuarios[2]) usuarios.append("Rosa") #agrega elementos nuevos en el final de la lista usuarios.insert(2,"pedro") #mete un elemento nuevo en la posición designada usuarios.remove("Rosa") #borra un elemento preciso usuarios.pop (1) #par...
179f6fe98d52973016b00e5c3aa8b26ee78dca1f
CodeInDna/CodePython
/Basics/06_rock_paper_scissors_v1.py
3,539
4.21875
4
######### FINAL VERSION ########### from random import randint # OR import random player_wins = 0 computer_wins = 0 while player_wins < 2 and computer_wins < 2: print(f"Player Score {player_wins} Computer Score {computer_wins}") #-----------------------Rock Paper Scissor Game-------------------------# print('*****...
a15f156dd1edd1adc47f43c927aff142ddff3da1
auribe83/curso_python
/bucle_while_II.py
666
4.03125
4
#como hacer que un bucle sea infinito #Raiz cuadrada de un numero import math print("Programa de calculo de raiz cuadrada") numero= int(input("Introduce un numero por favor: ")) intentos=0 while numero<0: # aqui la condicion es true print("No se puede hallar la raiz de un numero negativo") if intentos==2: pri...
88a1f5c2255f461125caad53983c976b9c855157
handleart/python_code
/hackerrank/checkMagazine.py
1,901
3.578125
4
#!/bin/python import math import os import random import re import sys from collections import Counter # Complete the checkMagazine function below. def checkMagazine(magazine, note): #result = (Counter(note) - Counter(magazine)) mDict = {} nDict = {} for i in magazine: if i not in mDict: mDict[i] = 0 ...
724c62f9f024d14c1475ae3a4f7bbc26d8066d58
Nicoconte/Katas-from-Codewars
/Python/MovingZerosToTheEnd.py
539
4.03125
4
""" Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. """ def moveZeros(arr): new_arr = [] zeros = [] for e in arr: if e != 0 or type(e) == bool: new_arr.append(e) else: ze...
f3b741d62d4f0605c1fea367068b9f636017f557
juarezmunguia/Prueba
/listas.py
523
4.03125
4
#Listas separadas por coma y entre corchetes l = [2,"tres",True,["uno",10],3,"diez"] l[2] = 'a' #Cambiar valores de la lista l2 = l[3][1] #Acceder a un elemento de una lista dentro de otra lista l3 = l[0:3] #Primer elemento -> desde dónde #Segundo elemeto -> cuántos l4 = l[0:6:2] #Primeros dos -> rango #Último...
23ccb5c1839cffa246a0a4f768b2bac55e3b543e
Aakashjagwani/linear-regression-gd
/simple.py
416
3.515625
4
import pandas as pd from sklearn import linear_model import matplotlib.pyplot as plt #read Data dataframe = pd.read_fwf("D:\ML\Siraj Raval\linear_regression_demo\\brain_body.txt") x_values = dataframe[['Brain']] y_values = dataframe[['Body']] #train model b = linear_model.LinearRegression() b.fit(x_values,y_values)...
fd90489b4670c15223803a8d3554259414196f96
emptymalei/haferml
/haferml/preprocess/ingredients.py
6,035
3.671875
4
import inspect import time from functools import wraps from loguru import logger def attributes(**attrs): """ A decorator to set attributes of member functions in a class. ```python class AGoodClass: def __init__(self): self.size = 0 @attributes(order=1) def firs...
6a11112c907cec2c8ddcf7c84156874cc3e38731
alexwongapps/project-fa20-isolde-aidan-alex
/input_generator.py
1,930
3.75
4
from random import * from utils import * def create_input_file(n, max_stress): ret = "" ret += str(n) + "\n" ret += str(round(max_stress, 3)) + "\n" for i in range(0, n): for j in range(0, n): if i < j: rand_happiness = round(random() * 99.999, 3) rand...
0a58d7b239d3dcc7e6b0d8d0a6537bb6c484cc63
AadityaDeshpande/PythonAssignments
/Intermediate/IntermediatePython/Day1/RECharClass.py
415
3.890625
4
''' Search any 1 char class from a character class group mentioned use a special meta character [] r"a|b|c|d" -----> [abcd] [psl|wipro] ----> all OR ==>> p s l | w i p r o //any one character ''' import re str1 = "Welcome to PSL. IBM in Pune. Wipro and Infosys" pat1 = r"PSL|IBM|Infosys|Wipro" #...
7497f64cff56735bef60b2ac19e1cefb54c87ff1
iamieht/MITx-6.00.1x
/Final Exam/myDict.py
520
3.703125
4
class myDict(object): """ Implements a dictionary without using a dictionary """ def __init__(self): """ initialization of your representation """ self._extra = {} def assign(self, k, v): """ k (the key) and v (the value), immutable objects """ self.__dict__[k] = v ...
f003eb7052aef5ec8418043912349cc31f4cbc1e
richardju97/card-games
/data/results/test.py
2,608
3.546875
4
# test.py # parse result files to ensure game results are correct and bots are correct import os import csv def testGameBasic(playerScore, dealerScore, playerBusted, dealerBusted, gameResult, line_count): """test the basics of blackjack game win/lose. playerScore/dealerScore/line_count are integers, while the res...
790b54f98e988ea3377d24f8203b447a6e3e5fa2
veerat-beri/dsalgo
/mathematical/bit_manipulations/utils/highest_power_of_2.py
493
4.1875
4
# Problem Statement # https://www.geeksforgeeks.org/highest-power-2-less-equal-given-number/ import sys def get_max_power_of_2(num: int): # Method 1 # dup_num = num # count = 0 # while dup_num: # dup_num = dup_num // 2 # count += 1 # return count # Method 2 ##############...
ffc10f62008a5a3711853324cffcb75c820a37f4
von/sandbox
/python/graveyard/pycrypto-rsa-verify.py
501
3.546875
4
#!/usr/bin/env python """Use pyCrypto to generate a RSA key, sign something and then verify signature""" from Crypto.Hash import MD5 from Crypto.PublicKey import RSA from Crypto.Util.randpool import RandomPool rpool = RandomPool() print "Generating RSA key pair" RSAkey = RSA.generate(1024, rpool.get_bytes) print "Cr...