blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3c866e16fd2941bdcd5a0a51cf7017b702e72f0d
MatheusOldAccount/Exerc-cios-de-Python-do-Curso-em-Video
/exercicios/ex042.py
507
3.96875
4
l1 = float(input('Digite o comprimento do primeiro lado: ')) l2 = float(input('Digite o comprimento do segundo lado: ')) l3 = float(input('Digite o comprimento do terceiro lado: ')) if l1 > l2: sub = l1 - l2 else: sub = l2 - l1 if l1 + l2 > l3 > sub: print('É um triângulo', end=' ') if l1 == l2 and l1 =...
3cf991e79ae9b0c84b2893c3f913cdd4ddebc67c
rwooley159/PublicScrap
/looptest.py
2,913
3.515625
4
from threading import Thread from time import sleep isUnderMaintenance = False class BaseThread(Thread): def __init__(self, parent=None): super(BaseThread, self).__init__() self.parent = parent self.stay_alive = True def run(self): pass def interruptible_sleep(self): ...
38a7024503fe28181c21c90a4a341bb21fcd5ab5
svworld01/group-coding
/day0001/2_Kids_candies.py
376
3.625
4
# created by KUMAR SHANU # 2. Kids With the Greatest Number of Candies # https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: max_candy = max(candies) return ...
9d150095760de25f5b589642c6e5529671327d88
osmarsalesjr/AtividadesProfFabioGomesEmPython3
/Atividades1/At1Q29.py
345
3.796875
4
def main(): qtd_meses = int(input("Quantidade de tempo em meses: ")) print("Valor é equivalente a ", calcula_anos(qtd_meses), " anos e ", calcula_meses(qtd_meses), " meses.") def calcula_anos(total_meses): return int(total_meses/12) def calcula_meses(total_meses): return total_meses%12 if __name__ =...
23528108997a2c5a97e6fcc58d87ee79e7eacacb
GabrielT98/Representa-grafica-de-grafo
/grafos.py
1,652
3.703125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import networkx as nx while True: print("**************************************") print(" Algoritmos de grafos ") print("**************************************") print(" MENU PRINCIPAL ") print(...
106a0f3a353109736c3cd0ae9078643972c35e12
robinDovo/data
/data03.py
262
3.9375
4
scores = list() total = number = 0 while number != -1: number = int(input('請輸入學生分數:')) if number != -1: scores.append(number) total += number avg = total/len(scores) print('全班人數%d個,總分:%d,平均:%.2f'%(len(scores),total,avg))
fb4727c9d6a9b898d0a0f3718d938a587e5443bb
Baltimer/Ejercicios_Python
/Ejercicios de inicio/Ejercicio 7.py
565
4.21875
4
# Escribe un programa que pida por teclado un número y que a continuación muestre # el mensaje el número leído es positivo o bien el número leído es negativo # dependiendo de que el número introducido por teclado sea positivo o negativo. # Consideramos al número 0 positivo. # # Autor: Luis Cifre # # Casos tipo: # # ...
dcba5776bfcc4213887fe0efbb8bce6e030c7358
loongqiao/learn
/python1707A/0724/bigfile.py
590
3.65625
4
""" 由于计算机内存有限所以对大文件 进行分开处理 """ def copy(): #提示用户输入原文件名称 source=input("请输入源文件名称") target=input("请输入目标文件名称") #打开文件 old_file=open(source,"br") new_file=open(target,"bw") #复制文件 while True: contennt=old_file.read(1024*1024) if contennt: new_file.write(contennt) ...
02e1b7b9f30c17c14d4b1cea325d8c56e789bc50
kirbalbek/pprog_balbek
/warmup_uml.py
1,443
4.09375
4
#1 задача ''' class Shape: def __init__(self, side, height): self.side = side self.height = height class Triangle(Shape): def area(self): return self.side*self.height/2 class Rectangle(Shape): def area(self): return self.side*self.height a = int(input()) b = int(input()...
038014593c90df86257166ae6e86c849a3e2d378
ctc316/algorithm-python
/Lintcode/Ladder_23_L/1_Easy/30. Insert Interval.py
989
3.96875
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: """ @param intervals: Sorted interval list. @param newInterval: new interval. @return: A new interval list. """ def insert(self, interval...
acdabcf4f84f1033ae71487c3f63850d9792bc34
vbelous2020/PythonIntro
/Homework5/task1 - drawings.py
541
4.15625
4
height = 11 width = 11 # Треугольник for x in range(width): for y in range(height): if x == width//2 or y == width//2 - x or y == width//2 + x: print('* ', end='') else: print(' ', end='') print() print() # Ромб for x in range(width): for y in range(height): ...
58da33017fd50ed4fba1b70336248cc1b804437b
bssrdf/pyleet
/M/MinimumNumberofFlipstoMaketheBinaryStringAlternating.py
2,529
4.53125
5
''' -Medium- *Sliding Window* Minimum Number of Flips to Make the Binary String Alternating You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: P...
b219902a453ca046ece3abb248adcce5a247b3eb
joshuafreemn/py
/tshirt.py
168
3.515625
4
def make_shirt(size='Large', msg='I <3 Python'): print("You have chosen a shirt size: " + size) print("You shirt will read: " + msg) make_shirt(msg='Lorem Ipsum')
aa358097e440f671b5549c7ff6eec8570ee34b7e
efren1990/codepy
/PythonMultiplataforma_Udemy/00_Iniciales/Condicionales.py
666
4.0625
4
"""------------------------------CONDICIONALES-------------------------------------""" """ if(condicion): Haga Esto() elif(condicion2): Haga Aquello () else: Entonces haga esto () """ """-------------------------------------------------------------------------------------------------------""" accion = int(i...
0ce7498244b64c2ee29933a32b458e0f0f1d1c65
NULLCT/LOMC
/src/data/1268.py
2,017
3.796875
4
class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] # 隣接リストG[u][i] := 頂点uのi個目の隣接辺 self._E = 0 # 辺の数 self._V = V # 頂点の数 def E(self): return s...
c1e62df16ffce5461b47b06719f86f37b57e48db
ma-al/plusser
/yamler/main.py
2,131
4
4
"""Parses CSVs and outputs a YAML.""" import csv import os import argparse from datetime import datetime as dt import yaml def parse_arguments(): """ Get and parse the program arguments. :return: Parsed arguments object :rtype: argparse.Namespace """ pars = argparse.ArgumentParser() par...
81faf74289315b9446929cd79b1c5a69f80d26bc
DamonZCR/PythonStu
/47Tkinter/Text文本输入/14-2Text中Mark的用法.py
328
3.5
4
from tkinter import * '''Mark 这里面就是将这个索引位标记为‘here’这个名字, 可以使用mark.unset()删除这个索引名。''' root = Tk() text = Text(root, width=30, height=20) text.pack() text.insert(INSERT, 'Damon wants to sleep') text.mark_set('here', 1.2) text.insert('here', '插入') mainloop()
80677410e2e07307fcf7f8ac6d6bbd040ad3c927
JeongWonjae/Coding_Practice
/Python/Parity_Bit.py
360
3.796875
4
#Odd parity def prtBit(bit): bit=list(str(bit)) count=0 if len(bit)!=7: print('Input Wrong!') return for j in bit: if j=='1': count=count+1 if count%2==0: bit.append('1') elif count%2==1: bit.append('0') return bit res=prtBit(1001101) print('Result of odd parity is '...
0899109e62885d39b35ecfea79cb18c3c9af244b
praveenbommali/DS_Python
/sorting-algo/SelectionSort/SelectionSortImpl.py
739
3.78125
4
# Implementation of Selection Sort class SelectionSortImpl(object): def __init__(self, inputdata): self.inputdata = inputdata def selection_sort(self): input_lenght = len(self.inputdata) for i in range(input_lenght): min = i for j in range(i + 1, input_lenght):...
f7e9fbc925b1d817e0c6489950f62956cffd7f6a
heechul90/study-python-basic-1
/Python_coding_dojang/Unit 28/practice.py
625
4.21875
4
### Unit 28. 회문 판별과 N-gram 만들기 ## 28.3 연습문제: 단어 단위 N-gram 만들기 ## 표준 입력으로 정수와 문자열이 각 줄에 입력됩니다. ## 다음 소스 코드를 완성하여 입력된 숫자에 해당하는 단어 ## 단위 N-gram을 튜플로 출력하세요(리스트 표현식 사용). ## 만약 입력된 문자열의 단어 개수가 입력된 정수 미만이라면 'wrong'을 출력하세요. n = int(input()) text = input() words = text.split() if len(words) < n: print('wrong') else: n...
d1504f658319e9469b5329d62e1f3e560eefa119
ThatGuy00000/LPTHW
/ex4.py
839
4.0625
4
cars=100 #how many cars space_in_a_car=4.0 #how many people can fit in each car drivers=30 #people able to drive any of the 1000 cars passengers=90 #number of people that need to fit into cars_not_driven=cars-drivers #more cars than drivers so all the leftover cars cars_driven=drivers # how many cars actually get driv...
11b9786b7b910e733ad89747c3a0f20b69c874e5
max-conroy/Python
/TrainTimeCalculator.py
3,456
4.53125
5
#Max Conroy; Jordan Westfall; Andrew Weaver #CSC 485; Program 1- Train Problem #Group 2 #User enters data and program calculates time that trains will meet based on the data entered import datetime from datetime import timedelta # Print welcome messages print("=================================") print(" Train Time ...
38499faebc2c08cceafb8dd0049d1c72851311a7
WolfeLogic/CS372-Computer-Networking
/PROJECT-1/chatserver.py
2,587
3.703125
4
#!/usr/bin/env python #****************************************************************************** # COURSE: CS372-400 W2018 # PROJECT: Programming Assignment #1, client-server network application # AUTHOR: DREW WOLFE # RUN: python chatserver.py <port number> # NOTES: # USABLE TCP PORT RANGE: 1024-65535 (...
64c8b8b0346a617a0cdf17a2c3868b004fd0fee3
YuliiaAntonova/leetcode
/Truncate_sentence.py
377
3.625
4
# Input: s = "Hello how are you Contestant", k = 4 # Output: "Hello how are you" # Explanation: # The words in s are ["Hello", "how" "are", "you", "Contestant"]. # The first 4 words are ["Hello", "how", "are", "you"]. # Hence, you should return "Hello how are you". class Solution: def truncateSentence(self, s: str...
e06b89fc9cd786a01e350ce061fbd350cd539d46
chemplife/Python
/python_core/meta_programming/meta_programming_basics.py
3,369
4.40625
4
''' MetaProgramming is a technique in which our programs will treat other programs as their data. -> These programs are designed to read, generate, analyze, or transform, and even modify other programs and/or itself while running. -> Basically, code can modify code.. -> Keeps our code DRY (Don't Repeat Yourself) ...
2c21688b1d96f0157d5efe380917627f3c765243
mehulthakral/logic_detector
/backend/dataset/solveSudoku/sudoku_10.py
2,017
4
4
from typing import List class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ ## RC ## ## APPROACH : BACKTRACKING ## ## Similar to Leetcode : 51. N Queens, 36. Valid Sudoku ## ## Time Complexity: O(...
63436bb4b87c6c50eb7e4b8f1376347a7e2059a3
Satily/leetcode_python_solution
/solutions/solution367.py
639
3.640625
4
class Solution: def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ n = 0 n_list = [] while n ** 2 <= num: n_list.append(n) n += 1 result = 0 for n in reversed(n_list): r = result + n ...
4c816318ec99eb66bb7bb8da480e0b10a12c21a4
pdebuyl/threefry
/example_gallery/plot_random_series.py
298
3.96875
4
""" ====================== Drawing random numbers ====================== Example of drawing random uniform number with threefry. """ import threefry import matplotlib.pyplot as plt r = threefry.rng(8760396957664838051) data = [r.random_uniform() for i in range(10)] plt.plot(data) plt.show()
e9053b482794d360f0e942196f785d6f4afcbe15
106360130/Python_Class
/HW1_106360130/quiz5.py
599
3.84375
4
def main(): import random num_right = random.randint(0,100) print("num_right : {}".format(num_right)) i = 1 start = 0 end = 100 while(i <= 6) : num_guess = int(input("Please guess a number from {} to {} : ".format(start, end))) if(num_guess > start and num_guess < num_right...
e5bd6196455138ec5b148610b3e9b04d77d8fd26
barcenitas/Django
/Serie 1/10.py
222
3.84375
4
cadena =input("Dígame la palabra: ") lista=list(cadena) print("inicio") for letra in lista: if letra == 'a' or letra== 'e' or letra== 'i' or letra== 'o' or letra== 'u': continue print (letra) print("fin")
45de67fa918326557323a9ae6f119949469c3cdd
jytaloramon/monitoria-estrutura-dados-2k20
/prova-ab1/main_driver.py
1,669
3.59375
4
count_pass = 0 def main(): data = [ {'id': '15', 'dist': 52}, {'id': '56', 'dist': 41}, {'id': '1', 'dist': 10}, {'id': '5', 'dist': 2}, {'id': '2', 'dist': 156}, {'id': '136', 'dist': 465} ] print('Antes da Ordenação') for d in data: print(' ...
f2f8abfadab38e887900e6b005cc372629103f4d
jemsonjacob/Mypythonworks
/venv/bin/file/opps/calc.py
399
3.8125
4
class Calc: def __init__(self,a,b): self.a = a self.b = b def add(self): return self.a+self.b def sub(self): return self.a - self.b def mul(self): return self.a * self.b def div(self): return self.a/self.b a=int(input("first")) b=int(input("second")) ...
d48834b99a1a10004ec7d8ac2b3b2499f6f88617
saikpr/short_codes
/py/network_security_lab/hill.py
1,393
3.78125
4
import utils def encrypt(message, matrix, encryption=True): """ Hill encryption (decryption). """ message = message.upper() if not utils.invertible(matrix): # The matrix should be invertible. return "Non invertible matrix" if len(message) % 2 != 0: message = m...
9576ee1260fa82e6efacb7ddc4710e282ead9ecd
Manvichauhan/python-project
/tuple.py
144
3.515625
4
# a = ("ram","rohit","mohit"1,20.3,True,) print(a) a[0]="abc" #not update print(a) b=() b = (1) #empty tuple b = (1, ) print(b) print(type(b))
d10b78da747c5826df42f5d81989cf26dccbbf34
idnd/mit-algorithms
/sort.py
1,987
4.03125
4
def arrayPrint(A): for i in xrange( len( A) ): print A[i] , print '' def less(a,b): return a < b def greater(a,b): return a > b def insertionSort(A, func = less): """ Insertion sort: - Simple implementation - Efficient for (quite) small data sets - Adaptive (...
c675d8b48f5c249f335e69d113f5952db9c0bcd6
bikongyouran/python_practice
/BasicAlgorithm/bubbleSort.py
509
3.828125
4
import numpy as np def bubble_sort(source): length = len(source) i = 0 j = 0 while j < length: while i < length - j - 1: if source[i] > source[i + 1]: temp = source[i] source[i] = source[i + 1] source[i+1] = temp i += 1 ...
746c9e902bea010214cda6f547e398d5db6712f3
jaeyoon-lee2/ICS3U-Assignment-03-Python
/the_bigger_number.py
1,152
4.46875
4
#!/user/bin/env python3 # Created by: Jaeyoon # Created on: Oct 2019 # This program display which number is bigger import random def main(): # this function display which number is bigger # input integer1_as_string = input("Enter the first number (integer): ") integer2_as_string = input("Enter the...
d9f6354ae5a567166ec312cb3e95e68b5ea0dec3
weltonvaz/Zumbis
/alfabeticamente.py
483
3.625
4
# organizar_alfabeticamente.py - 20.07.2004 # por Luiz E. Lepchak Jr. <jr.lepchak@ig.com,br> # Declaração da função def organizar_alfabeticamente(lista): "Organiza alfabeticamente as strings contidas dentro de uma lista." for x in range (len(lista)): for y in range (len(lista)): if lista[x] < lista[y]: list...
89a115d1acdacc49522ddfbd9e55e27f1acc2b58
amelialin/tuple-mudder
/ex42.py
2,000
4.46875
4
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): def __init__(self): print "Made an Animal" ## ?? Dog is-a Animal class Dog(Animal): def __init__(self, name): ## ?? Dog has-a name self.name = name print "Made a Dog named %s" % n...
c13ab31e5b014dda5de92c286de7253cf34b42fe
loongqiao/learn
/python1707A/0710-0716/demo01私用字典.py
1,407
3.875
4
""" 这是一个私有字典的 有用户的固定信息 可以增加信息 可以修改信息 可以查询信息 """ users=[] u1={"name":"a","age":"20","sex":"男","phone":"123456"} u2={"name":"b","age":"18","sex":"女","phone":"124563"} users.append(u1) users.append(u2) while True: #打印界面 print("\t\t信息查询") print("------------------------------------------------------------------") pri...
74d28ab2eb606f887bcf11615d6948198e48952c
yqz/myalgoquestions
/partition.py
992
3.90625
4
#!/usr/bin/python """ QUESTION: Quick sort partition function """ def partition(a, p): """ Parition array a by pivot a[p]. """ if a is None or len(a) == 1: return 0 # Swap a[p] to the last position pivot = a[p] a[p] = a[len(a) - 1] a[len(a) - 1] = pivot j = 0 k = 0 ...
d1ff201eea78a78f404ae1d0fccd18b80aa58dcd
ethyl2/Intro-Python-I
/src/misc/hackerrank/activity_notifications.py
2,795
3.984375
4
""" https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting&isFullScreen=true&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen Given d <- number of trailing days needed before bank sends n...
fd9154d5a2686f190e80945b95cf8f9ce5ba3d08
allester/cis40
/day_converter.py
498
4.03125
4
def day_converter(num): if num == 1: day = "Monday" elif num == 2: day = "Tuesday" elif num == 3: day = "Wednesday" elif num == 4: day = "Thursday" elif num == 5: day = "Friday" elif num == 6: day = "Saturday" else: day = "Sunday" r...
954eec135fd979cec4bb3aa59c98cfcc307258d3
TREMOUILLEThomas/ex-68
/ex 68 (3).py
401
3.96875
4
from turtle import * def triangle(a): begin_fill() for i in range (3): forward(a) left(120) end_fill() def tritri(a): for i in range(3): triangle(a) left(90) up() forward(a/2) right(90) forward(a/6) down() a=a*(2/3) ...
f275dea1b8f0cadacfccb70b5bcd4b3001f79bf7
Anikcse18/CodeforcesSlovedProblempart-1
/A. Rainbow Dash, Fluttershy and Chess Coloring.py
122
3.765625
4
size = int(input()) for i in range(size): s = int(input()) if s==1: print(s) else: print(s-1)
09cd2d99b22d3a678adbe6cf3c794e7e79b8b9a1
juanbolivar/python
/agenda_telefonica.py
3,461
3.875
4
#Agregar un contacto #Eliminar Contactos #Actualizar un Contacto #Ver un Contacto #Ver toos nuestros contactos agenda_telefonica = dict() def imprimir_operacion(nombre_operacion): print() print("------------Agenda Telefónica------------") print(nombre_operacion) print("------------------------------...
1e954a288215b45f0c10f7fceb70772c8752053b
aa18514/workbook-solutions
/Python/challenge 22 super_saving.py
927
4.09375
4
total_money = input("What is the total amount in Rs. before discount?") if total_money > 5000: discount = 1000 elif total_money > 1000: discount = 150 elif total_money > 500: discount = 50 elif total_money > 100: discount = 5 else: disount = 0 discounted_price = total_money - discount print("The ...
e5fb4d48ef90a4a3d77d88e313949c24562bc3d5
Mohamad11002/Mixed-Python-Projects
/WordCloud/test.py
832
3.734375
4
################################################## #### Word Cloud with Python #### pip install matplotlib #### pip install wordcloud #### pip install numpy #### pip install Pillow #### you have to run this code on terminal or cmd ################################################## import matplotlib.pyplot as pPlot f...
a12107517ff64eb1332b2dcfcbe955419bc5d935
kelvin5hart/calculator
/main.py
1,302
4.15625
4
import art print(art.logo) #Calculator Functions #Addition def add (n1, n2): return n1 + n2 #Subtraction def substract (n1, n2): return n1 - n2 #Multiplication def multiply (n1, n2): return n1 * n2 #Division def divide(n1, n2): return n1 / n2 opperators = { "+": add, "-":substract, "*": multiply,...
9d5786dcca0cfe8aa14663ee338da17b5b3b1b1a
StarkTan/Python
/OpenCV/image_processing/contours/contour_features.py
6,161
3.515625
4
""" To find the different features of contours, like area, perimeter, centroid, bounding box etc """ import numpy as np import cv2 as cv def feature_1(): """ 图像矩 cv.moments(cnt) : mji 几何矩,muji 中心距,nuji 中心归一化距 图形面积 cv.contourArea(cnt) 图形周长 cv.arcLength(cnt, True) 图形多边拟合 cv.approxPolyDP(cnt, epsilo...
d319ffd027d11cca12d7e2260ab66ab6b16cc18a
jpusterhofer/polynomial-regression
/regression.py
2,568
3.640625
4
import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt #Calculate h(x) def h(x, weights): y = 0 for i in range(len(weights)): y += weights[i] * x**i return y #Calculate the model's weights def calc_weights(data, degree): alpha = 0.001 weights = np.zeros(...
6f5a7790b1e0c62345d9cc6ef593378b35074d81
evansuslovich/PythonPrograms-
/quadratic.py
392
3.859375
4
import math def main(): print("Hello! Welcome to to a quadratic calculator") a, b, c = input("Please enter the coefficients(a,b,c):") start = (-1*b) root = math.sqrt((b*b) - 4 * a * c) divide = (2*a) first = (start + root) / divide second = (start - root) / divide print("The first so...
2e728d3e739dbcc38a5f3ffddeea066ca3add4f3
divya-nk/hackerrank_solutions
/Python-practice/itertools/comb_with_replacement.py
530
3.765625
4
itertools.combinations_with_replacement(iterable, r) This tool returns r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produ...
e2f3e5037b1fb6af94504e5eedd156b992dba018
dks1018/CoffeeShopCoding
/2021/Code/Python/PythonCrypto/Module_3/Fernet_Cryptograhy.py
1,867
3.875
4
from cryptography.fernet import Fernet from Cryptodome.Cipher import AES def generate_key(): key = Fernet.generate_key() return key def save_key(): file = open('key.key', 'wb') store_key = generate_key() file.write(store_key) file.close() def get_key(): file = open('key.key', 'rb') ge...
95df76b25a85ac603507d25268b936fd7399ec84
Ankit-Developer143/Python-Medium-Question-Solve
/python Hard edabit/sentence Searcher.py
520
3.515625
4
def sentence_searcher(txt,word): txt = txt.split(".") for i in txt: if word.lower() in i.lower(): return "{}".format(i) txt = "I have a cat. I have a mat. Things are going swell." print(sentence_searcher(txt,"have")) #I have a cat def using_lambda(text,sentence): lst = ([i for i i...
cea6eac4eae56b5cb5246f602da345bb5071700f
shaneslone/cs_week4_day4
/quicksort.py
359
3.953125
4
def quicksort(a): if len(a) <= 1: return a pivot = a[0] left = [] right = [] for i in range(1, len(a)): if a[i] > pivot: right.append(a[i]) else: left.append(a[i]) left = quicksort(left) right = quicksort(right) return left + [pivot] + r...
739a5f1b330ee2b2b9992b25fd52686ac8129c99
libasoles/search-and-sort-algorithms
/algorythms/binary_search_tree.py
994
3.828125
4
class Node: value = None left = None right = None def __init__(self, value=None): self.value = value def attach(self, value): if not self.value: self.value = value return if value >= self.value: if not self.right: self....
5b3e9921963e09babb38189b51ac0ccef9bf2cdd
tormobr/Programming
/chess/movement.py
3,424
3.78125
4
class Movement: def __init__(self, board): self.board = board def move(self, board, piece, start, end): self.board = board if piece.name == "pawn": return self.pawn(piece, start, end) elif piece.name == "bish": return self.bishop(piece, start, end) elif piece.name == "knig": return self.knight(piece, star...
c8c6b42f2dcc3d77138473ecaa6eb324f14c40c7
matkuhlm/python-challenge
/PyBank/main.py
2,407
3.890625
4
# Modules import os import csv print("__________________________________________________________") csvpath = os.path.join("Resources", "budget_data.csv") # Method 2: Improved Reading using CSV module with open(csvpath) as csvfile: #CSV reader specifies delimiter and variable that holds contents csvreader =...
bed18016bff322cef041fee3b03c276e1a8718c7
kiransy015/Python-Frameworks
/venvScripts1/venvScripts/Pgmlambda.py
807
3.953125
4
# filter functionality from functools import reduce List = [1,2,3,4,5,6,7,8] # evens = [] # # def get_even_no(list): # for i in range(0,len(list)): # if list[i]%2==0: # evens.append(list[i]) # print("Even nos :",evens) # # get_even_no(List) # # # def even(n): # if n%2==0: # ret...
b37cbac9a53341c3075a711c8c68c30ead49c973
dongkooi/ngothedong-fundamental-C4E18
/session04/login.py
455
3.671875
4
import getpass user = "qweqwe" password = "123123" u = input("User: ") count = 0 while True: if u == user: p = getpass.getpass('Pass:') if p == password: print("Welcom, c4e") break else: print("Wrong password, please try again") elif u != user: ...
b83b0599ae5737069b8e90f5d2ae1bdc940fc66b
yuto-dev/fsd-corona-new
/test/test.py
266
3.65625
4
newList = ["a;b", "c;d"] f = open("test.txt", "w") counter = 0 for items in newList: f.writelines(newList[counter]) f.writelines("\n") counter = counter + 1 f.close() #open and read the file after the appending: f = open("test.txt", "r") print(f.read())
3e1be83dfb0645c4066e656632359e73a2921c02
Phil-U-U/Evaluate-Amazon-Book-Reviews
/code/featureEngineering.py
1,791
3.5
4
''' Evaluate Amazon Book Reviews - create categorical features Author: Phil H. Cui Time: 10/12/2016 ''' import numpy as np class feature_engineering( object ): def __init__( self, df ): self.df = df def createNWordsLabel( self ): NWords_category = np.empty( [ len(sel...
1b0528e2f35aea0327c30fbd0642573b968e8e44
marcellasiqueira/programacao1
/minmax/minmax.py
934
3.828125
4
# coding: utf-8 # MinMax Sort = Selection Sort Duplicado # 2017, Marcella Siqueira / UFCG, Programação 1 # Matrícula: 117110492 def minmax_sort(lista): lista_final = [] maior, menor, m = 0, 0, len(lista) for i in range(0, int(m/2)): for j in range(i, m): if lista[j] < lista[menor]: ...
9c57b7a8a70d5ae1ea2eae273239c11be01911d1
barun12/PythonClass
/calculator_file_input.py
2,251
3.890625
4
""" simple calculator with file IO author: Barun Kumar Sharma(barun12) """ def addition(num1, num2): """ :param num1: 1st number :param num2: 2nd number :return: sum of num1 and num2 """ return num1 + num2 def subtraction(num1, num2): """ :param num1: 1st number :param num2: 2nd n...
b33dd6402c054a1f13940008cbc817928bf162ab
henryyecode/Constraint-Satisfaction
/constraint.py
2,163
3.546875
4
from domain import domainDay, domainTime def sameDay(m1, m2): #Works day1I = m1.split(' ', 1)[0] day2I = m2.split(' ', 1)[0] if day1I == day2I: return True else: return False def oneDayBetween(m1, m2): #Works day1I = domainDay.index(...
aaed5b59897d3cd3da97da0fca8fbf20fb8fb008
NCRivera/Personal-Projects
/dnd_dice_roll_function.py
311
4.0625
4
import random def roll_dice(sides, rolls): for roll in range(rolls): score = random.randint(1,sides) print(score) dice_sides = int(input("How many sides does your dice have? ")) roll_number = int(input("How many rolls do you want to make? ")) roll_dice(dice_sides,roll_number)
f884b7dd94b61ccc2c290d33e266dab8b6222742
PimpatDev/CP3-Peerapat-Pimmaha
/Lecture53_Peerapat_P/Lecture53_Peerapat_P.py
161
3.734375
4
def vatCaculate(totalPrice): result = totalPrice + (totalPrice*7/100) return result print("Total price : ", vatCaculate(float(input("Enter price : "))))
fa61bd648e9b4397c09e2555d1687dcf8d4ec892
zhangshv123/superjump
/interview/google/hard/LC683. K Empty Slots.py
3,320
4
4
""" There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then. Given an array flowers consists of number from 1 to N. Each number in the array represents the ...
5fca54ea42d1625c4fe03c994acfe8c22037a2b4
EslamFawzyMahmoud/Data-Structure
/Algorithms/Sorting/BubbleSort.py
333
4.09375
4
def bubblesort(arr): for i in range(len(arr)-1): for j in range(len(arr)-1): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp return arr arr=[5,4,1,2,7,8,0,100,6] print("Before Sort: ",arr) print("After Sort: ",bub...
b2b4729cfbe47e3b3f417795bee9c0975ca3da20
Theofilos-Chamalis/edX-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science
/Running The Simulation.py
1,823
3.921875
4
# Enter your code for runSimulation in this box. def runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type): """ Runs NUM_TRIALS trials of the simulation and returns the mean number of time-steps needed to clean the fraction MIN_COVERAGE of the room. Th...
bb92f164096cc04ef6799ec06ac02c0b6855202c
jayjay1973/CIS115-Python-Labs
/williamPrudencio_lab2-15.py
697
4.28125
4
#program, williamPrudencio_lab2-15.py, 01/26/19 ''' This program will use Turtle Graphics to draw the first shape shown on page 107 of the "Starting Out With Python" book. ''' import turtle; #Change the fill color to orange------------ turtle.fillcolor("orange") #Begin filling the shape with color---------- turtle...
94397c3ce7ec4c3032bf1e24e0439e1fb44a6fa7
cosmincelea/CodeAdvent2018
/day1/main.py
392
3.78125
4
import itertools fileName = input('What is the name of the file my Dude?\n') data = [float(x) for x in open(fileName).readlines()] print("The Total freq is: " + str(sum(data))) freq = 0 allFreqValues = set() for val in itertools.cycle(data): freq = freq + val if freq in allFreqValues: print("The Repea...
1fa80a84529ad474148f03cfad123d7666f38029
lichangg/myleet
/titles/226. 翻转二叉树.py
333
3.78125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from utils.util_funcs import TreeNode class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root: root.right, root.left = root.left,root.right self.invertTree(root.left) self.invertTree(root.right) ...
843732c8e492928da162bbe34766f65d138a0fa0
govex/python-lessons-for-gov
/section_14_(exceptions)/exceptions_03.py
840
4.1875
4
# Example #3: Different types of exceptions can be caught. print("Example #3: Phonebook!") phonebook = {} while True: # this will loop forever until we issue a break! key = raw_input(" (Ex #3, Phonebook) Please enter a person's name, or leave blank to quit: ") if key == '': break value = r...
956d46bf238375a95f184d1dfd9d9001644d4fe0
Genyu-Song/LeetCode
/Algorithm/GreedyAlgorithm/QueueReconstructionByHeight.py
1,636
3.953125
4
# -*- coding: UTF-8 -*- ''' Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the ...
9dce87320791825b0b614f10cb2e41ed1fe66e5d
Jsonghh/leetcode
/200101/Degree_of_An_Array.py
766
3.640625
4
from collections import Counter class Solution: def findShortestSubArray(self, nums): if not nums: return 0 nums_degree = self.find_degree(nums, 0, len(nums) - 1) l, r, min_len = 0, 0, len(nums) for l in range(len(nums)): while r < len(nums) and self.find_deg...
392cddb1c6414144eca29a9ef8591d748604a2c4
wgrh12/gitdemo3
/code1.py
124
3.546875
4
#!/usr/bin/env python print("Hello world!") from datetime import timedelta year = timedelta(days=365) year.total_seconds()
20c51cd040743803cb34b9b0c838af57841d7dd5
madeibao/PythonAlgorithm
/PartB/py回文子串2.py
286
3.5625
4
class Solution(object): def countSubString(self, s): count = 0 for i in range(len(s)): for j in range(i+1,len(s)+1): if s[i:j] ==s[i:j][::-1]: count += 1 return count if __name__ == "__main__": s = Solution() str2 ="abc" print(s.countSubString(str2))
65b9ec3d91d2297b5c9b1391ebc7a4ac9057ab1c
1012378819/2020kingstar
/src/fun/func1.py
1,479
3.890625
4
def init(data): data['first']={} data['middle']={} data['last']={} def lookup(data,lable,name): return data[lable].get(name) def store(data,full_name): names=full_name.split() if len(names)==2: names.insert(1,'') lables=('first','middle','last') for lable,name in zip(lables,nam...
e8ebbfb45ea8455b488fe36bbede3b7bbb5bfae0
Rapha-Y/My_Python_Studies
/Basic_Python/NinthClass.py
1,264
3.578125
4
import shutil def write_file(text): path = 'C:/Users/Anni/Documents/Projects/My_Python_Studies/teste.txt' file = open(path, 'w') file.write(text) file.close() def update_file(file_name, text): file = open(file_name, 'a') file.write(text) file.close() def read_file(file_name): file = o...
e96219a0c2c5d06589d5e596bce1935b33145981
amangla20/CS550
/decimaltobinary.py
248
3.671875
4
import math import sys binarynum = sys.argv[1] def toDecimal(binarynum): i = 0 number = 0 binarynum = binarynum[::-1] for num in binarynum: number += int(num)*2**i i += 1 print(number) toDecimal(binarynum) # with 1101 should answer 13
96071bd6c69a7ed1e5fc2584f180d73bfefe9625
MegIvanova/PythonTesting
/PythonTests/TestingPython/PythonLab1Exercise11.py
304
3.6875
4
''' Created on Sep 8, 2015 @author: Meglena ''' #Python Program to Print all factorials Numbers in an Interval 0 to 20 def main(): f = 1 n = 0 for a in range (0,20): n += 1 f = f * n print(n,"! = ",f) main() # prints all factorials from 1 to 20
435f565922d1354cae3436e415f2830667defea7
ZhangRui111/MorvanRL
/02_Q_learning_maze/RL_brain.py
3,263
3.6875
4
""" This part of code is the Q learning brain, which is a brain of the agent. All decisions are made in here. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ """ import numpy as np import pandas as pd class QLearningTable: def __init__(self, actions, learning_rate=0.01, reward...
bb50e0c0a8f33699865edb9acec46429a2551a70
Karagul/Hierarchical-Portfolio-Construction
/Supplied code/CovarianceEstimator.py
3,235
3.671875
4
import numpy as np from random import random from scipy.interpolate import pchip_interpolate import matplotlib.pyplot as plt ##################### # STEP 1 # import the data ##################### # uncomment for a toy example #n=5 # problem size #A = 10*np.random.rand(n,n+3) # n stocks wit...
df4ae7d7d057e542b206cf15a4995b64718c8dbc
voicezyxzyx/python
/Exercise/面向对象/对象属性与类属性/动态给实例添加属性和方法并使用.py
693
3.75
4
from types import MethodType #创建一个空类 class Person(object): __slots__ = ("name","age","speak") per=Person() #动态添加属性,这体现了动态语言的特点(灵活) per.name="zyx" #动态添加方法 def say(self): print("my name is " +self.name) per.speak=MethodType(say,per) per.speak() #思考:如果我们想要限制实例的属性怎么办? #比如:只允许给对象添加name,age,height,weight属性 #解决:定义类的时...
836060c2af40adefaa9f526790dd112af3dc977e
kkemppi/TIE-courses
/Ohjelmointi 1/Ohjelmointi 1/alle 7. krs/kolmio.py
529
4.09375
4
# Johdatus ohjelmointiin # Introduction to programming # Mikko Kemppi, 272670, mikko.kemppi@tuni.fi # Area from math import sqrt def area(a, b, c): s = float((a + b + c)/2) ala = float(sqrt(s*(s - a)*(s - b)*(s - c))) return ala def main(): line1 = float(input("Enter the length of the first side: "...
ad35a773796f6ed21c283dfd257b0be69129fe9a
Abusagit/practise
/Stepik/dataStructures/traversls.py
4,537
3.671875
4
import sys class Node: def __init__(self, key, value, left=None, right=None, parent=None): self.key = key self.payload = value self.left = left self.right = right self.parent = parent class Tree: def __init__(self, n): self.root = None s...
2a381a40ced555a26802737a25b6a4d051a63176
alejandrogonzalvo/Python3_learning
/IES El Puig/for-range/eqsegundogrado2/eqsegundogrado.py
1,075
3.859375
4
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # Este programa genera numeros de forma pseudo aleatoria y los utiliza como valores para resolver una equación de segundo grado. import math import funciones as f import random as r import time as t coef = [] soluciones = [] for x in range(3): coe...
108f548024053725f59b0d97a375781a0ddda1fc
SyXo/InfoSecEngineering
/directory_buster.py
435
3.625
4
#Python dirb (Web Content Scanner) import requests site = input("Site name to scan: ") webReq = "http://www." + site + "/" wordlist = input("Wordlist to use: ") wordlistFile = open(wordlist, 'r') print("These paths returned an HTTP status code of 200:") for line in wordlistFile: line = line.strip() ...
f26ef8085fcea1c3c96ccb601b3f229ee33f15c0
huongtran196/Python_DataCamp
/Introduction to Python/list.py
1,482
4.09375
4
# Create a list # area variables hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # Create a list areas areas = [hall, kit, liv, bed, bath] print(areas) # Update the list house = [['hallway', hall], ['kitchen', kit], ['living room', liv], ['bedroom', bed], ['bathroom', ba...
1eb4e9372d0e34ae8f7ccaed52727d3f81013c40
mekhrimary/python3
/csvwriterandreader.py
2,145
4.5625
5
#!/usr/bin/env python3 # Write a comma separated value (CSV) file and then read it. def main(): """Write and read a comma separated value (CSV) file.""" persons = [('George', 'New York', 32), ('Eve', 'Boston', 29), ('Matt', 'Los Angeles', 26)] print('This program demonst...
2ac4aabc1359f50e2d2de5da511a7fe627b11570
superggn/myleetcode
/array/easy/53-maximum-subarray.py
549
3.921875
4
""" 去除边界条件 初始化cursum和res 更新cursum和res(全局最大子序列之和,就是max) """ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: if len(nums) == 0: return 0 res, current_sum = float('-inf'), float('-inf') for n in nums: current_sum = n ...
3910fd17e87e747a6a07771ec8682c0aee37322c
BParesh89/The_Modern_Python3_Bootcamp
/dictionaries/playlist_example.py
707
3.9375
4
# make a spotifyesque playlist using nested dicts and lists #my approach: playlist will be a dict, song list will be a list, each song will be a dict example1 = {"song_name": "cool boys", "song_artist/s": ["the boiz"], "duration": 2.3} example2 = {"song_name": "chilly billy", "song_artist/s": ["bill","chill"], "durat...
7d5906599387b55730106806ad0fa146ff7ba387
andregalvez79/Intro_to_Python
/2/chaptertrurtle.py
5,152
4.3125
4
#turtles import turtle # allows us to use the turtles library wn = turtle.Screen() # creates a graphics window alex = turtle.Turtle() # create a turtle named alex alex.forward(150) # tell alex to move forward by 150 units alex.left(90) # turn by 90 degrees alex.fo...
94a815ffa2e4a98ce36f8acc019bd4da6a1489e3
hotoku/samples
/python/pandas/iterate.py
298
4.15625
4
#!/usr/bin/env python """ 単純にiterateすると、列をなめる """ import pandas as pd df = pd.DataFrame(dict( x=range(3), y=range(3) )) for c in df: print(c) """ 行をなめたい場合はiterrowsを使う """ for r in df.iterrows(): print(r[0], r[1]["x"], r[1]["y"])
1159d141238837b0e607821c6756bbb362e46a10
mdagostino00/First-Integration-Project
/main.py
36,504
3.75
4
""" RPG Battle Sim for Integration Project This was originally a fighting game themed project, but I thought it was too limited in scope, so it's now an RPG themed project. This is a script that plays like an autoclicker with RPG elements. It uses python's tools to manage files, perform calculations, and present i...
ebca0c7654af2c383b50a3920e9292083d398957
eoriont/machine-learning
/src/graphs/node.py
734
3.640625
4
class Node: def __init__(self, index, value=0): self.index = index self.value = value self.neighbors = [] self.parent = None def set_value(self, value): self.value = value def set_parent(self, parent): self.parent = parent def set_neighbor(self, neighbo...
f04cf9e49d65696a94f156ab2f70e9ee2e3898e9
Aaron-cdx/py-codecode
/Leetcode117_FixTheNodeRightNode.py
1,175
4.03125
4
# -*- coding:utf-8 -*- """ @author caoduanxi @date 2020/9/28 10:27 Keep thinking, keep coding! """ class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next c...
fdafa0f0003012113288513d58fc9ee0de7d6f2b
timetobye/BOJ_Solution
/problem_solve_result/2947.py
327
3.59375
4
def bubble_sort(a): n = len(a) if n <= 1: return a for j in range(n - 1, 0, -1): for i in range(j): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] print(a[0], a[1], a[2], a[3], a[4]) return a n = list(map(int, input().split())) bubble_...