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
067e39b32f8981e601c8ef9d5e4d2db7d6c820aa
harshil1903/leetcode
/Array/0004_median_of_two_sorted_array.py
1,341
3.6875
4
# 4. Median of Two Sorted Arrays # # Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ # # Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. class Solution: def findMedianSortedArrays(self, nums1, nums2) -> float: size = l...
e6d7519cb6a1ef4e535e95bb87764c3d183a952c
harshil1903/leetcode
/Linked List/0025_reverse_nodes_in_k_group.py
2,197
3.6875
4
# 25. Reverse Nodes in k-Group # # Source : https://leetcode.com/problems/reverse-nodes-in-k-group/ # # Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. # # k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not...
4ff8ab8c1c38294cdebcc8b90c6a79aa0a82cf5a
harshil1903/leetcode
/Array/0169_majority_element.py
1,225
3.921875
4
# 169. Majority Element # # Source : https://leetcode.com/problems/majority-element/ # # Given an array nums of size n, return the majority element. # # The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. from typing import Lis...
80ac4c9e806ca376c9682cda700837514feb9668
itbatya/prac2
/task2.py
259
3.78125
4
print('2 задание') str = input('Введите сторку: ') list = str.split(';') max = list[0] for i in range(len(list)): if len(list[i]) > len(max): max = list[i] print('Самое длинное слово: ', max) #python task2.py
f7994769531b14292877ed6539d76aae73288cd7
arseniypopugay/Graph-algorithms-for-all-intents-and-purposes
/Dijkstra.py
1,183
3.8125
4
# Need Start vertex number and Graph # Graph structure: # Grap = list of vetrexes # Graph[vertex]=list of neighbour_vertexes # neighbour_ver = list: # neighbour_ver[0] - number of vertex # neighbour_ver[1] - distanse frome origin_vertex to neighbour` # Also required inf - "number that could be thought about as ...
a65e5799286694cc9cfadd91a4ad026213f87db6
eminem54/AlgorithmStudy
/Backjoon/11651 좌표 정렬하기.py
173
3.59375
4
N = int(input()) numbers = [] for i in range(N): numbers.append([int(i) for i in reversed(input().split())]) numbers.sort() for i in numbers: print(i[1], i[0])
e8700b62b622bf4eb0d2f4edc3a274e9346ef6c9
yellowsimulator/tsaug
/src/tsaug/cross_sum.py
5,988
3.796875
4
""" Cross sum """ import numpy as np from .dimensionalize import dimensionalize from .augmentor import _Augmentor @dimensionalize def cross_sum(X, Y=None, inds=None): """Sum cross given time series. Time series will be summed with others based on the given indices. Time points at which at least one time...
edbcee8de4c7388781621e130ce96acccf1ebbdb
yellowsimulator/tsaug
/src/tsaug/jitter.py
3,183
3.625
4
""" Jitter module """ import numpy as np from .dimensionalize import dimensionalize from .augmentor import _Augmentor @dimensionalize def random_jitter(X, Y=None, dist="normal", strength=0.05, random_seed=None): """Add random noise to time series. Parameters ---------- X : numpy.ndarray Time...
72f101f735258aa1a9c5cec30998ae1acaae2d0c
andrewunifei/CS229-Machine-Learning
/General Linear Model/Lowess Regression/regression.py
1,925
3.71875
4
# Andrew Enrique Oliveira # Computer Science at Universidade Federal de Itajubá (2017 - ) # 09/03/2021 # # I wrote this as a learning exercise. The focus is not performance but to explore the concepts around this theme import numpy as np from numpy.linalg import inv from sklego.linear_model import LowessRegression cl...
7c0e7ea0e7e8ee970e575d8d618f6bbdc2e88c05
imrehg/pulse-programmer
/software/python/sequencer/pcp/events/infinite_loop.py
1,169
3.578125
4
# Module : infinite_loop # Package: pcp.events # Class definition for an infinite loop event. from sequencer.pcp.events import * from sequencer.pcp.events.jump import * #============================================================================== class InfiniteLoop_Event(Sequence_Event): """ Base class for...
d8bcc02beb10416621bfa25dcd117824183749a0
imrehg/pulse-programmer
/software/python/set_pins.py
901
3.59375
4
# This script turns pins or lights on and off. # To turn a pin on, pass the pin's number as an argument. # Example: to turn on only the first pin: # set_pins.py 0 from test_config import * import sys setup() parse_params(('dummy', 'int')) # Process args pins = 0 # I2C slave address # Slave addresse...
89af4e670e5ad5e6420fc325eaa651e3cf697141
cdede/ketpegs
/ktpgs/group.py
612
3.734375
4
class Group: def __init__(self ): self.id = '' self.cells = [] self.map = 0 def add(self,cell1): if cell1.is_oil: return if self.id =='': self.id = "%d_%d" % (cell1.x,cell1.y) self.cells.append(cell1) cell1.group =self ...
deaf6d122ea9e3e4750710357d297e8ef0734536
cpoIT/Graphs
/projects/graph/src/graph.py
6,047
4.03125
4
from collections import deque """ Simple graph implementation """ class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, id): if id not in self.vertices: self.vertices[id] = set() ...
cf2ffa3bf9e7cdaab0c4e095328655cd88a6852b
wolfcomm/python
/catmass.py
265
3.765625
4
x = int(input('Введите массу всех котов\n')) y = int(input('Введите число котят\n')) z = x / 2 #масса кошки print('Масса кошки = ', z) a = (x - z) / y print('Масса одного котенка = ', a )
78f8d275f9f3e53d990f4077dc7d749e0c2cf9ce
chenzheng128/RSAlgorithms
/utility/similarity.py
7,549
3.609375
4
# encoding:utf-8 import sys sys.path.append("..") import numpy as np from math import sqrt # from utility.tools import sigmoid_2 # x1,x2 is the form of np.array. def euclidean(x1, x2): # find common ratings new_x1, new_x2 = common(x1, x2) # compute the euclidean between two vectors diff = new_x1 - n...
6af7d5a276ed65e7b8d221e836ebfcc073a1966f
goalong/lc
/v1/81.search-in-rotated-sorted-array-ii.134553780.ac.python3.py
1,584
3.84375
4
# # [81] Search in Rotated Sorted Array II # # https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ # # algorithms # Medium (32.71%) # Total Accepted: 114.8K # Total Submissions: 350.9K # Testcase Example: '[]\n5' # # # Follow up for "Search in Rotated Sorted Array": # What if duplicates ar...
8f27d0ab7ce120ebdf9a988d035f03d9cb5e2b0b
goalong/lc
/v1/315.count-of-smaller-numbers-after-self.136426749.notac.py
1,365
3.734375
4
# # [315] Count of Smaller Numbers After Self # # https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/ # # algorithms # Hard (35.07%) # Total Accepted: 44.2K # Total Submissions: 126K # Testcase Example: '[5,2,6,1]' # # # You are given an integer array nums and you have to return a new co...
2acea34c4bfb338110e99bd35cc442cb486979e6
goalong/lc
/v1/15.3sum.134250369.ac.py
1,273
3.515625
4
# # [15] 3Sum # # https://leetcode.com/problems/3sum/description/ # # algorithms # Medium (21.80%) # Total Accepted: 299.7K # Total Submissions: 1.4M # Testcase Example: '[-1,0,1,2,-1,-4]' # # Given an array S of n integers, are there elements a, b, c in S such that a + # b + c = 0? Find all unique triplets in the ...
c165e51384c581333d87df155c931818f7e1d83c
goalong/lc
/v1/165.compare-version-numbers.132733412.ac.py
1,472
3.671875
4
# # [165] Compare Version Numbers # # https://leetcode.com/problems/compare-version-numbers/description/ # # algorithms # Medium (20.72%) # Total Accepted: 97K # Total Submissions: 468.2K # Testcase Example: '"1"\n"0"' # # Compare two version numbers version1 and version2. # If version1 > version2 return 1, if vers...
d563cbf07fa37483ea1be26734dcd9344a0d7a70
goalong/lc
/v1/122.best-time-to-buy-and-sell-stock-ii.134821853.ac.py
1,398
3.90625
4
# # [122] Best Time to Buy and Sell Stock II # # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ # # algorithms # Easy (47.78%) # Total Accepted: 190.7K # Total Submissions: 399.2K # Testcase Example: '[]' # # Say you have an array for which the ith element is the price of a given stoc...
b96414273e1073a894568555e3a95cd5346a4b22
goalong/lc
/v1/56.merge-intervals.133306213.ac.py
1,055
3.8125
4
# # [56] Merge Intervals # # https://leetcode.com/problems/merge-intervals/description/ # # algorithms # Medium (31.77%) # Total Accepted: 184.7K # Total Submissions: 581.4K # Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]' # # Given a collection of intervals, merge all overlapping intervals. # # # For example, ...
f89fdacbf10b51920f1ed74e746dafe37b7386d4
goalong/lc
/v1/38.count-and-say.131841902.ac.py
1,423
3.84375
4
# # [38] Count and Say # # https://leetcode.com/problems/count-and-say/description/ # # algorithms # Easy (36.49%) # Total Accepted: 180.7K # Total Submissions: 495.3K # Testcase Example: '1' # # The count-and-say sequence is the sequence of integers with the first five # terms as following: # # 1. 1 # 2. ...
8df22d21b32f3b959ab96fd041011f7b3251d832
goalong/lc
/v2/61.py
1,072
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ # 3 star, 小心处理边界 if n...
fd49cf53714b32d57c440c2100e9029247b0f3ca
goalong/lc
/v1/59.spiral-matrix-ii.133314120.ac.py
1,364
3.65625
4
# # [59] Spiral Matrix II # # https://leetcode.com/problems/spiral-matrix-ii/description/ # # algorithms # Medium (40.81%) # Total Accepted: 97.2K # Total Submissions: 238.1K # Testcase Example: '0' # # Given an integer n, generate a square matrix filled with elements from 1 to # n2 in spiral order. # # # For exa...
cf7077bfa2eb541547b4903759687bab1ef7753f
goalong/lc
/v1/74.search-a-2d-matrix.133453292.ac.py
1,960
3.890625
4
# # [74] Search a 2D Matrix # # https://leetcode.com/problems/search-a-2d-matrix/description/ # # algorithms # Medium (34.74%) # Total Accepted: 151.3K # Total Submissions: 435.4K # Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,50]]\n3' # # Write an efficient algorithm that searches for a value in an m x n ...
01502ebcc9166d79dcbe6a3eae8b0c84c61b392e
goalong/lc
/v1/179.largest-number.132650343.ac.py
888
3.734375
4
# # [179] Largest Number # # https://leetcode.com/problems/largest-number/description/ # # algorithms # Medium (23.35%) # Total Accepted: 89.8K # Total Submissions: 384.6K # Testcase Example: '[1]' # # Given a list of non negative integers, arrange them such that they form the # largest number. # # For example, gi...
31b7652722323a68727b36894573703d4b1f5082
goalong/lc
/v1/463.island-perimeter.137328080.ac.python3.py
1,448
3.921875
4
# # [463] Island Perimeter # # https://leetcode.com/problems/island-perimeter/description/ # # algorithms # Easy (57.80%) # Total Accepted: 73K # Total Submissions: 126.2K # Testcase Example: '[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]' # # You are given a map in form of a two-dimensional integer grid where 1 # repr...
9bc10287df71b50df81f808487446212a23ab451
goalong/lc
/v1/263.ugly-number.136255492.ac.python3.py
920
3.796875
4
# # [263] Ugly Number # # https://leetcode.com/problems/ugly-number/description/ # # algorithms # Easy (39.62%) # Total Accepted: 118.9K # Total Submissions: 300.2K # Testcase Example: '-2147483648' # # # Write a program to check whether a given number is an ugly number. # # # # Ugly numbers are positive number...
2d6b506867905c871c88713d687315caad9a0a79
goalong/lc
/v1/73.set-matrix-zeroes.133446155.ac.py
1,295
3.671875
4
# # [73] Set Matrix Zeroes # # https://leetcode.com/problems/set-matrix-zeroes/description/ # # algorithms # Medium (36.48%) # Total Accepted: 131.8K # Total Submissions: 361.2K # Testcase Example: '[[0]]' # # # Given a m x n matrix, if an element is 0, set its entire row and column to 0. # Do it in place. # # #...
39146ab99238c8573380fa42f7cdced46451b0bf
goalong/lc
/v1/287.find-the-duplicate-number.135173027.ac.py
1,408
3.78125
4
# # [287] Find the Duplicate Number # # https://leetcode.com/problems/find-the-duplicate-number/description/ # # algorithms # Medium (44.20%) # Total Accepted: 99.9K # Total Submissions: 225.9K # Testcase Example: '[1,1]' # # # Given an array nums containing n + 1 integers where each integer is between 1 # and n (...
77a31321e3d5ec65eeab0f4a0c91240bc09e64d1
goalong/lc
/v1/190.reverse-bits.132673558.ac.py
979
3.734375
4
# # [190] Reverse Bits # # https://leetcode.com/problems/reverse-bits/description/ # # algorithms # Easy (29.40%) # Total Accepted: 127.5K # Total Submissions: 433.6K # Testcase Example: ' 0 (00000000000000000000000000000000)' # # Reverse bits of a given 32 bits unsigned integer. # # For example, given i...
4796317d41e3a78627fe1a524c8e348c905fd24a
goalong/lc
/v1/72.edit-distance.106836202.ac.py
1,196
3.625
4
# # [72] Edit Distance # # https://leetcode.com/problems/edit-distance/description/ # # algorithms # Hard (32.45%) # Total Accepted: 110.6K # Total Submissions: 340.7K # Testcase Example: '""\n""' # # # Given two words word1 and word2, find the minimum number of steps required to # convert word1 to word2. (each op...
40ecc38c261f02552f1402107dd650057a3d9406
goalong/lc
/v1/215.kth-largest-element-in-an-array.131715851.ac.py
900
3.78125
4
# # [215] Kth Largest Element in an Array # # https://leetcode.com/problems/kth-largest-element-in-an-array/description/ # # algorithms # Medium (40.45%) # Total Accepted: 193.9K # Total Submissions: 479.2K # Testcase Example: '[1]\n1' # # Find the kth largest element in an unsorted array. Note that it is the kth #...
773abd1fd5b3b72fa4d3f2812dfac5ab84e1e363
goalong/lc
/v1/236.lowest-common-ancestor-of-a-binary-tree.134107798.ac.py
1,717
3.703125
4
# # [236] Lowest Common Ancestor of a Binary Tree # # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ # # algorithms # Medium (29.98%) # Total Accepted: 152.3K # Total Submissions: 508.2K # Testcase Example: '[1,2]\nnode with value 1\nnode with value 2' # # # Given a binary tree,...
3fc635beb9248a283beac17c567671f9a8d93f3b
jeroen107/pig-game
/the pig game.py
2,085
3.71875
4
from random import random, randrange mode = '' players = int(input('hoeveel spelers zijn er: ')) while players < 2 or players > 6: print('je kan maar met 2 tot 6 spelers spelen') players = int(input('hoeveel spelers zijn er: ')) c = 0 playernames = [] while c < players: playernames.append(input('your nam...
0ec6e3a00b1d6df49fe56057448a0e03b9ec823c
srikanthpragada/PYTHON_01_OCT_LANGDEMO
/libdemo/sort_phone_numbers.py
289
3.59375
4
with open("phones.txt","r") as f: phones = set() for line in f.readlines(): input_phones = line.strip("\n").split(",") for phone in input_phones: if phone.isdigit(): phones.add(phone) for phone in sorted(phones): print(phone)
0c54896baa27b60625a858bf6c45265d2bed170e
Dondicine/LearnPython
/其他/test.py
249
3.65625
4
# test.py # import sys # if __name__ == "__main__": # print(sys.path) # a = int(input("get a number:")) # print(a**2) a = int(input("输入多少行:")) for i in range(1, a + 1): print("{}{}".format(" " * (a - i), "*" * (2 * i - 1)))
7e3f5e7c14de0f757795cf09cf3910b360b0c9d2
michalbachowski/pyqp
/pyqp/reducers.py
2,989
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division from functools import wraps import math # in python there are built in: sum, min and max def last(values): """Returns last value from given list >>> last([1,2,3]) 3 >>> last([]) Traceback (most recent call last): ....
49865447a11b1689fe85de8c0204c423c7b7eaee
michalbachowski/pyqp
/pyqp/aggregate.py
3,097
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from operator import itemgetter from collections import deque from time import time class LastValue(object): """Aggregator that hold only last given value >>> lv = LastValue() >>> lv.append(1) >>> list(lv) [1] >>> lv.append(2) >>> lv.append(3)...
883420bed2eef7919b977baad55c0e207cbcf23f
RBeaudet/Utils
/autosuggestion/tries.py
2,112
3.8125
4
from typing import Generator, Sequence class Node(object): """A Trie Node. Each node has a dictionary of children keyed on character """ def __init__(self): self.children = {} @property def is_leaf(self) -> bool: return len(self.children) < 1 def insert(self, text: str) -> No...
a5c6246f16e38192b9fb9c815e0245617f9d3423
Suvid-Singhal/Python-Port-Scanner
/port_scanner.py
1,203
3.859375
4
import socket print("--------------------------------") print("Welcome to Python 3 Port Scanner") print("--------------------------------\n") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) target = input('Enter host: ') targetip = socket.gethostbyname(target) def portscan(port,state): if state == 1: ...
9e7759d85fcbb01927a384a2f42506b824639d44
qkcire/lpthw
/exercises/ex22.py
877
3.8125
4
""" ex.1, ex.2, ex.3, + 'print': outputs information to the console ex.4 + '=': assignment operator ex.5 + "#": comment operator (octothrope) ex.6 + 'f""': formatted string literals ex.7 ex.8 + '.format()': format string ex.9 + ' \""" ': triple quote block comments ex.10 + '\t': tab cha...
afcf21cb881f870f9dae2dd8f4a5b41af25d0f6f
anishmo99/Python-Functionality
/customizationPanda.py
418
3.75
4
import pandas as pd print(pd.get_option("display.max_rows")) # displays default number of rows value # same for columns pd.set_option("display.max_rows", 80) print(pd.get_option("display.max_rows")) # same for columns pd.reset_option("display.max_rows") print(pd.get_option("display.max_rows")) pi = 3.14159265 pd.set_...
8cee7226336939d2d6f17eb5e16bc09bd8299aad
anishmo99/Python-Functionality
/wordEmbedding.py
1,435
3.609375
4
# Python program to generate word vectors using Word2Vec # importing all necessary modules from nltk.tokenize import sent_tokenize, word_tokenize import warnings warnings.filterwarnings(action='ignore') import gensim from gensim.models import Word2Vec # Reads ‘alice.txt’ file sample = open("alice.txt", "r") s = sam...
a31914c0cfd408f204bf50c24b8c085d3461ed68
CATHRIN-h/Python-Programming
/Beginner level/leapyr.py
102
3.75
4
k=int(input('enter the year:')) if(k%4==0): print('its a leap yr') else: print('its not a leap yr')
cbe53a36159629675de57a155e32cb26f69e9726
CATHRIN-h/Python-Programming
/Beginner level/primeinterval.py
168
3.796875
4
n=int(input('enter the number') k=int(input('enter the number') for num in range(n,k): if(num>1): for i in range(2,num): if(num%i==0): break else: print('num')
8c1e72d62ca4f9dcdc61a861d0dc8ed095d922ba
sankari-chelliah/Python
/int_binary.py
414
4.34375
4
#Program to convert integer to Binary number num= int(input("Enter Number: ")) result='' #Check the sign of the number if num<0: isneg=True num = abs(num) elif num==0: result='0' else: isneg= False # Does actual binary conversion while num>0: result=str(num%2)+result num=num//2 #Display resu...
6fcb1e4b29f37bf0d6894927e21c9910273f0a84
sankari-chelliah/Python
/more_class.py
574
3.765625
4
class Animal(object): pass class Dog(Animal): def __init__(self, name): self.name = name class Cat(Animal): def __init__(self, name): self.name = name class Person(object): def __init__(self, name): self.name = name self.pet = None print(self.name, self.pet) c...
e9c2c58ba9a7456dc7b1603fafdd480aa96fbf8a
sankari-chelliah/Python
/linked_list.py
699
4.0625
4
# A single node of a singly linked list class Node: def __init__(self, data = None, next=None): self.data = data self.next = next # A Linked List class with a single head node class LinkedList: def __init__(self): self.head = None # insertion method for the linked list def insert(self, data): ...
311e9ef89148b46e3614b254caf35a3cd421573d
vebjorre/vebjorre.github.io
/Deep_learning.py
10,654
3.6875
4
#Small project in TMA4215 Numerical Mathematics #Classification of red/blue points in 4D-space using Deep learning. import numpy as np import numpy.random as rnd import matplotlib.pyplot as plt def make_circle_problem(n,nx,PLOT): # This python-script uses the following three input parameters: # n - N...
57be296c1ec6b4e416a2934eb811ca27ef51883a
saijannali/Kriegsspiel-Chess
/Board.py
3,571
3.9375
4
class Board(): def __init__(self, size=4, *args, **kwargs): #***** self.board = [[0 for x in range(size)] for y in range(size)] # sideboard is for the use of the ai player. # by establishing the location of every piece the player has, the entire board won't need to be scanned... ...
1cbf9d10d54a258d9f11cfaf8f249a5992c3b9b4
robibhatt/python_classes
/binary_search.py
804
3.703125
4
# returns the unique index i such that # compare(search_list[i-1], key) == False # compare(search_list[i], key) == True def binary_search(search_list, key, compare): length = len(search_list) def c(index): return compare(search_list[index], key) if length == 0: return 0 if length == 1...
0df08bfba50168d0082872578c5e4b56de1777e6
cardel/maratonesProgramacion
/10299-Relatives/relatives.py
1,297
3.5625
4
# -*- coding: utf-8 -*- from sys import stdin #https://algorithmist.com/wiki/UVa_10299 #https://cp-algorithms.com/algebra/phi-function.html #https://www.geeksforgeeks.org/eulers-totient-function/ #https://www.geeksforgeeks.org/optimized-euler-totient-function-multiple-evaluations/ primos = [] #Función para encontrar...
4e199ebfe697dc5071ab393d4783a3a996fe14b7
chanshik/HackerRank
/detect_cycle.py
955
3.796875
4
""" Linked Lists: Detect a Cycle https://www.hackerrank.com/challenges/ctci-linked-list-cycle """ import unittest class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def has_cycle(head): short_mover = head long_mover = head whil...
2e96816ef652a0b6ad429852ade1cbbead99ddfb
abhinavm24/Coursera-DS-and-Algo
/1.algorithmic-toolbox/Pycharm course Algorithmic Toolbox/Greedy Algorithms/Maximum Value of the Loot/maximum_loot.py
1,696
3.75
4
# python3 from sys import stdin def maximum_loot_value(capacity, weights, prices): assert 0 <= capacity <= 2 * 10 ** 6 assert len(weights) == len(prices) assert 1 <= len(weights) <= 10 ** 3 assert all(0 < w <= 2 * 10 ** 6 for w in weights) assert all(0 <= p <= 2 * 10 ** 6 for p in prices) pr...
19a1cd466d1375a23cae2ef2c2c2f8196a0a3135
abhinavm24/Coursera-DS-and-Algo
/2.data-structures/week5_binary_search_trees2/2_is_bst/is_bst_solution2.py
5,118
3.921875
4
#!/usr/bin/python3 import sys import threading sys.setrecursionlimit(10**8) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size # this class represents a node in a binary tree class Node: def __init__(self, key, left=None, right=None): self.key = key s...
6d02ed6e59b2301e57692bae4075064f2f6e993b
Fellylove/Lambdata-Burris1
/datasplit.py
304
3.75
4
import pandas as pd from pandas import dataframe def split_dates(date_series): df = dataframe date_series = df[date_series] df['day'] = pd.DatetimeIndex(date_series).day df['month'] = pd.DatetimeIndex(date_series).month df['year'] = pd.DatetimeIndex(date_series).year print(df)
8355ae4eaa7fd124ea569726cc449365f711bef7
ddjokic/Jacket-Leg-Flooding-Time
/floodingjacket_leg.py
1,165
3.53125
4
#!/usr/bin/env python import inout print("Calculating time to flood a jacket leg from diaphragm rupture") print("Script downloaded long time ago and modified to my liking. Credits to (unknown) author") rb1 = inout.get_float("Input Reserve buoyancy - intact [t] or '0' for 50: ", 50) rb2=inout.get_float("Input Reserve b...
2f65b56c8e44929296963e62c0cd0b1e2009087b
Bruce-zhangyuyang/Leetcode
/easy/874模拟行走机器人.py
2,222
3.671875
4
from typing import List #思路: 先把所有障碍物的位置存入字典,然后机器人走路 ,查看路线中是否存在障碍物 def robotSim(commands: List[int], obstacles: List[List[int]]) -> int: loc = [['y', 1], ['x', 1], ['y', -1], ['x', -1]] x= 0 a = 0 b = 0 o = 0 x2y, y2x = {}, {} for n,m in obstacles: if n not in x2y: x2y[n...
7a5d455134bd20533bf861003d51c5fa9b07aa70
Bruce-zhangyuyang/Leetcode
/easy/66加一.py
269
3.71875
4
from typing import List # 思路:先变成数字 然后加一 再变成列表 def plusOne(digits: List[int]) -> List[int]: sum = 0 for i in digits: sum = sum*10 + i x = [j for j in str(sum+1)] return x digits = [1,2,3] print(plusOne(digits))
c5af7111b6f33879fbe08443916541a405ef2dd1
Bruce-zhangyuyang/Leetcode
/easy/836矩形重叠.py
320
4.09375
4
from typing import List # 思路:排除不可能 def isRectangleOverlap(rec1: List[int], rec2: List[int]) -> bool: return not( rec2[2]<=rec1[0]or\ rec2[3]<=rec1[1]or\ rec2[0]>=rec1[2]or\ rec2[1]>=rec1[3] ) rec1 = [0,0,1,1] rec2 = [1,0,2,1] print(isRectangleOverlap(rec1, rec2))
f806222f88d600395ce47146448465f229406c40
Bruce-zhangyuyang/Leetcode
/easy/594最长和谐子序列.py
399
3.65625
4
from typing import List # 思路:用Counter生成字典 然后计算最长和谐子序列 def findLHS(nums: List[int]) -> int: le = 0 from collections import Counter dic = Counter(nums) for i in dic: if i + 1 in dic: k = dic[i] + dic[i + 1] else: continue le = max(le, k) return le nums...
c5f076e1f510413e6343b8296330b99d532c5cdc
Bruce-zhangyuyang/Leetcode
/easy/581最短无序连续子数组.py
1,186
3.671875
4
from typing import List # 思路1: 寻找一个数后面比他小的数的位置 以及前面比他大的数的位置 最后将最后面的位置 减去最前面的位置 # def findUnsortedSubarray(nums: List[int]) -> int: # s = [] # i = 0 # while i <= len(nums) -1: # g = 1 # h = 1 # while i+g <= len(nums) - 1 and nums[i] > nums[i+g] : # s.append(i) # ...
d96ac89874f14ab3ecd5dbc8b641dd34b8baff29
Bruce-zhangyuyang/Leetcode
/easy/231. 2的幂.py
420
3.765625
4
# # 思路1: 暴力解锁,控制小数位数 # def isPowerOfTwo(n: int) -> bool: # import math # s = int(math.log(n, 10)) # result = round(math.log(n, 2), s + 3) # print(result) # return int(result) == result # 思路:二进制种所有2的幂次方都是最高位是1 其他都是0 def isPowerOfTwo(n: int) -> bool: return n > 0 and n & (n - 1) == 0 n = 5368709...
033c19b0318fe45f0bab470eae6d33477b621fd1
Bruce-zhangyuyang/Leetcode
/easy/941有效的山脉数组.py
626
3.640625
4
from typing import List # 思路:找到临界山顶 然后没有相等的存在的降序 输出为True def validMountainArray(A: List[int]) -> bool: if len(A) < 3: return False a = 0 while a < len(A)-1 and A[a] < A[a+1] : a += 1 if a == 0: return False s = A[a:] s_ = sorted(s)[::-1] print(s, s_) if s == s_ and len(set(s_)) ...
5d942cbab1e73c764a639a9b44ffe5da158a5360
Bruce-zhangyuyang/Leetcode
/easy/204计数质数.py
424
3.828125
4
# 按照所含的数字造一张全是 1 的表 然后将所有的合数全部标记为0 最后求 表的总和 def countPrimes(n: int) -> int: x = [1] * n if n < 3: return 0 x[0] = x[1] = 0 for i in range(2, n): if x[i] == 1: num = 2 while i * num < n: x[i * num] = 0 num += 1 return sum(x) ...
008f74ddd702979bb2008ebf00ea6b53a76843cb
Bruce-zhangyuyang/Leetcode
/easy/125验证回文串.py
395
3.984375
4
# 思路:把里面的空格和其他非数字字符全部清除 然后变为小写 看是否为回文 def isPalindrome(s: str) -> bool: s = ''.join(filter(str.isalnum, s)).lower() # isalnum:判断字符只有数字和字符 isalpha:判断只有字符 isalnum:判断只有数字 return s == s[::-1] str.isalnum() # s = "A man, a plan, a canal: Panama" s = '0P' print(isPalindrome(s))
5eb935b2dd6f27ac06d427907173e5f85a2f0659
bivasmaiti26/AI-Projects
/Path Search Algorithms/route.py
21,253
4.25
4
#!/bin/python # put your routing program here! #!/bin/python # put your group assignment problem here! # --------------------------------------abstraction----------------------------------------------- # state space : All cities and intersections given in the city-gps.txt and road-segments.txt constitute the s...
e1f6e479897fa6cf340ce5ea4bb9078460056025
anoopvalluthadam/Huffman_Data_Compression_Algorithm
/test.py
1,664
3.8125
4
codes={} def function(str): dec={} for ch in str: dec[ch]=dec.get(ch,0)+1 return dec var="abcddeee" dec1=function(var); print var print dec1 def funcSort(str): keys=str.keys() touple=[] for ch in str: touple.append((str[ch],ch)) touple.sort() return touple touple1=funcSort(dec1) print touple1 def b...
e19191a0976609c21cbea507512cae62913da971
robal852/zadaniaPython2020
/Zestawy_Zaliczone/zestaw7/triangles.py
3,508
3.984375
4
import math from Zestawy_Zaliczone.zestaw6.points import Point def distance(x1, y1, x2, y2): '''Distance between two points''' return math.sqrt(abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2) class Triangle: """Klasa reprezentująca trójkąty na płaszczyźnie.""" def __init__(self, x1, y1, x2, y2, x3, y3): ...
ce2be0d7767ea95e833b7f6a60f9b61742b7f074
robal852/zadaniaPython2020
/projektGraWStatki/Game.py
4,555
3.671875
4
from Player import Player from Board import Board from os import system, name import random class Game: """ Główna klasa reprezentująca gre w statki """ def __init__(self): """ Przygotowanie do rozgrywki, Wybor graczy i rozstawianie statkow player1, player2 - gracze board1, board2 - o...
9165cde1f83b9f4eae5a92816233263a815e4809
meghakorade16/leetcode-solution
/july-leetcode-challenge/subsets.py
475
3.65625
4
from collections import deque def findSubsets(nums, result, index): if index < 0: print(list(result)) return result.append(nums[index]) findSubsets(nums, result, index - 1) result.pop() while index > 0 and nums[index] == nums[index - 1]: index -= 1 findSubsets(nums, res...
a8c244c9d210e3ad64cd31af0fe7eb07ee37907a
meghakorade16/leetcode-solution
/leetcode-June-challenges/queue-recontsruction.py
471
3.734375
4
def main(): people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]] d = {} for h, k in people: if h not in d: d[h] = [[h, k]] else: d[h].append([h, k]) re = [] for h in sorted(d.keys(), reverse=True): group = sorted(d[h]) if not re: ...
dea162e4198bbcdd4e1493ffd3a8c9f07610df76
meghakorade16/leetcode-solution
/leetcode-June-challenges/reverse_string.py
172
3.53125
4
def main(): s = ["h","e","l","l","o"] for i in range(0, len(s) // 2): s[i], s[-i - 1] = s[-i - 1], s[i] print(s) if __name__ == '__main__': main()
602ab89ebac8e1aa3abc570f0653d9fe29bff22a
meghakorade16/leetcode-solution
/leetcode-June-challenges/add-numbers.py
158
3.671875
4
def Add(x, y): while y != 0: carry = x & y x = x ^ y y = carry << 1 return x if __name__ == '__main__': print(Add(4, 2))
f26b9424d6c2ca2a5cb05b9c0897e9daf3ca0eb5
meghakorade16/leetcode-solution
/leetcode-June-challenges/word-search.py
807
3.84375
4
class TrieNode: def __init__(self): self.children = {} self.end_node = 0 class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): root = self.root for symbol in word: dict_to_search = root.children if symbol not in dict...
84b4ad84ab15bec7520e8086a11f7d30aad57e35
ywkpl/DataStructuresAndAlgorithms
/Queue/ArrayQueue.py
1,465
3.5625
4
from typing import TypeVar, Generic T=TypeVar('T') class ArrayQueue(Generic[T]): def __init__(self, capacity:int): self._capacity=capacity self._top=-1 self._arr=[] def is_full(self)->bool: return self._capacity==self._top+1 def enqueue(self, value:T): if self.is_fu...
3a40e7b025d83d81c9f59ee9b5774f4d68a5039b
ywkpl/DataStructuresAndAlgorithms
/Sort/MergeSort.py
1,611
4.15625
4
#归并排序,分而治之 import random,time class MergeSort: def __init__(self, capacity:int): self._arr=[] self._insert_values(capacity) def _insert_values(self, capacity:int): for x in range(capacity): self._arr.append(random.randint(1,100000)) def print_all(self): print(s...
d1688eee799257ca46b10f1dbba17c8ebcfb8c09
bckohn/E-mailList
/main.py
2,101
3.8125
4
# func para formatar os nomes def create_mail(full_name, count, mail_created): interlist = [] if len(full_name) < 3: interlist.append(full_name[-1].strip()) mail_created.append(interlist[-1]+"."+full_name[0][0]) elif len(full_name) > 2: interlist.append(full_name[-1].strip...
e9183fe58f9f37cfe2598fad992ca6d595d30b6b
hoangthevuongvn/TEST_J
/3.py
273
3.875
4
tuple1=(2,3,4,5,6) tuple2=(2,11,7,8) def Check(c,e): for i in c: for v in e: if i == v: return True break return False if Check(tuple1,tuple2) == False: print("Khong trung") else: print("trung")
f476fa91a9100db21655035ebdec7bbce6116e33
jeanlucamtp12/Arvore-de-Huffman
/Huffman.py
10,386
3.78125
4
class No: def __init__ (self): self.frequencia = None self.simbolo = "" self.proximo = None self.visitado = False self.codificado = None class Arvore: def __init__ (self): self.ptr = None self.arvoreCodificada = "" self.arvoreDecodificada = "...
c9ab4becc1a51600d19928a551c7aa23b08f8e67
conbench/conbench
/conbench/numstr.py
5,563
3.9375
4
""" A module for turning a floating point number into short, meaningful text, for representation in a user interface, or in e.g. JSON documents. Guidelines: - no unnecessary precision (reasonable number of significant digits) - shortest possible output (e.g., no trailing ".0" or even ".") At first we started using s...
f83f13cb4535ecef9b9aada607ee915374a69ee0
Dalspd/Python_study
/Study/s_basic.py
849
3.984375
4
# Welcome print("welcome to this repo.") # A test for pycharm[x.print==>print(x)] x = 3 print(x) # x.print # 换行符 one = 1 two = 2 three = 3 total = one + \ two \ + three fruits = ['apple', 'banana', 'orange'] # [],{},()不需要换行符 # 从键盘输入 # insth = input("input sth pls\n") # print(insth) """ ...
1a83be66f9389efc8297568bd53408d74e9b98ac
namand010/Project4091998
/hackerrank/all_in_one.py
305
4
4
def print_formatted(number): # your code goes here for i in (1,n+1): print(i, end=" ") print(str(oct(i))[2:] , end=" ") a = str(hex(i))[2:] print(a.upper(), end=" ") print(str(bin(i))[2:]) if __name__ == '__main__': n = int(2) print_formatted(n)
83c21e86783befbef33de9b06d0f1d8934b56cd7
namand010/Project4091998
/Eulersiteproblem/level2_(PrimeFactornumber).py
599
3.8125
4
import math def primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: print (2) n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3, int(math.sqrt(n)) + 1, 2): # while i divides n , print i ad divide n ...
f874e6208f53d56b7165318de593eac0233a5e93
namand010/Project4091998
/Learning_code/nextday.py
223
3.96875
4
def nextday(year, month, day): if day < 30: return year,month, day+1 else: if month == 12: return year+1,1,1 else: return year,month+1,1 print(nextday(2013,8,21))
d993b4399e4953c39a0748644a6d706786265784
namand010/Project4091998
/hackerrank/product_except_index.py
514
3.984375
4
def product(arr, n): if n == 1: print(0) return left = [0] * n right = [0] * n prod = [0] * n left[0] = 1 right[n - 1] = 1 for i in range(1, n): left[i] = arr[i - 1] * left[i - 1] for j in range(n-2, -1, -1): right[j] = arr[j + 1] * right[j + 1] for...
e00cd5b8f7123eb566e5bb8c84aaa479e2300877
namand010/Project4091998
/Learning_code/DaysinBtwDates.py
1,661
4.1875
4
def isleapyear(year): if year % 4 == 0 or year % 400 == 0: return True else: return False def DaysInmonth(year,month): if month == 1 or month == 3 or month == 5 or month == 7 \ or month == 8 or month == 10 or month == 12: return 31 else: if month == 2: ...
b0c3856fadd44e1c763e939edfa2e8e97c0ffcb6
namand010/Project4091998
/hackerrank/min_subarray.py
377
3.84375
4
from hackerrank import unit_f # print(arr[]) def minArray(arr, wind): # wind = 3 vcf = [] tmp = 0 for i in range(len(arr) - (wind - 1)): temp = sorted(arr[i:i + wind]) print(temp) diff = temp[-1] - temp[0] # if diff not in vcf: vcf.append(diff) return vcf[0...
5a2df24f3b29bcaf9b1522e8c9390b39b142b2ee
yielding/code
/0.algorithm/combinatorics.basic/permutation.list.r.py
208
3.890625
4
#!/usr/bin/env python def permutations(head, tail=''): if len(head) == 0: print tail else: for i in range(len(head)): permutations(head[0:i] + head[i+1:], tail + head[i]) permutations("123")
3cf41f21af87d1a68f0ef019641092f9f29c00c5
taylormitchell/roam_orbit
/date_helpers.py
950
3.515625
4
import re from datetime import datetime ROAM_FORMAT = '%B %d, %Y' def remove_day_suffix(dt): return re.sub(r"\b(\d{1,2})(st|nd|rd|th)\b", "\g<1>", dt) def strptime_day_suffix(date_string, format=ROAM_FORMAT): # Parse datetime from date string with day suffix date_string = remove_day_suffix(date_string)...
932e7ff84d93da6509d9a8b44eb161d873ec72a4
uestcljx/pythonBeginner
/prime.py
1,415
4.15625
4
#odd_iter 生成一个无穷奇数数列,作为初始数列(2以外的偶数都不是素数) def odd_iter(): n = 1 while True: n = n + 2 yield n #not_divisible 输入参数n, 内部定义一个匿名函数,输入参数x, 判断x是否能被n整除 def not_divisible(n): return lambda x: x % n > 0 # 注意这里定义了一个匿名函数,所以实际上not_divisible函数要接受两个参数 #生成无穷素数数列 def prime(): _iter = odd_iter() #初始数列 ...
ffa70e070e47ef16f86a7a8d9953a612a18ed0de
MustofAhmed41/DrawIt
/venv/testFile.py
3,170
3.609375
4
import pygame class Grid(): def __init__(self,position_x,position_y,color): self.position_x = position_x self.position_y = position_y self.length = 5 self.width = 5 self.color = col # https://www.pygame.org/docs/ref/mouse.html#comment_pygame_mouse_get_pressed pygame.in...
e41ebd3862e8c14980204682aeb0793b200767c7
FredericoTakayama/blackjack
/deck.py
1,893
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from random import randint class Card(object): def __init__(self, suit_idx = 0,number_idx = 0, deck_name=None): suits = ['Club', 'Heart', 'Spade', 'Diamond'] numbers = [i for i in range(1,14)] # indica o valor da carta names = ['ace','two','th...
4278b69bfe5a55dc821ef2379ca6f3455319a55d
joemcilheran/Wages
/grosswages.py
691
4.0625
4
while True: hoursWorked = input("How many hours did you work? \n") try: hoursWorked = float(hoursWorked) except ValueError: print("Please enter a number(i.e. 24, not twenty-four)") continue break while True: payPerHour = input("How much do you get paid per hour? \n")...
c4273dbb06d26543e621301c7072509493fb24d1
pavelbrn/DataQuestProjects
/custom-python-functions/customFunctions.py
1,178
3.953125
4
import pandas as pd # Iterate through string, append "_" to character # strip "_" if it was appended directly at the beginning or end of a word # return the snakecase string def change_to_camelcase(string): new_string = "" for char in string: if char.isupper(): char = char.lower() ...
75d37f4711f658b8dc4c6e78d55a6373199a4e8f
CubeACloud/Python
/git py/function.py
1,801
3.765625
4
def add_number(): firstNum = 15 secondNum = 30 total = firstNum + secondNum print(total) add_number() def pakistan(): karachi = "malir " lahore = " johar" sindh = karachi + lahore print(sindh) pakistan() def button(): onn = "fan" close = " start" Thi...
8a406a745e482331fde53edcdf24bacb17fa33f8
naashonomics/LeetCode
/100.sametree_rec.py
723
3.984375
4
#Given two binary trees, write a function to check if they are equal or not. #Two binary trees are considered equal if they are structurally identical and the nodes have the same value. #Divide and conquer(Recursion), time complexity = O(n), #n is the number of nodes, class Sol...
297215fc23a4dbea3d253a5df20c39bd86a7f130
rtg0795/python_snippets
/enumerate.py
289
4.0625
4
# Source # https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 # Enumerate to get index and elements of list # logic & test lst = ['a', 'b', 'c', 'd'] for index, element in enumerate(lst): print(f'lst[{index}] = {element}')
3c4343c419e12c367f6cf6045103934525aad57b
rtg0795/python_snippets
/remove_falsy_values.py
413
3.6875
4
# Source # https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172 # remove falsy values like False, None, 0 and '' from a list by filter lst = [0, 1, False, 2, '', 3, 'a', 's', 34, None] print(list(filter(None, lst))) # 1 filter(function, sequence) function as ...