blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
df0bee4818a723f2ea5eb1ba6f52ff4bee88c391
rak-19/glowing-spork
/hol.py
89
3.859375
4
rak=input("") if(rak=='Saturday' or rak=='Sunday'): print("yes") else: print("no")
ad103ed85b7b2dd45727a417f6f4879d7ad9fe27
hoj2atwit/Yapa-Bot-PY
/card.py
739
3.703125
4
import random def make_deck(): deck = [] for i in range(4): suit = "" if i == 0: suit = "♦️" elif i == 1: suit = "♣️" elif i == 2: suit = "♥️" else: suit = "♠️" for x in range(13): num = "" if x == 0: num = "A" elif x == 10: num = "J...
a1502c4a04c3ec60c736d677ecd218ea8d5bc346
GastonCabrer/Logica-Clase-Diurna
/Ejercicio Tarea.py
378
4.09375
4
print("Operadores Arismeticos") # +, -, *, /, %, //, ** print("Ingrese un numero") num1 = int (input()) print("Ingrese otro numero") num2 = int(input()) suma = num1 + num2 resta = num1-num2 multi = num1 * num2 division = num1 / num2 # print print("La suma es =", suma) print("La resta es =", resta) print("La Multipli...
0b3f866ee487b13300622a9595693d6ca360712f
effyhuihui/leetcode
/backtracking/sudokuSolver.py
3,116
3.75
4
__author__ = 'effy' ''' Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. ''' ''' dfs!!!!!! ''' class Solution: # @param {character[][]} board # @return {void} Do not return anything,...
46e57e6164b9ffa7a8d60e44996aabf09334f44d
nikhilprashanth/EulersProblems
/sum square difference.py
236
3.5625
4
i=1 s=0 s2=0 i2=0 s3=0 s4=0 while i<=100: s=(i*i)+s i=i+1 print('SUM OF THE SQUARES =',s) while i2<=100: s2=i2+i2 i2=i2+1 s3=s2*s2 print('THE SQUARE OF THE SUM =',s3) s4=s3-s print('THE DIFFERENCE IS,',s4)
5cce1d42781f52dfc9283c22c54ac99002586a30
saierding/leetcode-and-basic-algorithm
/sorting algorithm/merge sort.py
756
3.8125
4
# 归并排序(分治法) class Solution: def mergesort(self, alist): if len(alist) <= 1: return alist mid = len(alist)//2 left = self.mergesort(alist[:mid]) right = self.mergesort(alist[mid:]) return self.merge(left, right) def merge(self, left, right): i, j = ...
8ed79350ce8f2933d06653c8eb4e00755dfc2bfd
bienvenidosaez/2asir1415
/04 Python/condicionales/ej8.py
989
4.125
4
# -*- encoding: utf-8 -*- # Ejercicio 8. Juan Aurelio import math print ('Ecuación a x² + b x + c = 0') print ('Escriba el valor del coeficiente a') nCoeficienteA = float(input()) print ('Escriba el valor del coeficiente b') nCoeficienteB = float(input()) print ('Escriba el valor del coeficiente b') nCoeficiente...
733bd477f3ef6859d365f10679a5404b4573784e
Soopernoodle/labs2testing
/02_basic_datatypes/1_numbers/02_04_temp.py
444
4.3125
4
''' Fahrenheit to Celsius: Write the necessary code to read a degree in Fahrenheit from the console then convert it to Celsius and print it to the console. C = (F - 32) * (5 / 9) Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius" ''' Fahren = input("Please put in your degrees in Fahren...
4c55a08e12865384f57eb460d81d041c6d856593
EduardoSlonzo/python_project
/Exercicio_em_python/Tabuada.py
126
3.75
4
N = int(input("Deseja a tabua para qual valor? ")) for i in range(1, 11): mult = i * N print(f"{N} X {i} = {mult}")
4cb301f6dbbce1bb091aeffd8f2daca5ce1392d2
gitkenan/Random-Password
/pasword_gen.py
2,296
4.25
4
# we import some modules to use import random import string # we define lists of numbers, lowercase letters # and capital letters, special characters number_list = range(1, 27) number_list2 = range(1, 5) letter_list = [x for x in string.ascii_lowercase] caps_list = [x for x in string.ascii_uppercase] symbol_list =...
f1a8d6fd74e5f1bcc3122075014ba390dab8e4be
weilanhanf/algorithm-exercises
/剑指offer/面试题3_二维数组中的查找/二维数组中查找元素.py
920
4
4
""" question des 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 """ def find_elem(target, array): """元素规律排列的二维数组查找数据元素,如果成功返回元素在二维数组中的位置下标,否者返回空""" row = len(array) col = len(array[0]) i = 0 j = col - 1 while i<= row and j>=0: if arra...
72b5f3c44c19e776eabca2ff0662d51c0d4736ba
marcelodias/documents
/python/apraticafazaperfeicao10-15.py
231
3.953125
4
def censor(text, word): censurado = "" for i in text.split(): if i == word: censurado += "*" * len(i) return censurado print censurado else: print "".join(censurado) censor("Este e um teste hack", "hack")
998f2cb573f1742119fb3222a224c7a2d6e5e4f8
q1003722295/WeonLeetcode
/_32-LongestValidParentheses/LongestValidParentheses3.py
1,335
3.75
4
''' 给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。 示例 1: 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()" 示例 2: 输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()" ''' ''' 见题解2、3.png ''' # 栈+排序 class Solution1: def longestValidParentheses(self, s): res=[] stack=[] for i in range(len(s)): if(stack and s...
6263a6d71b96d83efbfef0bb52dac9ad88657cc4
msencer/leetcode-solutions
/easy/python/MinStack.py
1,017
3.96875
4
""" Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. """ class MinStack(object): def __init...
be490d0c23de0ed686f397c013e1d9845894efbd
Malika939/Classy3
/Problem1.py
1,298
4.03125
4
class Human: default_name = 'No name' default_age = 0 def __init__(self, name=default_name, age=default_age): #Динамические поля self.name = name self.age = age #Приватные поля self.__money = 0 self.__house = None def info(self): print(f'Name: {...
98a289ba1da11481536083d91dfca267d9097423
pocketpair22/ABCpractice
/ABC011/ABC011_2.py
109
3.953125
4
S = input() print(S[0].upper(), end='') for i in range(1, len(S)): print(S[i].lower(), end='') print()
0fb7c629a727613b889f5d65c6deaacc15ec5b1d
FelipeSilveiraL/EstudoPython
/meuCursoEmVideo/mundo2/exe045.py
1,010
3.671875
4
from random import randint import time itens = ('Pedra', 'Papel', 'Tesoura') computador = randint(0,2) print('Vamos jogar ?') print( '[0] Pedra\n' '[1] papel\n' '[2] Tesoura\n' ) jogador = int(input('Escolha sua opção: ')) print('Jo') time.sleep(1) print('Ken') time.sleep(1) print('po') time.sleep(1) pri...
969c047b1189e287e153ae7ed7c360e7ff13ae2b
uzaymacar/python-interview-review
/practice/CH2 - linked_lists/intersection.py
4,786
4.21875
4
# LINKED LIST IMPLEMENTATION class Element(object): # single unit (Node) in a linked list def __init__(self, value = None): # to initialize a new element self.value = value self.next = None def get_value(self): # get value (data) of element return self.value class LinkedLis...
e7f4696f64438a67e4ca68a1e08b0f57f36ecef6
lulock/cs231a
/ps3_code/p3/problem3/models.py
2,594
3.625
4
import torch import torch.nn as nn from torch.autograd import Variable import numpy as np from PIL import Image class ImageEmbedNet(nn.Module): """ A set of Conv2D layers to take features of an image and create an embedding. The network has the following architecture: * a 2D convolutional layer with 1 ...
ccf20421c326c8dd7905ba213f2233b7e3496c90
Acrelion/various-files
/Python Files/se51.py
625
4.125
4
import re a = [1, 2, 3] print "We have a list:", a print print 'The first item in a is', a[0] print print "We will change it to a different number. Enter a new one.\n" inf = 1 while inf > 0: h = (raw_input("> ")) if re.match("^[0-9]*$", h): h = int(h) a.append(h) break elif no...
e0625a5687cc4a2b3d25ace6301be755abcf740c
KevinVaghani/ex01
/2021-10-01_Vaghani_K_matrixMultiplication.py
953
4.15625
4
A=[] print("Enter value for first matrix") for i in range(3): a=[] for j in range(3): j=int(input("enter input for ["+str(i)+"]["+str(j)+"]")) a.append(j) A.append(a) B=[] print("Enter value for second matrix") for i in range(3): b=[] for j in range(3): j=int(input("enter inp...
cda133d0452cbbac08f8565c1c24d684f0931167
slowisfaster/algorithm024
/Week_01/rotate-array.py
2,128
3.5625
4
class Solution:     def rotate(self, nums: List[int], k: int) -> None:         """         Do not return anything, modify nums in-place instead.         """         #O(n),         #[nums.insert(0,nums.pop()) for _ in range(k)]                  #O(n), O(n)         """         n = len(nums)         new = [0 for _ in rang...
cd6d47a1fd6917822e5185e4a1eec601bc6e37ed
node31/PDP
/understanding_iterator_pattern/pow_two.py
1,014
3.921875
4
class PowTwo(object): """Class to implement an iterator of powers of two""" 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 ...
a925deeb3c28c39c1244c8e8b38fd9f8c8d8f09d
Yogesh7920/Algorithms
/graph/view/topo_sort.py
511
3.65625
4
from collections import deque def topological_sort(g): stack = deque([]) visits = set() vertices = g.nodes for ver in vertices: if ver not in visits: loop(vertices, ver, visits, stack) stack.reverse() return stack def loop(vertices, ver, visits, stack): if ver not in...
e223985d9c7cd11be98830acb08b45afc38dcf5e
nitinworkshere/algos
/algos/DynamicProgramming/EggDropping.py
482
3.5625
4
from math import inf #Find minimum number of attempts to find which floor is safe to drop out of k def number_of_attempts_egg_drop(k, n): if n == 0: return 0 if k == 1 or k == 0: #if there are 0 or 1 floor then no or only one trial needed return k trials = inf for x in range(1, k+1): ...
a529e029cde664b1614cca95f065635a546f713f
IronChariot/tensorflow-deepq
/tf_rl/simulation/asteroid_game.py
22,141
3.5
4
""" Details of AsteroidGame: - Hero can be always in the middle (movement makes everything ELSE move) or free - Hero can accelerate forwards and has momentum - Hero has a current direction and field of view (so looking around has value!) - Inputs are: closest object in each sight line distance to object in sigh...
1ac843926cf0f77774e7f27b72383b786a775347
rugbyprof/5143-OperatingSystems
/ztrunk/spring.16/HelperFiles/scratch_code.py
1,131
3.515625
4
import sys class Stack: def __init__(self): self.list = [] self.empty = True self.size = 0 def empty(self): return self.empty def push(self,val): self.list[size] = val self.size +=1 self.empty = False def pop(self): ...
ea49ea572aa231ac4f3c8b5bf015048a5a55c1b6
enix223/stackoverflow-question
/app/helper.py
323
3.5
4
import re def parseQ(strQ): tmp = strQ while True: match = re.search(r'(?<=\().*(?=\))', tmp) if match: match = re.search("(\w+): ([\w\s_:()',\[\]]+)", match.group()) if match: lop, rop = match.groups() if lop == 'OR': ...
10be864781d35de1a04490d987ef5d7c5cf32ced
wcphkust/sling
/python/grass_dl_insert.py
927
3.59375
4
import random import pprint class node: def __init__(self, nxt = None, prev = None): self.next = nxt self.prev = prev ################## # accessory func # ################## def create_list(size): root = None tl = root for i in range(1, size): new_node = node() if root is None: root = new_node tl =...
f486ff855415f4a36ae15bb651cfee93cf35a29e
liuluyang/openstack_mogan_study
/myweb/test/leetcode/str-medium/palindromic-substrings.py
839
3.609375
4
#coding:utf8 class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ length = len(s) result = 0 for index in xrange(length): first = index-1 last = index+1 while first>=0 and last<length: ...
37b94555d80835fe96a28cbc4145776eb3590603
Fyziik/python_exam
/9._session_9/innerFunctions.py
523
4.125
4
# In python we dont have to return a specific value for a function, we can also have a function return a function def calculate(a, b, method): if method == 1: def add(a, b): return int(a) + int(b) return add(a, b) elif method == 2: def subtract(a, b): retu...
011107874fb09928bae58e9a8e566d732806f1c4
bopopescu/Learn2Mine-Main
/rps/theOfficialHillaryClintonBot.py
1,520
3.546875
4
#theOfficialHillaryClintonBot import random shortTermMemory = [] if input == "": rockCount = paperCount = scissorsCount = 0 elif input == "R": rockCount += 1 if len(shortTermMemory) <= 10: shortTermMemory.append(["P", rockCount]) else: shortTermMemory.pop() shortTermMemory.append(["P", rockCount]) elif inp...
4fd7f77e08114deb2ff1a11979785a6937daacd5
euribates/Jupyter-Intro
/hilbert_curve.py
634
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Hilbert curve using L-system # Authour: Alan Richmond, Python3.codes # https://en.wikipedia.org/wiki/L-system # Uses Lindenmayer System import time from turtle import * def A(n): if n>0: L("-BF+AFA+FB-", n) def B(n): if n>0: L("+AF...
98ae6996aa0b587767198da68169589e426738f7
ssangitha/guvicode
/reverse_each_word_except_first_and_last.py
171
3.5625
4
s=input() l=list(s.split(" ")) a=[l[0]] for i in range(1,len(l)): if i==len(l)-1: a.append(l[-1]) else: c=l[i] b=c[::-1] a.append(b) print(" ".join(a)) #reverse
530cd01e5888ee63d12cf4d8770e8f943377d811
jack-morrison/cs-review
/CTCI/chapter_1/1.2/isPermutation.py
466
3.8125
4
# Given 2 strings, write a method to decide if one is a permutation of the other. def string_to_dict_of_counts(inString): counts = {} for char in inString: if char not in counts: counts[char] = 0 counts[char] += 1 return counts def check_dict_equivalence(d1, d2): for key in...
db638cd7dc3135fef012f784d98c086fc5c3c934
aksharanigam1112/Titanic-Survivors
/MLProject_Titanic.py
13,488
3.84375
4
# Step1 importing libraries import numpy as np import pandas as pd pd.set_option('display.width', 1000) pd.set_option('display.max_column', 16) pd.set_option('precision', 2) import matplotlib.pyplot as plt import seaborn as sbn import warnings warnings.filterwarnings(action="ignore") # Step2 Reading data trai...
1fc47affe2de254a7d81e9597f45861d419cf95e
LuHG18/Crypto-Calculator
/CryptoCalculator.py
4,469
3.625
4
import time import urllib import json import datetime try: #tries to read file f = open("Coins.json", "r") userCoin = json.loads(f.read()) f.close() except IOError: #if file doesn't exist then it's created f = open("Coins.json", "w+") json.dump({}, f) f.close() f =...
d983437f6383da9cada81cecec4454a5e0689053
anzumpraveen/Programming-Exercise
/sum_of_power.py
171
3.703125
4
num=int(input("enter the number")) pow=int(input("enter power")) user=num**pow x=str(user) x.split() i=0 sum=0 while i<len(x): sum+=int(x[i]) i+=1 print(sum)
5ca19965f5d0eeb1cd42db4f61304526a68cb710
GiosueAcosta/Maincra
/Punto 40.py
452
4.03125
4
#40. Escribe un algoritmo o el respectivo diagrama de flujo que lea 3 números e indique si al menos 2 de ellos son iguales print("Ingrese tres números: ") lista = [] for i in range(3): numero=int(input()) lista.append(numero) if len(lista) != len(set(lista)): # Se convierte en verdadero porque hay dos ...
c4bc1390fb30bb0750343008ec8e592be440569e
thehyve/coding-dojo
/dojo-2-roman-calc/roman.py
517
3.65625
4
import re class Roman: roman_dict = { "IIII": "IV", "IIIIII": "VI" } def add(self, A, B): if self.rank_string(A) > self.rank_string(B): result = A + B else: result = B + A if result in self.roman_dict: result = self.roman_dict[result] elif result[0] == "I...
8646de891c918ae7538bce75ae753e5a0b20e6ca
ParvathyGS/My-learnings
/Python/countarray.py
162
4.03125
4
numlist = [1,3,4,5,2,3,8,1,9,3,5] numlist1 = set((1,3,4,5,2,3,8,1,9,3,5)) print(numlist1) for x in numlist1: print(x,"repeats",numlist.count(x),"times\n")
244cfbb4eb8320814f86be6627e05ebf5c1ce9bd
tmsick/grokking-algorithms
/recursion.py
409
3.859375
4
def countdown(n): print(n) if n > 0: countdown(n - 1) def factorial(n): if n == 1: return 1 return n * factorial(n - 1) def factorial_detailed(n, tier=0): if n == 1: return 1 tab = " " * tier print(tab + "n: " + str(n)) ans = n * factorial_detailed(n - 1, tie...
4d30767567a52ee8c85f134dc42b9f490182cd56
hathaipat-p/Software_Dev_I
/Circle/final_make_circle.py
2,946
4.09375
4
# 6201012620244 ######### Assignment I (2020-07-15) ######## # Ref. https://stackoverflow.com/questions/58717367/how-does-the-collidepoint-function-in-pygame-work import pygame from random import * pygame.init() screen = pygame.display.set_mode([800,600]) pygame.display.set_caption('non-overlapping circ...
5dfd1676df4371feb19487b3772f228bb826a303
JohnDi0505/MonteCarlo_Simulation-Biostats
/US_President/US_President.py
1,085
3.859375
4
import pandas as pd import numpy as np from pandas import DataFrame import matplotlib.pyplot as plt df = pd.read_table("presidents.txt", names=["num", "name", "presidency"]) name_list = list(df.name) # create a list to store matches after each shuffle shuffle_record = [] # create a function in which the first a...
f2f8394ba5c39d9247e16db91dfe37775b8e24cf
farhan0581/gfgcodes
/dp/number_of_steps_ways.py
695
3.84375
4
# https://www.geeksforgeeks.org/count-ways-reach-nth-stair/ class Solution: # @param A : integer # @return an integer def traverse(self, n): if n == 1: return 1 if n == 2: return 2 try: s1 = self.map[n-1] except KeyError: s...
ff7af5cba4b1ebc0f31140119f085d053c3dc82d
mdhatmaker/Misc-python
/interview-prep/techie_delight/division_without_division_operator.py
188
3.625
4
import sys # Perform Division of two numbers without using division operator (/) if __name__ == "__main__": x = 1 y = 2 print("correct result:", x / y) print(y**-1 * x)
9695a229615ff57175e63e1d39b430a14161d1fe
Carmenliukang/leetcode
/算法分析和归类/其他/两个字典的不同.py
660
3.84375
4
""" 对比两个字典的所有不同 """ def pprint(dictA: dict, dictB: dict) -> None: for k, v in dictA.items(): if dictB.get(k) != v: print(f"dictA {k}:{v}") for k, v in dictB.items(): if dictA.get(k) != v: print(f"dictB {k}:{v}") return None def pprintMethodA(dictA: dict, dictB: d...
ff3c5d299f539402c78a63d766b9bb3c6f364a3e
sourav-dscml/impfeature
/featureimportance.py
3,877
3.6875
4
#our code here #import required libraries import pandas as pd import numpy as np from catboost import CatBoostRegressor, CatBoostClassifier class FeatureImportance: def __init__(self): pass def model_build(self,df,target,verbose): # Purpose == function for identifying if it is regre...
7190cea35b66bbcc27339e0979fa8c37e0670b9c
Joshua56/covid-19-estimator-py
/src/estimator.py
4,866
3.5625
4
def number_of_days_in_period(periodType, timeToElapse): """ Receives the period type and calculates the number of days in that period """ if periodType == "days": return timeToElapse elif periodType == "weeks": return timeToElapse * 7 elif periodType == "months": return timeToEl...
37b33bd35a4b5a9bf3099628988e34c3a651e5ed
sabin890/pytho-class
/function_continued.py
1,395
4
4
# def func(*args): # print(args) # # print(type(args)) # func(1,2,"sabin",4,3) # def func(*args,**kwargs): # print(args,"\n",kwargs) # func(1,2,3,"sabin",name="ram",contact="98238080",address="kathmandu") # def welcome(): # print("hello word") # w=welcome# call by reference # print(w) # w() # def w...
411fdacb3ed33c50f7bc964f960dbe32417c27e8
Rapt0r399/HackerRank
/Python/Strings/ Capitalize!.py
199
3.53125
4
s = raw_input() k = s l = s.split() n = len(l) for i in range (n) : l[i] = ''.join((l[i])[0].upper() + (l[i])[1:] ) s = ' '.join(l) if (len(k) == len(s)) : print s else : print k.title()
ba41fb7674ef43c6253102da696332e6a8e0ae98
nervig/Starting_Out_With_Python
/Chapter_2_programming_tasks/task_10.py
576
3.96875
4
#!/usr/bin/python ''' 1,5 glass of sugar } 1 glass of oil } = 48 cookies 2.75 glass of flour } ''' glass_of_sugar = 0.028 glass_of_oil = 0.021 glass_of_flour = 0.057 amount_of_cookies = int(input("Please, enter the amount of cookies: ")) amount_sugar = amount_of_cookies * glass_of_sugar amount_oil = glass_o...
224295119c7e37e8f9f3185b8887c1973c08f0d7
henkkah/pathfinding
/src/data_for_app.py
1,739
3.796875
4
def data_for_app(): """Reads base data for the app (city and highway data) and stores it in appropriate format for the app. Args: no arguments - reads data from csv files which need to be in data folder in order for the application to work Returns: tuple of (cities, coordinates, sp...
7088eb229bcc861c58024935cd4ec7ef6cbb08f3
arindampaulripon/Python-for-Data-Science
/Data-Structures-and-Algorithms/Turtle/turtleCode.py
3,247
4.5
4
# Imports always at the top. # The unsafe way of importing a module in Python: # from turtle import * # t = Turtle() # The correct/safe way to do it is: import Turtle # Other function definitions followed by the main function definition def main(): # The main code of the program goes here # This line reads a...
fb37bfb40bca475ea4f3178fd99ea8446ec3e4c8
Queena-Zhq/leetcode_python
/5.longest-palindromic-substring.py
1,275
3.78125
4
# # @lc app=leetcode id=5 lang=python3 # # [5] Longest Palindromic Substring # # https://leetcode.com/problems/longest-palindromic-substring/description/ # # algorithms # Medium (28.05%) # Likes: 5941 # Dislikes: 488 # Total Accepted: 852.4K # Total Submissions: 2.9M # Testcase Example: '"babad"' # # Given a str...
9a7c8097890678f8fdc68e6443e1d00afdd70b96
sky-dream/LeetCodeProblemsStudy
/[剑指offer_v2][57_II][Easy][和为s的连续正数序列]/和为s的连续正数序列_3.py
1,490
3.78125
4
# leetcode time cost : 32 ms # leetcode memory cost : 13.6 MB # Time Complexity: O(N) # Space Complexity: O(1) # solution 3, 间隔法,求根法的进一步优化, # https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/xiang-jie-hua-dong-chuang-kou-fa-qiu-gen-fa-jian-g/ class Solution: def findContinu...
f95a4c79f2fb864fb854129e4d1f1602b2170b60
AwsafAlam/Machine_Learning
/Regression/Multiple_Linear_Regression/multiple_linear_regression.py
1,979
3.890625
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # -- Problem statement: # We need to find our whether there is a relationship between expenses and marketing, # and what will yeild the max profit # Importing the dataset dataset = pd.read_c...
ce8f210f80a7daafce239e6f6ae062abbae33e30
RRisto/learning
/algorithms_learn/what_can_be_computed/src/throwsException.py
559
3.515625
4
# Python file throwsException.py # This file is used as an example in section 2.4. import utils; from utils import rf def throwsException(inString): return 5 / 0 def testthrowsException(): testVals = ['', 'asdf'] for inString in testVals: val = None try: val = throwsExceptio...
4c00e043908c08ef77fe33479d3dd1d65016506d
g4brielsol/leet_code_debug
/array3.py
1,703
4.125
4
class Solution: def merge_sort(self, array: list) -> list: """ Implementation of merge sort """ if len(array) > 1: # find middle (int) middle = len(array) // 2 # two arrays divided in the middle index left = array[:middle] right = array[mid...
dbc53da34d017f9d6c35c998bfc2744d29ee5d20
GeertVanDeyk/SomePythonCode
/Find_File_And_Rename.py
1,304
3.65625
4
import os def FindFileAndRename(the_path,change_from_this,change_into_that): os.chdir(str(the_path).replace('\\','/')) number_files_changed = 0 number_of_files_in_directory = len(os.listdir(os.getcwd())) for file in os.listdir(os.getcwd()): original_filename = s...
ca4e99d68e6d221dd23aa5b3ef679ea468d4a4b0
Ivan-yyq/livePython-2018
/test/8.py
986
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/4/14 09:45 # @Author : yangyuanqiang # @File : 8.py ''' 8、输出空心正方形 5 * 5,结果为 ***** 脚本名:8.py * * * * * * ***** ''' #打印空心正方形 for i in range(5): for o in range(5): ...
46c5263a0186b53c706075440a53444028c8cdd1
Mohamed2del/Computer-Vision
/Image Representation and Classification/maximum_and_minimum_grayscale_values_in_the_image/maxmin.py
605
3.734375
4
import matplotlib.pyplot as plt import numpy as np import cv2 import matplotlib.image as mpimg #Read image #image size (490, 655, 3) in uint8 datatype img = mpimg.imread('car.jpeg') #To print image dimensions print 'Image dimensions = ', img.shape #Convert image from RGB to GRAY #image size will be (490, 655) in u...
4a1ce5ed80f109c794f76f4ffd4aecc83b5cbb90
bharat0071/Python_Assignments
/frequentlist.py
332
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon May 25 17:50:13 2020 @author: MOHANA D """ # write a program to find the 2nd most frequently occurring number in a given list. Read list from input def most_frequent(List): return max(set(List), key = List.count) List = [2, 1, 2, 2, 1, 3] print(most_f...
7091668b92fdb38be317613be8f1b088777e851d
ricky4235/Python
/Book/Ch10/Ch10_1_3.py
102
3.703125
4
str1 = 'Hello' print(str1[0]) # H print(str1[1]) # e print(str1[-1]) # o print(str1[-2]) # l
027d4d92f36925c826c249b576846a1ffcb3e515
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4176/codes/1644_1055.py
264
3.671875
4
from math import* velocidade0= float(input("v0: ")) angulo= radians(float(input("Ângulo: "))) distancia= float(input("Distancia: ")) g= 9.8 formula= ((velocidade0**2)*sin(2*angulo))/g if (abs(formula - distancia)) <= 0.1: print("sim") else: print("nao")
2eecea7ee47357c17a033fca2a7a68565010497a
sangm/Test-Driven-Development
/Chop/Python/chop.py
2,370
3.734375
4
import unittest def recursive_chop_aux(li, left, right, element): if left > right: return -1 mid = left + (right - left) // 2 if li[mid] == element: return mid elif li[mid] > element: return recursive_chop_aux(li, left, mid-1, element) else: return recursive_chop_aux(li, mid+1, right, element) def ...
4690cf8f1ccf6650a53eb03630b27a64536df4e3
nickderobertis/py-file-conf
/pyfileconf/basemodels/container.py
1,543
3.703125
4
from copy import deepcopy from typing import Any, List class Container: items: List[Any] = [] def __iter__(self): for item in self.items: yield item def __getitem__(self, item): return self.items[item] def __contains__(self, item): return item in self.items ...
e19b84022a782423f713ff28c78c7ea576501625
elf666/python-exercises-3
/gui_buttons.py
819
3.5625
4
from tkinter import * def print1(): print("Nacisnieto przycisk 1") button1.configure(bg='yellow') button2.configure(bg='pink') button2.configure(text='jestes glupi') def print2(): print("Nacisnieto przycisk 2") button2.configure(bg='white') button1.configure(bg='green') but...
32fae2c9ebb9d1cf6a9d8e1b8c54fc0304c2fb1e
jestinajohn/Mypythonworks
/python programs/calculatorfunction.py
647
4
4
def add(n1,n2): print(n1+n2) def mult(n1,n2): print(n1*n2) def sub(n1,n2): print(n1-n2) def div(n1,n2): print(n1/n2) print("Choose your options \n 1.ADD \n 2.SUB \n 3.MULT \n 4.DIV \n") while True: opt = (input(" Enter your option here : ")) if opt in ('1','2','3','4'): n1 = float(in...
b6c03c34948b0edc1c89aa6021043d1a1ec8e087
StanScott94/python_algorithms_and_data_structures
/sort_algorithms/quick_sort_basic.py
445
4
4
def quick_sort_basic(array): if len(array) < 2: return array else: pivot = array[-1] smaller, equal, larger = [], [], [] for number in array: if number < pivot: smaller.append(number) elif number == pivot: equal.append(number) else: ...
1381c1555aef32f82cef44519cd0642c5b632cc5
qperotti/Cracking-The-Coding-Interview-Python
/Chapter 4 - Trees and Graphs/ex8.py
1,137
3.9375
4
''' Exercise 4.8 - First Common Ancestor: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Result: ...
1273d97ee8b4a4faf06f087408881694d32fbdeb
joycegodinho/Python
/funcao_macaco.py
2,219
3.703125
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 22:21:36 2020 @author: joyce """ ''' Teorema do macaco infinito. A frase que vamos filmar é: "acho que é como uma doninha" A maneira como simularemos isso é escrever uma função que gera uma string com 27 caracteres, escolhendo letras aleatórias das 26 l...
6daf9058e2026964b0bed8be105e30aede0cabfc
nicklindgren/smart-gliders
/search/bruteForceSearch.py
2,548
3.59375
4
#!/usr/bin/env python def bruteForceSearch(toSearch, toMatch): # This function takes the m*n matrix toMatch and exhaustively searches # the p*q matrix toSearch for a match. Matrices are column-major m = len(toMatch) n = len(toMatch[0]) p = len(toSearch) q = len(toSearch[0]) matches = list(...
123e08e9179a3a3ed2f55437d0fda182c35fd765
TheWizard91/VignereCipher
/test.py
6,048
4.09375
4
#from VignereCipherProjectPackage.cipher import Vignere; from cipher import * #garbage just trying to display stiff nicely. def display(key): """Will display the how Vignere is implemented and a beautiful text-based GUI pre: key is selfexplanatory post:wisplay user the key table.""" k...
d5e07114629464be2f6499f6c01f1c9eacf686d3
shoichiaizawa/edX_MITx_6.00.1x
/lecture06/l6_problem02.py
1,921
4
4
def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' # Your Code Here newTup = () for idx, item in enumerate(aTup): if idx % 2 == 0: newTup += (aTup[idx],) return newTup # ---------- # Test cases # ---------- print oddTuples(())...
a784b5f588005e800a8aa8327f4a1621629a6570
harveylabis/GTx_CS1301
/codes/CHAPTER_3/Chapter_3.4_Functions/Lesson_3/PrintYen.py
185
3.828125
4
#Defines the function "printYen" def printYen(): #Prints "¥", without the new line afterward print("¥", end='') #Calls the function "printYen" printYen() print(5)
b8bf35ce4dc1bb4550eb1a3c5c5e0f4251448edf
shah0112/Aritificial-Intelligence
/NRooks-NQueens/Nrooks-NQueens.py
4,036
4.3125
4
# coding: utf-8 # In[6]: #!/usr/bin/env python # nrooks.py : Solve the N-Rooks problem! # D. Crandall, 2016 # Updated by Zehua Zhang, 2017 # Optimized and included N-Queens - Shahidhya, 2017 # The N-Rooks problem is: Given an empty NxN chessboard, place N rooks on the board so that no rooks # can take any other, i.e...
eca7785b77a960758c056350f08294fd6d987447
Linkney/LeetCode
/LeetCodeAnswer/167.py
1,008
3.875
4
""" 给定一个已按照升序排列的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明: 返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 """ # def twoSum(self, numbers: List[int], target...
5b83b1c64c03575495a94c790e1616bbe4bdb998
harshitpoddar09/HackerRank-Solutions
/Python/Zipped!.py
301
3.734375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT data=list(map(int,input().split())) n=data[0] x=data[1] marks=[] student_marks=[] for i in range(x): subject=list(map(float, input().split())) marks.append(subject) for i in zip(*marks): print(sum(i)/len(i))
021adf875223b5e9bfda8c6c9992fbed3dd362fa
JuniorCardoso-py/Pw-Sabados
/Modulo-2/Aula2-2-Classes/Exercicios/exercicio4.py
5,683
3.75
4
# Crie uma classe que possa cadastrar Produtos # fazendo o uso dos modelos getters e setters # Essa classe deve conter validações dos valores recebidos # não podendo envia letras por exemplo # Deve ter um cabeçalho # Deve poder cadastrar os valores com o metodo input # Deve ter um menu de escolhas # Por exemplo # 1. ...
8ed44f676e29a187fa95e25265b30806a6d49138
anju-netty/pylearning
/fizzbuzz_test.py
795
3.578125
4
import unittest from fizzbuzz import solve_fizzbuzz class TestFizzBuzz(unittest.TestCase): def test_multiple_of_5(self): list_zz = solve_fizzbuzz(5) expected = "buzz" self.assertEqual(list_zz,expected) def test_solve_fizzbuzz_zero(self): with self.assertRaises(ValueE...
892eb890711a3036f7aeb94c2cc28b40a9d3bf90
PBuszek/game-statistic
/part2/reports.py
1,125
3.578125
4
# I DON'T UNDERSTAND THAT FUNCTION!!!!! def get_most_played(file_name): with open(file_name) as file: most_played = (max(file, key=lambda line:float(line.split('\t')[1])).split('\t')) return most_played[0] def sum_sold(file_name): copies_sold = [] with open(file_name) as file: for l...
3023b79203a7ef933d25b733ed03ab4c63130065
estraviz/codewars
/6_kyu/Numericals of a String/numericals.py
237
3.75
4
""" Numericals of a String """ def numericals(s): chars = {} result = "" for c in s: if c in chars: chars[c] += 1 else: chars[c] = 1 result += str(chars[c]) return result
cb9e3479691e884ed1ab9470cdaff4fe156ef273
LarmIg/Algoritmos-Python
/CAPITULO 7/Exercicio K.py
709
3.9375
4
# Elaborar um programa que leia duas matrizes A e B de uma dimensão do tipo vetor com dez elementos inteiros cada. Construir uma matriz C de mesmo tipo e dimensão, que seja formada pela soma dos quadrados de cada elemento correspondente das matrizes A e B. Apresentar a matriz C em ordem decrescente. A = [] B = [] C...
0ad61f3b358a0a045753f2fa945689d28c39cc4d
howinator/CS303E
/CalculatePI.py
2,058
4.21875
4
# File: CalculatePI.py # Description: A program to calculate pi using a Monte Carlo Algorithm # Student Name: Paul Benefiel # Student UT EID: phb337 # Course Name: CS 303E # Unique Number: 90110 # Date Created: July 20th, 2014 # Date Last Modified: July 20th, 2014 ###############################################...
5783854a22a0c93408094ef9e9c65a8c2ad3e7b3
realDashDash/SC1003
/Week3/Discussion1.py
376
4.0625
4
value = 6 if (value % 2 == 0): print("first", value) elif (value % 3 == 0): print("second", value) while (value <= 9): value += 1 if (value == 8): continue else: pass print("third", value) else: print("fourth", value) print("fifth", value) # print result: # first...
05cccb8020d72b50e3aa6f22748c2eb9337cb7ff
cheoljoo/problemSolving
/ps/no0003.py
6,482
3.65625
4
from collections import defaultdict import sys INIT = 0 NORMAL = 1 EARLY = 2 class Node(object): def __init__(self, name=None, data=None, parent=None): self.name = name self.data = data self.parent = parent self.status = INIT self.early_count = 0 self.children = []...
0d95025673965bd2eda2a1771e19f5ff83bc82f6
Aasthaengg/IBMdataset
/Python_codes/p03523/s550037550.py
254
3.546875
4
import re s = input() pattern = re.compile("(A?KIHA?BA?RA?)") ret = pattern.findall(s) ret2 = pattern.findall("[^AKIHBR]") #print(ret) if ret is not None and len(ret) == 1 and len(ret[0]) == len(s): ans = "YES" else: ans = "NO" print(ans)
aaea34b04da92ef8f06ec078c4a737514c69ca88
qiangzuangderen/My_code
/python_learn/py_test/mypro_Class/Class_load.py
792
4.15625
4
#运算符重载 class Person: def __init__(self,name): self.name = name #"+"运算符的重载 def __add__(self,other): if isinstance(other,Person): #判断other的实例对象属性是否为Person类的继承 print("{0}--{1}".format(self.name,other.name)) #取other实例对象name属性:other.name ...
55d989ac30eac9c2908384bb360f1c0dda2fad0d
jerickleandro/uri_online_python
/RPG-Legacy.py
703
3.90625
4
op = True print("Bem vindo ao sistema de RPG Legacy, vamos começar?") name = input("Primeiramente digite seu nome:\n") print("Muito bem {} agora digite a opção referente a sua raça:".format(name)) while(op): raca = int(input("1 - HUMANO\n2 - ELFO\n3 - ANÃO\n")) if(raca == 1): print("Boa escolha {}, ago...
395e5e0293883be4956ad212c15c1e153011870e
okcoders/data_analysis_fall2019
/classes/week2/notes_s1.py
3,238
3.890625
4
# Comments: any line that begins with the Hash/Pound sign will be ignored by the interpreter, it is # used as a way to keep notes right next to your code for both you and other people to read. # Comment notes will be used here to help explain basic outlines of what we are doing and for future # homework assignments. ...
6932e007ed7c52693999248dbbf8a137066227ca
zeroohub/leetcode
/8_string_to_integer_atoi.py
1,078
3.5625
4
# -*- coding: utf-8 -*- class Solution(object): def myAtoi(self, str): int_max = 2**31 - 1 int_min = -2**31 """ :type str: str :rtype: int """ strl = list(str) result = "" while strl: char = strl.pop(0) if char == " ": ...
2e4cd8a7fc23ba5f5e10e5b14328011939ccd772
kamyu104/LeetCode-Solutions
/Python/find-in-mountain-array.py
1,471
3.609375
4
# Time: O(logn) # Space: O(1) # """ # This is MountainArray's API interface. # You should not implement it, or speculate about its implementation # """ class MountainArray(object): def get(self, index): """ :type index: int :rtype int """ pass def length(self): """ ...
0e65fa19889cc3b217f72f893384340cfa5deb3a
veervohra03/Processing
/Python/circle_illusion/circle_illusion.pyde
500
3.703125
4
# Veer Vohra # Circle Illusion # Python Ver 1.0 t = 0 r = TWO_PI/20 c = 0 def setup(): size(1000, 800) def draw(): global t, r, c background(220) fill(51) translate(width/2, height/2) for i in range(10): rotate(r) stroke(255) strokeWeight(2) ...
fdb3503c9fd56a334552cade513b9a1d50c185d3
sbobbala76/Python.HackerRank
/1 - Algorithms/0 - Warmup/8 - Time Conversion.py
327
3.78125
4
# input e.g. 07:05:45PM time_string = input().strip() is_pm = (time_string[8:10] == "PM") if is_pm: hours = int(time_string[0:2]) if hours != 12: hours += 12 res = format(hours, "02") + time_string[2:8] print(res) # then am... elif time_string[0:2] == "12": print("00" + time_string[2:8]) else: print(time_string...
c4c2371f9aa1ab413bafa1f12bebc720bb0a5625
MaZdan6/workspacePython-InzynieriaOprogramowania
/Python_lab/lab_09/zad1.py
9,115
3.5
4
class Ksiazka: def __init__(self, tytul, autor): self.tytul = tytul; self.autor = autor; class Egzemplarz: ''' def __init__(self, Ksiazka, rok_wydania, wypozyczony): self.Ksiazka = Ksiazka; self.rok_wydania = rok_wydania; self.wypozyczony = wypozyczony; ...
d9d072dc775728b60fcf09533ddd2926fd83a443
TurkerTercan/Introduction-to-Algorithms
/Final/171044032_python_codes/171044032_final_q4.py
1,943
3.859375
4
# CSE 321 - Introduction to Algorithm # Türker Tercan - 171044032 # Final Takehome Exam - Question 4 def minimize_maximum_assignments(assignments): n = len(assignments) m = len(assignments[0]) if m < n: print("Job size must be greater or equal to Person size\n") return None rows = [True]...
35eb05c37908efee3c70c794b70221a3a11cc225
sandskink/LearningPython
/venv/Exercises/Exercise005.py
478
4.21875
4
#Exercises from https://www.w3resource.com/python-exercises/python-basic-exercises.php #Write a Python program which accepts the user's first and last name and print them in reverse order with # a space between them fullName = input("Please enter your full name (First Last)") nameBreak = fullName.rfind(" ") nameParts ...
3b0eeff578d53f537ee195784816de0fbdca3cfe
fant0m-e/basicPython
/advancedvotingcheck.py
165
4.15625
4
votingAge = "18" age = input("Enter your age, please: ") if age >= votingAge: print("You are old enough to vote") else: print("You are too young to vote.")
1d712354b3c72e8d29df73d7b739d04e7407c3d1
msd7at/DYNAMIC-PROGRAMMING-DECODED-
/02 1D-DP Climbing Stairs.py
242
3.625
4
#https://leetcode.com/problems/climbing-stairs/ class Solution: def climbStairs(self, n: int) -> int: l=[0,1] if n==1: return n for i in range(n): l.append(l[-1]+l[-2]) return l[-1]