blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d84fa89700790b33ce24166bf4dda533dc600c2c
0x0400/LeetCode
/p48_v2.py
1,029
3.765625
4
# https://leetcode.com/problems/rotate-image/ # 按边处理;从外圈到内圈 # 选定4个顶点,其他点通过距离这些顶点的距离来计算翻转后的坐标 from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ totalLen = len(matrix) # ...
5f2a449235f995c6cd288ddc2f68cdc4fed10685
0x0400/LeetCode
/p216.py
910
3.625
4
# https://leetcode.com/problems/combination-sum-iii/ from typing import List, NamedTuple class Plan(NamedTuple): nums: List[int] @property def sum(self) -> int: return sum(self.nums) def __len__(self) -> int: return len(self.nums) class Solution: def combinationSum3(self, k: in...
c89b3d7df2fef8f59fc73a1d2cda73463a4d96a8
0x0400/LeetCode
/p129.py
874
3.75
4
# https://leetcode.com/problems/sum-root-to-leaf-numbers/ from typing import List from common.tree import TreeNode # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solu...
af7cfd5d6492c82191d9929feff68e0f7b326845
0x0400/LeetCode
/p86.py
1,826
3.625
4
# https://leetcode.com/problems/partition-list/ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # 使用 双链表 def partition(self, head: ListNode, x: int) -> ListNode: if not head: ret...
d678fc8efff4e79f291d1910959ba9b8370d4a84
0x0400/LeetCode
/p73.py
962
3.765625
4
# https://leetcode.com/problems/set-matrix-zeroes/ from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rowLen = len(matrix) colLen = len(matrix[0]) zeroCols = {...
e35a74c2fbd256cd6f855488d822cd281e5e60fa
0x0400/LeetCode
/p16.py
1,358
3.5
4
# https://leetcode.com/problems/3sum-closest/#/description class Solution(object): def closestNum(self, nums, target): low, height = 0, len(nums) -1 while low + 1 < height: mid = (low + height) / 2 if nums[mid] == target: return target elif nums[...
5b06fd46806e714dbda3654c97e295e5e8289979
0x0400/LeetCode
/p46.py
443
3.515625
4
# https://leetcode.com/problems/permutations/ from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if not nums: return nums if len(nums) == 1: return [nums] rst = [] for i, num in enumerate(nums): plans =...
98a543d5aeb99c90f2a489b5ad31d7366a4a3b69
0x0400/LeetCode
/p48.py
2,324
3.578125
4
# https://leetcode.com/problems/rotate-image/ # 按边处理;从外圈到内圈 # 选定4个顶点,其他点通过距离这些顶点的距离来计算翻转后的坐标 from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ sideAction = [ { ...
92f9a6c1ee427a73a87152586269148b01936ecc
0x0400/LeetCode
/p211.py
1,496
3.921875
4
# https://leetcode.com/problems/design-add-and-search-words-data-structure/ from typing import Dict, List class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.isWord = False self.children: Dict[str, 'WordDictionary'] = {} def ad...
f0491e1752d3319cc70596249e6fd73213fc5a1c
0x0400/LeetCode
/p90.py
991
3.546875
4
# https://leetcode.com/problems/subsets-ii/ from typing import List class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() rst = self.subsetsWithoutBlank(nums) return [[]] + rst def subsetsWithoutBlank(self, nums: List[int]) -> List[List[int]]: ...
1079ed7cf724c0e11c57f0420a18c68f45692c23
0x0400/LeetCode
/p105.py
788
3.828125
4
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: ...
2157d622577d66165666e7d1ccf4a22f9303da1b
0x0400/LeetCode
/p99.py
1,684
3.78125
4
# https://leetcode.com/problems/recover-binary-search-tree/ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __str__(self) -> str: return "<Tree...
f12a89d16a3e488ce98c64da0b2cb021bb46a492
0x0400/LeetCode
/p33.py
1,674
3.609375
4
# https://leetcode.com/problems/search-in-rotated-sorted-array/ class Solution(object): def ascendingSearch(self, nums, target, leftIdx, rightIdx): if rightIdx < leftIdx: return -1 if leftIdx == rightIdx: return leftIdx if nums[leftIdx] == target else -1 midIdx = (...
ac8c29b23d558ab91d8c0f07a320ea18d73c471f
0x0400/LeetCode
/p893.py
843
3.53125
4
# https://leetcode.com/problems/groups-of-special-equivalent-strings/ from typing import List, Tuple class Solution: def numSpecialEquivGroups(self, A: List[str]) -> int: cache = {} for s in A: # cache[self.getStrKey(s)] = True cache[self.getStrKeyV2(s)] = True ret...
378cc8a05a2b4398172062870df0264d3e16e48a
0x0400/LeetCode
/p124.py
1,216
3.765625
4
# https://leetcode.com/problems/binary-tree-maximum-path-sum/ from common.tree import TreeNode # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __ini...
cb698c1299c7446cc4aa42923ba2af0b2a2efe9e
0x0400/LeetCode
/p215.py
1,066
3.625
4
# https://leetcode.com/problems/kth-largest-element-in-an-array/ from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return sorted(nums, reverse=True)[k-1] def findKthLargestQS(self, nums: List[int], k: int) -> int: ''' 使用 快排 的方式,查找对应的值 ''...
50d2e92ecbf1f3eea0e856c18578aaefe8e0427e
0x0400/LeetCode
/p131.py
839
3.78125
4
# https://leetcode.com/problems/palindrome-partitioning/ from typing import List class Solution: def __init__(self) -> None: self.cache = {} def partition(self, s: str) -> List[List[str]]: if not s: return [] if s in self.cache: return self.cache[s] ...
d056db37420acf908e4387f007aa87d7001d67bd
tjlakin/University
/Other Examples/Python/Linked List.py
1,417
3.703125
4
import sys, random array = [[0 for i in range(2)]for i in range(15)] for i in range(10): array[i][0]=str(random.randint(1,1000)) for i in range(10): array[i][1]= i + 1 print(array) pointer = 0 def checknext(pointer): global array n = array[pointer][1] return n if pointer == None: exit() ...
846587aba4df9fc06c052c9230cb987932b372e0
tjlakin/University
/CT4021/Python/Tax deduction calculator.py
821
3.8125
4
def calculate(gross_salary): if (gross_salary <= 11850): print ("Net Salary after tax is ",gross_salary) print ("Tax deduction is 0%") elif (gross_salary>=11851 and gross_salary<=46350): print ("Net Salary after tax is ",round (gross_salary-(gross_salary*0.20),2)) print("Tax dedu...
428aa39cbcb655176d5ac7b23407316bf93a613a
Emericdefay/OCR_P7
/AlgoInvestNTrade/brut_strategy/Management/bruteforce.py
5,099
3.640625
4
# Std Libs: from itertools import combinations from typing import Optional import time # Local Libs: from csv_translator import CsvTranslator class BrutForce: """ Simulate the benefits according to a given sequence. """ def __init__(self, sequence: list, actions: list...
8e544650d4c76767ff3092e614978bc4b5b69584
fahimnis/CS303_Computer_Programming_Projects
/NextDay.py
5,756
4.125
4
# File: NextDay.py # Description: HW4 # Student's Name:Fahim N Is # Student's UT EID: fni66 # Course Name: CS 303E # Unique Number: 50180 # # Date Created: 2/11/20 # Date Last Modified: 2/13/20 def NextDay(): #Take inputs y = int(input("Please enter the year: ")) m = input("Please enter...
a55db03c2d0ccfe6c86920ea4c26131ec980d539
fahimnis/CS303_Computer_Programming_Projects
/Reverse.py
505
4.21875
4
# File: Reverse.py # Description: Homework_4 # Student's Name: Fahim N Islam # Student's UT EID: fni66 # Course Name: CS 303E # Unique Number: 50180 # # Date Created: 2/6/20 # Date Last Modified: 2/10/20 def Reverse(): x = int(input("Enter an integer: ")) a = int(x/100) b = int(...
6593f0e92118c50a96535de39da0aae02a38a7f9
aatmanvaidya/Web-Scrapper
/link_scrapper.py
631
3.546875
4
import requests from bs4 import BeautifulSoup url = "https://www.geeksforgeeks.org/home/" #Get the HTML req = requests.get(url) htmlContent = req.content #print(htmlContent) #parse the HTML soup = BeautifulSoup(htmlContent, 'html.parser') #Get the Title of the HTML page title = soup.title # Get all the anchor tags...
422dd0e284e590667cb88b3da88e9a7bd3cf9949
doctoryes/project_euler
/python/prob1.py
124
3.609375
4
sum = 0 for count in range(1, 1000): if count % 3 == 0 or count % 5 == 0: sum = sum + count print sum
89d47577d446f8f701e2847dafdbd7b78533eb19
doctoryes/project_euler
/python/prob12.py
2,756
4.09375
4
#!/usr/bin/env python # -*- coding: latin-1 -*- # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # Let us list the factors of the first seven ...
f3b87d3ae5ed6f7704920151ee8430be1ce1e3b6
mbassale/noteprg
/lorem/loremlib.py
1,133
3.90625
4
import random WORDS = ("adipisci aliquam amet consectetur dolor dolore dolorem eius est et" "incidunt ipsum labore magnam modi neque non numquam porro quaerat qui" "quia quisquam sed sit tempora ut velit voluptatem").split() def get_word(): return random.choice(WORDS) def get_sentence(num_of_...
f542b03e60b159f12efa105551ea0bce8d205aea
Emerson-O/PythonBasicoE_Gerber
/HT3.py
806
4.15625
4
#Ejercicio1 print("EJERCICIO 1") con1 = input("Ingrese la contraseña a almacenar por favor: ") print("") contraseña = input("Introduce tu contraseña para ingresar: ") print("") if con1.lower() == contraseña.lower(): print("Contraseña correcta, Bienvenido") else: print("La contraseña incorrecta") print...
864e98f58a6b0bb2875de0c44e803d9c6c40307f
IiroNiemel/morsemachine
/morsemachine.py
2,080
3.609375
4
import winsound import time def changeFreq(frq): newFreq = input("Type new freq, it must be between 37 and 32000") if newFreq > 37 and newFreq < 32000: print("Success") return frq else: print("Invalid, go home") def goToMorse(word, Frequency): try: frequency = int(Frequ...
83390dfec4886f82aeeb437ca7dec456ea6ffc53
LijunRio/AI01002H-ImageProcessing
/section_2/gaussKernel.py
851
3.53125
4
""" @leofansq https://github.com/leofansq """ import cv2 import numpy as np import math def gaussKernel(sig, m=None): """ Generate a Gauss kernel. Parameters: sig: sigma m: the shape of the Gauss kernel is m*m Return: a Gauss kernel """ # Cal & Judge m M = math.ceil(...
3bf45d13c3d658a6d676522e19ef5c5e8eef4adc
AYMANWARDI/peruke
/src/game_implementation/dice.py
405
3.578125
4
from random import randrange from typing import Collection from game_implementation.types import DiscId def get_dice() -> Collection[DiscId]: dice = [randrange(0, 6) for _ in range(3)] print(f"Dice: {[d + 1 for d in dice]}") return dice def get_unique_dice() -> Collection[DiscId]: # For initial saf...
d257b52336940b64bc32956911164029f56c5f22
maxz1996/mpcs50101-2021-summer-assignment-2-maxz1996
/problem3.py
1,587
4.40625
4
# Problem 3 # Max Zinski def is_strong(user_input): if len(user_input) < 12: return False else: # iterate through once and verify all criteria are met number = False letter = False contains_special = False uppercase_letter = False lowercase_letter = False...
6ecbe8835796ebee5ac626c08653a3b6b8b9c1bf
takeller/Code-Challenges
/how_many_words/test_how_many_words.py
621
4.03125
4
import how_many_words def test_how_many_words(): sentence1 = "Hello World! ? 54 94" sentence1_word_count = 2 sentence2 = "Hello My name 456 Is Taylor AND i am a back-end engineer. 57 83" sentence2_word_count = 11 sentence3 = "he is a good programmer, he won 865 competitions, but sometimes he don...
7e52333c372dac152d046fb6d2f6ff763b9cf019
rajila/courserapython
/enfoqueoopI.py
1,132
4.125
4
class SupA: varA = 1 def __init__(self): pass def funA(self): return 'A' def funC(self): return 'CA' class SupB: varB = 2 def __init__(self): pass def funB(self): return 'B' def funC(self): return 'CB' def do(self): ''' ...
215af76f4f8a25fedfebf786496d41664c485c79
rajila/courserapython
/generadores.py
2,577
3.921875
4
# Using CLASS class Fibonacci: def __init__(self, N): self.__N = N self.__index = 0 self.__F1 = self.__F2 = 1 # Obligatorio (Se ejecuta una sola vez) def __iter__(self): return self # Obligatorio (Se ejecuta en cada iteración) def __next__(self): self.__inde...
3775b1b90e4c887bbf357bf5d7cbd493e9831063
rajila/courserapython
/enfoqueprocedimental.py
1,068
3.875
4
''' La programación procedimental fue el enfoque dominante para el desarrollo de software durante décadas de TI, y todavía se usa en la actualidad. Además, no va a desaparecer en el futuro, ya que funciona muy bien para proyectos específicos (en general, no muy complejos y no grandes, pero existen mucha...
2aa706bd06c91b18bf6a63e9b47e75708597a401
dvtruongson/ManufacturingNet
/ManufacturingNet/models/xgb.py
41,957
3.765625
4
"""XGBoost trains a XGBoost model on the given dataset. Before training, the user is prompted for parameter input. After training, model metrics are displayed, and the user can make new predictions. Classification and regression are both supported. View the documentation at https://manufacturingnet.readthedocs.io/. ""...
d0ef21fce9b9e8d7df440faf4eab6a39f09660d2
dvtruongson/ManufacturingNet
/ManufacturingNet/models/random_forest.py
45,062
3.703125
4
"""RandomForest trains a random forest model implemented by Scikit-Learn on the given dataset. Before training, the user is prompted for parameter input. After training, model metrics are displayed, and the user can make new predictions. Classification and regression are both supported. View the documentation at https...
56c94622c6852985b723bf52b0c2f20d2617f6c8
kaozdl/property-based-testing
/vector_field.py
2,082
4.125
4
from __future__ import annotations from typing import Optional import math class Vector: """ representation of a vector in the cartesian plane """ def __init__(self, start: Optional[tuple]=(0,0), end: Optional[tuple]=(0,0)): self.start = start self.end = end def __str__(self) ...
326f40b06c80681926a9b81f4bfb22a0c81e214a
Redux-TTV/Daily_Coding_Problems
/serialize_deserialize_root.py
1,219
3.859375
4
#07/20/2018---------------------------------------------------------------------------------------------------- #Given the root to a binary tree, implement serialize(root), #which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. #For example, given the following ...
69359dc40e3f574dc243e51ab9de5d74aa38f0f1
Jose-Humberto-07/pythonFaculdade
/avaliacao-formativa-02/Q-05.py
413
3.59375
4
#import random print("============Média de Idade Funcionários==============") idade = [] soma = 0 for c in range(90): print("Qual a idade do",c+1,"º funcionário?") idade.append(int(input())) # idade.append(random.randint(16, 90)) # print(idade[c]) soma += idade[c] media = round(soma/len(idade)...
abe6210f57601e0db989022a42f3f226b5939fc6
Jose-Humberto-07/pythonFaculdade
/avaliação-somativa/Q-10.py
842
3.640625
4
print("=========================================") print("=========================================") print("==================BANCO==================") print("=========================================") print("=========================================") banco = [] for i in range (2): cliente = {"nome":''...
83abb38c6594abacbf8e6d615624e4db9d1bbeb5
Jose-Humberto-07/pythonFaculdade
/arquivo-json/carrosJson.py
620
3.515625
4
import json ''' teste = { "nome": "", "idade": 0, "altura": 0.0, "peso": 0.0, "sexo": "" } #convertendo arquivo json em dicionário carros_json='{"marca":"honda,"modelo":"HRV""cor":"prata"}' carros=json.loads(carros_json) print(carros["marca"]) print(carros) for i in carros: ...
c8e5802061a5e24d9c599560209057ae269b53a8
Jose-Humberto-07/pythonFaculdade
/vetores.py/vetor.py
429
3.84375
4
idades = [16,14,31,22,48,31] idades.append(26) print(idades) #idades[1] = 56 #print(idades) #idades.remove(31) #print(idades) #idades.pop(3) #print(idades) #idades.clear() idades.insert(0,38) print(type(idades)) print(idades) idades.sort(reverse=True) print(idades) print("maior:",idades[0]) print("3 mai...
0989f50d9620cbe6e4124d46817a8c3451c7f179
Jose-Humberto-07/pythonFaculdade
/loops/while.py
124
3.953125
4
print("Quer contar até quanto? ") num = int (input()) cont = 1 while (cont <= num): print(cont) cont += 1
033813da0698f0fbfee6e4925b9117b8faee476f
Jose-Humberto-07/pythonFaculdade
/funcoes/exe01.py
376
4.21875
4
def inverter(texto): return texto[::-1] pessoas = [] for p in range(3): perguntas = {"Qual o seu nome?":"", "Em que cidade você mora?":"",} print((p+1),"° entrevistado") for pe in perguntas: print(pe) perguntas[pe] = input() print() pessoas.ap...
4e0d1652ff247f7dd2a691796035f27d4d193ff2
Jose-Humberto-07/pythonFaculdade
/funcoes/exe02.py
163
3.546875
4
print("nota 1: ") n1 = float(input()) print("nota 2: ") n2 = float(input()) def media(n1, n2): return (n1 + n2) / 2 print("Média: ",media(n1, n2))
19b3936f8b619cd06285819573a853cb497c1fd7
AvPelli/pacman_python
/Pac-Man/Gate.py
1,368
3.921875
4
class Gate(): def __init__(self, port1, port2): """ Constructor of Gate (2 Coordinates are given).\n :param port1: type: Coordinate :param port2: type: Coordinate """ self.__port1 = port1 self.__port2 = port2 def give_other_port(self, port): """ ...
3af85509e1d65d7898b3dce8742ad52e09d31ef8
AvPelli/pacman_python
/Pac-Man/Character.py
4,990
3.96875
4
from abc import ABC, abstractmethod from copy import deepcopy from Coordinate import Coordinate from Direction import Direction class Character(ABC): def __init__(self, PIXELSIZE, speed, moving_pos, direction, game, coordinate): """ Creates a Character object, Ghost and Pacman subclasses also use...
1797d722a2a157e7b6a5589c01b795ad7ebebaf6
rajeshkumarkasarla/my_python_practice
/while example 2.py
65
3.71875
4
x=0 while False: print("hello") else: print(" x is not")
0d4872c39de8dc25f1201e247db75c8541eb16e5
rajeshkumarkasarla/my_python_practice
/swap example.py
114
3.84375
4
x=input("enter x") y=input("enter y") x=(x+y) y=(x-y) print('The swapped values are {}{}'.format(x,y) )
5e9618e391a9389f7c002a9452a58775563d4f45
tillderoquefeuil-42-ai/bootcamp-ml
/day03/ex12/confusion_matrix.py
953
3.53125
4
import numpy as np def prac(y_true, y_hat, l1, l2): cl1 = np.full(y.shape, l1) cl2 = np.full(y.shape, l2) a = cl1 == y_true b = cl2 == y_hat return np.sum(a * b) def confusion_matrix_(y_true, y_hat, labels=None): """ Compute confusion matrix to evaluate the accuracy of a classification. ...
a339e6fbc030ddbf9106ae635d9deb10486852ab
Andrea-Oliveri/ML-Project-Unet-Robustness
/Scripts/image_processing_methods.py
4,605
3.59375
4
# -*- coding: utf-8 -*- import numpy as np import cv2 from abc import ABC, abstractmethod from utils import normalize class ImageProcessingMethod(ABC): """ Class ImageProcessingMethod. Abstract class representing a classical image processing method used for segmentation. """ @abstractmeth...
2a6807bdbf17a07c5b28476d2737fc0969696cad
ianhaddock99/Nov2020Coh1
/week01/5-Friday/labs/recursion.py
3,167
4.3125
4
# 1. Write a function called power which accepts a base and an exponent. # The function should return the power of the base to the exponent. <<<<<<< HEAD # RECURSION EXAMPPLE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # def power(base, exponent): # if exponent == 0: # return 1 # return base * power(base, ex...
2c285764a116c75106ad169572f0425fa7c86496
suzannastep/RootFinding
/groebner_from_roots.py
9,769
3.53125
4
''' Catherine Kellar Nov 24 17 Groebner basis generator given roots ''' import numpy as np import scipy as sp from scipy.misc import comb nchoosek = lambda n,k: int(comb(n,k)) def getMonBase(d,n): '''base = getMonBase(d,n) --------------------- Returns a set of monomials of total degree d in n variables...
4d0c234338684126b16d074db2f76f759d6fb607
jphuart/2014_think-of-the-children
/data/sources/reversegeo.py
645
3.546875
4
import csv import json import urllib2 import urllib schoolsfile= csv.reader(open('datasets/Ecoles primaire-maternelle 2012_FLANDRE.csv')) # Read thefirst row of garbage schoolsfile.next() schoolsfile.next() for row in schoolsfile: #0 nis #1 sex #2 ageground #3 quantity street=row[2] city=row[3]...
deb1a80c8b8cb1224b377b25a2d6169b4aaa68d4
TotesReptilian/CelestialShell
/globe.py
2,762
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import math from util.angle import Angle, Degree, Latlon, HourAngle from util.location import StarLocation, SphereLocation from util.vector3 import Vector3 class Star(StarLocation): def __init__(self, ra, dec): """ :param ra: Latlon Right As...
be6428ebc19910c267d99294c8e38dc1b6b69b43
EricLi404/nb
/leetcode/tencent-hot50/46_permutations.py
754
3.703125
4
# https://leetcode-cn.com/problems/permutations/ from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def dfs(path, size, done, depth, res): if depth == size: res.append(path[:]) return for i in nums: ...
2dacd939c43e8588c4dddf05d5361023d6b56315
EricLi404/nb
/leetcode/tencent-hot50/53_maximum-subarray.py
771
3.65625
4
# https://leetcode-cn.com/problems/maximum-subarray # 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 # # 示例: # # 输入: [-2,1,-3,4,-1,2,1,-5,4], # 输出: 6 # 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: maxv = nums[0] c_maxv ...
4b8ef77a97b9dccdf8f48efa01dfa0a92f7ce153
EricLi404/nb
/algorithm/others/mae&rmse.py
730
3.71875
4
import math from typing import List def RMSE(records): return math.sqrt(sum([(rui - pui) ** 2 for _, _, rui, pui in records]) / (len(records))) def MAE(records): return sum([abs(rui - pui) for _, _, rui, pui in records]) / len(records) class Solution: def minSubsequence(self, nums: List[int]) -> List[...
05b032915d09ae0fa44f51ec0aafe3997b1d00d2
EricLi404/nb
/leetcode/sequence/1.two-sum.py
496
3.5
4
class Solution: # def twoSum(self, nums: List[int], target: int) -> List[int]: def twoSum(self, nums, target: int): for i in range(len(nums)): try: cc = nums.index(target - nums[i]) except Exception: continue else: if i ...
9d419f957965b54a61c414e52bdc961b3e8b1a98
Zhangtuoyuan/leetcode-pthon-file
/code_determine.py
1,506
3.734375
4
import re class Solution(): def __init__(self, password: str): self.password = password self.lens = len(password) self.password_list_entry = [i for i in password] self.low = 0 self.upp = 0 self.cha = "abcdefghijklmnopqrstuvwxyzABCD...
b2ac24701ad55824b4f97c464f2157cde1f0cc30
RenBaixiao/MyCLRS
/important/2-3-2-merge-sort.py
849
3.859375
4
import random max_integer = int(input('integer scope:0-? ')) + 1 length = int(input('how many integers? ')) A = [] if length <= max_integer + 1: A = random.sample(range(0, max_integer), length) else: for i in range(0,length): A.append(random.randrange(0, max_integer)) def merge(A, p, q, r): L = A[...
5b193de3163c5e546a0823effdf8964c698294de
RenBaixiao/MyCLRS
/important/2-1-2-insertion-sort.py
572
4.09375
4
import random max_integer = int(input('integer scope:0-? ')) + 1 length = int(input('how many integers? ')) A = [] if length <= max_integer + 1: A = random.sample(range(0, max_integer), length) else: for i in range(0, length): A.append(random.randrange(0, max_integer)) print('before sorting:') print(...
75d440d3a361287beb8207c7cc3c92dc682d4885
RenBaixiao/MyCLRS
/important/7-quick-sort.py
2,094
3.5
4
import random max_integer = int(input('integer scope:0-? ')) + 1 length = int(input('how many integers? ')) A = [] if length <= max_integer + 1: A = random.sample(range(0, max_integer), length) else: for i in range(0,length): A.append(random.randrange(0, max_integer)) def partition(A,p,r): k = ran...
f3de12b845723a9d49f92c8ec1b187b8103f4262
vusalhasanli/python-tutorial
/turtle/do_polygon.py
351
3.8125
4
import turtle import random def do_polygon(size, side): colors = ( 'blue', 'green', 'red', 'red', 'pink', 'magenta', 'purple', 'gray', 'yellow' ) angle = 360 / side for i in range(side): turtle.color(random.choice(colors)) #picks color randomly for each side turtle.fd(size) turtle...
d629fb9d9ce965a27267cbc7db6a33662e0ff1d1
vusalhasanli/python-tutorial
/problem_solving/up_runner.py
403
4.21875
4
#finding runner-up score ---> second place if __name__ == '__main__': n = int(input("Please enter number of runners: ")) arr = map(int, input("Please enter runners' scores separated by space: ").split()) arr = list(arr) first_runner = max(arr) s = first_runner while s == max(arr): arr.r...
2d885d0792068aa627ecfdab2db1bd3954e06dd8
bgergovski/simple-webapp
/other/test.py
466
3.734375
4
a = 'Hello, Borislav' print((a.split(','))[1]) print(type(a)) #thislist = ["apple", "banana", "cherry"] #thislist.pop(1) #print(thislist) thislist = ["100", "200", "500"] new_env = 'bobasdafe23rewr dasdasdv3443' print(new_env.count(new_env)) print(thislist) odd_name_list = [listnew for listnew in thislist] dict_bob ...
a073b6795efabc2a737764526d855984b98f8101
sho-portfolio/machine-learning-logistic-regression
/google-colab/main.py
5,063
3.609375
4
""" author: sho date: 2019-10-15 description: multiclass classification of text inputs using keras. code to train, evaluate, productionize and use model to predict in ~35 lines of code Three main sections: 1) train and evaluate model 2) productio...
732fbf6bbd0653f9a39ce9872ab80b35f9f0d26d
mwendo/Python
/fundamentals/Function_basics2/functions_basic2.py
853
3.84375
4
# 1 def countdown(num): result = [] for x in range(num, -1, -1): result.append(x) return result print(countdown(10)) # 2 def print_and_return(x): print(x[0]) return x[1] print(print_and_return([1,2])) # 3 def first_plus_length(x): sum = x[0] + len(x) return sum print(first_plus_l...
30a50e8fe6c61956e1387af1d0ea8dfad03d9c25
geekgodgagan/Python_automation
/menu_lvm.py
3,363
3.921875
4
def lvm(): import os def displayDisks(): print("fdisk -l") os.system("tput setaf 3") print("""\t\t\t LVM menu. \n Before starting you need to attach atleast 2 hard disks to your virtual machine.\n Do this by going to setting->storage->add new storage (at the bottom)->hard disk->add or create(virtual hard ...
3052d83b3609a50f51e5d3aa8d022d45dfe924a5
w0ytaz/pyth
/func_prog/code/0903_lang__decorator__second_level_wraps.py
479
3.578125
4
""" ## Wraps https://docs.python.org/3.9/library/functools.html#functools.wraps """ from functools import wraps def decorator(func): print(f"Run {func.__name__} function") @wraps(func) def inner(*args, **kwargs): print(f"With args:{args} and kwargs:{kwargs}") return func(*args, **kwarg...
2b012c6cd805fa8a6a7984803f0161bba9a7d9fb
w0ytaz/pyth
/func_prog/code/0301_lang__first_class_citizen__map.py
436
3.84375
4
""" ## Functions map """ def add(a, b): return a + b def sub(a, b): return a - b def collect(y, a, b): print(f"Run {y.__name__} function with {a} and {b}") return y(a, b) string = "5+2" map = {"+": add, "-": sub} a, sign, b = string result = map[sign](a, b) print(f"{string}={result}") stri...
72e97d852c2173896805eeb22bbab59c88d77684
w0ytaz/pyth
/func_prog/code/0401_lang__lambda__args.py
152
3.828125
4
""" ## Lambda arguments """ hello = lambda x: print(f"Hello {x}") hello("You") hello = lambda x, y: print(f"Hello {x} and {y}") hello("You", "Me")
ff96a1d6e5d0a6f44b45a5f61ad43556fc1511f1
maxmavv/ddsCrewBot
/database.py
1,750
3.703125
4
# -*- coding: utf-8 -*- import sqlite3 as sql import config as cfg ct_text = """CREATE TABLE PARTICIPANT ( chat_id integer, participant_id integer, participant_first_name text, participant_last_name text, participant_username text ); ...
9c8413496b73c4133b5ce740229128c6e9407cfe
Saptarshisaha777/Python-Programs
/longest word in a sentence & it's length.py
350
3.84375
4
s=input("Enter the sentence:") str=s n=len(str) res=0 j=-1 k=0 parts=str.split(' ') n=len(parts) for i in range(0,n): w=len(parts[i]) if ((res!=max(w,res)) or ( k==0 and i==n-1)): res = max(w, res) k=k+1 j=i; print(j,i,n) print("The longest word is (",parts[j],") A...
0d277ebffd4672aaacaff13b1cac26a541da92f2
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Codes/decomposition.py
1,578
3.921875
4
''' Task: cook dinner ''' def cook_dinner(chicken, beans, veggies): ''' cut up the chicken wash veggies cut and sate the chicken boil water ... ''' pass ''' Sort numbers, len(L) = n Running time: T(n) is in Theta(n^2) Space: S(n) is in Theta(n) ''' def sort1(L): ''' 1.find the smalles...
9563b9c441cf2cee25e9f7a93c79aa13ca1a852c
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Codes/qsort.py
311
3.875
4
def quicksort(items): if len(items) <= 1: return items else: pivot = items[0] lesser = [x for x in items[1:] if x < pivot] greater = [x for x in items[1:] if x > pivot] return quicksort(lesser) + [pivot] + quicksort(greater) L = [-1, 10, 2, 5, 4, -2, -9, 0, 4, 23, 64] print(quicksort(L))
2f8523d3905b9dfa46cf3415468bfa3b4f9ac78c
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Fall2017/hw-sol/hw1/tmiles.py
3,956
3.5
4
# *censored* Comp 4030 Assignment 1 import random #------------------------------------------------ def get_list(n): L = list(range(n)) for i in range (len(L)): L[i]=2 L[randint(0, n-1)]=1.5 print('The array is:') print(L) print('The number of items is '+str(len(L))+'.') return L #--------------------------...
5d6c5619df66476c3f5ac9554e462785d1299058
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Codes/dyn_prog_study_guide.py
1,603
3.6875
4
########################################################### # coins = [4,5,13,17] X = 11 # make_change(L, value) returns True if and only if it is possible to make # change for value dollars using coins in L. # make_change(L, value) = OR{ make_change(L, value-coin) for some coin in L } # Table[value] stores the value ...
2c453ed87f9a1dc70ae8881d76b2d21f5b7c0a02
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Codes/fibonacci.py
561
4.0625
4
Table = {} # Use Table[x] to store the output of f(x) # When we compute f(x), first before we do anything, # check to see if x is in Table. # 1. if x is in Table, simple return Table[x] # 2. else, do whatever f does to compute f(x). Before we return the output, store # the output into Table[x]. # fib(0) = 0...
c476c4ec4acd1daf30d7af4ac5c6dfd6ac2f6d79
Coaxecva/COMP4030-Design-and-Analysis-of-Algorithms
/Fall2017/hw-sol/hw8/tgodman1.py
1,689
3.65625
4
#Problem 1 def restorable(string, dictionary): if len(string) == 0: return True if string in dictionary: return True for i in range(len(string),-1,-1): u = string[0:i] v = string[i:len(string)] if v in dictionary: for j in range(len(u),-1,-1): y = u[j:len(u)] x = u[0:j] if x in ...
2ba0b30bf2aef7dcb34eeb8ecac170aebac177c4
TwoSails/ElfGame
/elfGame.py
7,749
3.609375
4
""" Program: Elf Game Description: a probability based game about elves Author: TwoSails Version: 1.3.1 """ import random import colours as color import config version = config.version print("------ Elf Game ------") messageOne = 'All the elves sent out died in a horrific gang related incident with goblins. th...
d05f29f9830f327c30cad3f79e1cf08871d20dd5
elit-altum/OOP-Python
/zip.py
115
3.640625
4
list_1 = [10, 20, 30, 40] list_2 = [1, 2, 3, 4, 5] list_3 = [40, 50, 60] print(list(zip(list_1, list_2, list_3)))
26ea07e2b9dc828aafbaec01038f49ffa71c6bae
elit-altum/OOP-Python
/comprehensions.py
502
3.921875
4
# list comprehensions # squaring numbers my_list = [num**2 for num in range(1, 10)] print(my_list) # squaring and only using odd numbers my_list2 = [num**2 for num in [1, 2, 3] if num % 2] print(my_list2) # set comprehensions my_set = {num*2 for num in [1, 2, 3, 4, 1, 2] if num > 1} print(my_set) # duplicate value...
99bf71a4b19ddc7495692c96d362671f2b8ce618
jorn252/jornsteels
/guessing game.py
12,521
3.6875
4
#########################################start############################################# mode2 = 0 category_secure = 0 print("For more info: whatsapp:+310610240195") #################################system and disclaimer############################################################# while mode2 == 0: single_...
2c44353f720f87cf511ed13faab6eeb640b01aef
prachi173/Python
/Virtual Assistant/Virtual_Assistant.py
6,270
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[8]: # Description: This is a virtual assistant program that gets the date, time and responds back with a random greeting. Returns information on a person #pip install pyaudio #pip install SpeechRecognition #pip install gTTS #pip install Wikipedia #Import the Libraries im...
4a50cdce034f5fc9fe4367c141aa77af9379f2e2
lariodiniz/Udemy-Python-Kivy
/app-comerciais-kivy/aulas/operacao_matematica.py
719
4.21875
4
#print(10+10) #print(10(50.50)) ''' print(10-10) print(1000-80) print(10/5) print(10/6) print(10//6) # devolve a divisão sem os pontos flutuantes print(10*800) print(55*5) #Módulo de Divisão 6 % 2 #Resultado da divisão entre dois numeros print(3 % 2) print(4 % 2) print(5 % 2) print(7 % 3.1) num1 = float(input("D...
464a49465a7067cd6b1602e4411ce946bf3901a2
lariodiniz/Udemy-Python-Kivy
/app-comerciais-kivy/aulas/exercicio_pratico2.py
7,161
4.125
4
#1) Faça um algoritmo que leia um número e mostre se o mesmo é positivo, # negativo ou zero. num = int(input('Digite um número: ')) if (num > 0): print("O numero é positivo.") elif (num < 0): print("O numero é negativo.") else: print("O numero é zero.") #2) Faça um algoritmo que leia um número e mos...
d4ed2875ee9e98891d885e415d31ad470c268195
lariodiniz/Udemy-Python-Kivy
/app-comerciais-kivy/aulas/interacao.py
1,211
4.125
4
# -*- coding: utf-8 #Enquanto """ x = 0 while( x <= 10): print(x) x += 1 #Enquanto com Else x = 0 print("while") while(x<10): print(x) x+= 1 else: print("else") print("fim") #Laço For #For em python sempre trabalha com lista for c in "python": print(c) #range range(0,10,2) # devolve um obje...
68ab025f154cd1f9c23703f96ed3e389b1dc7d58
lariodiniz/Udemy-Python-Kivy
/app-comerciais-kivy/aulas/operadores_listas.py
393
3.9375
4
# verifica se o valor de uma variavel esta em uma lista x = 'b' lista = ['a', 'b', 'c'] print(x in lista) print(2 in (1,2,3,4,5)) print(6 in (1,2,3,4,5)) print(6 not in (1,2,3,4,5)) print(1 in range(1,6)) print( 3 and 5 in range(1,6)) print(((1 and 6) or(5 and 6)) in range(1,6)) print(((1 and 3) or(5 and 6)) in ra...
35ed9c3baf43851e7df245767bf6e011c70689e5
hp396/Leetcode
/Python Solutions/35 Search Insert Position/35 Search Insert Position.py
275
3.75
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: for num in nums: if num == target: return nums.index(num) elif num > target: return nums.index(num) return int(len(nums))
32ae25720a58c1615ba4f0b9308115034b864edd
hp396/Leetcode
/Python Solutions/19. Remove Nth Node From End of List/Solution.py
678
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: first_head =second_head= head for i in range(n): ...
75f6b1cee2318bcc496470ff275472f90f968735
gulmehmet1/pdsnd_github
/bikeshare.py
11,057
4.0625
4
import time import pandas as pd import numpy as np VALID_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'all'] VALID_MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'all'] LST_CITY=["Chicago","New york city","Washington"] CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new...
666ffad39631eeba4b0abe3855c46c2c01094fc7
divir94/EECS-348-Intro-to-AI
/Lia_Bla_Mur.py
9,639
3.515625
4
import heapq import time import random class Lia_Bla_Mur: def __init__(self): self.board = [[' ']*8 for i in range(8)] self.size = 8 self.board[4][4] = 'W' self.board[3][4] = 'B' self.board[3][3] = 'W' self.board[4][3] = 'B' # a list of unit vectors (row, col) self.directions = [ (-1,-1...
90533af94c31c8774c5329c5da66e93a3444dfb3
markwatkinson/project-euler
/17.py
1,256
4
4
""" If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? """ # this question is a pain WORDS = { 'digits': [None, 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', # inconsistent 'eleven', 'twelve', 'thirteen'...
33909e633a9028170e1bdd097b4cad4ff968f43b
markwatkinson/project-euler
/62.py
942
3.96875
4
""" Find the smallest cube for which exactly five permutations of its digits are cube. """ """ this is easy if you look at it right, and incredibly hard if you don't. Instead of generating permutations, generate a list of cubes and count the digits in each. Make a list of the digit counts, and see which is the first ...
adc772bacf15683fec2648227487ba6774162a64
markwatkinson/project-euler
/42.py
691
3.984375
4
""" A triangle number is 1/2 * n(n+1) for integer n >=1 A triangle word is a word whose letters sum to a triangle number (a = 1, b = 2 etc) In the given word list, how many are triangle words? """ import csv reader = csv.reader(open('data/42.words.txt')) words = [w for w in reader][0] # generate a list of sums co...
6d652210da9a9dc8527e1cf507c3f6082fd176ee
markwatkinson/project-euler
/33.py
1,477
3.546875
4
""" http://projecteuler.net/index.php?section=problems&id=33 strange fractions """ a, b = 11, 1 fractions = [] while b <= 99: # apologies for terrible naming here. We use lists to more easily manipulate # the contents than strings b_ = list(str(b)) for a in range(10, b): # check if a and b have a commo...
74c6443493082d171c2e18960e42753f9b96e1c3
markwatkinson/project-euler
/25.py
215
3.59375
4
"""What is the first term in the Fibonacci sequence to contain 1000 digits?""" from lib import euler for i, f in enumerate(euler.fibonacci()): #print i+1, f if len(str(f)) >= 1000: print i+1 break
bb2811852b58ace339ff0642c875502df30fe4f0
markwatkinson/project-euler
/56.py
269
3.796875
4
""" Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum? """ from lib import euler max_ = (0, 0) for a in range(100): for b in range(100): s = euler.digital_sum(a**b) if s > max_[1]: max_ = (a**b, s) print max_[1]