blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5709066b4cf1c38ad86be5c64ac6d66bb3f086d7
nathanielam0ah/homework
/projects/pythoninYminutes/section03.py
761
3.953125
4
#!/usr/bin/env python some_var = 5 #variable declaration #if statement if some_var > 10: print("bigger than 10") elif some_var < 10: print("less than 10") else: print("some_var is 10") #for loops for usernames in ["nathaniel", "nat7202", "nathanielam0ah"]: print("{0} is nathaniel" .format(username)) ...
293ec179ef52fb38f11fa349be3ac71924245bae
myfairladywenwen/cs5001
/lab10/pacman_starter/pacman_starter.pyde
3,302
3.75
4
WIDTH = 500 HEIGHT = 500 PACMAN_HEIGHT = 100 PACMAN_WIDTH = 100 SPEED = 3 x = WIDTH/2 y = HEIGHT/2 x_add = 0 y_add = 0 ANGLE_SPEED = 5 ROUND_ANGLE = 360 DOWN_START_EDGE = 90 UP_START_EDGE = 270 LEFT_START_EDGE = 180 RIGHT_START_EDGE = 0 start_edge = RIGHT_START_EDGE end_edge = ROUND_ANGLE curr_start = start_edge curr...
e6ebf1e480cf69d5ac5395b1127007c003dfc086
NavtejKahlon/chem160module9
/testcopy.py
231
3.546875
4
A = 2 print(A) B = A print(B) A = 5 print(B) print("========") A = [2,14,7] print(A) B = A print(B) A[0] = 5 print(B) print("========") import copy A = [2,14,7] print(A) B = copy.copy(A) print(B) A[0] = 5 print(B) print("========")
2fd284eb789b3e9853bc8599bfad24a102e8e726
khuyentran1401/Python-data-science-code-snippet
/code_snippets/pandas/get_data_in_year_range.py
458
3.640625
4
import pandas as pd from datetime import datetime df = pd.DataFrame({'date': [datetime(2018, 10, 1), datetime(2019, 10, 1), datetime(2020, 10, 1)], 'val': [1, 2, 3]}).set_index('date') print(df) """ val date 2018-10-0...
b4e38fcda870d8b866c955f13fb467509450df08
Just-silent/algorithm
/栈/二叉搜索树的后序遍历序列.py
1,065
3.65625
4
# -*- coding: utf-8 -*- # @Author : Just-silent # @time : 2021/1/29 10:03 class Solution: def VerifySquenceOfBST(self, sequence): if len(sequence)==0: return False else: return self.isbst(sequence) def isbst(self, sequence): if len(sequence)<=1: ...
68d7af12ac71837875942a7b3ecd4c5f0fe9a47b
Zuker-nie/marihacks
/1.py
335
4.1875
4
def IntInput(x,y): while True: try: print(y, end="") x= int(input()) except ValueError: continue if x >= 0: return x break else: continue value = IntInput(int, "Please enter a positive integer:") ...
cf4844f2766ce77f82e0898f31f2f69868a651d0
feddieminas/HackerRank
/Python/Quicksort_In-Place.py
1,267
4.15625
4
''' https://www.hackerrank.com/challenges/quicksort3 Quicksort_In-Place.py HacckerrankPy ''' ''' Solution. Fully accepted QSort Lomuto Partition ''' def swap(A,left,right): tmp=A[left] A[left]=A[right] A[right]=tmp def partition(A, start, end): pivot = A[end] pindex = start for i in range(st...
60c60e50c600faa65f90ae357a905c79f74ca31a
MohammadAsif206/Revature
/PyDay3/lambda.py
287
3.828125
4
# a lambda is an anonymous function #() =?{} # popular in funcitonal programming def multiply_10(n): return n*10 num = [1,2,3,4,5,6] result = map(lambda n : n*10, num) for r in result: print(r) # lambdas are Nowhere near as common or useful in py as in other languages like JS
1daf51f82a7ecbe6c96406803735939cc43c54f4
sky7sea/KDD_Daily_LeetCoding_Challenge
/0412-0418 (Week_3)/RobertHan/283. Move Zeroes/solution.py
1,015
3.859375
4
# 283. Move Zeroes # https://leetcode.com/problems/move-zeroes/ """ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Ex) 1 Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] ...
20bcd5891add7d5be7f3ce260535e3a1fa644381
duran221/curso_python
/22.Excepciones-Finaly/excepciones.py
1,254
4.09375
4
def divide(): try: num1= int(input("Ingrese un numero: ")) num2= int(input("Ingrese un numero: ")) print("El resultado de la division es: "+str(num1/num2)) #Es posible anidar una o mas excepciones para encerrar los distintos errores que se pueda producir except ValueError: ...
c4d76a1632ad67e91a8c3e6d3a8e88e3a5576c94
Make7UpYours/Code-Portfolio
/Spring 2013/Python/Subtotal Program.py
1,347
4.09375
4
##CS 101 ##Program 1 ##William Freeman ##wjfkc2@mail.umkc.edu ## ##PROBLEM: Ask the user for the subtotal of a purchase, and for the tax rate. ## Compute and print the total. ## ##ALGORITHM: ## 1. Prompt input from user for the subtotal and the tax rate ## (as a percentage) of a purchase. ## 2. Conver...
d31a39b17aa87c7aab2cc6e9e504e1b3e30446d6
stin2289/PythonExamples
/fibonacci_09_28_18.py
506
4.09375
4
class Fibonacci(): def fib_recursive(self,n): if n == 0 or n == 1: return n return self.fib_recursive(n-2) + self.fib_recursive(n-1) def fib_iterative(self,n): if n == 0 or n == 1: return n fib_array = [0,1] for i in range(2,n+1): fib_array.append(fib_array[i-1]+fib_array[i-2]) return fib_arr...
58216182d167441944c73f01cfa80f28e5166ce3
UcheEneh/q_a_dmnn
/model.py
19,732
3.59375
4
import tensorflow as tf # import util # import data # import numpy as np """ The network is designed around having a recurrent layer's memory be set dynamically, based on other information in the text, hence the name dynamic memory network (DMN). The person gets a chance, first of all, to read the context and create...
46feb07c777b1741c87ef25f24f2f2fc08334a8d
danbi5228/DataItGirls
/python_basic/pybasic_0922.py
581
4.03125
4
# 두 수를 더하는 함수 def add(a, b): return a+b # 두 수를 곱하는 함수 def mul(a, b): return a*b # 두 수를 더한 값과 곱한 값을 같이 리턴하는 함수 def add_and_mul(a, b): # def add_and mul(a, b = 0) 과 같이 디폴트값을 설정할 수 있다. # 디폴드 파라미터 뒤에 non-default 값이 올 수 없다. return add(a, b), mul(a, b) print(add_and_mul(3, 5)) # print(add_and_mul...
015bf000fb4c55eea6940c538347505f33013be9
PoojaR24/Linked-List-1
/reverselinkedlist.py
1,336
4.0625
4
#time complexity O(n) #Space Complexity O(1) #both approach tried on leetcode and accepted #iterative class Solution: def reverseList(self, head: ListNode) -> ListNode: #Initialize previous node as none prev_node = None #initialise current node as head curr_node = head while...
e1b18ce30e6d1ab79cc166e231df878cff292e97
PXMYH/ds_algo
/601-700/657.py
2,991
4.09375
4
# 657. Robot Return to Origin # There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. # The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves ar...
f1c9f39fca1a01e13d8117e8c6bbf0f8b4982737
KJSui/leetcode-2020
/triaggle.py
568
3.53125
4
class Solution: def triaggle(self, triag): rowLength = len(triag) for i in range(rowLength-2, -1, -1): for j in range(i+1): triag[i][j] += min(triag[i+1][j], triag[i+1][j+1]) if triag[i+1][j] < triag[i+1][j+1]: print("row: ", i, "col: "...
2f91c9dbe2990f3f4d9870ceaf9f8573e526ccde
ismailtuncel35/PYTHON
/pythonda sözlük.py
1,012
3.6875
4
#key - value ##41 => kocaeli 35 => izmir sehirler=['kocaeli','izmir'] plakalar=[41,35] print(plakalar[sehirler.index('izmir')]) #print(plakalar['kocaeli])=>41 #prin(plakalalar['izmir])=>35 plakalar={'kocaeli':41,'izmir':35} print(plakalar['kocaeli']) print(plakalar['izmir']) plakalar['ankara']=6 prin...
62e1331579e368af288425d610e589872d549b23
massey-high-school/91883-4-assessment-Wrightl71559
/09_full_game_v1.py
3,386
3.96875
4
# Full game # put together all components and make sure it works as expected (debug accordingly) # imports random import random # integer checking function def intcheck(question, low, high): valid = False error = "Please enter an integer" while not valid: try: response = int(input(ques...
ebac23a592186a8cbdc52f2a5e82740008666ea7
botprophet/aiops-data-collector
/custom_parser/tar_gz_csv.py
686
3.71875
4
import tarfile from itertools import chain import pandas as pd def csv_parser(filename): """Extract CSV data from TAR.GZ file. Extracts all CSV files from a TAR.GZ archive and combines them into a list of dictionary objects. :param filename: Name of the filename to parse """ entries = list() ...
b6f9c79d868b19dd416b9a7c76f7d7f6511e0c64
AshishMaheshwari5959/InfyTQ
/Programming Fundamentals using Python/Day 7/Assignments/Assignment 50: Mandatory Assignment (puzzle) - Level 3.py
1,410
4.1875
4
''' Write python function, sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence. Rules are as follows: a. Spaces are to be retained as is b. Each word should be encoded separ#PF-Assgn-50 def sms_encoding(data): #start writing y...
7d5b045b9dcda4ebb7a5751d24a6673ea27d68a2
LittleRichard/learntocode
/python101/008_while_loops.py
2,279
4.375
4
import random # a for loop runs over a finite set of values, # but what if we aren't sure when we want to stop? # the while loop runs until a boolean expression is met, x = 0 while x < 5: # equivalent to: # `x = x + 1` x += 1 print(f'while x < 5: {x}') # maybe a better example total = 0 while total <...
765f34bbef1d8ed436721ffc31420178c865a83b
SergeiLSL/PYTHON-cribe
/Глава 2. Основы Python/Раздел 1. Переменные и типы данных/Переменные и типы данных.py
5,401
3.8125
4
""" Переменные и типы данных """ """ Переменная хранит определенные данные. Название переменной в Python должно начинаться с алфавитного символа или со знака подчеркивания и может содержать алфавитно-цифровые символы и знак подчеркивания. И кроме того, название переменной не должно совпадать с названием ключевых сл...
1f92c9c9f53f01f14c581ebea46d8422439851df
Anirudhsh/Python3challenges
/problem3.py
280
3.953125
4
#Let there Be a list adhoc adhoc=[1,2,3,1,4,5,66,22,2,6,0,9] li1=[] li2=[] for i in adhoc: if i<=2: li1.append(i) elif i>5: li2.append(i) print("values less than or equal to 2:\n") print(li1) print("\nvalues greater than 5:\n") print(li2)
ff4d558323067a1c6b1f17a3819384f06722dbb6
mikhilnagarale/PythonTricks
/PythonIteration.py
405
3.796875
4
#Ref:https://www.programiz.com/python-programming/iterator class PowTwo: def __init__(self,max=0): self.max=max def __iter__(self): self.n=0 return self def __next__(self): if self.n<=self.max: result=2**self.n self.n +=1 return result ...
56b318d59d7934422241176ec6ddd6f9c713eff9
RevantMakkena/python_challenges
/A7_series/series_2.py
319
3.625
4
from typing import List def slices(series: str, length: int) -> List[str]: """Output all the contiguous substrings of length n in series.""" if length > len(series) or length <= 0: raise ValueError(f"Error Length: {length}") return [series[i:i + length] for i in range(len(series) - length + 1)]
f99dd7a8fec35a47eab0a0aeb76553e09a48d9d5
yogprabhu/ga-learner-dsmp-repo
/SPY_GAME/code.py
2,270
3.546875
4
# -------------- ##File path for the file file_path #Code starts here def read_file(path): fp = open(file_path, 'r') sentence = str(fp.readline()) fp.close() return sentence sample_message = str(read_file(file_path)) print(sample_message) # -------------- #Code starts here f1 = file_pa...
a68227c6d9840b3aff590266be1f57771f3b13c5
andrewsonin/4sem2
/H_advertisment.py
214
3.546875
4
def maximize(length, element): summa, element = 0, sorted(element)[length//2:] for obj in element: summa += obj return summa print(maximize(int(input()), list(map(int, input().split()))))
3ec955d889fa8e6c3234ad2688557337c1988221
g-boscaro/RemovedorDeBarrasPretas2000
/GUI/Testes/tkCommand.py
246
3.859375
4
import tkinter as tk #Janela principal janela = tk.Tk() #Label label = tk.Label(text = "Hello") #Pega o valor texto do label texto = label["text"] print(texto) #Muda o valor do label label["text"] = "Good Bye" label.pack() janela.mainloop()
7a660d8215bb1070f4c3e4bc6132a6dfdbf179a2
HenryFilho/Tamburetei
/prog1/implementacoes/sortingAlgorithms.py
5,010
3.5625
4
# coding: utf-8 import random #======================================================================# # Algoritmos de ordenação # #======================================================================# # Frequentemente quando se trabalha com estruturas de dados (como por ...
ba3889c187a824c8c47a0a96fbdc1a68d84c9b09
glmanhtu/3stages
/demonstration/utils/fps.py
967
3.546875
4
# import the necessary packages import datetime class FPS: def __init__(self, max_frames=30): # store the start time, end time, and total number of frames # that were examined between the start and end intervals self._start = None self._end = None self._numFrames = 0 self._max_frames = max_frames self....
652fe49d11f5fb18e15cbad5085f680d3aed13a0
ddxygq/PyCode
/Python基础语法/面向对象/senior_object.py
579
3.875
4
# 面向对象高级 class Teacher(object): # 限制该类能动态添加的属性 __slots__ = ('name', 'age') pass def set_name(self, name): self.name = name def set_age(self, age): self.age = age if __name__ == '__main__': teacher = Teacher() # 给实例绑定方法 from types import MethodType teacher.set_name = MethodTy...
cf222c0b60691fef462239612f77caa893989f84
thaynarbo/python-exercises
/aula 09 -18.06/exercicio02.py
2,371
4.375
4
# #01 - Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com essa formatação: # [ 1 ][ 2 ][ 3 ] # [ 4 ][ 5 ][ 6 ] # [ 7 ][ 8 ][ 9 ] # linha_1 = input("Linha 1: Escreva 3 números separados por espaço").split() # lin...
37106f6add6f7b6aef56f47fdeaabed58461316c
rajat1293/ALL_PROGRAMS
/python/pylabb3.py
667
3.515625
4
principal = 10000 #initial investment interestRate = 0.05 years = 20 values = [] for i in range(years + 1): values.append(principal) principal += principal*interestRate pylab.plot(range(years+1), values,'ro',linewidth=21)# (to change color of line to red # and 'o'to use dots instead of line) pylab.title('5% Gro...
11f48d14ae995804c0bab79109226d097520f2e3
hasanahmvd/CS1026B
/Assignment1/sahme339_Assign1.py
1,662
4.09375
4
# This program computes the reward of a carnival game where a toonie is tossed and reward is given if it does not lands on a line from random import random # import random so random number can be generated later #Ask user for distance and reward and store as float variables distance = float(input("Please enter the di...
96b9bc1a0a4166b4c68edcb14b954ce0cdf6db68
MarcelinoChagas/Python
/IntroducaoPython/05_Cap/Exercicios/57_Exercicio.py
234
3.859375
4
n = int(input("Tabuada de : ")) inicio = int(input("Digite o número de inicio da tabuada: ")) fim = int(input("Digite o número fim da tabuada: ")) while inicio <= fim: print(n,"x",inicio,"=",(n*inicio)) inicio = inicio + 1
019dea3af005f6d57fb0b6d3da60e2a553656701
chengshifan/LeetCode
/74-search-a-2d-matrix/Solution.py
330
3.734375
4
from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for nums in matrix: if not nums: continue if nums[-1] < target: continue else: return target in nums ret...
4ea9881480c137dae45f712dfd4b4b45354b98d4
DDUDDI/mycode1
/0518/divide.py
663
3.796875
4
# 키보드에서 두 수를 받아서 앞의 수를 뒤의 수로 나눗셈을 하고 그 결과식을 화면에 표시한다. # 만약에 이용자가 뒤의 수를 0으로 입력한다면 어떤 오류가 발생하는지 확인하고 오류를 해결해보세요. while True: nums = input('나눗셈할 두 수를 입력하세요: ') divide = nums.split() num1 = int(divide[0]) num2 = int(divide[1]) try: msg = f'{num1} / {num2} = {num1/num2}' except ZeroDivisio...
84de2529806c46e6d29cc4c870f792a4b1466123
stefanvangastel/adventofcode2020
/day3/day3.py
1,600
4
4
# Read file lines into lines var with open('input.txt', 'r') as inputFile: lines = inputFile.readlines() # Check lines (height) height = len(lines) # # Define function for travel # def gimmeTrees( pattern: dict ): # Create a full map (matrix for this pattern) mapz = [] # Duplicate initial map until lin...
8ac582f8642aed4838bf9b14ad8b9d234fdca34b
jisooj/AMU-ML-2018-1Q
/DecisionTree/CarInfo.py
1,952
3.5625
4
# CarInfo class which represents single car info with 7 diff attributes class CarInfo: # Car info input file format: # 1. mpg: continuous <-- this one is going to be used to determine label # 2. cylinders: multi-valued discrete # 3. displacement: continuous # 4. horsepower: continuous ...
6af2e1181b307a8cc6ec7e23a7b9a8f5a4751b43
R5D4/dark_forest
/items.py
2,590
3.609375
4
""" Contains the Item class and its subclasses (Weapon, Armor) Contains functions to randomly generate an item. """ import data.weapon_data as wd import data.armor_data as ad from random import choice import combat # items types # 'weapon' # 'armor' # 'consummable' ########## CLASS DEFINITIONS ########## class It...
45567e985fe7d534933b9c968f4373f3273bdc7d
dxv2k/CS338_Pattern_Recognition
/kmeans/src/kmeans.py
6,572
3.921875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import random # NOTICE: This K_means only expected numberical dataset # Steps: # 1. Random selection of centroids # 2. Calculate distance to each point and assign each point to cluster # 3. Calculate AVG of the assigned points and move # c...
8f77347276b5315a5b1757c3214d2c4276a55c95
adityawebdev/Turtle-Projects
/heart.py
471
3.78125
4
from turtle import * def draw(x,y): penup() goto(x, y) pendown() speed(5) pensize(5) draw(-260 , -100) pensize(30) left(90) forward(200) left(90) forward(40) backward(80) draw(-260 , -100) forward(40) backward(80) draw(-40 , -100) color("red") pensize(5) begin_fill() right(130) forward(150) circle(60 , 200) lef...
577e3e1eb9aad894796d1def8cc9cd531e549a73
ississ0/PythonWebProject
/OC_1206/function1.py
591
3.65625
4
#이 함수는 두 개의 숫자 재료를 건네 받아 곱한 값과 나눈 값을 고객에게 리턴해준다. def multiplyAndDivide(a,b): multiplyResult = a*b divideResult=a/b return multiplyResult, divideResult result=multiplyAndDivide(12,6) #여러개의 값을 Return하는 함수는 tuple 형태의 값을 돌려준다. print(type(result)) print(result[0]) print(result[1]) #함수를 호출할 때, 재료를 차례대로 넣을 수도 있지...
fd818e5cd4786df5c01bcef62ca60fa1d3a8b173
KevinChen1994/leetcode-algorithm
/top100/399.py
1,760
3.515625
4
# !usr/bin/env python # -*- coding:utf-8 _*- # author:chenmeng # datetime:2020/5/13 17:02 ''' solution1: 图+dfs。先构建一个图,图的结构是graph[x][y]=v,那么就是x/y=v。然后通过dfs进行递归遍历图,最终的结果是图上路径的乘积。看一下注释就清楚了。 ''' class Solution: def calcEquation(self, equations, values, queries): graph = {} for (x, y), v in zip(equatio...
f610ab948c1ae9227aa13061c365abe8ad5b544f
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/mtrdud001/question4.py
473
4
4
def palindrome(starting, finishing): for j in range(starting+1,finishing): if str(j) == str(j)[::-1]: if j == 2: print(j) for i in range(2,j): rem = j%i if rem ==0: break if i == j-1: print(j) input1 = eval(input...
0b752b8a1458f0cc1dff27501322d1ec23bb6091
aimanaijaz/movietrailers
/media.py
803
3.78125
4
import webbrowser class Movie(): """ This class provides a way to store movie related information """ def __init__(self, movie_title, movie_storyline, movie_starring, movie_release_date, poster_image, trailer_youtube): """ Stores movie information when an instance of the class Movie is initialized ""...
de9cab1c02f5c9f534b440fd8ee9f1c41a6418ef
PanPapag/A-Complete-Python-Guide-For-Beginners
/Classes_and_Inheritance/Inheritance/super.py
2,302
3.8125
4
from random import randrange # Here's the original Pet class class Pet(): boredom_decrement = 4 hunger_decrement = 6 boredom_threshold = 5 hunger_threshold = 10 sounds = ['Mrrp'] def __init__(self, name = "Kitty"): self.name = name self.hunger = randrange(self.hunger_threshold) ...
7fdd1415be8837455205d978a942dae7fd5aabe2
tony89824396/Udacity-CS101
/lesson14/Antisymmetric Square.py
635
3.671875
4
def antisymmetric(a): compare1=[] compare2=[] # [] null is True if a==[]: return True # check if it's nxn square or not. if not len(a)==len(a[0]): return False for i in range(0,len(a)): temp=[] for j in range(0,len(a)): b=a[i][j] temp.a...
ded2bb81b4a63a74ebf89d2129dd67a999d32e45
yogesh371/SDP_Python_Day2
/task_2.py
187
4.03125
4
# WAP To cal factorial of any number 5!=120 n = int(input("Enter the number: ")) fact = 1 for i in range (1,n+1): fact = fact * i print("The factorial of a given number is: ",fact)
b4a2f926b7cb1d11ce3ed9d21b442e9155ff36bb
danishkkmeppayur/pythondjango
/luminarpythonprgms/LUMINAR/LOOPING/lower&upperlimit.py
143
4.0625
4
lower=int(input("enter lower limit")) upper=int(input("enter upper limit")) while(upper>=lower): print(upper) upper=upper-1
bfd4d3b1cf96d8bae76bf9755e4c5b569e267f5b
harshjoeyit/BJP
/Python/test.py
1,358
4.28125
4
# .......................sorted function in python # vowels list py_list = ['e', 'a', 'u', 'o', 'i'] print(sorted(py_list)) # string py_string = 'Python' print(sorted(py_string)) # vowels tuple py_tuple = ('e', 'a', 'u', 'o', 'i') print(sorted(py_tuple, reverse = True)) names = ["harshit", "tim", "savvy", "ke...
0dbc966ebad90fa079f3787ecb4530d13417dfa1
Amnx404/minesweeper
/original code/bomb_single.py
1,202
3.703125
4
import random def minesweeper(n): """add bombs randomly in the grid and update the numbers around it""" arr = [[0 for row in range(n)] for column in range(n)] x = random.randint(0,4) y = random.randint(0,4) arr[y][x] = 'X' if (x >= 1 and x <= 3): arr[y][x+1] += 1 # center right ...
b7e48aa76d0ce274653a0ee73f05d73d3d887131
cmdelcarmen/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
358
4.25
4
#!/usr/bin/python3 '''prints a square''' def print_square(size): '''prints a square''' if not type(size) is int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for count in range(0, size): for count2 in range(0, size): ...
436acbd59a014582f33798af21f49895e9a25e91
uoojin1/algo_study
/Facebook/best_time_to_buy_and_sell_stock.py
737
4.09375
4
''' best time to buy and sell stock say you have an array for which the ith element is the price of a given stock on day i if you were only permitted to complete at most one transaction, buy one and sell one share design an algorithm to find the maximum profit * you cannot sell stock before you buy one ex) [7,1,5,3...
5a79a8bc4ae3b1ec3c1c401ceb28482e118835ce
JoseChavez98/Competitive-Programing
/coinChange.py
387
3.890625
4
def coinChange(array,amount): table = [0 for k in range(amount+1)] table[0] = 1 for i in range(0,len(array)): for j in range(array[i],amount+1): table[j] += table[j-array[i]] return table[amount] # array = [1,5] array = [1,2,3] # amount = 6 amount=4 print(coinChan...
31636dfc22bea92c5b8a6ac14cca88a20f2146b5
estebansolo/PythonScripts
/platzi_coding_challenge/04_repeat_the_word.py
484
4.375
4
def repeat_recursion(word, times): if times == 0: return "" return word + repeat_recursion(word, times - 1) def main(): word = input("Add the word you want to repeat: ") n_times = int(input("How many times you want to repeat the word? ")) repeated_word = repeat_recursion(word, n_times) ...
1806ae5978daf095e32c979991c23875bf9e06d0
cafaray/atco.de-fights
/isSum.py
434
3.671875
4
def isSum(value): s = 0 for x in range(0,value+1): s += x if s == value: return True elif s > value: return False return False def isSum_optimized(value): s,x=0,0 while s<value: x+=1 s+=x if s==value:return True return Fal...
2d7eae50bde8d51b0e4ea860620809ec72d6e02a
jaCod3r/Thinkful
/prob.py
1,295
3.828125
4
""" Write a script called "prob.py" that outputs frequencies, as well as creates and saves a boxplot, a histogram, and a QQ-plot for the data in this lesson. Make sure your plots have names that are reasonably descriptive. Push your code to GitHub and enter the link below. """ import numpy as np import scipy.stats as ...
4b35e0995ca8cf30f02299965b0ecc8c72b98cbd
mtakamichi/ProjectEuler
/Python/Problem_017.py
1,261
3.609375
4
#!/usr/bin/env,python3 #,-*-,coding:,utf-8,-*- ''' Problem 17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be use...
4db26422ff95965655475251339a8e7d35f447bf
lead-techs/python_util
/Util/Practice/D1.py
355
3.5625
4
#题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? count=0 num=[1,2,3,4] for i in range(1,5): for j in range(1,5): for k in range(1,5): if i!=j and i!=k and j!=k: print(i*100+j*10+k) count=count+1 print("the total number is ",count)
82bc2c82433201f9781cecf97c4d2722dfa09714
Wanderson-A-Timoteo/Transferir-arquivo-python
/servidor.py
1,288
4.03125
4
import socket ## Inportação do socket que irá permitir as conexões s = socket.socket() ## Atribui "s" para o socket criar o objeto host = socket.gethostname() ## host recebe o endereço do programa port = 8080 ## Definido a porta 8080, mas poderia ser qualquer outra que você queira. s.bind((host, port)) ## Ligação...
9684884b5648eb46851c67085f5cb50ddcc8f914
peistop/Leetcode
/accept/383.RansomNote.py
1,126
3.859375
4
""" 383. Ransom Note https://leetcode.com/problems/ransom-note/ Easy: 83.82% Testcase Example: "a"\n"b" Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it...
50d980a78d81d652362b744d9b08c7dbbab8b262
amansar/Practice-Problems
/balanceBST.py
696
3.84375
4
Program takes array as input and inserts elements in to a BST in a way that the tree is balaned and height is minimal def balance(arr, middle, left, right): if(len(arr) == 1): toReturnNode = BSTNode(arr[0]) return toReturnNode else: middle = len(arr)/2 left = middle - 1 right = middle + 1 r...
b4fd522485319776d61720a419ac491cba50c6d6
allisgao/pcc-study
/Section1_Getting_started/Chapter8/8-12_sandwich.py
274
3.6875
4
#! python3 def make_sandwich(*toppings): print("\nMaking a sandwich need such toppings:") for topping in toppings: print(" - %s" % topping) make_sandwich('eggs') make_sandwich('apple', 'orange', 'peal') make_sandwich('chicken', 'milk', 'cheese', 'beckon')
2b67c3b9e65909399d35c36f143af1d99ea3b292
GrupoC-TM/GrupoC-TM
/Proyecto/INARI.py
48,030
3.5
4
#La sintaxis del import varia segun la version de Tkinter/Python """Tener en cuenta!!!,el programa no da errores pero si se produce error de coneccion de base de datos o de imagen no encontrada, puede ser la version de linux, en este caso debe colocar el archivo .db y la imagen en la carpeta Documentos de su pc...
b28438cd2b152ef4022b35a5528cb52053288cee
CanadianCaleb/SortingAlgorithms
/ReverseInsertionSort.py
1,658
3.765625
4
import time import random from os import system, name def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') clear() fWrite = open("nums.txt", "w+") fRead = open("nums.txt", "r") randNums = [] avTime = [] avRunTime = [] runAverage = [] greatestTime = 0 leastTim...
9c5e88298fdee87e8ff99c79073bf2ab168741d1
jbhennes/CSCI-220-Programming-1
/Chapter 10 Class/die1.py
696
3.5625
4
#Create a die from random import randint MIN = 1 MAX = 6 class Die: #Set the initial value for all attributes def __init__(self): #default constructor self.faceValue = 1 ## def __init__(self, value): ## self.faceValue = 1 ## self.setFaceValue(value) #### if value ...
2b7a5382b13d29847d832dc0371fb7eb7b6d2e82
CaizhiXu/LeetCode-Solutions-Python-Weimin
/0044. Wildcard Matching.py
1,676
3.75
4
# method 2, recursion with memo, time O(m*n) class Solution(object): def isMatch(s, p): self.memo = set() return self.isMatchHelper(s, p, 0, 0) def isMatchHelper(self, s, p, i, j): if j == len(p): return i == len(s) if (i, j) in self.memo: return Fals...
eb188aa26a5387fdeda5fc1f32cb3520d3e7d736
mannhuynh/Python-Codes
/python_codecademy/physics_class.py
3,028
4.375
4
""" You are a physics teacher preparing for the upcoming semester. You want to provide your students with some functions that will help them calculate some fundamental physical properties. """ # Write a function called f_to_c that takes an input f_temp, a temperature in Fahrenheit, and converts it to c_temp, that te...
342504a8d9574743141553b8b1121178ca109081
namanagr/Competitive-Programming-in-Python
/nk-python/6-trees/15.no_of_full_nodes_recursion.py
670
4.3125
4
#!/usr/bin/python # Author: Naman Agrawal # This program finds the number of full nodes in a binary tree using recursion import Queue class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def number_of_full_nodes(root): if not root: return ...
da80b270d96b4f7377c31610ab58fffc818dfa8e
dhbans/Python_Dev
/sqllite_tutorial/db_fetch.py
343
3.703125
4
import sqlite3 conn = sqlite3.connect('Training_DHruv11.db') c = conn.cursor() c.execute("SELECT * FROM EmpData") # this while give one entry base on cursor print(c.fetchone()) # this will give user define size row entries from current cursor position print(c.fetchmany(2)) # this will give all entries base on curs...
fa1cf3705443352076d114e1531cd863f0dd1ed5
1414003104/OldSheep_TensorFLow2.0_note
/4,Tensorflow常用函数/tf.nn.softmax.py
616
3.578125
4
#柔性最大值:使其具有统计数据特性 #用指数,因为得分可能为负,即该分类基本不可能,指数能满足这要求 #当n分类的n个输出(y0,y1,....yn-1)通过softmax()函数,便符合概率分布了。 #softmax用于多分类过程中,它将多个神经元的输出,映射到(0,1)区间内,可以看成概率来理解,从而来进行多分类! import tensorflow as tf y=tf.constant([1.01,2.01,-0.66])#三个值为前向传播结果 y_pro=tf.nn.softmax(y) print(y_pro) #输出的是每个输出值变为0到1之间的概率值,概率和为1
2172dbab0fca4789050019c680436945daaa3b61
AnaTrzeciak/Curso_Python
/3-Looping/break_continue.py
1,320
3.96875
4
#ecoding:utf-8 #================================================================ #While + Else #while TESTE: # codigo # codigo # ... #else: # codigo # ... #Enquanto o TESTE for verdadeiro, ele roda o código dentro do WHILE.Quando a condição vira falso, e não se usa uma instrução BREAK, o código do ELS...
ebd623dcfee72659bbf059f8e57392f964fa97e7
sunrain0707/python_exercise_100
/ex52.py
124
3.65625
4
#52.学习使用按位或 | a = 0x77 print(a) b = a | 3 print ('a | b is %d' % b) b |= 7 print ('a | b is %d' % b)
710851ecfaa649429e091e18e005a590fe23e4ef
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/3670.py
678
3.65625
4
def is_tidy(n): n = str(n) tidy = True previous = '0' for digit in n: if digit < previous: return False previous = digit return True def last_tidy(n): for i in range(n,0,-1): if is_tidy(i): return i def solve_file(file_path): f = open(file_pa...
d096787b365cd47fb718fe02573719c3e273edbb
sabrinsingh/Python
/21_2_comprehensionlist.py
870
4.03125
4
my_list=['x','y','z'] print(my_list) result=[x for x in my_list] print(result) # How it works result=[] for x in my_list: result.append(x) print(result) result = [x*i for x in my_list for i in range(1,4)] print(result) # How it works result=[] for x in my_list: for i in range(1,4): result.appen...
1e05d566b66431326fa5001acb3e3daeed8b8a5d
I-browz/csp1718
/GUI-Project/Choose your own adventure.py
1,989
3.84375
4
#Dice Sim/ Choose own adventure # Nathan.B_Keaton.C from Tkinter import * #don't import like this except for Tkinter root = Tk() #create main window # Make and place a canvas widget for events and drawing canvas = Canvas(root, height=600, width=600, relief=RAISED, bg='white') canvas.grid...
334293e6b5eaf3273b740f9b24d454531d27e366
ucsb-cs8/python-text-files
/countLines.py
388
4
4
#!/usr/bin/env python3 import sys if len(sys.argv)<2: print(""" Please supply a filename when you run this file For example: python3 {0} input.txt python3 {0} nums.txt """.format(sys.argv[0])) sys.exit(1) filename = sys.argv[1] with open("nums.txt","r") as infile: linecount = 0 for line i...
02f83da16ff3445b8d2776f3db483110aff7b4a0
sptechguru/Python-Core-Basics-Programs
/string.py
222
3.9375
4
mystr = "Santosh is good Boy" # print(len(mystr)) # # print(mystr[10]) print(mystr.upper()) print(mystr.lower()) print(mystr.count("0")) print(mystr.find("is")) print(mystr.capitalize()) print(mystr.replace("is" ,"are"))
a6a33e1e5d0ae74504014ed2e8f3be331a6d8503
raffipython/intro
/3-4.py
159
3.828125
4
# Start the program print("How old are you?") age = int(input()) if age >= 18: print("Go vote!") else: print("Sorry, not yet") # End the program
71eaf58669e2e9a160b5967649cb2602875a8386
Kumar1998/github-upload
/scratch_13.py
336
4.1875
4
#python code to demonstrate the working of zip() name=["Karan","Pratik","Justin","Mark"] roll_no=[4,2,3,6] marks=[60,89,97,76] #using zip() to map values mapped=zip(name,roll_no,marks) #converting values to print as set mapped=set(mapped) #printing resultant values print("This zipped result is:",end="") ...
d84a250ed0732694a72d9a5fe3ca887dd72bd127
padre-lab-eu/pypadre
/pypadre/core/util/inheritance.py
580
3.515625
4
class SuperStop: """ TODO this class resolves the issue TypeError: object.__init__() takes exactly one argument by being the last class in a mro and ommitting all arguments. This should be always last in the mro()! """ def __init__(self, *args, **kwargs): mro = self.__class__.mro() ...
fbfa9b84b9f148a784d85fbd7cefddbb1710b500
captainhcg/leetcode-in-py-and-go
/captainhcg/py/257-binary-tree-paths.py
662
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): self.ret = [] self.helper(root, []...
bd2f4df1decb60861bc453f421d6de0d32c0a41c
ThibautPicart/TkInter-Piano
/Utils/listes.py
2,123
3.546875
4
import sys # print("Your platform is : " ,sys.platform) major=sys.version_info.major minor=sys.version_info.minor # print("Your python version is : ",major,minor) if major==2 and minor==7 : import Tkinter as tk import tkFileDialog as filedialog elif major==3 and minor==6 : import tkinter as tk from tkin...
2346411e77298813e050abbb1d80d0fa25a663df
Muhammad-huzaifa18/LAB-05_HOME-TASK
/lab 05 q3.py
612
4.125
4
print("Muhammad Huzaifa") print("18B-048-CS-A") print("LAB 05 PROGRAMMING EXERCISE") print("Question 3") def arithmetic_sequence(): n = int(input("Please enter the number of the term you want to find: ")) a= int(input("Please enter the first term: ")) d= int(input("Please enter the common differenc...
57c6471f2a518768befe39648b6c399c93de111d
crizzy9/Algos
/leetcode/tree_from_inorder_preorder.py
1,334
3.90625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return "{}->({}, {})".format(self.val, self.left, self.right) class Solution: def buildTree(self, preorder, inorder): """...
ebddbb97d3835d23324bfcebc19718215b8167c2
Hr09/Python_code
/Bubble sort.py
681
3.6875
4
import random as r num_list=[] for i in range(5): num_list.append(r.randrange(1,9)) i =len(num_list)-1 for k in num_list: print(k, end="") print() while i>1: j=0 while j<i: print(":\n Is {}>{}".format(num_list[j],num_list[j+1])) print() if num_list[j]>num_list[j+1]...
cf2464b00b71b97b8dd79760f6970de4af6d1a75
BJV-git/leetcode
/math/sum_of_squares.py
283
3.515625
4
# logic: go until can find the numebrs till n # again see if we can find the number of sum def ifsq(n): seen = set() i=1 while i**2 <n : target = n - (i**2) if target in seen: return True seen.add(i**2) i+=1 return False
dacc604c86d91d8b2f00742cdbf02671a804d54c
kamrandar/Word-Sense-Disambiguation-Lesk-Algorithm-NLP
/lesk4.py
1,582
3.5
4
from nltk.corpus import wordnet from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(r'\w+') import sys stop_words = set(line.strip() for line in open('stopwords.txt')) def simplified_lesk( word, sentence ): final = None maxoverlap = 0 word=wordnet.morphy(word) print("Total senses ar...
72015fd0dd902480618b2cec66c58e793c7e4f71
p-enel/PyReservoir
/PyReservoir/learning/testing.py
8,586
3.78125
4
#-*-coding: utf-8-*- ''' Created on 7 sept. 2012 @author: pierre ''' import random import numpy as np def cross_validation_indices(nbTrialsPerClass, nbTrialsUsed=None, nbValidationTrialsPerClass=1): '''Generate the indices that point to the trials in a dat...
9c5410ea522d1b8230a94448f823f6a901294dd8
applicationsbypaul/Module7
/test_collections/test_basic_list_exception.py
1,237
3.671875
4
""" Program: test_basic_list_exception.py Author: Paul Ford Last date modified: 06/21/2020 Purpose: Test range of 1-50 """ import unittest from unittest.mock import patch from fun_with_collections.basic_list_exception import make_list class TestList(unittest.TestCase): @patch('fun_with_collections.basic_list_ex...
4600dcf04871f41e043dcbf53ecb7f3a0fa2a62d
bptfreitas/Project-Euler
/problema42.py
1,622
3.921875
4
#!/usr/bin/python #We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. #What is the largest n-digit pandigital prime that exists? import euler import string from euler import is_pandigital from euler i...
85b39324a5fd18618aa2acb8dbf2ccb7dd831449
gilberto-009199/MyPython
/Tec.Program.I/ACS/5 AC/1/main.py
555
3.734375
4
# Escreva a funcao media_pares_impares(lista) abaixo: def media_pares_impares(list): sumPar = 0; itemPar= 0; sumImP = 0; itemImP= 0; for item in list: if item % 2 == 0 : sumPar += item; itemPar += 1; elif item > 0: sumImP += item; ite...
d81485bb21b2d37e49a2d5147ad683cd4b3aee46
pramilagm/Data_structure_and_algorithm
/threeSum.py
1,156
4.3125
4
# Write a function that takes in a non-empty array of distinct / unique integers representging a targer sum. # The function should find all triplets in the array tha sum up to the target sum and return a two dimensional array of all these # triplets. The numbers in each triplet shoul be ordered in ascending order, and ...
87920609731f60becfaea514a5454f729704b31a
SergeyKomanich/homework_6
/power_of_two.py
540
4.25
4
""" По данному натуральному числу N найдите наибольшую целую степень двойки, не превосходящую N. Выведите показатель степени и саму степень. Операцией возведения в степень пользоваться нельзя! """ num_n = int(input("Введите число: ")) num_power_tow = 2 power = 1 while num_power_tow <= num_n: num_power_tow *= 2 ...
81377cfbae8ba8c34b61323638b7bcf4c7813d65
colinbruner/hacker-rank
/python/kangaroo.py
1,016
3.90625
4
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/kangaroo/problem # COMPLETE class Kangaroo: def __init__(self, start, jump_distance): self.position = start self.jump_distance = jump_distance def jump(self): self.position += self.jump_distance def kangaroo(x1, v1, x2, ...
0653f12963766a72b461625fbe8edddbb6dbb936
AnupBagade/Hackerrank
/Algorithms/Codewars/simple_pig_latin.py
912
4.40625
4
""" Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. Examples pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway ! """ import re def pig_it(s): s_list = s.split(' ') res = [] #...
016dbc0099f4b94bcc91dedbe243f26b853bff2a
rotus/the-python-bible
/fun_with_strings.py
752
4.03125
4
# Fun with String methods data = "Hello sir" print("The data we are going to manipulate is: {}".format(data)) print("There are {} letter L's".format(data.count("l"))) # Or just simply print count of L's print(data.count("l")) # Force UPPERcase print("Let's capitalize all the words: {} ".format(data.upper())) # O...
3e64ae4fc6912b98821c98b806e5e35a59366ffb
rferrucci/algorithims-data-structures
/Fractions.py
4,067
4.0625
4
#!/usr/bin/env python """essesntially, replicating the Fraction class on my own, following programming exercises for learning algorithms and data structures. https://interactivepython.org/runestone/static/pythonds/index.html Excercises 1.7 """ def gcd(m,n): """outputs greatest common devisor """ while m%n != 0: ...