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
e88b870d86c2508b8ac2090b943c5738610302cb
fangyuan2015/python2018
/class2.py
586
3.875
4
#!/usr/bin/env python #coding=utf-8 class Employee: "所有员工的基类" empCount = 0 def __init__(self,name,salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name: ",self.name,...
fc74d1c4f18897efb73d853b3ff943d5dcdb2fbf
fangyuan2015/python2018
/for1.py
207
3.859375
4
#!/usr/bin/env python #coding=utf-8 for letter in 'Python': print '当前字母:',letter fruits = ['banana','apple','mango'] for fruit in fruits: print '当前水果:',fruit print 'Good bye!'
2d3311492764e06635ad8227e63a624b054e3710
ranlongyu/movie_knowledge_graph
/IMDB_data/database_operation.py
1,804
3.578125
4
import pymongo # 运行之前先启动数据库 sudo service mongod start class database(): # 传入数据库名和集合名初始化 def __init__(self, database_name, collection_name): # 链接数据库 client = pymongo.MongoClient(host='localhost', port=27017) # 链接数据库 db = client[database_name] # 指定数据库中的集合,类似于表 self...
d4c2e09013e58e3e56ba53fc4fb292dc2066edd0
ranlongyu/movie_knowledge_graph
/IMDB_data/test2.py
791
3.71875
4
import pymongo # 运行之前先启动数据库 sudo service mongod start # 链接数据库 client = pymongo.MongoClient(host='localhost', port=27017) # 链接test数据库 db = client['kg'] # 指定数据库中的集合,类似于表 collection = db['people'] student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': [1, 2, 3] } student1 = { 'id': '20...
c6fa3cbc24909ce03ce6f5243738806b0b4356a8
AkshaykumarG26/Data-Science
/cl.py
267
4
4
'''num = list(range(10,33)) list print(num) num2 = num[::-1] print(num2)''' import tkinter as TK import turtle my = turtle.Turtle() my.speed(0) def square(length, angle): my.forward(length) my.right(angle) for i in range(200): square(200, 90) my.right(7)
913dac2e645ad3165ceb2eedead8a66bf8f83483
gc-westover/date-checker
/date_checker.py
353
3.921875
4
date1 = [ 3, 4, 2021 ] date2 = [ 3, 3, 2021 ] def dateCode(dateArray): return 100*dateArray[2] + 10*dateArray[0] + dateArray[1] def compareDates(d1,d2): if dateCode(d1) < dateCode(d2): print("Date 1 earlier") elif dateCode(d1) == dateCode(d2): print("same date") else: print("Date 1 lat...
1155ae92da6520c32e0014a143ec0bcdc14ed902
hyperbora/python-coding-notes
/sorting/insertion_sort.py
340
4
4
def sort(arr): length = len(arr) for i in range(1, length): for j in range(i, 0, -1): if arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] else: break return arr if __name__ == "__main__": arr = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8] ...
5d284deff89111d732e92c19567070008b87b3f4
nikitajuneja1/CompetitiveProgramming
/CodeForces/D-900/48A. Rock-paper-scissors.py
654
4
4
#rock pair scissor f = input(); m = input(); s = input(); if f=='rock' and m=='scissors' and s=='scissors': print('F') elif m=='rock' and f=='scissors' and s=='scissors': print('M') elif s=='rock' and f=='scissors' and m=='scissors': print('S') elif f=='scissors' and m=='paper' and s=='paper': print('F'...
cbf020dd78332deb25a70a5082f072a8bcfd5558
fnmartinez/unit-testing-workshop
/calc/__main__.py
681
3.78125
4
import argparse import calc def get_args(args=None): parser = argparse.ArgumentParser() parser.add_argument('operand', choices=['add', 'subtract', 'multiply', 'divide']) parser.add_argument('a', type=int) parser.add_argument('b', type=int) return parser.parse_args(args) ...
2cef4fb4367302c8bdbeb9b0974138a47b164df4
eirihoyh/sudoku_solver
/sudoku.py
3,557
3.78125
4
import numpy as np class Solve_sudoku: board = [[3, 5, 0, 9, 0, 6, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 9, 0], [0, 0, 6, 0, 0, 6, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 7, 0, 0, 0, 8], [8, 9, 0, 0, 0, 5, 1, 0, 4], [6, 3, 0, 0, 4...
37a8e0fb0800f7cf0da9616455457b0272072f2f
95chengjie/PythonStudy
/Test/Study/TestList.py
1,084
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/12 16:50 # @Author : iszhang # @Email : # @File : TestList.py # @software: PyCharm L = ['Adam', 'Lisa', 'Bart', 'Paul'] # 取出前3个元素;从索引0开始取,直到索引3为止 print L[:3], L[1:3] # 每两个元素取出一个来,也就是隔一个取一个 print L[::2] # range()函数可以创建一个数列: # >>> range(1, 101) # ...
6d10321d5a634428dbcd7ee2b0ce542d2bc267f6
ROPilicious/src
/print_pretty.py
418
3.765625
4
#!/usr/bin/python3 ''' This routine will take a list of gadgets (list of instructions) and print them ''' def print_pretty(L): for i in range(len(L)): gadget = L[i] start_addr = gadget[0]['address'] print(str(hex(start_addr))+": " ,end = "") for insn in gadget: ...
63728b16ba6002b2d1add7cc080e3597bffa486b
DerekMartens/Python-Practice
/Hangman/hangman.py
2,141
3.90625
4
import random def loadWords(): words = [] f = open("Hangman\words.txt", "r") for line in f: words.append(line.strip("\n")) f.close() return words def generateBlankedWord(): generateBlankedWord = [] for i in selectedWord: generateBlankedWord.append("_") return generateBl...
a7e6329001dbaa2b5be7ca98c3ba77acae3cf6e5
guojh/aenon-OnlineJudge
/leetcode/RemoveElement.py
777
3.890625
4
# Remove Element https://oj.leetcode.com/problems/remove-element/ # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. #Arrays # Xilin SUN # Jan 8 2015 # Don't forget to ret...
faa5907d95f8ab25764f7dd6b0a05ef44f5e7f9b
rp764/untitled4
/Python Object Orientation /OrientationCode.py
1,348
4.40625
4
# OBJECT ORIENTED PROGRAMMING # INHERITANCE EXAMPLE CODE class Polygon: width_ = None height_ = None def set_values(self, width, height): self.width_ = width self.height_ = height class Rectangle(Polygon): def area(self): return self.width_ * self.height_ class Triangle(...
e9344a2e39167bed6246db7a76f0af615c13f5af
chaythanyanair/python-practise-book
/chapter2/grp.py~
369
4.03125
4
#Write a function group(list, size) that take a list and splits into smaller lists of given size. #>>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) #[[1, 2, 3], [4, 5, 6], [7, 8, 9]] def group(List,size): if size<=len(List): i=0 while i<len(List): p=List[i:i+size] i=i+size print p group([1,2,3,4,5,6,7,8,9],3) g...
dd0865c1149ef65b39e9aae7a552bd8598b82b92
venkywarriors/python_basic2Adv
/PackageName/TestNegativeLOOp.py
976
4.03125
4
''' Created on Mar 28, 2018 @author: venkateshwara.d ''' def rearrange(arr, n): # Auxiliary array to hold modified array temp = n*[None] #int temp[] = new int[n]; # Indexes of smallest and largest elements # from remaining array. small,large =0,n-1 # To indicate whether we n...
398c4eccb042069dd0bc50fd426fb7f58993f1af
Jayamadhuri/lab-program-for-dsp
/idft.py
678
3.5625
4
import cmath as cm import matplotlib.pyplot as plt import numpy as np def DFT(X): N=len(X) # size of x print(N) j=cm.sqrt(-1) x=[] i=3 for n in range(N): sum=0 for k in range(N): sum=sum+(X[k]*(cm.exp((j*2*cm.pi*n*k)/N))) x.append(sum/N) print(x) plt.subplot(1,2,1) plt.stem(np.abs(x...
1a057628c822895bf6e506846fb5fc7de0e10184
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x07-cnn/1-pool_forward.py
1,717
4.125
4
#!/usr/bin/env python3 """ Pooling """ import numpy as np def pool_forward(A_prev, kernel_shape, stride=(1, 1), mode='max'): """ pool - performs pooling on images Args: A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer. ...
c91e6c7edcae395f3b36697db5c6c26457146347
giovannyortegon/holbertonschool-machine_learning
/math/0x00-linear_algebra/14-saddle_up.py
276
3.734375
4
#!/usr/bin/env python3 """ matrix multiplication """ import numpy as np def np_matmul(mat1, mat2): """ np_matmul - matrix multiplication mat1: First matrix mat2: Second matrix Return: matrix multiplied """ mat = np.matmul(mat1, mat2) return mat
beaf01b519552537ec7dfa837963bdcf20ffe891
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x00-binary_classification/8-neural_network.py
1,328
4.03125
4
#!/usr/bin/env python3 """ neural network with one hidden layer """ import numpy as np class NeuralNetwork: """ NeuralNetwork - defines a neural network with one hidden layer """ def __init__(self, nx, nodes): """ Args: nx: is the number of input features nodes: i...
da02f0927540beb618c748d5c7e384648584512b
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/3-mini_batch.py
3,952
3.703125
4
#!/usr/bin/env python3 """ mini-batch gradient descent """ import numpy as np import tensorflow as tf shuffle_data = __import__('2-shuffle_data').shuffle_data def train_mini_batch(X_train, Y_train, X_valid, Y_valid, batch_size=32, epochs=5, load_path="/tmp/model.ckpt", save_...
e97603a1bf321aaede95c36998fe3c780b94ef84
giovannyortegon/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
551
4.25
4
#!/usr/bin/env python3 """ the transpose of a 2D matrix """ matrix_shape = __import__("2-size_me_please").matrix_shape def matrix_transpose(matrix): """ matrix_transpose - the transpose of a 2D matrix mat1: Input first matrix mat2: Input second matrix Return: New matrix """ m_length = matrix_s...
eacaa2d9a9c42352546d714119d265a76a8361a7
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/0-norm_constants.py
560
3.875
4
#!/usr/bin/env python3 """ calculates the normalization """ import numpy as np def normalization_constants(X): """ normalization_constants - calculates the normalization (standardization) constants of a matrix. Args: X is the numpy.ndarray of shape (m, nx) to normaliz...
83c1137b93f4e4bf3fb8a98ed9c3ef5351c5d8a9
mister-michael/classProperties
/solidStudent/student.py
1,774
3.765625
4
class Student(): @property def first_name(self): try: return self.__first_name except AttributeError: return 0 @first_name.setter def first_name(self, first): if type(first) is str: self.__first_name = first else: raise Ty...
adea7e4d433c8b1b45e2bfe49d42551da5b02c1f
maxingjian/2524
/homework3/mult.py
520
3.796875
4
#!/usr/bin/python2 # ECE 2524 Homework 3 Problem 1 <Xingjian Ma> import sys import argparse parser = argparse.ArgumentParser(description='Process some numbers.') args = parser.parse_args() total = 1 line = sys.stdin.readline() while line: if line == '\n': print >> sys.stdout, total total = 1 els...
229498b1a710d9c7961436cf857e4d4766e25ae5
Cloudspindle/helloml
/helloml.py
2,070
3.65625
4
#-------------------------------------------------------------------------------- # Copyright (C) 2015 - 2020 Cloudspindle Inc. # HelloMotion.ipynb: - 'hello world' example for Deep Learning using # - motion data generated from the MeKit platform. # - Learn to classify clockwis...
c5b97144bec1984e550de190969ab383e7864f65
santoshr1016/WeekendMasala
/itsybitsy/TH/find_uniq.py
597
3.84375
4
def find_uniq(arr): d = {} for num in arr: if num in d: d[num] = d[num] + 1 else: d[num] = 0 for k in d: if not d[k]: return k def find_uniq_2(arr): arr = sorted(arr) if arr[0] == arr[1]: return max(arr) else: return m...
9c0a6af5710db5a8921f02a6420006081eb802fd
santoshr1016/WeekendMasala
/itsybitsy/MyDP_Quest/stair_case_to_heaven_with_fee.py
843
4.125
4
""" You can take at max 2 steps if _ ways 1, you are already there 1 _1 if _| ways needed from Ground 1, G->1 _2 _| if _| ways needed from Ground 2, G->1, 1->1 G->2 _3 _|2 _|1 if _| steps needed from Ground will be Ways to reach from seco...
01590c40e99c849456f16f1e518037d10d3b85fc
santoshr1016/WeekendMasala
/itsybitsy/MyDP_Quest/hackerrank_abbr.py
1,222
3.796875
4
""" Pi P AfPZN APZNC LDJAN LJJM UMKFW UMKFW KXzQ K LIT LIT QYCH QYCH DFIQG DFIQG sYOCa YOCN You can perform the following operations on the string, : Capitalize zero or more of 's lowercase letters. Delete all of the remaining lowercase letters in . Given two strings, and , determine if it's possible to ma...
2431403257a1cf2922a4a63f438c1597a3831833
santoshr1016/WeekendMasala
/itsybitsy/codility/find_duplicate.py
238
3.578125
4
def duplicate(A): A.sort() for i in range(len(A)): if (A[abs(A[i])] < 0): print("duplicate exist") return True else: A[A[i]] = -1 * A[A[i]] print(duplicate(A=[1,2,3,4,5,6,7,4]))
bc01c99359f5eac0cbc29148fa6ec49e80e97984
santoshr1016/WeekendMasala
/itsybitsy/TH/wierd_case.py
279
3.828125
4
def to_weird_case(big): flag = True l = [] for ch in big: if flag: l.append(ch.upper()) flag = False else: l.append(ch.lower()) flag = True return "".join(l) print(to_weird_case('Weird string case'))
d97d68c12b6024ecef744cad439ef203986bc4a1
santoshr1016/WeekendMasala
/itsybitsy/MyDP_Quest/recursion/rev_string.py
113
4.09375
4
def reverse(str1): if len(str1)<=1: return str1 return str1[1:] + str1[0] print(reverse("Hello"))
ebe88e8d54928e59585caaa5f1823f033425af65
santoshr1016/WeekendMasala
/itsybitsy/arrays_ds/intersection_of_list.py
212
3.703125
4
list1 = [1, 2, 3, 4, 5, 6, 7, 8] list2 = [1, 3, 5, 7, 9, 11, 33, 44, 55] # intersection = [list(filter(lambda x: x in list1, sublist)) for sublist in list2] l = list(filter(lambda x: x in list1, list2)) print(l)
296515176b82ea277859a2773096249ce399318e
santoshr1016/WeekendMasala
/itsybitsy/TH/jumping_final.py
599
3.828125
4
from emoji import emojize def jumping(a): jump_dict = {} count = 1 end_of_list = len(a) - 1 start_idx = 0 while True: next_idx = a[start_idx] + start_idx if next_idx > end_of_list or next_idx < 0: print(jump_dict) return count else: if st...
bb400baa71463d5193e771daa19b426cdbdd7af9
santoshr1016/WeekendMasala
/itsybitsy/collections_DS/remove_duplicate_save_order.py
804
3.75
4
def ordered_remove_duplicate(ll): seen = set() for item in ll: if item not in seen: yield item seen.add(item) # Problem with this is Since hashes the item, the order is not maintained def normal_remove_duplicate(ll): seen = set() for item in ll: if item not in s...
f7b0e597a87a9c77cf2655e79320d9f04f134536
santoshr1016/WeekendMasala
/itsybitsy/HRank/string_manipulation/string_conversion.py
1,149
3.796875
4
def levenshtein(s, t): if s == "": return len(t) if t == "": return len(s) if s[-1] == t[-1]: cost = 0 else: cost = 1 res = min([levenshtein(s[:-1], t) + 1, levenshtein(s, t[:-1]) + 1, levenshtein(s[:-1], t[:-1]) + cost]) return res ...
ec067113ac01c8ee212d676270e5296599c56a9c
santoshr1016/WeekendMasala
/itsybitsy/TH/jumping_ver_2.py
579
3.859375
4
def jumping(a): count = 0 end_of_list = len(a)-1 start_idx = 0 prev_idx = 0 while True: next_idx = a[start_idx] + start_idx if prev_idx == next_idx and next_idx < end_of_list: print("infinite loop") return -1 count += 1 if next_idx > end_of_lis...
7d19eb3f453acd08dc5ac3a415c51f6e3a01afdc
santoshr1016/WeekendMasala
/itsybitsy/collections_DS/most_occuring_items.py
657
4.4375
4
words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Count...
6515f243a9e9193ce14b9d94478763ea6c658042
santoshr1016/WeekendMasala
/itsybitsy/collections_DS/dictionary_hacks/sort_dictionary_1.py
612
3.953125
4
from collections import defaultdict str1 = "The lines are printed in reverse order and the meaning is still in order" dd = defaultdict(list) lst_str = [item for item in str1.split(" ")] print(lst_str) for item in lst_str: dd[len(item)].append(item) for k, v in dd.items(): print(k, v) ########################...
bcc686369f4b1594ed71a82464a78ce8184f3d6f
santoshr1016/WeekendMasala
/itsybitsy/HRank/some_arrays/new_prob.py
520
3.5
4
from collections import Counter def show_list(res, item): if len(res) >= 2: count = Counter(res) for val in count.values(): if val == item: return 1 return 0 def freqQuery(q): res = [] ans = [] for ll in q: query, item = ll[0], ll[1] if q...
fbf7e15f452ff374e2a3ff76c15ef38c1a7b0c18
EachenKuang/LeetCode
/code/204#Count Primes.py
932
3.59375
4
# https://leetcode.com/problems/count-primes/description/ class Solution: # 1 常规方法,数字较大会memory溢出 def countPrimes(self, n): """ :type n: int :rtype: int """ def isPrime(num): for i in range(2,int(num**0.5)+1): if num%i==0: re...
192d8c2fa81b0f8469deb319622e8962d4e1273a
EachenKuang/LeetCode
/code/202#Happy Number.py
2,457
4.125
4
# First of all, it is easy to argue that starting from a number I, if some value - say a - appears again during the process after k steps, the initial number I cannot be a happy number. Because a will continuously become a after every k steps. # Therefore, as long as we can show that there is a loop after running the ...
bf1b5bb7314986e3955923b276481d475b0fc031
EachenKuang/LeetCode
/code/57#Insert Interval.py
3,234
3.984375
4
# https://leetcode.com/problems/merge-intervals/description/ """ Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]...
897b1a078f2a3105d2e616c3543cae687fce73a6
EachenKuang/LeetCode
/code/984#String Without AAA or BBB.py
979
3.921875
4
# https://leetcode.com/problems/string-without-aaa-or-bbb/ """ Given two integers A and B, return any string S such that: S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters; The substring 'aaa' does not occur in S; The substring 'bbb' does not occur in S. Example 1: Input: A = 1, B = 2...
212e86e2429bb4fea286ec28ca97010523e51f72
EachenKuang/LeetCode
/Classify/Sort/heap_sort.py
1,250
4.03125
4
def swap(nums, i, j): nums[i], nums[j] = nums[j], nums[i] class HeapSort: def __init__(self, nums): # 初始化全局变量,堆剩下还需要排序的长度 self.heap_len = len(nums) def heapify(self, nums, i): """ 调整以 i 为根节点的堆,使之成为大根堆 这里使用递归的方式 """ largest = i left = i * 2 ...
0a22f706d301412e4de2b8bfbb3266c9cbb339c6
EachenKuang/LeetCode
/code/100#Same Tree.py
1,408
3.84375
4
# https://leetcode.com/problems/same-tree/description/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 1 递归 def isSameTree(self, p, q): """ :type p: TreeNode ...
aabee33e82f3ebff84adfd341ab350078f81e170
EachenKuang/LeetCode
/code/1496#spath crossing.py
1,080
3.921875
4
# https://leetcode.cn/problems/path-crossing/ # 给你一个字符串 path,其中 path[i] 的值可以是 'N'、'S'、'E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。 # 你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。 # 如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false 。 class Solution: def isPathCrossing(self, path: str) -> bool: start_x = 0 ...
94735f151594edee36908a88160af4b550cdb0bc
EachenKuang/LeetCode
/code/23#Merge k Sorted Lists.py
865
3.984375
4
# https://leetcode.com/problems/merge-k-sorted-lists/ """ Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. class ListNode: def __init__(self, x...
eac0161a70cd6ae7415ac33de27bbd97916a5be8
EachenKuang/LeetCode
/code/409#Longest Palindrome.py
1,286
3.625
4
# https://leetcode.com/problems/longest-palindrome/description/ class Solution: # 1 使用字典来计数 # 长度为一个奇数加上偶数个字母 # 字母个数为奇数的可以使用偶数个字母 # 只需要判断是否有一个奇数,那么最后就加一即可 def longestPalindrome(self, s): """ :type s: str :rtype: int """ res = 0 flag = 0 count = ...
7753499d5d7848d6d94441c1feacae8ac6683578
EachenKuang/LeetCode
/code/905#Sort Array By Parity.py
559
3.546875
4
# https://leetcode.com/problems/sort-array-by-parity/description/ class Solution: # 1 def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ 让奇数在后,偶数在前 两点法 p1,p2 = 0,len(A)-1 while p1<p2: while A[p1]%2==0 and p1<p2: ...
178f3316c801d35331556074602047551e042c76
EachenKuang/LeetCode
/LeetCodeWeekly/April/Week2/backspace-string-compare.py
1,893
4.03125
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a # backspace character. # # Note that after backspacing an empty text, the text will continue empty. # # Example 1: # # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # Exam...
3bba3a1f7b901eb643efbf6285d3e14065233593
EachenKuang/LeetCode
/code/525#Contiguous Array.py
959
3.921875
4
# https://leetcode.com/problems/contiguous-array/ """ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanati...
ac86dfd9cff0926f58a8d34b81df05793481542b
EachenKuang/LeetCode
/code/74#Search a 2D Matrix.py
2,043
3.96875
4
# https://leetcode.com/problems/search-a-2d-matrix/description/ """ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row...
31312e67dcd2e2b3b3e30b6a846303dcab61f280
EachenKuang/LeetCode
/code/844#Backspace String Compare.py
439
3.703125
4
class Solution: def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ def convert(string): stack = [] for s in string: if s == '#': if stack: stack.pop() ...
3ffb5ebf2f95d8294dda0eba680f10c706db29fb
EachenKuang/LeetCode
/code/96#Unique Binary Search Trees.py
1,074
3.890625
4
# https://leetcode.com/problems/unique-binary-search-trees/ """ Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? Example: Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ ...
1cb7c7ad7ccee63ab260004f2ed1e7eb44ed947f
EachenKuang/LeetCode
/SwordOffer/SwordOffer_12.py
1,616
3.59375
4
# 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。 # # 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 # 输入:board = [["A","B","C","E"],["S","F"...
4e50d19ccc59bb7be0950e319e5757601845d908
EachenKuang/LeetCode
/code/442#Find All Duplicates in an Array.py
623
3.734375
4
# https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ class Solution: def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ from collections import Counter mapping = Counter(nums) return [i for i,v in mapping.it...
0ae17c1310b85450ba72c44ff0dfdf77dd5be618
EachenKuang/LeetCode
/SwordOffer/SwordOffer_19.py
1,643
3.703125
4
# 请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。 # 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但与"aa.a"和"ab*a"均不匹配。 # # # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof class Solution: def isMatch(self, s: str, p: str) -> bool: "...
617654263c762b72d8525062cb3aa9cfd689979a
EachenKuang/LeetCode
/code/849#Maximize Distance to Closest Person.py
1,174
3.609375
4
# https://leetcode.com/problems/maximize-distance-to-closest-person/description/ class Solution: # 1 # [1,0,0,0,1] output:2 # [0,0,0,1] outpu:# # [0,0,0,1,0,0] output:3 # 找连续的0 def maxDistToClosest(self, seats): """ :type seats: List[int] :rtype: int """ m...
9995fb26b93dd92f9c18f4d5d1edef4eaac39d3a
EachenKuang/LeetCode
/code/98#Validate Binary Search Tree.py
3,204
4.09375
4
# https://leetcode.com/problems/validate-binary-search-tree/ """ Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys gr...
07ca6e28a117f3d352aee8d04c29ef843f8ddd45
EachenKuang/LeetCode
/Classify/String/680#Valid Palindrome II.py
995
3.5
4
# https://leetcode.com/problems/valid-palindrome-ii/description/ class Solution1: def validPalindrome(self, s): l = 0 r = len(s)-1 while l<r: if s[l] != s[r]: return self.isValidPalindrome(s,l,r-1) or self.isValidPalindrome(s,l+1,r) l+=1 r-...
2f7b94498ca64880d3f95258b0aed8dbabc2fc15
EachenKuang/LeetCode
/code/867#Transpose Matrix.py
751
3.5625
4
# https://leetcode.com/problems/transpose-matrix/description/ class Solution: # 1 # 常规法 # O(mn) def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ trans = [] for c in range(len(A[0])): temp = [] for r ...
e59ea8e4abd52991f93b5c29894d1302bcd74b82
EachenKuang/LeetCode
/code/530#Minimum Absolute Difference in BST.py
1,707
3.859375
4
# https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 1 使用栈 class Solution: def getMinimumDifference(self, root): """...
eef7079a9680d1c7314d2a1448fae4bdb3b83610
EachenKuang/LeetCode
/code/91#Decode Ways.py
1,519
3.875
4
# https://leetcode.com/problems/decode-ways/ """ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanatio...
0ccd17b58a71709a399179bbd689bb01b1aac3ef
EachenKuang/LeetCode
/code/101#Symmetric Tree.py
850
4
4
# https://leetcode.com/problems/symmetric-tree/description/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: ...
1855f20a068ba53889864a7383417d68a5e59317
EachenKuang/LeetCode
/SwordOffer/SwordOffer_58.py
572
3.71875
4
# https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/ # 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: # 切片法 return s[n:] + s[:n] def reverseLeftWords(self, s: str, ...
3d6b80a129e314abf628c88a24819a1c4a0712e2
EachenKuang/LeetCode
/code/700#Search in a Binary Search Tree.py
1,125
3.78125
4
# https://leetcode.com/problems/search-in-a-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 1 递归法 class Solution: def searchBST(self, root, val): """ :type root: Tr...
2cc3f1650079c60de5dfb532bcc7810a2690c629
andres22216/python
/ActModuloCuatro/ActModuloCuatro.py
8,319
4.3125
4
# Aplicación para registro de productos de la tienda escolar # Fecha: Septiembre 29 de 2020 # Autor: Andrés Mauricio Ortiz Gallego # variable para iniciar el ciclo while operacion = 5 print("+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -+") print("| - - - PROGRAMA DE REGISTRO ...
d54ad2f107c404eb62b3599e9c9dcfe014a8d33c
badalsarkar/Algorithm-Practice
/code/listOfDepths/ListOfDepths.py
1,158
3.8125
4
''' Question: List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth 4, you'll have 4 linked levelList). ''' class Node: def __init__(self, value): self.value=value self.left=None self.right=Non...
0f03a300cee18237ecc443c4b29c202fd80b103a
mflood/mail_forward_flask_app
/flask_app/mail_forward_flask/message_tools/__init__.py
1,287
3.671875
4
""" Utility functions * convert_html_to_text * validate_email_address * text_to_email_addresses """ import logging import re import html2text from mail_forward_flask.loggingsetup import APP_LOGNAME # I pulled this regex from # https://stackoverflow.com/questions/8022530/how-to-check-for-valid-email-a...
be8e4b811fdb1a0a9cb60f0048bf1667679a512d
Athenian-ComputerScience-Fall2020/dictionary-building-maleich
/my_code.py
438
3.859375
4
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # pets = {} while True: key = input("Enter the name of a pet. ") key = key.strip() value = input(f"What kind of pet is/was {key}?") value = value.strip() pets[key] = value again = input("Enter anoth...
89da4ad1e215eab2db1d2c73f5425df4fca77e72
arjun-1102/Yatzy-game-python
/dice.py
1,294
3.734375
4
import random class Die: def __init__(self, sides = 2, value = 0): if not sides >=2: raise ValueError("Must have at least 2 sides") if not isinstance(sides, int): raise ValueError("Side must be whole number") if not isinstance(value, int): raise TypeError("Value must be whole number") self.value = va...
d390fe8ee52c9d7d5d02e25b2a79782bcc30edb4
Xanonymous-GitHub/data-structure
/hw3/hw3.py
6,215
3.640625
4
from typing import Final, List, Tuple from string import digits class Term: def __init__(self, coefficient: int or float, exponent: int): self.__coefficient = coefficient self.__exponent = exponent @property def coefficient(self) -> int or float: return self.__coefficient @pr...
de6d507d7bd95d2d2be3d4632a8eb7a15de07afd
Xanonymous-GitHub/data-structure
/hw2/hw2.py
4,578
3.84375
4
import sys import timeit as ti sys.setrecursionlimit(10 ** 6) def recursive_multiplication(m: int, n: int) -> int: # Zero multiplied by any number is zero. if m == 0 or n == 0: return 0 # In order to reduce the number of calculations, choose a smaller number as the multiplier. if m < n: ...
da82a7c906d4c100176b5994979f58c4b7d290da
KevinStoneCode/CS50_2018
/2018/pset6/cash/cash.py
279
3.625
4
from cs50 import get_float while True: change = get_float("Change owed: ") if change >= 0: break cents = round(change * 100) coins = 0 coins += cents // 25 cents %= 25 coins += cents // 10 cents %= 10 coins += cents // 5 cents %= 5 coins += cents print(coins)
4c599c9f902ed403eb88fa39b61657003917751d
Billoncho/EncoderDecoder
/EncoderDecoder.py
1,469
4.5625
5
# EncoderDecoder.py # Billy Ridgeway # Encode or decode your messages by shifting the ASCII characters. message = input("Enter a message to encode or decode: ") # Prompt the user for a message to encode/decode. message = message.upper() # Convert the string of letters to upper...
ed517c9362bdc8e35b6a315077d34d111fc59d22
Guido1123/programming1
/Les 7/Formatting.py
233
3.859375
4
def convert(Celsius): Fahrenheit = Celsius*1.8+32 return Fahrenheit def tabel(temp): for c in temp: convert(c) print("{:5} {:5}".format((convert(c)),c)) return temp = range(-30,41,10) tabel(temp)
52ce226b38875cac7cd7c8b47b10fcf68444bb1a
Guido1123/programming1
/Les 9/Dictionary.py
219
3.71875
4
studentcijfers = {"kees":6, "henk":6, "james":8, "tim":2, "Kevin":5, "Bob":9, "Diana":9, "Bart":5, "Amber":9, "Guido":4} for key in studentcijfers: if studentcijfers[key]>=9: print(key, studentcijfers[key])
4abedc788aaff81d23a2508aee5072bc068b2d71
Guido1123/programming1
/Les 6/password optioneel.py
433
3.703125
4
def new_password(oldpassword, newpassword): cijfer1 = False for cijfers in newpassword: if cijfers in '0123456789': cijfer1 = True if newpassword != oldpassword and len(newpassword) >= 6 and cijfer1: return True else: return False oldpassword = input('wat is je oude ...
0c86732ac33d42de793325664bca5080473e8ec2
rohan-kekatpure/mlsandbox
/mcmc/mcmc_knapsack.py
824
3.625
4
''' Solution of the knapsack problem using Metropolis algorithm ''' import numpy as np from copy import deepcopy def main(): values = np.array([10, 9, 20, 5]) weights = np.array([1, 2, 3, 4]) w_max = 5 beta = 1.0 assert values.shape == weights.shape N = values.shape[0] x = np.zeros(N)...
754f77bc4c52127574e54778bfebe69126ca76a1
canyucelbal/Bal_C_PythonHW
/gameFunctions/gameVars.py
348
3.75
4
from random import randint #adding lives -> when one or the other gets to 0, win / lose player_lives=5 computer_lives=5 total_lives=5 #basket of choices ARRAY - index 0, 1, 2. choices=["rock", "paper", "scissors"] #let AI make a choice computer=choices[randint(0, 2)] # Set up a game loop here so we don't have to ke...
f5bd50a1fedbc170d49f64b974e3a1a347991b9d
Sanchezz17/GeneticAlgorithm
/Point.py
522
3.8125
4
import numpy as np class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def distance(self, other: 'Point') -> float: """Возвращает расстояние между двумя точками.""" x_dis = abs(self.x - other.x) y_dis = abs(self.y - other.y) dista...
12cba480a3e7069a22a0c7e58e6103d2056dfbc1
peterken674/weather-api
/weather/tests.py
4,268
4.1875
4
from weather.models import Weather, WeatherResults from unittest import TestCase from .request import fetch_data import requests import statistics class WeatherTest(TestCase): """Test class that defines test cases for the Weather class behaviours. Args: unittest (TestCase): TestCase class that...
6d1b8bc9a8ad4b6593ec0d5e99faf2834af5295f
amritanag1/PRO-C104-Mean-Median-Mode
/mean.py
234
3.625
4
import pandas as pd import statistics df = pd.read_csv("data.csv") data = df["Weight(Pounds)"].tolist() sum = 0 count = 0 for i in data: sum = sum + i count = count+1 a = sum/count print("The mean is ",a)
60abc35e5b24395898d7a3c38dd1301416114d2c
Simochenko/Python_Basics_and_Applications
/1_Basic_principles_of_the_Python_language/1.4_Namespaces_and_scopes.py
8,205
4.28125
4
'''Какие числа будут выведены на экран в результате выполнения данного кода? x, y = 1, 2 def foo(): global y if y == 2: x = 2 y = 1 foo() print(x) if y == 1: x = 3 print(x)''' # x, y = 1, 2 # # def foo(): # global y # if y == 2: # x = 2 # y = 1 # # foo() # print(x)...
66ca9d86e2fc88d1402c31fbc1078c4cf9b262b3
Sophon96/2021-software-general-homework
/lesson_2_1.py
1,443
4.21875
4
# A student has taken 3 tests in a class, and wants to know their current grade # (which is only calculated by these tests). # Ask the user to input all three of the test scores for the student, one by one. # The program should then calculate the average test score (average is adding all three # test scores toget...
5cb57f3241a7f43e7cc54cd361692f43d035a8d0
cbkruppa/disaster_response
/data/process_data.py
4,372
3.515625
4
import sys import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): """Load messages and categories datasets from CSV and merge. Args: messages_filepath: string. Filepath of csv containing message data categories_filepath: string. Filepath of...
c24c8759cfb0c0341ddb3db820ac9b442125c16b
kevin31613/Leetcode
/Leetcode/1.Two_Sum.py
353
3.625
4
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ h = {} for i, num in enumerate(nums): n = target - num if n not in h: h[num] = i else: print(h) return [h[n], i] nums = [2,11,7,15] target...
e7eb03c3142cde3d4522dd7832cc11c33f0af1ef
CScarame/mafiabot
/mafiabot/MTimer.py
2,644
3.984375
4
import time import threading class MTimer: """Used to create a timer object and bind functions to specific times for it""" def __init__(self, value, alarms, low_set_lim=0): """ value is the starting time value in seconds alarms is a dict mapping a second value to a list of alarm functions ...
850833ceeefc9b53463eabbe461e4b064d479c5e
vFense/toppatch
/tp/src/utils/security.py
1,210
3.796875
4
import bcrypt import scrypt import random class Crypto(): """ Helper functions to create, and verify, bcrypt and scrypt encrypted strings. """ @staticmethod def hash_bcrypt(password): return bcrypt.hashpw(password, bcrypt.gensalt()) @staticmethod def hash_scrypt(password, salt_length=...
44d936e0c4fa92754a501c1d52a742e61f300333
dpinezich/fs19_python_uzh
/examples/grades.py
553
3.734375
4
def calculate_mark(points, max_points): mark = (float(points) * 5.0 / float(max_points)) + 1 return mark max_points = 20 marks = {} while True: points = input('Points: ') if points == 'exit': print('Bye Bye') break name = input('Name: ') marks[name] = calculate_mark(int(poin...
d8d641c6074e6c8ebde79ca1f507bc3dd1a90664
dpinezich/fs19_python_uzh
/examples/elif.py
161
4.0625
4
x = -14 if x > 0: print(str(x) + ' is bigger than zero') elif x == 0: print('x is equal to zero') else: print(str(x) + ' is smaller than zero')
e23fbe9ae54d915ef1f0d80ae967ea42182ffca8
dpinezich/fs19_python_uzh
/examples/json_dumps.py
117
3.5625
4
import json my_dict = {'one': 'uno', 'two': 'dos'} my_dict_as_string = json.dumps(my_dict) print(my_dict_as_string)
4db824ca06fcb183b3cdd4afb8c1407541610ba5
Seonghyeony/DataStructure-Algorithm
/Baekjun/Dijkstra/10282. 해킹.py
1,060
3.65625
4
import heapq def dijkstra(graph, n, start): distances = [float('inf') for _ in range(n + 1)] distances[start] = 0 queue = [] heapq.heappush(queue, [0, start]) while queue: current_distance, current_node = heapq.heappop(queue) if distances[current_node] < current_distance: ...
d6d90f48f68f45fbdebcf42710ac64ea44f57783
Seonghyeony/DataStructure-Algorithm
/PS_vsCode/2661. 좋은수열.py
384
3.609375
4
import sys def check(num): length = len(num) for idx in range(1, length//2 + 1): if num[-idx:] == num[-(idx*2):-idx]: return False else: return True def dfs(num): if len(num) == N: print(num) sys.exit() for i in '123': if check(num + str(i)): ...
713c1242482cc1eab8305b50d0962d2c793cb953
Seonghyeony/DataStructure-Algorithm
/PS_vsCode/1181. 단어 정렬.py
158
3.6875
4
N = int(input()) lst = [] for _ in range(N): lst.append(input()) lst = sorted(list(set(lst)), key=lambda x: (len(x), x)) for word in lst: print(word)
3e5973f7d0f0b7025860d83cb306023f3e7f731d
Seonghyeony/DataStructure-Algorithm
/SWEA/1231. 중위순회.py
424
3.546875
4
def inorder(root): global result if root <= N and len(tree[root]): inorder(root * 2) result += tree[root] inorder(root * 2 + 1) for test_case in range(1, 11): N = int(input()) tree = [''] * (N + 1) for _ in range(N): temp = list(map(str, input().split())) tr...
21f3e5f25c9e04f102b6f128d7c84711411a1990
MCGallaspy/mas_dse_capstone
/data/NOAA_ISD/isd_parse.py
1,751
3.578125
4
import datetime def value_or_missing(val): ''' ISD values uses a string of 9s to indicate missing data. This method checks if the data is missing and returns None if it is, or the actual string if not ''' nval = len(val) all_9s = "9"*nval signed_9s = "+" + "9" * (nval-1) missing = (...
5712811d0a316d12063e30da725e12ff4d3a43b6
HussainAther/machinelearning
/languagemodel/generatetext.py
536
3.59375
4
import random # starting words text = ["today", "the"] sentence_finished = False while not sentence_finished: # select a random probability threshold r = random.random() accumulator = .0 for word in model[tuple(text[-2:])].keys(): accumulator += model[tuple(text[-2:])][word] # select words tha...