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
13548ce06d0c0de0af661842c4994464c26c53be
izabeleb/Minesolver
/minefield.py
7,976
3.546875
4
"""Defines the Minefield class gor generating game board.""" from __future__ import annotations import json from random import randint import struct from typing import Generator from typing import Tuple from cell import Cell class BadField(Exception): """Raised when a field is corrupted or malformed.""" class O...
c308b093537d2799c2c9df126bacfcca2123af88
LCKYN/leetcode
/1603.Design Parking System/Solution.py
388
3.609375
4
class ParkingSystem: def __init__(self, l: int, m: int, s: int): self.p = [l, m, s] def addCar(self, t: int) -> bool: if(self.p[t-1]): self.p[t-1] -= 1 return True return False # Your ParkingSystem object will be instantiated and called as such: # obj...
2498823fbadd31325a85bb4e98596c53eff273d7
PamalM/COSC499_GitEx
/main.py
601
4.03125
4
# Student Name & #: Pamal Mangat - 62994785 # Course: COSC 499 - Capstone Project; (GitHub Ex #1) # Empty array to be filled after user prompt. array = [] # Prompt user for integers to fill array. print('\nEnter 5 integers to fill the empty array:') element = None # Append user integers into array. for x in range(1, ...
d6fa836d4f51e5cae1853e87494a2eefd450d064
russellwhitaker/morse-works
/scripts/morsewords.py
4,921
3.65625
4
#!/usr/bin/env python from argparse import ArgumentParser from itertools import chain from random import shuffle from string import Template import sys class MorseWriter(): def __init__(self, farnsworth_reduction, speed, sstep, frequency, fstep, unique): self.speeds = [speed + (sstep*i) for i in range(6...
839d50381a7fc825ce31b7110c6c5a156154c2c9
blakecsutton/programming-challenges
/quora_nearby/kdtree.py
25,897
3.90625
4
#!/usr/bin/python """ kdtree.py: a simple kd-tree class (only tested with two dimensions). This is a class for a space-partitioning data structure (a kd-tree KDTree), which is a binary tree made up of KDTreeNode's. All data points are stored in leaves, and internal nodes (including the root if there i...
3ad1a7fcb0a7b6d2c7ba0e1f639d396c6adf6fe7
Peter-Moldenhauer/Python-For-Fun
/If Statements/main.py
502
4.3125
4
# Name: Peter Moldenhauer # Date: 1/12/17 # Description: This program demonstrates if statements in Python - if, elif, else # Example 1: age = 12 if age < 21: print("Too young to buy beer!") # Example 2: name = "Rachel" if name is "Peter": # you can use the keword is to compare strings (and also numbers), it...
5f3cacb9f3e998b165026a8582ee6189640239e6
VitorDaynno/Exercicios-Python
/Capitulo 7/7_2.py
368
3.546875
4
''' Created on 15 de out de 2016 @author: vitor ''' string1= input('Entre com a primeira string: ') string2= input('Entre com a segunda string: ') string3='' if len(string1)<len(string2): aux=string1 string1=string2 string2=aux i=0 while i<len(string2): if string1.count(string2[i])>0: str...
465b5f440b63ee66a421fc006bfa3b93c1f46d4d
VitorDaynno/Exercicios-Python
/Capitulo 5/5_4.py
144
3.84375
4
''' Created on 2 de set de 2016 @author: vitor ''' fim=int(input("Digite o ultimo numero a imprimir")) x=1 while x<=fim: print(x) x=x+2
5043073389c48168bf76a0fe0fd0912f9b7e8f2c
VitorDaynno/Exercicios-Python
/Capitulo 8/8_2.py
142
3.734375
4
def multiplo(a,b): if a%b == 0: return True else: return False print(multiplo(8,4)) print(multiplo(7,3)) print(multiplo(5,5))
61f923a51418fc0d8bd0f0cc10020c95cd2ae3df
VitorDaynno/Exercicios-Python
/Capitulo 5/5_8.py
215
3.75
4
''' Created on 2 de set de 2016 @author: vitor ''' inicio=int(input('Digite o primeiro numero: ')) fim=int(input('Digite o segundo numero: ')) x=1 soma=inicio while x<fim: x=x+1 soma=soma+inicio print(soma)
d07bd6e8045f6385147939f4d6706f5f74e729ef
VitorDaynno/Exercicios-Python
/Capitulo 7/7_10.py
1,948
3.984375
4
#-*- coding: utf-8 -*- jogo = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] regra = [[7,8,9],[4,5,6],[1,2,3]] print("Digite o número no teclado númerico para escolher a casa") for linha in regra: print(linha) anterior = 'O' while True: #Imprime o tabuleiro if anterior == 'O': print('\n Vez...
1865fa27885f9d7a4b6b8ec91c14f0ec3cfc76a5
VitorDaynno/Exercicios-Python
/Capitulo 5/5_15.py
449
3.546875
4
''' Created on 25 de set de 2016 @author: vitor ''' total=0 while True: codigo=int(input('Digite o codigo do produto: ')) if codigo==1: total=total+0.5 elif codigo==2: total=total+1 elif codigo==3: total=total+4 elif codigo==5: total=total+7 elif codigo==9: ...
8226a0cfecc8a8b280f305b27f26de3538c1c5c7
vickio/compgen
/main.py
361
3.609375
4
from company import Company for _ in range(10): company = Company() print('---------------') print(f'{company.name}{company.suffix}') print(f' {company.url}') print(f' {company.phone}') print(f' {company.street_address}') print(f' {company.city}, {company.state}') print(f' Founded ...
1bb880a82fe854303dc13be691025ff930493fa8
subhradeepguha123/Innomatics_Internship_APR-21
/Task6_Innomatics/Dot and Cross.py
212
3.546875
4
#!/usr/bin/env python # coding: utf-8 # In[10]: import numpy n=int(input()) a=numpy.array([input().split() for i in range(n)],int) b=numpy.array([input().split() for i in range(n)],int) print(numpy.dot(a,b))
9a12facd7640f994f07c7d774fc79b28601f54f5
subhradeepguha123/Innomatics_Internship_APR-21
/Task6_Innomatics/Array.py
194
3.625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy def arrays(arr): return numpy.array(arr,float)[::-1] arr = input().strip().split(' ') result = arrays(arr) print(result)
e3ccea6771d49fd63161f3cd259a0274176875dc
Oliviabug/Dissertation_Automation
/modules/Filter_Quandl_data.py
2,881
3.546875
4
from modules import Quandl_request from modules import read_sheets #From Quanld API, only fetch data we are interested in. Gather the data into a list def Filter_Quandl(): #Empty list where will be appended lists of data final_data = [] #Fetch the symbol of the companies we cover from 'Companies covered'...
dfae10a243a7ceff506d3608abfc3779f9f8b2d5
maxim-pr/databases-course
/lab5/btree_index/analyze.py
314
3.515625
4
import psycopg2 conn = psycopg2.connect(dbname="customers", user="postgres", password="postgres", host="localhost", port="5432") cursor = conn.cursor() cursor.execute("EXPLAIN ANALYZE SELECT * FROM customer WHERE age > 10 AND age < 30;") for el in cursor.fetchall(): print(el[0])
f74e1912aa103a288c489f1570604e9135d0d638
iconbaby/python_demo
/com/slkk/test_dict.py
187
3.640625
4
dd = {'a': 1, 'b': 2, '3': 3} if 'a' in dd: print(dd['a']) print(dd.get('4')) dd.pop('a') print(dd.get('a')) a = set(['a', 'b', 'c', 'd']) a.add('bbbb') a.remove('a') print (a)
0ec316528c017e5c817b8d0f7a5f3b9535bd5b17
jinbuw/mpbdb
/src/lib/libmath.py
1,133
3.59375
4
from math import sqrt import numpy as Npy _array = Npy.array class Vector: def cross(self, v1, v2): "Returns the cross product of two vectors """ return _array([(v1[1]*v2[2] - v1[2]*v2[1]), (v1[2]*v2[0] - v1[0]*v2[2]), (v1[0]*v2[1] - v1[1]*v2[0])]) ...
dbcd5f2d914f25b378cef4417e09b14d4f16fd51
AKiwiCoder/advent-of-code
/python-advent-of-code/advent/twenty_eighteen/day01_chronal_calibration.py
743
3.5625
4
import functools from advent.utilities.file_reader import FileReader from advent.utilities.converters import Converters def calc_sum(a, b): return a + b class Day01ChronalCalibration: def __init__(self, filename): frequency_changes = FileReader.read_file(filename, Converters.as_integer) sel...
b26499e29901a2733e78fc344d500378924488e6
python-programming-1/homework-3-kmc89
/HW3.py
310
4.1875
4
num = 0 try: num_input = input('Enter a number: ') except: print('Invalid input!') num = int(num_input) def collatz(num): if (num)%2 == 0: col_num = int(num /2) print(col_num) return (col_num) else: col_num = num * 3 + 1 print(col_num) return (col_num) while num > 1: num = collatz(num)
3c16ad5c6e2a0620e655a487ec0ee643f8f2d90a
chaixihan598825114/VIPstudy
/day2/练习.py
311
3.84375
4
name = input('请输入姓名') className = '小明,小刚,小李,小李,小张' res = className.find(name) only = className.count(name) if res == -1: print(f'{name}不在班级内') elif only == 1: print('不重复') elif only > 1: print('姓名重复',end = '') print(className.count(name))
3fa2e20b7489aa0270e5af9b85f779c12c72fa40
chaixihan598825114/VIPstudy
/day1/运算符.py
519
3.921875
4
# 复合赋值运算符,先算右侧 a = 100 a += 1 # 输出101 a = a + 1 print(a) b = 2 b *= 3 print(b) c = 10 c += 1 + 2 print(c) # 比较运算符,通常用来判断 a = 7 b = 5 print(a == b) print(a != b) print(a < b) print(a > b) print(a <= b) print(a >= b) # 逻辑运算符 # and 且,全真为真,否则为假 # or 或,一个真为真,全真为真,否则为假 # not 取反值 a = 1 b = 2 c = 3 print((a < b) and (b...
abd0e064f4a534b21c48460c5ff231b69ccbbcdb
chaixihan598825114/VIPstudy
/day2/循环遍历.py
524
4.03125
4
''' name_list = ['Tom', 'Lily', 'Rose'] # i = 0 # while i < len(name_list): # print(name_list[i]) # i += 1 for i in name_list: print(i) ''' # 循环遍历字典 dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'} # 遍历字典里的key for key in dict1.keys(): print(key) # 遍历字典里的value for value in dict1.values(): print(val...
440143963b255f87194e9212a1c9284a14176ce5
chaixihan598825114/VIPstudy
/day2/公共用法.py
230
3.875
4
list1 = ['a','b','c','d','e'] # for i in enumerate(list1): # print(i) for index,char in enumerate(list1,start=1): print(f'下标是{index},对应的字符是{char}') # min最小值 str1 = 'hjksahfk12378' print(max(str1))
6f044d95b425ab07a9baa4df86c403426e37dca2
DongJoonLeeDJ/jhy0409
/5 Python/py_work/ex01.py
183
3.75
4
# ctrl+ ~ 터미널창 열기 shell 열기 # # 으로 하면 주석입니다. import time print(1) time.sleep(3) print("안녕하세요") for i in range(0,5,1): print("i = ",i)
cee9f988c5efefee1ec6266689cb6fe39da6855d
intLyc/Undergraduate-Courses
/Test/Python/Test/The_Most_Wanted_Letter.py
377
3.78125
4
import re def checkio(text): a = "".join([i for i in list(text) if re.search('[a-zA-Z]',i)]) a = a.lower() l = ([(x,a.count(x)) for x in list(a)]) l.sort(key = lambda k:k[1],reverse = True) x = [i for i in l if i[1]==l[0][1]] x.sort(key = lambda k:ord(k[0])) return x[0][0] if __name__ == '__main__'...
6885ac941ce9abbcd8b80a2e78a7107c1a11e52b
intLyc/Undergraduate-Courses
/3ComputerNetwork/RIP.py
4,188
3.53125
4
def inputRouterGraph(): '''从命令行获取路由器连接图''' graph = [] print("输入路由器连接图:") getInput = input() while getInput != 'end': graph.append(getInput.split(' ')) # 按照空格分割,加入图 getInput = input() return graph def inputInitTable(): '''从命令行获取初始路由器连接的网络''' table = [] print("输入初始路...
708df5a7f7e7687d4d83c94fb89d646818cfcbcc
intLyc/Undergraduate-Courses
/Test/Python/Test/home_password.py
205
3.59375
4
import re def checkio(data): if len(data)>=10: if re.search(r'\d',data) and re.search('[a-z]',data) and re.search('[A-Z]',data): return True return False pw = input() print(checkio(pw))
14374e3bd8bb7660eb66376665f42da2d775ab53
brandonartner/machine-learning
/Volume1_SupervisedDeepLearning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/cnn.py
4,660
3.609375
4
#Convolutional Neural Network #Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git #Installing Tensorflow # Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_started #Installing Keras # pip install --upgrade keras epochs = 25 batch_size = 32 im...
971e882b734c6217358ea3c384e58b0554206a3b
FA0AE/Mision-04
/Triangulos.py
1,519
4.3125
4
#Francisco Ariel Arenas Enciso #Determinación de un triángulo de acuerdo a la medida de sus lados ''' Mediante el uso de operadores lógicos y relacionales, y de los datos enviados por "main()", la función decide que tipo de triángulo es. ''' def decidirTriangulo(lado1, lado2, lado3): if lado1 == lado2 an...
a7c486e2caf8e259239e05f16c32321feb83f3d7
ThomasBrouwer/kmeans_missing
/tests/test_kmeans.py
16,046
3.6875
4
""" Unit tests for the K-means clustering algorithm implementation with missing values in the data points. """ from kmeans_missing.code.kmeans import KMeans import numpy, pytest, random """ Test constructor """ def test_init(): # Test getting an exception when X and M are different sizes, X is not a 2D array, an...
12d3b5839e6db2809274f70b5391dfe7177b5afc
paulmureithi/Python-Bootcamp
/quiz_game/quiz_brain.py
969
3.640625
4
class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.score = 0 self.question_list = q_list def still_has_questions(self): if self.question_number < len(self.question_list): return True else: return False def ...
c4708282907f11399b10f4091a8d5c2a8dab75ee
ComputingTelU/Batch-1
/Stack/App.py
480
3.84375
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) s = Stack() #inisialisas...
c3384a0100c8bd382a2681ed62c580c8004b205e
Douglas1688/Practices
/info_permanente.py
1,742
3.75
4
import pickle class Persona: def __init__(self,nombre,genero,edad): self.nombre=nombre self.genero=genero self.edad=edad print("Se ha creado una persona nueva con el nombre de : "+self.nombre) def __str__(self): return "{} {} {}".format(self.nombre,self.genero,self.edad)...
e63ec8db658c07dffd413854427d8ff1ea7d2b6c
Douglas1688/Practices
/poligono_regular.py
516
3.828125
4
import turtle as t import random as r def polygon(sides, length, x, y, color): t.penup() t.setposition(x,y) t.pendown() t.color(color) t.begin_fill() for i in range(sides): t.forward(length) t.left(360//sides) t.end_fill() t.hideturtle() t.tracer(0) for i in range(20): ...
c89c4b6083b9044fa4e88a40f89ed94e248a7ff1
Douglas1688/Practices
/expresiones_regularesII.py
359
3.546875
4
import re lista_nombres=[ 'Ana Gómez', 'María Martín', 'Sandra López', 'Santiago Vásquez' ] cad = input("Ingrese expresión: ") long = len(lista_nombres) cont=1 for elemento in lista_nombres: if re.findall(cad+'$',elemento) or re.findall('^'+cad,elemento): print(elemento) else: cont +=1 if cont...
86148c0044b69aea97ee2609548116160898a6bb
Douglas1688/Practices
/operaciones_matematicas/calculos_generales.py
549
4.1875
4
"""Este módulo permite realizar operaciones matemáticas""" def sumar(x,y): print("El resultado de la suma es: ",x+y) def restar(x,y): print("El resultado de la suma es: ",x-y) def multiplicar(x,y): print("El resultado de la suma es: ",x*y) def dividir(x,y): print("El resultado de la suma es: ",x//y) def...
0591a6216ae78aaa852ac8ded51d9b898a21ea17
Douglas1688/Practices
/filter_2.py
640
3.734375
4
class Empleado : def __init__(self, nombre,cargo,salario): self.nombre = nombre self.cargo = cargo self.salario = salario def __str__(self): return "{} que trabaja como {} tiene un salario de {} $".format(self.nombre,self.cargo,self.salario) lstEmpleado = [ Empleado("Juan", "Di...
f099f8ae395455235d27693d681040f33db47611
jdhfeathers/Projects_Python_hmwrks
/watch.py
1,599
3.53125
4
# coding: utf-8 # In[1]: import time import datetime from collections import namedtuple from time import sleep ''' just second watch ''' h=15 m=26 s=33 wtch=namedtuple('wtch','hour') tm=wtch(hour=datetime.time(h,m,s)) #print statemts to verify print(tm.hour) print(tm.hour.minute) print(tm.hour.second) def secnd...
c870a0acdc42fdd9abc949e1bbd164de4d58f752
babtsoualiaksandr/jobs
/zodiac.py
1,677
3.765625
4
from datetime import datetime def get_zodiac(birthday): """ Return Zodiac sign for users’ birthday Args: birthday ([str]): [exp: 1972-11-03] Returns: [str]: [sign zodiac] """ dt = datetime.strptime(birthday, '%Y-%m-%d') month = dt.month day = dt.day if ((month == 12 and ...
ebcf98d7c9f6ef4ebeba4a484fd9bc9fa377ba29
aimschroeds/cs50
/pset6/dna/dna.py
2,397
3.8125
4
import sys, csv # Check if DNA sequence's STR repeat sequences is in database provided # Create dictionary for dna database def create_dna_db(file): dna_csv = open(file) dna_reader = csv.DictReader(dna_csv) return dna_reader # Get db headers to determine STR sequences to check for def get_str_sequences...
f95faf5176abd3c002e2469131de961b2026c1fb
gauravdesale8/pythonpracticals
/leap year.py
137
3.859375
4
n=int(input("Enter the year:")) if(n%4==0): print("Entered no. is leap year") else: print("Entered no. is not a leap year")
a86d9ee2dd3663c329fb37498ecc6fb30b80d101
gauravdesale8/pythonpracticals
/operation.py
235
4.03125
4
Fruit=['banana','apple','cherry'] Fruit[2]='cocunut' print("fruit") del "fruit"[1] print(fruit) fruit.insert(2,'pear') print(fruit) fruit.append('peach') print(friut) friut.sort() print(friut) fruit.reverse() print(fruit)
ba5d05cdd3eb6d64a6f84119c490f0a87a58f7ab
gauravdesale8/pythonpracticals
/swapping values.py
154
4
4
a=int(input("Enter the value of first variable:")) b=int(input("Enter the value of second variable:")) a=a+b b=a-b a=a-b print("a is:",a,"b is:",b)
aaa312ffa73830ae8f951328c8be3a2c596f0bf7
redikod/ai-chatbot-framework
/app/commons/validations.py
151
3.578125
4
def is_list_empty(inList): if isinstance(inList, list): # Is a list return all(map(is_list_empty, inList)) return False # Not a list
3b61bbcf45830b988fac0e080b2d51d25ce0da49
juajang/algorithm
/DFS & BFS/하노이의 탑.py
371
3.78125
4
# 참고 https://shoark7.github.io/programming/algorithm/tower-of-hanoi def hanoi(num, start, to, mid, answer): if num == 1: return answer.append([start, to]) hanoi(num - 1, start, mid, to, answer) answer.append([start, to]) hanoi(num - 1, mid, to, start, answer) def solution(n): answer = [] ...
e5eb8ebc2a7e940c7cabc776d2a4ba8be5a9fe7b
juajang/algorithm
/Strings/괄호 변환.py
984
3.671875
4
from collections import deque def isCorrect(string): dq = deque() for s in string: if s == '(': dq.append(s) elif dq: dq.popleft() else: return False return False if dq else True def divide(string): cntLeft = cntRight = 0 for i in range(l...
b5a147f825896488398b0ce52352a8161bdbc5be
Terfno/2017_yayoifes_safenet
/Untitled-1-DESKTOP-80N2MUM-2.py
572
3.84375
4
import tkinter import sys #初期化 root = tkinter.Tk() root.title=('2017弥生祭展示作品') root.minsize(1000,1500) event='title' canvas = tkinter.Canvas(bg='white',width=8000,height=10000) canvas.place(x=0,y=0) #title用 def title_drow(): label_title = tkinter.Label(root, text='~名前はまだ無い~',font=('none','45','bold'),bg='white') ...
08b07c5a01a99dc9c28b4b07b35334ac4631598b
rkpillai1995/Computer-Vision
/Image Manipulations/gray_scale.py
2,036
3.71875
4
__author__ = 'Rajkumar Pillai' import numpy as np import cv2 """ Description: This program converts original color swatch image to grayscale using weighted mean and adpative threshold technique """ def grayscale_color_swatch(): ''' This method is used to generate the grayscale image of original ...
bda62fab31e84c7569144db7354b0072603f52b4
seashore001x/PythonDataStructure
/BinarySearchTree.py
1,514
4.21875
4
class BinaryTree: def __init__(self): self.tree = EmptyNode() def __repr__(self): return repr(self.tree) def lookup(self, value): return self.tree.lookup(value) def insert(self, value): self.tree = self.tree.insert(value) class EmptyNode: def __repr__(self): ...
239824a9d1a24a50654c611196a73e2065177f8c
mcs010/python-nano-course-fiap
/Manipulacao_Arquivos/textos.py
201
3.71875
4
texto = "Leia e Han Solo" print(texto[0:4]) # Prints Leia print(texto[7:]) # Prints Han Solo print(texto[-8:]) # Prints Han Solo print(texto[::-1]) # Prints the String inverted -> oloS naH e aieL
f594741f05b4a5963dba694302259d9b12d2dc2a
jbrun008/Internship
/SelectionSort.py
665
3.75
4
import LinkedList #---------------------------------------------------------- # SelectionSort.py #---------------------------------------------------------- def SelectionSort(LinkedList): for index in range(0,len(LinkedList)): pos = index currentMinPos = pos while pos < len(...
7b1b1a19d2ddbb26e43cf4a1a6e1ccce6553183b
johncmk/python27
/HW1/qsort2.py
3,958
3.640625
4
def BST(a): if a == []: return [] pivot = a[0] left = [x for x in a if x < pivot] right = [x for x in a[1:] if x >= pivot] return [BST(left)] + [pivot] + [BST(right)] def qsort(arr): if arr == []: return [] pivot = arr[0] left = [x for x in arr if x < pivot] right = ...
63173585ee401aed8a8b5ea884508bfd5675870b
johncmk/python27
/HW2/shortestPath.py
3,889
3.640625
4
class tree(object): __slots__ = "root left right".split() def __init__(self,root,left=None,right=None): self.root = root self.left = left self.right= right def printTree(t,lev= 0): if t is None: return None else: print("\t"*lev,t.root) return printTree(t....
34135362b2aa0af9d8affe98503af9e40845770b
mildewyPrawn/IA
/Gustavo/Proyecto2/ProyectoOthelloPy/Tablero.py
17,328
3.765625
4
class Tablero: ''' Definicion de un tablero para el juego de Othello ''' def __init__(self, dimension=8, tamCasilla=60): ''' Constructor base de un tablero :param dimension: Cantidad de casillas en horizontal y vertical del tablero :type dimension: int :param tamCasilla: El taman...
de1f5229031221d5057d80cafceb2902768b79d3
umartariq867/missing-values-
/customized_missing_values.py
379
3.9375
4
# Importing libraries import pandas as pd # Read csv file into a pandas dataframe df = pd.read_csv("employees.csv") print(df.head()) print("after:") # a list with all missing value formats missing_value_formats = ["n.a.","?","NA","n/a", "na", "--","-","n.a"] df = pd.read_csv("employees.csv", na_values = missi...
e969bf04e376e49c135472aad42d333002099a4a
stevenandres93/repositorio-clase-2
/ordenar_listas.py
494
3.515625
4
Lista_para_ordenar = [88, 24, 54, 96] print(Lista_para_ordenar) def ordenar_una_lista(lista): recorrido = len(lista) - 1 for j in range(0, recorrido): for i in range(len(lista)): if i + 1 < len(lista) and lista[i] > lista[i + 1]: variable_temporal = lista[i] ...
66e9f393680e81dab86a5e942e0c45279cd8958d
mattsteinpreis/CodinGame
/Python2/NetworkCabling.py
1,040
3.53125
4
__author__ = 'matt' def median(l, sort=True): s = l if sort: s = sorted(s) le = len(s) even = le % 2 == 0 half = int(le / 2) if even: return 0.5*(s[half] + s[half-1]) return s[half] def wire_length(xmin, xmax, yl, y): length = xmax - xmin for yi in yl: lengt...
1cc63aea81020d4de4f6aa324a974c0c269201a8
mattsteinpreis/CodinGame
/Python2/OptimalGiftShares.py
608
3.640625
4
__author__ = 'matt' # For "The Gift" def optimal_shares(cost, budgets): total = sum(budgets) l = len(budgets) if total < cost: return ["IMPOSSIBLE"] bsorted = sorted(budgets) shares = [] for budget in bsorted: avg = cost/l share = min(budget, avg) shares.append...
8f9345efb8fdbeaa552fb73e4c994fb9aacc56ea
SeniorZhai/PythonCode
/函数式编程/Functional.py
292
3.671875
4
# -*- coding:utf-8 -*- def f(x): print x*x map(f,range(1,10)) def f(x,y): print y,x,"* 10" return y + x * 10 print reduce(f,[1,2,3]) l = [2,3,1,32,11,34,12] print sorted(l) def cmp(x,y): if x > y: return -1 elif x < y: return 1 return 0 print sorted([2,3,1,32,11,34,12],cmp)
7061fa8af58878731fbf95ff0cacfdc4897320ab
bbarclay/urp2015
/classes/clothing_data_class.py
2,582
3.984375
4
__author__ = 'CJeon' """ clothing attributes를 효율적으로 관리하는 class """ class clothing_data(object): def __init__(self, attribute_list): self.attributes = attribute_list def __repr__(self): # to support print # when called, it will print all the attributes. return str(self.get_att...
1c76f9512b31e21179f536c5842ccc267864813f
robertux/python-practices
/Sesion5/lista1.py
531
3.875
4
#Creamos la lista dias dias = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"] dia = dias[0] print(dia) dia = dias[5] print(dia) dia = dias[6] print(dia) dia = dias[-1] print(dia) dia = dias[-4] print(dia) dia = dias[-7] print(dia) sublista = dias[0:4] print(sublista) sublista = dias[3...
b04dfa5ec5b5c5611034de7ee140ff32d7f74027
inteljack/cryptology
/encrypt.py
2,966
3.5
4
''' @@Author: Ying-Ta Lin Data format: "Username" + ':' + "Encryption Mode" + "salt" + "Password" |---(max)---| : |------3 * char-----|---32---|-----96-----| ''' import os import sys import datetime from Crypto import Random from Crypto.Cipher import AES from Crypto.Util import Counter FILENAME = "encryptd...
fa6a2c261802c615612bd6a8776073cf15096889
timurista/senior-web-dev-course
/interview-prep/python/sub_array.py
381
3.53125
4
import math def generate_power_set(S): power_set = [] for int_for_subset in range(1 << len(S)): bit_array = int_for_subset subset = [] while bit_array: subset.append(int(math.log2(bit_array & ~(bit_array - 1)))) bit_array &= bit_array - 1 power_set.append(subset) ...
df41b52417f3f769d2e6bfe452a76c7e9a67d886
su6i/masterIpsSemester1
/HMIN113M - Système/tp's/factoriel.py
316
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf8 -*- import sys, os os.system("clear") r=1 if len(sys.argv) == 2: n = int(sys.argv[1]) if n<0: print("Please enter a number superior than 2") elif n<2 and n>0: print(n,"!= 1") else: while n >= 2: r *=n n -=1 print(sys.argv[1]+"! = ",r)
3e66abfd6074412043d7e8bb3e03123081b82718
shifterj2/ClassSorter
/ClassSorter.py
5,642
3.71875
4
import csv import argparse class Student: # constants for class size range MAX_CLASS_SIZE = 15 MIN_CLASS_SIZE = 11 # constants for class score calculations LARGE_CLASS_IMPORTANCE = -100 SMALL_CLASS_IMPORTANCE = 40 GENDER_IMPORTANCE = 50 NOT_SELECETD_CLASS_IMPORTANCE = -100 def...
26cdf3876507195bf2db3deb50b2bee7eb316483
JatinBumbra/neural-networks
/2_neuron_layer.py
1,059
4.15625
4
''' SIMPLE NEURON LAYER: This example is a demonstration of a single neuron layer composed of 3 neurons. Each neuron has it's own weights that it assigns to its inputs, and the neuron itself has a bias. Based on these values, each neuron operates on the input vector and produces the output. The be...
9ea9f5a0afb7a13bab6f18bd53d717d7e46f469e
sankarshan-bhat/DS_Algo_Practice
/LeetcodeProblems/Binary Tree Level Order Traversal II.py
977
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
dfde97dccf306285a0641668d6bdfed94d054bc5
sankarshan-bhat/DS_Algo_Practice
/LeetcodeProblems/Path Sum.py
926
3.9375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathUtil(self,root,currentSum,sum): if root and root.left == None and root.right == None and (currentSum+...
1cc263c3401449dd301026f25f48959f08f20c9e
sankarshan-bhat/DS_Algo_Practice
/LeetcodeProblems/Rotate Image.py
528
3.890625
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. first rotate the matrix , then swap i,j accordingly to produce the desired result """ matrix.reve...
2ccaaaf1e399530ad3f0a9f8ae124e08f4ea5a85
sai-hardik/pythonlab
/apple.py
255
3.796875
4
n=int(input('enter the no. of students :')) k=int(input('enter the no. of apples :')) v=k//n #no. of apples each students will get r=k%n #remaining no. of apples print('the no. of apples which each student will get :',v,'remaining no. of apples',r)
e450d00dd25b850ae15b9b6c3f508c9c418f16d3
ChenJin1997/data
/算法/2) 指针去重.py
2,071
3.53125
4
class solution: # 有序的列表 # 去重的方法1 def removeDuplicats1(self,nums): # set 去重 n = len(set(nums)) i = 0 while i< n-1: if nums[i] == nums[i+1]: temp = nums[i+1] nums[i+1:len(nums)-1] = nums[i+2:] nums[i+n] = temp # 用指针去重...
82e2da81b08845c35c37be6ab072e6dab5f08bb7
ChenJin1997/data
/算法/9) 排序.py
6,142
3.609375
4
from random1 import random2 class Node: def __init__(self,data): self.data = data self.next = None def __repr__(self): return f"{self.data}" class Sort: # 冒泡排序 def bubbleSort(self,nums): size = len(nums)-1 for i in range(size): # 控制轮数 # 只要后面有一大循环...
c9b7b1053160ff94b9e41e362311d2afa512dc51
ChenJin1997/data
/类型/5) 列表实现栈.py
719
4
4
# 列表构件栈 class listStack: def __init__(self): self.stack = [] self.size = 0 # 压栈 def push(self,data): self.stack.append(data) self.size += 1 # 弹栈 def pop(self): if self.stack: temp = self.stack.pop() self.size -= 1 else: ...
7dd0260e2c3efe0609bf9b980d7b6b8864c1ea98
Boyary/Hillel
/HW_Boiarchuk_Kirill.py
1,284
4
4
import time # Todo Ex: 1 # Напишите декоратор, замеряющий время выполнения функции. # Декоратор должен вывести на экран время выполнения задекорированной функции def timer(function): def tmp(*args, **kwargs): t = time.time() res = function(*args, **kwargs) print("Function execution tim...
76bf9056266e392f28482e6cff2db2c514bd63f4
alex-1q84/leetcode
/python/src/leetcode/begin_algorithm/merge_sorted_array.py
1,679
3.53125
4
# 202202251714 # https://leetcode-cn.com/problems/merge-sorted-array/ # 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。 # 请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。 # 注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况, # nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。 from typing...
1c9136f37023783795a70d2dbcda33bf43eb1d51
alex-1q84/leetcode
/python/src/leetcode/begin_algorithm/shu_zu_zhong_zhong_fu_de_shu_zi_lcof.py
628
3.671875
4
# 202202241742 # https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/ # 找出数组中重复的数字。 # # 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。 # 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。 from typing import List class Solution: def findRepeatNumber(self, nums: List[int]) -> int: num_set = se...
3fc75155a816fde6dc4ddf8022c91f94a2559553
alex-1q84/leetcode
/python/src/leetcode/begin_algorithm/two_sum_ii_input_array_is_sorted.py
1,311
3.65625
4
# 2022022404 # 给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列, # 请你从数组中找出满足相加之和等于目标数 target 的两个数。 # 如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。 # # 以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。 # # 你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。 # # 你所设计的解决方案必须只使用常量级的额外空间。 f...
e415377e40de06a6ac066502a9da475ac0dee170
alex-1q84/leetcode
/python/src/leetcode/begin_algorithm/square_of_sorted_nums.py
706
3.703125
4
# https://leetcode-cn.com/problems/squares-of-a-sorted-array/ from typing import List class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # 双指针 low, high = 0, len(nums) - 1 squares = [0 for i in range(len(nums))] for i in range(len(squares) - 1, -1, -1): ...
cdda1b305d13ea8cc19e504f2800036fc8a554bf
alex-1q84/leetcode
/python/src/leetcode/RPNEmulator.py
520
3.5
4
__author__ = 'mywo' class Solution: # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): if not tokens: raise ValueError("tokens can't be empty") rpnStack = []; for token in tokens: if token in {"+", "-", "*", "/"}: ...
3d1bbc5476624020e04fd2049c7d129a916185f0
srpanall/evaluate_expression
/evaluate_expression/formatting_functions.py
3,880
3.75
4
""" The overall intent of this package is to evaluate mathematical expressions input as strings. This module collects the functions for the initial formatting of the expression to eliminate ambiguity that could be present in the given string. """ import re # Regular expressions used in module PAREN_RE = re.compile(r...
c663172d5bf32dcb928bf6964cc506cc08e322d4
ericlongxuan/Practice
/python/algorithms/practice/BFS2.py
493
3.875
4
graph = { 1:[2,3,4], 2:[5,6], 5:[9,10], 4:[7,8], 7:[11,12] } def backtrace(parent, start, end): path = [end] while path[-1]!=start: path.append(parent[path[-1]]) path.reverse() return path def bfs(graph, start, end): parent = {} queue = [] queue.append(start) while queue: node = queue.pop(0); i...
ad71eb3e6e28c160cb29b5ba7b49f266c868f2aa
DarkmatterVale/iterative-search
/iterativesearch/data_manager/data_processor/data_processor.py
424
3.59375
4
from abc import abstractmethod class DataProcessor: @abstractmethod def process(self, raw_data, **kwargs): """ Processes raw data, returning the processed data. :param raw_data: Raw data to process :type raw_data: Specific to implementation :return: Processed data. Typ...
bb1d1856c580b63385c8c96e0a8460874ae0716f
DarshanaPorwal07/Python-Programs
/CountNUmber.py
87
3.640625
4
count=0 for i in range (1,100): count=count+1 print("total count is :",count)
a9a880f241531db61a8cdb209502dbc806f92c36
DarshanaPorwal07/Python-Programs
/Stack.py
453
3.96875
4
def push(a,n): if len(list)>n: print("can't append,stack is full0") else: list.append(a) print(list) def pop(): if len(list)==0: print("list is empty") else: print(list.pop()) return list n=10 list=["pqr","abc","xyz"] choice=input("ente...
4890efd237e4c27f039514e00fd65b1b3a5905e2
Algoritm-Study-K/baekjoon
/2주차/5_1차원 배열/8958_yonghee.py
180
3.546875
4
N = int(input()) for _ in range(N): curr = 0 score = 0 result = input() for s in result: if s == 'O': curr += 1 score += curr elif s == 'X': curr = 0 print(score)
04af6672a9f347b6877c64e563917d11c387490b
Algoritm-Study-K/baekjoon
/4주차/12_정렬/11651_yonghee.py
241
3.515625
4
from sys import stdin N = int(input()) numbers = [] for i in range(N): numbers.append(list(map(int, stdin.readline().split()))) numbers = sorted(numbers, key=lambda x: (x[1], x[0])) for i in range(N): print(numbers[i][0], numbers[i][1])
db77707e694a4e70ea463fe803e9ab95dc5c3bc6
JungmoonH/columbia_class
/homework_two/question_25.py
310
3.84375
4
def smallest_prime_factor(n): if n == 0 or n == 1: return None if (n % 2 == 0): return 2 i = 3 while i * i <= n: if n %i == 0: return i i += 2 return n dicter = {} for value in range(0,101): dicter[value] = smallest_prime_factor(value)
5aa6e88a064312d41bd201bec661b982a1ebabd0
swhite22/password
/password.py
493
4.03125
4
correct_pass = "meme" failed_attempts = 0 password = input('Please enter password: ') if password == correct_pass: print('correct password entered, logging in...') else: while password != correct_pass: failed_attempts += 1 password = input('incorrect password, please try...
b228a150c354f678c12471782125a61a7e3d9d80
palathip/bbb_basic_python
/CH4-Time/intro.py
1,403
3.65625
4
# -*- coding: utf-8 -*- #BASIC s = "abcdef" print s[2:4] print len(s) print s[0:6] # # startswith # endswith # find # replace # count # TEXT AND SENTENCE # capitalize # title # upper # lower string = "This is a Python" # print string.capitalize(string) # print string.title(string) # print string.upper(string) # p...
e76cab2b2fc3082641315e235275584afac13d2e
palathip/bbb_basic_python
/CH2-Condition/Condition.py
211
3.71875
4
# -*- coding: utf-8 -*- print"Test Grade" test_score = input("Enter Your Score :") print "Test Result" if test_score > 90: print "Excellent" elif test_score >= 60: print "Pass" else: print "Fail"
593d8660cc1fb3111e1bf18ec4bf90980fc04b4a
WillemChen/CS50
/pset6/similarities/helpers.py
1,245
3.734375
4
from enum import Enum class Operation(Enum): """Operations""" DELETED = 1 INSERTED = 2 SUBSTITUTED = 3 def __str__(self): return str(self.name.lower()) def distances(a, b): """Calculate edit distance from a to b""" # set 2d list[a][b] cost = [[(0, None)for j in range(len(b...
8eb8573aacab9bc276179414ebd75e4cf664cf47
sankalp-sheth/FSDP2019
/day3/weeks.py
252
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon May 13 13:22:14 2019 @author: KIIT """ week_days=('Monday', 'Wednesday', 'Thursday', 'Saturday') new_days=(week_days[0],)+("Tuesday",)+week_days[1:3]+("Friday",)+(week_days[-1],)+("Sunday",) print(new_days)
10ecf4af2eaab7729da16a446e9194937a01f290
acoudert/ft_linear_regression
/estimation.py
305
3.546875
4
import config def estimatePrice(km, theta0=config.theta0, theta1=config.theta1): return theta0 + theta1 * km def main(): while True: try: print(estimatePrice(int(input("Car km ? ")))) except Exception as e: print(e) if __name__ == "__main__": main()
d3cb97888eebf5983bf991c11989ded303f3589c
paradise110302/COVIDAway
/COVIDAwayDistance/compile.py
1,057
3.625
4
from COVIDAwayDistance.DistanceComparison import * from COVIDAwayDistance.ParseSQLite import * # Convert any coords to places # Sample performed with Washington DC, the coordinates of the place would be here in terms of LAT, LONG coordinates = (38.89511, -77.03637) originName = reverseGeocode(coordinates) destinationN...
1a9e639cc77b7b67ba1a8f67f4adf3765e7db359
Arsalan-Syed/tetris_project
/src/helper.py
1,828
3.734375
4
import copy ''' Adds a piece to the board. The piece and board are 2D arrays. ''' def add_piece(board, piece, coord): off_x, off_y = coord for cy, row in enumerate(piece): for cx, val in enumerate(row): board[cy + off_y - 1][cx + off_x] += val return board ''' Removes a piece from ...
f781b6136696e3b26e9ea0d6bb289a0d1f6d95d0
drowsycoder/python-project-lvl1
/brain_games/games/calc.py
842
4.09375
4
"""Module for a game ('Calculate the result of an expression').""" import operator from random import choice, randint RULES_HEADLINE = 'What is the result of the expression?' MIN_NUMBER = 1 MAX_NUMBER = 100 operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, } def provide_game_roun...
bcced48902941454d09fe26c3f666ff10b4a3006
drowsycoder/python-project-lvl1
/brain_games/games/prime.py
1,167
4.03125
4
"""Module for a game ('Is a number prime or not').""" from random import randint RULES_HEADLINE = 'Answer "yes" if given number is prime. Otherwise answer "no".' MIN_NUMBER = 2 MAX_NUMBER = 100 def is_prime(prime_num_candidate): """Return True if the number is prime else False. Args: prime_num_can...
917369e4d17d35f5bb262a4e524d79c5b76e3e8b
hanbba92sch/baekjoon-step-by-step-challenge
/puzzle/hanoi.py
249
3.828125
4
def hanoi(source,goal,path,n): if n==1: print("move disk 1 from", source,"to",goal) return hanoi(source,path,goal,n-1) print("move disk",n,"from",source,"to",goal) hanoi(path,goal,source,n-1) N=4 hanoi('A','C','B',N)