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 |
|---|---|---|---|---|---|---|
9f13a29c757c6cc2ef8f0d7dfe29b37ddec47df0 | Dannikk/dfs_bfs_animation_-using-networkx- | /src/graph_reader.py | 567 | 3.921875 | 4 | import os
DELIMITER = ':'
NODES_DELIMITER = ','
def read_graph(file_path: str):
"""
Function that reads a graph from a text file
Parameters
----------
file_path : str
directory to file to read graph
Returns
-------
generator :
yielding node (any hashable object), lis... |
39bbe7fce725a7fb6fbc91def71fd88e6373b7e6 | endfirst/python | /first_class_function/first_class_function00.py | 511 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# 퍼스트클래스 함수란 프로그래밍 언어가 함수 (function) 를 first-class citizen으로 취급하는 것을 뜻합니다.
# 쉽게 설명하자면 함수 자체를 인자 (argument) 로써 다른 함수에 전달하거나 다른 함수의 결과값으로 리턴 할수도 있고,
# 함수를 변수에 할당하거나 데이터 구조안에 저장할 수 있는 함수를 뜻합니다.
def square(x):
return x * x
print square(5)
f = square
print square
print f |
938501b49e1f9678ac3f64094b2cf4eed46c35f6 | JasmineBharadiya/pythonBasics | /task_8_guessNo.py | 161 | 3.609375 | 4 | import random
a=int(raw_input("guess a no. between 1-10: "))
rA=random.randint(1,10)
if(rA==a):
print "well guessed"
else :
print "try again"
|
91d55cba2c6badcd157aae309c518f6fafcbf9c1 | mildzf/zantext | /zantext/zantext.py | 671 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
File: zantext.py
Author: Mild Z Ferdinand
This program generates random text.
"""
import random
POOL = "abcdefghijklmnopqrstuvwxyz"
def word(length=0):
if not length or length > 26:
length = random.randint(3, 10)
else:
length = abs(length)
word = [random.choi... |
4bdde3d9684f505ae85c0446465aa211a012a02d | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-2.py | 415 | 4.3125 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 2. In mathematics, the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅ n (as the product of all integer numbers from 1 to n).
# For example, 4! = 1 ⋅ 2 ⋅ 3 ⋅ 4 = 24. Write a recursive function for calculating n!
def calculateN(num):
if num == 1:
... |
7372b7c995d2302f29b8443656b50cae298a566b | luizfirmino/python-labs | /Python I/Assigments/Module 6/Ex-4.py | 742 | 4.40625 | 4 | #
# Luiz Filho
# 3/23/2021
# Module 6 Assignment
# 4. Write a Python function to create the HTML string with tags around the word(s). Sample function and result are shown below:
#
#add_html_tags('h1', 'My First Page')
#<h1>My First Page</h1>
#
#add_html_tags('p', 'This is my first page.')
#<p>This is my first page.... |
7207ee818fe1cd157874667ae152ee4e8072de3d | luizfirmino/python-labs | /Python Databases/Assigments/Assignment 1/filho_assignment1.py | 655 | 4 | 4 | #!/usr/bin/env python3
# Assignment 1 - Artist List
# Author: Luiz Firmino
#imports at top of file
import sqlite3
def main():
con = sqlite3.connect('chinook.db')
cur = con.cursor()
#query to select all the elements from the movie table
query = '''SELECT * FROM artists'''
#run the query
cur.... |
c13619368c38c41c0dbf8649a3ca88d7f2788ee8 | luizfirmino/python-labs | /Python Networking/Assignment 2/Assignment2.py | 564 | 4.21875 | 4 | #!/usr/bin/env python3
# Assignment: 2 - Lists
# Author: Luiz Firmino
list = [1,2,4,'p','Hello'] #create a list
print(list) #print a list
list.append(999) #add to end of list
print(list)
print(list[-1]) #print the last element
list.pop() #remove last element
pr... |
51d1e3a48b954c1de3362ea295d4270a884fea98 | luizfirmino/python-labs | /Python I/Assigments/Module 7/Ex-3.py | 1,042 | 4.3125 | 4 | #
# Luiz Filho
# 4/7/2021
# Module 7 Assignment
# 3. Gases consist of atoms or molecules that move at different speeds in random directions.
# The root mean square velocity (RMS velocity) is a way to find a single velocity value for the particles.
# The average velocity of gas particles is found using the root mean s... |
47d783748c562dd3c3f8b7644dda166f37b5f11e | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-6.py | 238 | 4.5 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 6. Write a simple function (area_circle) that returns the area of a circle of a given radius.
#
def area_circle(radius):
return 3.1415926535898 * radius * radius
print(area_circle(40)) |
6ca6fbf8e7578b72164ab17030f1c01013604b04 | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-4.py | 549 | 4.28125 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 4. Explain what happens when the following recursive functions is called with the value “alucard” and 0 as arguments:
#
print("This recursive function is invalid, the function won't execute due an extra ')' character at line 12 column 29")
print("Regardless any value... |
796c8bb615635d769a16ae12d9f27f2cfce4631c | luizfirmino/python-labs | /Python I/Assigments/Module 2/Ex-2.py | 880 | 4.53125 | 5 | #
# Luiz Filho
# 2/16/2021
# Module 2 Assignment
# Assume that we execute the following assignment statements
#
# length = 10.0 , width = 7
#
# For each of the following expressions, write the value of the expression and the type (of the value of the expression).
#
# width//2
# length/2.0
# length/2
# ... |
6c41276669d4b83b5b79074f60302f370c4eaa80 | wuga214/PlanningThroughTensorFlow | /utils/argument.py | 388 | 3.609375 | 4 | import argparse
def check_int_positive(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
return ivalue
def check_float_positive(value):
ivalue = float(value)
if ivalue < 0:
raise argparse.ArgumentTypeErro... |
910a369c1dc5ad07e8e4c1916ef31c0c044f7430 | Litao439420999/LeetCodeAlgorithm | /Python/integerBreak.py | 701 | 3.59375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: integerBreak.py
@Function: 整数拆分 动态规划
@Link: https://leetcode-cn.com/problems/integer-break/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-16
"""
class Solution:
def integerBreak(self, n: int) -> int:
if n < 4:
return n - 1
... |
78098f3c8900ab45f703158bfefd790be0cfe74b | Litao439420999/LeetCodeAlgorithm | /Python/maxProfitChance.py | 799 | 4 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: maxProfitChance.py
@Function: 买卖股票的最佳时机 动态规划
@Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-16
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -... |
a5dfcb4f79865d734ddfd7d9cf0c9061fcc6d187 | Litao439420999/LeetCodeAlgorithm | /Python/missingNumber.py | 611 | 3.828125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: missingNumber.py
@Function: 丢失的数字
@Link: https://leetcode-cn.com/problems/missing-number/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-22
"""
class Solution:
def missingNumber(self, nums):
missing = len(nums)
for i, num in enumerate(nu... |
ead8d1adb57d0b887ccd55638e88586230fe2d47 | Litao439420999/LeetCodeAlgorithm | /Python/maxArea.py | 868 | 4.03125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: maxArea.py
@Function: 盛最多水的容器
@Link: https://leetcode-cn.com/problems/container-with-most-water/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-08
"""
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
left, ri... |
f0df420f1b26891e1e1483da86615aa651a99815 | Litao439420999/LeetCodeAlgorithm | /Python/combinationSum2.py | 1,456 | 3.734375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: combinationSum2.py
@Function: 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合
@Link: https://leetcode-cn.com/problems/combination-sum-ii/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-12
"""
import collections
from typing import List
... |
4cf065dceacbfb09de77b2dba2d1f6879e080362 | Litao439420999/LeetCodeAlgorithm | /Python/removeNthFromEnd.py | 884 | 3.9375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: removeNthFromEnd.py
@Function: 删除链表的倒数第 N 个结点
@Link: https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-30
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, ... |
f5e0250259414bd762064edd430b574d691f7051 | Litao439420999/LeetCodeAlgorithm | /Python/isPowerOfThree.py | 825 | 4.09375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: isPowerOfThree.py
@Function: 3的幂 数学问题
@Link: https://leetcode-cn.com/problems/power-of-three/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-19
"""
import math
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
ret... |
8146a0a68782bf0745c250965e9440689dd3d957 | Litao439420999/LeetCodeAlgorithm | /Python/candy.py | 3,342 | 3.640625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: candy.py
@Function: 分发糖果 贪心策略
@Link: https://leetcode-cn.com/problems/candy/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-04
"""
# --------------------------------------------------------------
class Solution2:
"""0、只需要简单的两次遍历即可:把所有孩子的糖果数初始化为 1;
1、... |
268b790641e7a522cc7d2431dcdb28b9a30126c8 | Litao439420999/LeetCodeAlgorithm | /Python/MinStack.py | 754 | 3.65625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: MinStack.py
@Function: 最小栈
@Link: https://leetcode-cn.com/problems/min-stack/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-25
"""
import math
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def pu... |
03a7ff048927334379e9758f3d2e7b43d2ceee43 | Litao439420999/LeetCodeAlgorithm | /Python/hammingDistance.py | 636 | 3.78125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: hammingDistance.py
@Function: 两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目
@Link: https://leetcode-cn.com/problems/hamming-distance/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-21
"""
class Solution:
def hammingDistance(self, x, y):
return bin(x ^ y).... |
f04df87810d13395100540e524f48db20db18d52 | Litao439420999/LeetCodeAlgorithm | /Python/calculate.py | 1,149 | 3.875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: calculate.py
@Function: 基本计算器 II
@Link: https://leetcode-cn.com/problems/basic-calculator-ii/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-28
"""
class Solution:
def calculate(self, s: str) -> int:
n = len(s)
stack = []
preSign... |
a39d90db4f8ca2489ce1c157bc075f59aba7c24d | Litao439420999/LeetCodeAlgorithm | /Python/reconstructQueue.py | 1,015 | 3.859375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: reconstructQueue.py
@Function: 根据身高重建队列 贪心策略
@Link: https://leetcode-cn.com/problems/queue-reconstruction-by-height/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-06
"""
# ---------------------------
class Solution:
def reconstructQueue(self, people):
... |
0334614a346b0a1dcddf4da9b585a997ab561dad | Litao439420999/LeetCodeAlgorithm | /Python/matrixReshape.py | 850 | 4.0625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: matrixReshape.py
@Function: 重塑矩阵
@Link: https://leetcode-cn.com/problems/reshape-the-matrix/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-26
"""
from typing import List
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) ->... |
7b22af2549e23620e764bfe31cf5fbddf2a6b6bd | Litao439420999/LeetCodeAlgorithm | /Python/dailyTemperatures.py | 956 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: dailyTemperatures.py
@Function: 每日温度
@Link: https://leetcode-cn.com/problems/daily-temperatures/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-25
"""
from typing import List
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[... |
2c3bdd46d4cd3975dfb4cadb5f4f29af6bbd7872 | Litao439420999/LeetCodeAlgorithm | /Python/wiggleMaxLength.py | 1,074 | 3.71875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: wiggleMaxLength.py
@Function: 摆动序列 动态规划
@Link:https://leetcode-cn.com/problems/wiggle-subsequence/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-16
"""
class Solution:
def wiggleMaxLength(self, nums) -> int:
n = len(nums)
if n < 2:
... |
adb7c6349316892da5414d10a589f891e97bb1e5 | Litao439420999/LeetCodeAlgorithm | /Python/constructFromPrePost.py | 1,101 | 3.875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: constructFromPrePost.py
@Function: 根据前序和后序遍历构造二叉树
@Link : https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-02
"""
# Definition for a binary tree node.
class TreeNode... |
97427f841b2215fda35a0110c3323725acace837 | Litao439420999/LeetCodeAlgorithm | /Python/findKthLargest.py | 1,315 | 3.953125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: findKthLargest.py
@Function: 数组中的第K个最大元素 快速选择
@Link: https: // leetcode-cn.com/problems/kth-largest-element-in-an-array/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-10
"""
import random
class Solution:
def findKthLargest(self, nums, k):
def... |
b944a375a96ced5824239689a7e7b5f26dc854c4 | Litao439420999/LeetCodeAlgorithm | /Python/binaryTreePaths.py | 2,102 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: binaryTreePaths.py
@Function: 二叉树的所有路径
@Link: https://leetcode-cn.com/problems/binary-tree-paths/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-12
"""
import collections
from typing import List
import string
# Definition for a binary tree node.
class TreeN... |
6bc5f504ef16bea225cae8f52e818fb96687b002 | Litao439420999/LeetCodeAlgorithm | /Python/sumOfLeftLeaves.py | 1,006 | 3.78125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: sumOfLeftLeaves.py
@Function: 左叶子之和
@Link: https://leetcode-cn.com/problems/sum-of-left-leaves/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-01
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
... |
8b39bba2440821071ad46e65071a642da9ce5434 | Litao439420999/LeetCodeAlgorithm | /Python/lowestCommonAncestor2.py | 962 | 3.65625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: lowestCommonAncestor2.py
@Function: 二叉树的最近公共祖先
@Link : https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-08-02
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self... |
fbc71fc9cb47523ce6a7b1aed3f1c24b3723846b | Litao439420999/LeetCodeAlgorithm | /Python/numSquares.py | 1,301 | 3.671875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
@Filename: numSquares.py
@Function: 完全平方数 动态规划
@Link: https://leetcode-cn.com/problems/perfect-squares/
@Python Version: 3.8
@Author: Wei Li
@Date:2021-07-14
"""
class Solution:
def numSquares(self, n: int) -> int:
'''版本一'''
# 初始化
nums = [i**2 ... |
3bb8a813d915675a1aec37019e157674a162dfef | renatovvjr/candidatosDoacaoPython | /main.py | 1,269 | 3.796875 | 4 | #O programa receberá informações de 10 candidatos à doação de sangue. O programa deverá ler a idade e informar a seguinte condição:
#- Se menor de 16 ou acima de 69 anos, não poderá doar;
#- Se tiver entre 16 e 17 anos, somente poderá doar se estiver acompanhado dos pais ou responsáveis (neste caso criar uma condição:... |
ef1db11ab060501a5f23c772da2e3467889b3fb3 | Zetinator/just_code | /python/leetcode/jumping_clouds.py | 655 | 3.84375 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads.
"""
def deep(x, jumps):
i... |
dd146b10d8b6c0900a77754d93b0c9231e2737a8 | Zetinator/just_code | /python/leetcode/sorting_bubble_sort.py | 1,012 | 4.09375 | 4 | """https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting
Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines:
Arr... |
2dcdbed4df8b0608780c4d3a226c4f25d0de2b38 | Zetinator/just_code | /python/leetcode/binary_distance.py | 872 | 4.1875 | 4 | """
The distance between 2 binary strings is the sum of their lengths after removing the common prefix. For example: the common prefix of 1011000 and 1011110 is 1011 so the distance is len("000") + len("110") = 3 + 3 = 6.
Given a list of binary strings, pick a pair that gives you maximum distance among all possible pa... |
2b9f81e6106ebe23353158a2b4b3f12d034003e7 | Zetinator/just_code | /python/leetcode/simple_text_editor.py | 1,697 | 4 | 4 | """https://www.hackerrank.com/challenges/simple-text-editor/problem
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, . You must perform operations of the following types:
append - Append string to the end of .
delete - Delete the last characters of .
prin... |
18b95ddca9704d64627cde69375e30a880efaa95 | Zetinator/just_code | /python/leetcode/poisonous_plants.py | 3,076 | 3.921875 | 4 | """https://www.hackerrank.com/challenges/poisonous-plants/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues
There are a number of plants in a garden. Each of these plants has been treated with some amount of pesticide. After each day, if any plant has more pesticid... |
246928be6fa574268809d7291343ff2e7d099234 | Zetinator/just_code | /python/classics/max_change.py | 654 | 3.8125 | 4 | """
Coin Change problem: Given a list of coin values in a1, what is the minimum number of coins needed to get the value v?
"""
from functools import lru_cache
@lru_cache(maxsize=1000)
def r(x, coins, coins_used):
"""recursive implementation
"""
if x <=0: return coins_used
return min(r(x-coin, coins, co... |
319781d2b8b2a6bb1fdbb3070ac71057b4e949a0 | Zetinator/just_code | /python/data_structures/radix_trie.py | 5,142 | 3.53125 | 4 | """custom implementation of a radix trie with the purpose of practice
the ADT contains the following methods:
- insert
- search
- delete
"""
class RTrie():
class Node():
"""Node basic chainable storage unit
"""
def __init__(self, x=None):
self.data = x
sel... |
27db300075e7661296ee4d494f378aac89b21c83 | Zetinator/just_code | /python/algorithms/dinic.py | 2,041 | 4 | 4 | """implementation of the dinic's algorithm
computes the max flow possible within a given network gaph
https://visualgo.net/en/maxflow
https://en.wikipedia.org/wiki/Dinic%27s_algorithm
"""
from data_structures import network_graph
def dinic(graph: network_graph.NGraph) -> int:
"""computes the maximum flow value of... |
6fc20cea6cd490bd44af17299584ee0be51356e4 | Zetinator/just_code | /python/leetcode/min_swaps_2.py | 1,795 | 3.796875 | 4 | """https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=arrays
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. ... |
c1d4def8281d064203472299ab75b786a9261ae2 | Zetinator/just_code | /python/leetcode/find_maximum_index_product.py | 1,328 | 3.9375 | 4 | """https://www.hackerrank.com/challenges/find-maximum-index-product/problem
You are given a list of numbers . For each element at position (), we define and as:
Sample Input
5
5 4 3 4 5
Sample Output
8
Explanation
We can compute the following:
The largest of these is 8, so it is the answer.
"""
def solve(arr):
... |
308f485babf73eec8c433821951390b8c2414750 | Zetinator/just_code | /python/leetcode/pairs.py | 966 | 4.1875 | 4 | """https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=search
You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
Complete... |
671ea3e72e4ff94b20aed867eb3c4075b2be4d92 | Zetinator/just_code | /python/classics/longest_common_substring.py | 828 | 3.9375 | 4 | """In computer science, the longest common substring problem is to find the longest string (or strings) that is a substring (or are substrings) of two or more strings.
https://en.wikipedia.org/wiki/Longest_common_substring_problem
"""
from functools import lru_cache
@lru_cache(maxsize=1000)
def r(x, y, record=0):
... |
d7927eb47f552113d335a0e1b04f608e852a8c3a | Zetinator/just_code | /python/leetcode/string_comparator.py | 910 | 4.0625 | 4 | """https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
Comparators are used to compare two objects. In this challenge, you'll create a comparator... |
e823b273ed44482d8c05499f66bf76e78b06d842 | Zetinator/just_code | /python/leetcode/special_string_again.py | 2,477 | 4.21875 | 4 | """https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=strings
A string is said to be a special string if either of two conditions is met:
All of the characters are the same, e.g. aaa.
All characters excep... |
768f200cbdbbbd4808c4eea18004f7e4ff7c912c | Zetinator/just_code | /python/data_structures/double_linked_list.py | 3,017 | 3.96875 | 4 | """custom implementation of a double linked list with the purpose of practice
the ADT contains the following methods:
- append
- insert
- search
- delete
- traverse
"""
class DoubleLinkedList():
class Node():
"""Node basic chainable storage unit
"""
def __init__(self, x=N... |
51e43263d84055e470d62d41a870972357ab30f2 | Zetinator/just_code | /python/leetcode/give_change.py | 472 | 3.671875 | 4 | def give_change(quantity):
coins = [25, 10, 5, 1]
def go_deep(quantity, coins, change):
print('STATUS: quantity: {}, coins:{}, change:{}'.format(quantity, coins, change))
if quantity <= 0: return change
n = quantity // coins[0]
change[coins[0]] = n
quantity -= n*coins[0]
... |
6ee354648d87ca74e3a5c3776c70741bed442799 | Zetinator/just_code | /python/leetcode/candies.py | 3,186 | 3.984375 | 4 | """https://www.hackerrank.com/challenges/candies/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dynamic-programming
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a... |
7353020b0f9f4e876ad39334bad7953aa1096b44 | Zetinator/just_code | /python/leetcode/max_min.py | 965 | 3.953125 | 4 | """https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=greedy-algorithms
Complete the maxMin function in the editor below. It must return an integer that denotes the minimum possible value of unfairness.
maxMin has ... |
44b2c2a5ef7e890d3f38b6ccb1e990ed668930d2 | Zetinator/just_code | /python/data_structures/max_heap.py | 3,645 | 3.875 | 4 | """custom implementation of a max heap tree with the purpose of practice
the ADT contains the following methods:
- push
- peek
- pop
"""
class Heap():
def __init__(self, x=[]):
self.v = []
for e in x:
self.push(e)
def __len__(self):
return len(self.v)
def __... |
e2b8fe6ba7d4d000b5ef8578aae3caf1847efc9d | Zetinator/just_code | /python/leetcode/unique_email.py | 1,391 | 4.375 | 4 | """
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name p... |
c80ef444ca25f5a4a263ef68b3dfdab39aa85c89 | santiagoahc/coderbyte-solutions | /medium/swapII.py | 513 | 3.5 | 4 | def SwapII(str):
new_str = []
last_digit = (None, -1)
for i, s in enumerate(str):
if s.isalpha():
s = s.lower() if s.isupper() else s.upper()
elif s.isdigit():
if last_digit[0]:
new_str[last_digit[1]] = s
s = last_digit[0]
last_digit = (None, -1)
elif i+1 < len(st... |
b1310efca71f5bf0d3daa2d0ae9135a0edc70382 | santiagoahc/coderbyte-solutions | /medium/bracket_matcher.py | 711 | 3.96875 | 4 | def BracketMatcher(str):
round_brackets = 0
square_brackets = 0
total_pairs = 0
for s in str:
if s == '(':
round_brackets += 1
total_pairs += 1
elif s == ')':
if round_brackets < 1:
return 0
round_brackets -= 1
elif s == '[':
squa... |
a8b5da625783c4dc555005d83ebb04dbea1b4e50 | santiagoahc/coderbyte-solutions | /medium/most_free_time.py | 1,603 | 4.09375 | 4 | """
Using the Python language, have the function MostFreeTime(strArr) read the strArr parameter being passed which will represent a full day and will be filled with events that span from time X to time Y in the day. The format of each event will be hh:mmAM/PM-hh:mmAM/PM. For example, strArr may be ["10:00AM-12:30PM","0... |
91f2f7d0ab659ac5454438737642142c3c18af15 | santiagoahc/coderbyte-solutions | /hard/bitch.py | 2,860 | 3.625 | 4 | def gcd(a, b):
while a % b:
a, b = b, a % b
return b
def frac_reduce(num, den):
g = gcd(num, den)
return (num/g, den/g)
class Fraction:
def __init__(self, num, den=1):
self.num, self.den = frac_reduce(num, den)
def __neg__(self):
return Fraction(-self.num, self.den)
... |
70d7c7e63e2c431192dafc2df18f86ef0551541d | santiagoahc/coderbyte-solutions | /members/kaprekars.py | 1,338 | 3.671875 | 4 | """
Using the Python language,
have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits.
Your program should perform the following routine on the number:
Arrange the digits in descending order and in ascending order (adding zeroes to... |
c685e5a1b88a50e5206e108c18453cd8206aa855 | santiagoahc/coderbyte-solutions | /medium/polish notation.py | 633 | 3.984375 | 4 | """
"+ + 1 2 3"
expr is a polish notation list
"""
def solve(expr):
"""Solve the polish notation expression in the list `expr` using a stack.
"""
operands = []
# Scan the given prefix expression from right to left
for op in reversed(expr):
if op == "+":
operands.append(operand... |
0bca43812f3d8fcf893ca985c8f5f7db76335a25 | santiagoahc/coderbyte-solutions | /medium/arith_geo.py | 810 | 3.609375 | 4 | __author__ = 'osharabi'
def ArithGeoII(arr):
if len(arr) <= 1:
return -1
diff = arr[1] - arr[0]
mult = arr[1] / arr[0]
i = 1
while (i+1) < len(arr) and not (diff is None and mult is None):
cur_diff = arr[i+1] - arr[i]
curr_mult = arr[i+1] / arr[i]
if cur_diff != di... |
292d7fcf6be00f2e22950fc9af2abc9f6493bf0d | santiagoahc/coderbyte-solutions | /medium/three_five_mult.py | 130 | 3.875 | 4 | def ThreeFiveMultiples(num):
return sum([n for n in range(3, num) if (n % 3 == 0 or n % 5 == 0)])
print ThreeFiveMultiples(16)
|
2a2acbc1e8bf446dd7b8ac5582d9faa5f4f7f51b | nbonfils/fixed-probe | /sensor-server.py | 6,956 | 3.5625 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""Server that reads values from differents sensors.
This script is a server that is supposed to run on a RPi with the
adequate sensors hooked to it via GPIO.
It reads the value of the sensors then store them on disk or on
the usb drive if one is plugged, it also always expo... |
ca54ebba62347e2c3a4107872889e4746c51a922 | malbt/PythonFundamentals.Exercises.Part5 | /anagram.py | 497 | 4.375 | 4 | def is_anagram(first_string: str, second_string: str) -> bool:
"""
Given two strings, this functions determines if they are an anagram of one another.
"""
pass # remove pass statement and implement me
first_string = sorted(first_string)
second_string = sorted(second_string)
if first_string... |
c093ea69bbcc1a304b3d9d65580f3930ac9aeefc | jpages/twopy | /tests/quick_sort.py | 987 | 3.96875 | 4 | import random
# Very inefficient bubble sort
def bubble_sort(array):
for i in range(len(array)):
for j in range(i, len(array)):
if array[i] > array[j]:
# Swap these elements
temp = array[i]
array[i] = array[j]
array[j] = temp
... |
e7e5c25404dcbd2c211d1ac67d59909bc48c81f7 | jpages/twopy | /tests/sum35.py | 917 | 3.75 | 4 | def sum35a(n):
'Direct count'
# note: ranges go to n-1
return sum(x for x in range(n) if x%3==0 or x%5==0)
def sum35b(n):
"Count all the 3's; all the 5's; minus double-counted 3*5's"
# note: ranges go to n-1
return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))
def sum35c(n)... |
7530cd3094d1a69ac8a8ec7f8aff2555875167ba | Fashgubben/TicTacToe | /test_program.py | 12,276 | 3.578125 | 4 | import unittest
import check_input
import check_for_winner
import game_functions
from class_statistics import Statistics, Player
from random import randint
class TestCases(unittest.TestCase):
"""Test "check_input" functions"""
def test_strip_spaces(self):
test_value1 = '1 1 '
... |
a3ee45b658838526491e85141bc219b4e8a8d31e | Vipulhere/Python-practice-Code | /Module 10/3.1 insertinto.py | 322 | 3.796875 | 4 | import sqlite3
conn=sqlite3.connect("database.db")
query="INSERT into STD(name,age,dept)values ('bob',20,'CS');"
try:
cursor=conn.cursor()
cursor.execute(query)
conn.commit()
print("Our record is inserted into database")
except:
print("Error in database insert record")
conn.rollback()
conn.close... |
cc779c69d84dc9ea2afc1249646caef9f589c15e | Vipulhere/Python-practice-Code | /Module 3/12.1 loops with else block of code.py | 254 | 4.0625 | 4 | for a in range(5):
print(a)
else:
print("The loop has completed execution")
print("_______________________")
t=0
n=10
while (n<=10):
t=t+n
n=n+1
print("Value of total while loop is",t)
else:
print("You have value is equal to 10") |
e777115b8048caa29617b9b0e99d6fbac3beef99 | Vipulhere/Python-practice-Code | /Module 8/11.1 inheritance.py | 643 | 4.3125 | 4 | #parent class
class parent:
parentname=""
childname=""
def show_parent(self):
print(self.parentname)
#this is child class which is inherites from parent
class Child(parent):
def show_child(self):
print(self.childname)
#this object of child class
c=Child()
c.parentname="BOB"
c.childname=... |
3db13f56cd5cac39e2e32ba3a5aa460d3cd957c4 | Vipulhere/Python-practice-Code | /Module 8/7.1 object method.py | 237 | 3.84375 | 4 | class car:
def __init__(self,name,color):
self.name=name
self.color=color
def car_detail(self):
print("Name of car",self.name)
print("Color of car",self.color)
c=car("ford","white")
c.car_detail() |
e549aca0a2c1b27dcde960f56b65da2eb6632fbd | Vipulhere/Python-practice-Code | /Module 6/6.1 tuple.py | 169 | 3.75 | 4 | tuple=()
tuple2=(1,2,3,4,5,6)
tuple3=("python","java","php")
tuple4=(10,20,"java","php")
print(tuple)
print(tuple2)
print(tuple3)
del tuple3
print(tuple3)
print(tuple4)
|
bcabbb2b0ed927d608c3bd8a832aded14e53738f | Vipulhere/Python-practice-Code | /Module 7/2.1 exception handling.py | 209 | 3.796875 | 4 | try:
text=input("Enter a value or something you like")
except EOFError:
print("EOF Error")
except KeyboardInterrupt:
print("You cancelled the operation")
else:
print("you enterd".format(text))
|
5e9af0fd6c370d21c0ce17a5d6ccffad245abaf2 | Vipulhere/Python-practice-Code | /Module 8/16.1 encapsulation.py | 609 | 3.890625 | 4 | class encapsulation:
__name=None
def __init__(self,name):
self.__name=name
def getname(self):
return self.__name
e=encapsulation("Encapsulation")
print(e.getname())
print("________________")
class car(object):
def __init__(self,name="BMw",year=2020,mileage="250",color="white"):
... |
f37f6cfbbe1ca3542992c7a6673284d9b59666a1 | Vipulhere/Python-practice-Code | /Module 6/17.1 sort a dict.py | 172 | 3.921875 | 4 | dict={
"BMW":"2020",
"Ford":"2019",
"Toyota":"2018",
"BMW": "2012",
"Honda": "2015"
}
for key1 in sorted(dict,key=dict.get):
print(key1,dict[key1]) |
391625ce1ccb63a4471ba41a184c346114168c46 | Vipulhere/Python-practice-Code | /Module 2/5.1 Short Hand of operator.py | 83 | 3.71875 | 4 | var=2
var+=10
print(var)
var*=10
print(var)
var/=10
print(var)
var-=10
print(var) |
7b49801dcfbc7feeadb92bf9a9c8de86a7a90d48 | Vipulhere/Python-practice-Code | /Module 3/5.1 nested if else.py | 137 | 3.6875 | 4 | var=-10
if var>0:
print("Postive Number")
else:
print("Negative Number")
if -10<=var:
print("Two Digit are Negative") |
3c2b47f35531074d47b6e3022ae94d8c30d5e99d | Vipulhere/Python-practice-Code | /Module 8/2.1 Classes and Object.py | 170 | 3.921875 | 4 | class car:
model=2020
name="ford"
c=car()
print(c.model,c.name)
class animal:
age=20
name="dog"
color="Black"
a=animal()
print(a.name,a.age,a.color) |
3e49fd765e0672df380c18249f1b1cada092b1d9 | pivacik/leetcode-algorithms | /plan_calc.py | 272 | 3.71875 | 4 | import sys
def calculate_plan(a, b, c, d):
if d > b:
return a + c * (d - b)
else:
return a
string = ''
for line in sys.stdin:
string += line
lst = list(string.split())
a, b, c, d = lst
print(a, b, c, d)
print(calculate_plan(a, b, c, d))
|
aae533ba404018f1c31e8fb949d44741fc54c792 | frigusgulo/F4_Architecture | /VM_Control_Only.py | 1,540 | 3.71875 | 4 |
def Main():
pass
# VM Control
def goto(labelname):
return "@" + str(labelname) + "\n0;JMP\n"
def if_goto(labelname):
return pop_D() + "D=D+1\n@" + str(labelname) + "\nD;JGT\n"
# my understanding is if-goto jumps if top of stack is -1 (true) i.e. pop_D() + D=D+1 + D;JEQ
def label(labelname):
retu... |
78f055ae60f4eaa45424f8f9dea223ff1d5c667c | yukimiii/competitive-programming | /typical90/solved/75.py | 378 | 3.703125 | 4 | def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
n = int(input())
a=prime_factorize(n)
b=len(a)... |
b8585391d0425578a059c18ccd8399eaa4db1581 | Bullsquid/gitTask-1 | /halves.py | 693 | 3.8125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def min_halves(f, a, b, eps):
if b < a:
tmp = a
a = b
b = tmp
t = np.arange(a-1.0, b+1.0, 0.02)
right = []
left = []
plt.plot(t, f(t))
while b-a >= eps:
center = (a + b) / 2.0
delta = (b-a) / 4.0
... |
b0032fa5aa5281354ec4cd92162dc9ac2e1e2e78 | lohe987/ECE366Group4Project3 | /simulator_z.py | 5,921 | 3.640625 | 4 | import sys
import collections
# Class CPU will hold the information of the CPU
class CPU:
PC = 0 # Program Counter
DIC = 0 # Insturction Counter
R = [0] * 4 # Register Values
instructions = [] # instructions in array
memory = [] # memory in array
def check_parity_bit(machine_line):
# Count the... |
1dd2bc4d81e2f09a5dec71127ac5eade13be3dd8 | mayanksingh2233/ML-algo | /ML Algorithms/linear regression.py | 899 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # linear regression
# In[17]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[115]:
df=pd.read_csv('E:\\python\\datasets\\cars.csv',delimiter=';',skiprows=[1])
df.head()
# In[118]:
x=df[['Displacement']]
x
# In[120]:
y=df[['Acceleration... |
b59bb752bfdc1b3fdd2c2f2c961b79b27dcc9188 | 935375572/python_study | /1基础/13成员运算符in_notin.py | 146 | 3.65625 | 4 | # in 判断数据是否在序列之中
# not in 判断数据是否不再序列中
numbers = ["A", "B", "C"]
if "B" in numbers:
print("对的") |
3a40e487e84bdd009f31a2606a1261bf8d81ebaf | 935375572/python_study | /1基础/4在字符串上使用乘法.py | 563 | 3.78125 | 4 | info = "msg" * 5 # 重复5遍
print(info)
"""使用与逻辑运算符 and"""
name = "张三"
age = 13
result = name == "张三" and age == 13
print(result)
"""使用或逻辑运算符 or"""
name = "张三"
age = 13
result = name == "张三" or age == 13
print(result)
"""使用非逻辑运算符 and"""
name = "张三"
age = 13
result = not age == 13
print(result)
"""身份运算符:通过一个id()函数以获取数... |
883c2914bec7eb100a9d1eb5be239b04793af6d9 | 935375572/python_study | /1基础/3定义布尔型变量.py | 610 | 3.828125 | 4 | flag = True
print(type(flag)) # 获取变量的类型
if flag:
print("你好啊老哥") # 条件满足时执行
"""字符串的连接操作"""
info = "hello"
info = info + "world"
info += "python"
info = "优拓软件学院\"www.yootk.com\"\n\t极限IT程序员:\'www.jixianit.com\'"
print(info)
"""input()函数 获取键盘输入的数据"""
msg = input("请输入你的内容:")
wc = int(msg) # 将字符串转为int类型
if wc > 12:
... |
13398c4ff7dad957ac14f32791f942f9c9ed4b58 | AlSakharoB/easy_list_v1 | /ft_even_index_list.py | 265 | 3.640625 | 4 | def ft_len_mass(mass):
count = 0
for i in mass:
count += 1
return count
def ft_even_index_list(mass):
mass1 = []
for i in range(ft_len_mass(mass)):
if i % 2 == 0:
mass1.append(mass[i])
return mass1
|
13e0b3ecf515c7e7f35e947e6ae523eb40320e5e | sraghus/Python_examples | /triangle.py | 440 | 3.625 | 4 | #!usr/bin/env python
#import modules used here - sys is a very standard one
import sys
def area(base, height):
return (base * height) / 2
if __name__ == '__main__':
print('Area :', area(12,23))
def perimeter(side1, side2, side3):
return (side1 + side2 + side3)
if __name__ == '__main__':
print ('Perimet... |
979fb7ce2ecbf9672d9674f8da264b6e3d870e50 | chelseasenter/custom-dice-roller | /dice.py | 6,846 | 3.515625 | 4 | import random
run='y'
while run == 'y':
## introduction for user --------------------------------------------------------------------------------------------
# print(".")
# print(".")
# print(".")
# print(".")
# print(".")
# print(".")
# print(".--------------------------------------------... |
854bb5826a378627b9041b230607e51da2905cd8 | tberhanu/green_book | /ch2_LinkedLists/check_llist_palindrome.py | 772 | 3.984375 | 4 | # from LinkedList import LinkedList
def check_llist_palindrome(llist):
curr = llist
runner = llist
stack = [] #In python we use 'lists' as 'stacks'
while runner and runner.next:
stack.append(curr.data)
curr = curr.next
runner = runner.next.next
if runner:
curr = curr.next
while curr:
top = stack.pop()
... |
b1858530c96c0ff053d78237695ac3764ccc5362 | tberhanu/green_book | /ch1_Arrays&Strings/check_permutation3_counter.py | 690 | 3.859375 | 4 | from collections import Counter
def check_permutation3_counter(str1, str2):
if len(str1) != len(str2):
return False
cntr1 = Counter(str1) #gives a dictionary of each CHAR:FREQUENCY
cntr2 = Counter(str2)
for key1 in cntr1:
for key2 in cntr2:
if key1 == key2 and cntr1[key1] != cntr2[key2]:
return False
... |
4380cb3cb4bbdace75f27ff7059a0505e17687b7 | ToxaRyd/WebCase-Python-course- | /7.py | 1,757 | 4.3125 | 4 | """
Данный класс создан для хранения персональной (смею предположить, корпоративной) информации.
Ниже приведены doc тесты/примеры работы с классом.
>>> Employee = Person('James', 'Holt', '19.09.1989', 'surgeon', '3', '5000', 'Germany', 'Berlin', 'male')
>>> Employee.name
James Holt
>>> Employee.age
29 years ... |
eb44d31501175cf09d4eac5bfc3ab2e8784168f9 | jasonfhill/cronwatch | /app/utils.py | 1,391 | 3.953125 | 4 | import os
import re
import sys
_filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode
else:
text_type = str
def secure_filename(filename):
r"""Pass it a filename and it will return a secure version of it. This
filename can then safely be... |
d5532a8bf440890fd844ee1f0cdd02f06ea4dc55 | ckfChao/My-First-git-Repository | /main.py | 451 | 3.953125 | 4 | from op import op
#input
a = int(input("Enter value of a:"))
input_op = input("Enter operater:")
b = int(input("Enter value of b:"))
calc = op(a, b)
if (input_op == "+"):
print("%d + %d = %d"%(a, b, calc.add()))
elif (input_op == "-"):
print("%d - %d = %d"%(a, b, calc.sub()))
elif (input_op == "*"):
prin... |
9efdeb16d054511cf515531db3eb805fc690f4a5 | logchi/scrach_zone | /python/data_structure_algorithms/breath_first_serach.py | 1,055 | 3.78125 | 4 | from collections import deque
def search_queue(graph, dq, right, searched=[]):
def addnextlevel(dq, node):
next_level = graph.get(node)
if next_level:
dq += next_level
if dq:
node = dq.popleft()
if node in searched:
return search_queue(graph, dq, right,... |
0147ba4f123a05170e4ed99fea9f2741974301e4 | akashzcoder/coding_discipline | /CoderPro/day3/solution.py | 413 | 3.53125 | 4 | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return self._permute_helper(nums, [])
def _permute_helper(self, nums: list, values: list = []) -> list:
if len(nums) == 0:
return [values]
result = []
for i in range(len(nums)):
result... |
4fe543b01436500dd6ca7b3d2ff27746fc2508a5 | Wibbo/voting | /main.py | 240 | 3.515625 | 4 | from election import election
choices = ['Salad', 'Burger', 'Pizza', 'Curry', 'Pasta', 'BLT']
campaign = election(300, choices)
print('NEW ELECTION')
print(f'Number of voters is {campaign.voter_count}')
print(campaign.vote_counts)
|
9ae6c4d2f37119e7f90db29b3db050b40d5dff8b | nnicexplsz/python | /Work/test4.py | 606 | 3.578125 | 4 | a = input('enter number 1 \n')
b = input('enter number 2 \n')
c = input('enter number 3 \n')
d = input('enter number 4 \n')
c = input('enter number 5 \n')
a1 = float(a)
a2 = complex(a)
a3 = float(b)
a4 = complex(b)
a5 = float(c)
a6 = complex(c)
a7 = float(d)
a8 = complex(d)
a9 = float(c)
a10 = complex(c)
print('float o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.