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 |
|---|---|---|---|---|---|---|
c3688360514d51a23b43f08bd714ed0fcc9b43f9 | phlalx/algorithms | /misc/arith.py | 1,006 | 3.59375 | 4 | # ARITHMETIC
# O(log(n))
def is_prime(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def primes(n):
assert n >= 1
res = []
f = 2
while n > 1:
while n % f == 0:
res.append(f)
n //= f
f += 1
r... |
da9a62fa9afff75e121e3f41972b56ac03a1787c | phlalx/algorithms | /leetcode/654.maximum-binary-tree.python3.py | 494 | 3.515625 | 4 | # TAGS tree
# Better solutions https://en.wikipedia.org/wiki/Cartesian_tree
def build(nums, i, j):
if i == j:
return None
m, k = max(((nums[k], k) for k in range(i, j)))
t = TreeNode(m)
t.left = build(nums, i, k)
t.right = build(nums, k + 1, j)
return t
class Solution:
def constr... |
84129536931df7d2fe13be4b0b3c3d835acaac84 | phlalx/algorithms | /leetcode/517.super-washing-machines.py | 2,658 | 3.828125 | 4 | #
# @lc app=leetcode id=517 lang=python3
#
# [517] Super Washing Machines
#
# https://leetcode.com/problems/super-washing-machines/description/
#
# algorithms
# Hard (37.02%)
# Likes: 236
# Dislikes: 123
# Total Accepted: 14K
# Total Submissions: 37.4K
# Testcase Example: '[1,0,5]'
#
# You have n super washing m... |
3040a6b355ca4ac3a5a1e2c7c4c5cba7a70c4c58 | phlalx/algorithms | /leetcode/326.power-of-three.python3.py | 706 | 4.15625 | 4 | # TAGS trick
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return (
n > 0 and 3 ** 20 % n == 0
) # we suppose we know the biggest possible power
# def ispowerof3(n)
# if n < 1:
# return F... |
094c103be303b4c7b443994a45b3d47101b97178 | phlalx/algorithms | /misc/itertools.py | 780 | 3.546875 | 4 | # ITERTOOLS
from itertools import permutations, count, combinations
l = 'foobar'
for i, p in zip(count(1), permutations(l)): # all permutations
print( i, "".join(p) )
for i, p in zip(count(1), permutations(l, 2)): # permutations of all 2-elts subsets (A(n, p))
print( i, "".join(p) )
for i, p in zip(count(... |
3e091546a63f51b0a69bf9236739b0cdebfa8cdb | phlalx/algorithms | /leetcode/1042.flower-planting-with-no-adjacent.py | 1,997 | 3.875 | 4 | #
# @lc app=leetcode id=1042 lang=python3
#
# [1042] Flower Planting With No Adjacent
#
# https://leetcode.com/problems/flower-planting-with-no-adjacent/description/
#
# algorithms
# Easy (47.79%)
# Likes: 171
# Dislikes: 202
# Total Accepted: 15.2K
# Total Submissions: 31.7K
# Testcase Example: '3\n[[1,2],[2,3]... |
ca770131f4604f4355ac9e429073c69ef300cc5c | phlalx/algorithms | /leetcode/523.continuous-subarray-sum.py | 1,697 | 3.671875 | 4 | #
# @lc app=leetcode id=523 lang=python3
#
# [523] Continuous Subarray Sum
#
# https://leetcode.com/problems/continuous-subarray-sum/description/
#
# algorithms
# Medium (24.24%)
# Likes: 1107
# Dislikes: 1559
# Total Accepted: 110K
# Total Submissions: 449.6K
# Testcase Example: '[23,2,4,6,7]\n6'
#
# Given a li... |
62f2a981706a4e51a5f646eac5dc1c91aba910dd | phlalx/algorithms | /leetcode/382.linked-list-random-node.python3.py | 1,139 | 3.734375 | 4 | # TAGS list datatype
# Trick:
# for each elements, we pick up with odd 1 / i where i is the rank of the
# element.
#
# suppose n element (1 to n)
# P(X = n) = 1 / n (that's good)
# P(X = n - 1) = (1 / (n - 1)) * (1 - 1 / n) = 1 / n
#
# Definition for singly-linked list.
# class ListNode:
# def ... |
9d4e0493bf02795d20c3a463d87b85a2d1503ef9 | phlalx/algorithms | /leetcode/208.implement-trie-prefix-tree.python3.py | 1,409 | 3.75 | 4 | # TAGS datatype
""" Implementation of a trie """
from collections import defaultdict
class Trie:
def __init__(self, is_word=False, children=None):
self.is_word = is_word
if children:
self.children = children
else:
self.children = defaultdict(Trie)
def insert_tr... |
7bc4135c774a7453175d4597ede10c70519fa243 | phlalx/algorithms | /leetcode/541.reverse-string-ii.python3.py | 1,039 | 3.625 | 4 | # TAGS reverse, bounds
# reverse l[i:j] in place
# pythonic but not constant space as we need to allocate new lists
# Nonetheless, faster than the constant space solution `rev_aux`
# remark: l[i:j][::-1] != l[j:i:-1]
def rev_aux_pythonic(l, i, j):
l[i:j] = l[i:j][::-1]
# reverse l[i:j] O(1)
def rev_aux(l, i, j)... |
c42703e5d6af05bbf39a6a819004e8da37b6a511 | phlalx/algorithms | /leetcode/862.shortest-subarray-with-sum-at-least-k.py | 2,437 | 3.515625 | 4 | #
# @lc app=leetcode id=862 lang=python3
#
# [862] Shortest Subarray with Sum at Least K
#
# https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/
#
# algorithms
# Hard (22.65%)
# Likes: 761
# Dislikes: 22
# Total Accepted: 21.8K
# Total Submissions: 93.9K
# Testcase Example: '[1]\n1'
... |
3ca63f1605375e1aa0080bf8f1c6008da9088597 | phlalx/algorithms | /leetcode/422.valid-word-square.python3.py | 771 | 3.5 | 4 | # TAGS matrix
# A little tricky to get it right...
class Solution:
def validWordSquare(self, words):
"""
:type words: List[str]
:rtype: bool
"""
n = len(words)
i = 0
while i < n and len(words[i]) >= i + 1: # words[i][i] is defined
k = len(words[i]... |
50d1045d654e0733fef078c937b867d653b4fa9e | phlalx/algorithms | /leetcode/79.word-search.python3.py | 924 | 3.71875 | 4 | # TAGS grid, complete search, backtrack
s = list(zip([0, 1, 0, -1], [1, 0, -1, 0]))
def succ(a, b, m, n):
return ((a + x, b + y) for (x, y) in s if 0 <= a + x < m and 0 <= b + y < n)
def walk(board, word, i, j, i_word):
c = board[i][j]
if c != word[i_word]:
return False
if i_word == len(wor... |
9f1fc265a38da6a7bf34bb2787c153589a1c2069 | phlalx/algorithms | /leetcode/421.maximum-xor-of-two-numbers-in-an-array.python3.py | 1,323 | 4.0625 | 4 | # TAGS trie, bits, trick
#
# Trick here is to use a trie
# We insert each letter in the trie based on its binary representation
# Given a non empty trie, we can compute in one pass (basically one custom
# find) the max xor between this number and all numbers in the tree.
def insert(s, trie):
# very simple to ins... |
16fbeafd907e1ee1134fbd7dcd2f37b472db6365 | phlalx/algorithms | /leetcode/253.meeting-rooms-ii.py | 1,083 | 3.59375 | 4 | #TAGS intervals
# @lc app=leetcode id=253 lang=python3
#
# [253] Meeting Rooms II
#
# https://leetcode.com/problems/meeting-rooms-ii/description/
#
# algorithms
# Medium (43.51%)
# Likes: 1636
# Dislikes: 27
# Total Accepted: 182.1K
# Total Submissions: 418.2K
# Testcase Example: '[[0,30],[5,10],[15,20]]'
#
# G... |
c8de724f22f340f7dc6f2bcbba3d8af0d28246d7 | phlalx/algorithms | /leetcode/205.isomorphic-strings.py | 1,319 | 3.765625 | 4 | #
# @lc app=leetcode id=205 lang=python3
#
# [205] Isomorphic Strings
#
# https://leetcode.com/problems/isomorphic-strings/description/
#
# algorithms
# Easy (38.08%)
# Likes: 1038
# Dislikes: 291
# Total Accepted: 253.1K
# Total Submissions: 652.3K
# Testcase Example: '"egg"\n"add"'
#
# Given two strings s and ... |
a04de5b750cbd13b0a450d3204b64bfc45ce3b97 | phlalx/algorithms | /leetcode/289.game-of-life.python3.py | 1,032 | 3.609375 | 4 | # TAGS grid
# TODO use sliding window?
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
n = len(board)
p = len(board[0])
def get(i, j):
if 0 <= ... |
75e12e9b8cc63d469f226cceb8c74a81e487727d | phlalx/algorithms | /leetcode/480.sliding-window-median.py | 5,776 | 3.953125 | 4 | #TAGS median, bst, kselect
#
# TODO implement either a priority queue with removal or an ordered set
# structure
#
# see also 295
#
# @lc app=leetcode id=480 lang=python3
#
# [480] Sliding Window Median
#
# https://leetcode.com/problems/sliding-window-median/description/
#
# algorithms
# Hard (33.62%)
# Likes: ... |
f3eb657765dde71ff48a14d23ac8cf69fb51bb5a | phlalx/algorithms | /leetcode/285.inorder-successor-in-bst.py | 1,682 | 3.6875 | 4 | # TAGS BST classic
#
# @lc app=leetcode id=285 lang=python3
#
# [285] Inorder Successor in BST
#
# https://leetcode.com/problems/inorder-successor-in-bst/description/
#
# algorithms
# Medium (36.04%)
# Likes: 790
# Dislikes: 54
# Total Accepted: 116.3K
# Total Submissions: 322K
# Testcase Example: '[2,1,3]\n1'
#... |
44753a77e148e0d8760c5ac43981d5ad28e5e696 | phlalx/algorithms | /misc/bfs.py | 1,051 | 4.03125 | 4 | # BFS
import parse
from collections import deque
def bfs(graph, source):
print('--- bfs')
N = len(graph)
# we use this list both to keep track of the distance, and of the
# visited nodes.
# We could also enqueue the distance together with the node, if we don't
# need to store them (but we need... |
983ddcda31a42a91c70a09656259bcac49ebb472 | phlalx/algorithms | /leetcode/520.detect-capital.python3.py | 1,285 | 3.578125 | 4 | # TAGS string
class Solution:
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if len(word) <= 1:
return True
it = iter(word)
a = next(it)
b = next(it)
if b.isupper():
return a.isupper() and all(x... |
b1768a098f4432e47356d9793258fc926a591151 | phlalx/algorithms | /leetcode/535.encode-and-decode-tiny-url.py | 3,992 | 3.578125 | 4 | #
# @lc app=leetcode id=535 lang=python3
#
# [535] Encode and Decode TinyURL
#
# https://leetcode.com/problems/encode-and-decode-tinyurl/description/
#
# algorithms
# Medium (77.55%)
# Likes: 569
# Dislikes: 1250
# Total Accepted: 94.2K
# Total Submissions: 119.9K
# Testcase Example: '"https://leetcode.com/probl... |
61ee192500eea0a5be11e12e3eec00026690909c | phlalx/algorithms | /leetcode/310.minimum-height-trees.python3.py | 2,286 | 4.03125 | 4 | # TAGS tree, graph, diameter, khan
#
# Solution 1
#
# Idea:
# 1. find longest path.
# a. find longest path from arbitrary point.
# leaf of path is on a longest path (why?)
# b. find longest path from leaf of previous path
# c. compute previous path
# 2. return middle element(s)
#
# don't forget corner ca... |
32717f2223005c6cf52c536ed196a734bdec4f02 | phlalx/algorithms | /leetcode/69.sqrtx.python3.py | 359 | 3.515625 | 4 | # TAGS binary search
class Square:
def __getitem__(self, i):
return i * i
import bisect
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
res = bisect.bisect_left(Square(), x, 0, x + 1)
if res * res == x:
return res
... |
44af1b75baa8fe146c0dbbe3c4e4ac7e2189af4d | phlalx/algorithms | /leetcode/29.py | 1,163 | 3.5 | 4 | #TAGS binary search, euclidean division
# TODO not the right implementation
# interesting fact about division/modulo
# http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html
# https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/
# pythonic a = q.b + r with 0 <= r < b if b > 0 ... |
5290ed7f2079dd0b62e2e03fc2cb7fac4e9ed8f2 | phlalx/algorithms | /leetcode/718.maximum-length-of-repeated-subarray.py | 1,396 | 3.546875 | 4 | #
# @lc app=leetcode id=718 lang=python3
#
# [718] Maximum Length of Repeated Subarray
#
# https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/
#
# algorithms
# Medium (47.19%)
# Likes: 946
# Dislikes: 40
# Total Accepted: 50.4K
# Total Submissions: 103.8K
# Testcase Example: '[1,2,3,2,... |
f15f51319d6ab9fbe33802ca3b560f90b9f33deb | phlalx/algorithms | /misc/unionfind2.py | 760 | 3.921875 | 4 | #
# Union-find
#
# Interface:
# create : int -> t represents set [0, n)
# find : t -> int -> int returns a representent of the equivalence class
# union : t -> int * int -> unit merges two equivalence classes
#
# count : t -> int returns the number of equivalence classes
#
# Simplest implementation based on forest... |
e6b3d8047a7216f34ac7e6840329a0650f82b49b | phlalx/algorithms | /leetcode/143.py | 1,545 | 4.0625 | 4 | #TAGS linked list
# harder than other linked lists problem
#
# Trick:
# 1. For these linked list exercises, always wonder if we add at the end of
# an existing list, or at the top
# 2. if complex, try to divide into smaller problems
# 3. for this problem where lists are split into two parts, always think
# about ... |
1c1a47306dfb9c3fe705e487b5c351a01a81e848 | phlalx/algorithms | /leetcode/54.spiral-matrix.python3.py | 791 | 3.9375 | 4 | # TAGS matrix, tricky
# TODO iterative
def spiral(matrix, i, j, m, n, res):
if m <= 0 or n <= 0:
return
for jj in range(j, j + n):
res.append(matrix[i][jj])
for ii in range(i + 1, i + m - 1):
res.append(matrix[ii][j + n - 1])
if m >= 2:
for jj in reversed(range(j, j + n... |
2ebfb73bdf538ebdfec88dfc952572ce4ff9fe5a | phlalx/algorithms | /leetcode/33.search-in-rotated-sorted-array.python3.py | 832 | 3.671875 | 4 | # TAGS binary search
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
n = len(nums)
i = 0
j = n - 1
while i < j:
middle = (i + j... |
f23c1a224a341150b68f4ec0f80d20ab8e6c8032 | phlalx/algorithms | /leetcode/997.find-the-town-judge.py | 1,857 | 3.828125 | 4 | #
# @lc app=leetcode id=997 lang=python3
#
# [997] Find the Town Judge
#
# https://leetcode.com/problems/find-the-town-judge/description/
#
# algorithms
# Easy (49.50%)
# Likes: 327
# Dislikes: 44
# Total Accepted: 39.3K
# Total Submissions: 79.4K
# Testcase Example: '2\n[[1,2]]'
#
# In a town, there are N peopl... |
2135a8354974f4a198e026961f185625bf6d59d4 | phlalx/algorithms | /leetcode/825.py | 1,297 | 3.5625 | 4 | #TAGS counting sort, buckle sort, cool
#
# Trick: count persons of a given age
# because range of age is [1,120]
#
# Instead of doing
# for each person, count which other persons match the constraint,
#
# we compute for each person the candidate ages, and count how many person
# have that age
# We could do even simpl... |
0a6b1c11f5bce2881865591c415715f9c19d52de | phlalx/algorithms | /misc/segtree.py | 2,007 | 3.796875 | 4 | # segment tree
# TODO redo using array to store tree, and dynamic update
def build_seg(nums, i, j):
if i == j:
return Node( (nums[i], i) )
else:
t1 = build_seg(nums, i, (i+j) // 2)
t2 = build_seg(nums, (i+j) // 2 + 1, j)
return Node(max(t1.val, t2.val), t1, t2)
# compute max f... |
eab96c529f9e70bb8947f994cc16013633d2a84f | phlalx/algorithms | /leetcode/449.py | 976 | 3.59375 | 4 | #TAGS bst
# Trick we can re-build a bst from its preorder traversal
def insert(node, i):
if node is None:
return TreeNode(i)
elif i <= node.val:
return TreeNode(node.val, insert(node.left, i), node.right)
else:
return TreeNode(node.val, node.left, insert(node.right, i))
class Codec... |
1baeaabf01c46b562173a1e722c53641461e41ea | phlalx/algorithms | /leetcode/56.merge-intervals.python3.py | 417 | 3.515625 | 4 | # TAGS intervals, greedy
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort()
res = []
for inter in intervals:
if res and res[-1][1] >= inter[0]:
res[-1][1] = ... |
658fff55c945b2adb755ff7f596e7644bf057a85 | phlalx/algorithms | /leetcode/673.number-of-longest-increasing-subsequence.python3.py | 1,365 | 3.828125 | 4 | # TAGS dfs
# read the question well: it's the number of longest increasing subsequence
# not the the longest of increasing subsequence
# memoize two info: longest sequence, number of such sequence
class Solution:
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
... |
56a31551283736bb0ed71fc1f62c484172925bcc | phlalx/algorithms | /leetcode/877.stone-game.py | 3,199 | 3.734375 | 4 | #
# @lc app=leetcode id=877 lang=python3
#
# [877] Stone Game
#
# https://leetcode.com/problems/stone-game/description/
#
# algorithms
# Medium (64.08%)
# Likes: 610
# Dislikes: 932
# Total Accepted: 52.7K
# Total Submissions: 82.2K
# Testcase Example: '[5,3,4,5]'
#
# Alex and Lee play a game with piles of stone... |
3d2fb685d8ccedd148e643e5d3633775f67cbf76 | KonstantinKirchev/Python-Coursework | /hacker_rank_challenges/if_else.py | 270 | 4 | 4 | n = int(input().strip())
if 1 <= n <= 100:
if n % 2 != 0:
print("Weird")
else:
if 2 <= n <= 5:
print("Not Weird")
elif 6 <= n <= 20:
print("Weird")
elif n > 20:
print("Not Weird")
else:
print("Invalid input! The number has to be between 1 and 100")
|
a05b6b0bca79f10e389474d64365086a7df0e082 | alexeykomov/hacker-rank | /plus-minus/task.py | 764 | 4.03125 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plus_minus(arr):
fractions = reduce(make_fractioner(len(arr)), arr, {
'pos': 0,
'neg': 0,
'zero': 0
})
print fractions['pos']
print fractions['neg']
print fra... |
aaa22bd94d9eae70842f52932b372514a6959d6b | anupama2519/Probability-Problem | /Probability_problem.py | 1,639 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 20:27:54 2021
@author: Anupama
"""
# Problem Statement:
#There is bag that contains 3 colours of ball (Red, Green & Blue).
#Numbers of ball count of each colours are A, B, and C respectively
#We will 3 picks and in each pick we will take 2 balls out and we won... |
1049c9725e79172ea0a7f75ad9961decb8bc5fe6 | tdawg111/python-scripts | /3pandasreadfromcsv.py | 953 | 3.5 | 4 | import pandas as pd
df = pd.read_csv('WGEM-ZAF_CPTOTSAXNZGY.csv') # create dataframe from csv
print(df.head())
#df.set_index('Date', inplace = True)
# write out dataframe to csv
#df.to_csv('newcsv2.csv')
# write out one column of the dataframe to csv
#df['Value'].to_csv('newcsv2.csv')
# create dataframe from csv an... |
f542871f6252f891483d8b1dbb32061a182eec8e | hayoungishere/Algorithm | /Python/sumTwoNum.py | 529 | 3.75 | 4 | '''
정수 배열 numbers가 주어지면 서로 다른 인덱스에 있는 두 수를 뽑아 더해서 만들수 있는 모든 수를
배열에 오름차순으로 담아 반환하라.
접근 : set 자료형을 사용해서 unique를 유지하자
'''
def solution(numbers):
answer = []
s = set()
for i in range(len(numbers)-1):
for j in range(i+1, len(numbers)):
s.add(numbers[i]+numbers[j])
for item... |
0fa268c99cba2bf247f74d408a9c32fea7b95c18 | hayoungishere/Algorithm | /Python/eraseCharacter.py | 401 | 3.9375 | 4 |
def eraseChar(ori) :
res = []
if "#" not in ori:
return ori
for c in ori:
#print(res)
if c == "#":
if len(res) > 0:
res.pop()
else:
res.append(c)
return ''.join(res)
in1 = input()
in2 = input()
in1 = eraseChar... |
c3050341b766f637b39ba112c5967a9b43d74dfe | MortalKommit/Coffee-Machine | /coffee_machine.py | 2,630 | 4.1875 | 4 |
class CoffeeMachine:
def __init__(self, capacity, menu):
self.capacity = {}
contents = ("water", "milk", "coffee beans", "disposable cups", "money")
for content, cap in zip(contents, capacity):
self.capacity[content] = cap
self.menu = menu
def get_user_input(self):
... |
1702acae637148eee91612d432b6e8fa4d594205 | toddljones/advent_of_code | /2019/1/a.py | 1,013 | 4.4375 | 4 | """
Fuel required to launch a given module is based on its mass. Specifically, to
find the fuel required for a module, take its mass, divide by three, round
down, and subtract 2.
For example:
- For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get
2.
- For a mass of 14, dividing by 3 and rou... |
793d6b249b477087e98d677f2da2bc679c515483 | VictoryWekwa/Random_Questions | /damy_program/damy_program/question.py | 18,136 | 3.9375 | 4 | import json
import html
import requests
import random
"""
This is a module that contains 9 functions, that produces questions when called. Each function has the same underlying
principle, the only difference is in the number questions and difficulty of each function. The API is called into each
function. The API is ... |
c8ae45a9f5a0f99251959c266c0e43c827fd9db2 | ACDoyle/python2 | /robot.py | 673 | 3.84375 | 4 | #!/usr/bin/env python
class Robot(object):
def __init__(self, name, build_year, lk = 0.5, lp = 0.5):
self.name = name
self.build_year = build_year
self.__potentianl_physical = lk
self.__potential_psychic = lp
@property
def condition(self):
s = self.__potentianl_physical + self.__potential_psy... |
478a33c42d027d8da75656ddc25046ae90b9c597 | CertifiedErickBaps/Python36 | /Practica de aritmetica/video.py | 610 | 3.875 | 4 | # Authors:
# A01379896 Erick Bautista Pérez
# A01378568 Leonardo Valencia Benitez
# August 31, 2016.
#Description: Five Star Video rents new videos for $3.00 a night, and oldies for $2.00 a night.
#Write a program called video.py that the clerks at Five Star Video can use to calculate
#the total cha... |
24dd82f86a9961e118b464190244d7940e780cef | CertifiedErickBaps/Python36 | /Condiconal If/condicionales.py | 81 | 3.8125 | 4 | x = 5
if x * 3 > 10:
print("x es grande")
else:
print("x es chico")
|
12cd29f06a3438996e74f627d0fffacbbb3e4b1a | CertifiedErickBaps/Python36 | /Ciclos While/Practica 5/invert.py | 754 | 4.1875 | 4 | # Authors:
# A01379896 Erick Bautista Pérez
#
#Write a program called invert.py. Define in this program a function called invert(n)
#that returns an integer comprised of the same digits contained in n but in reversed order.
#For example, invert(2015) should return the number 5102. Do not use any string oper... |
694ac91eec52f84fdac4581f1cd3be42554925d4 | CertifiedErickBaps/Python36 | /Listas/Practica 7/positives.py | 1,028 | 4.125 | 4 | # Authors:
# A013979896 Erick Bautista Perez
#
#Write a program called positives.py. Define in this program a function called
#positives(x) that takes a list of numbers x as its argument, and returns a new
#list that only contains the positive numbers of x.
#
# October 28, 2016.
def positives(x):
a = ... |
c3cd971baa4a8123c5f729fc57820ae49f3abcd7 | CertifiedErickBaps/Python36 | /Practica de aritmetica/cilindro.py | 436 | 3.5625 | 4 | # area de un cilindro
from math import pi
def area_circulo(radio):# Tiene un parametro
#area= pi*radio**2 los dos son casi lo mismo o parecido
return pi*radio**2 #escriba la expresion para regresar a una funcion
def volumen_cilindro(radio, altura):
return area_circulo(radio)*altura
#-------------------... |
d85924ad06d5d8e4b843a0a78d89beb4c2d89975 | CertifiedErickBaps/Python36 | /TORTUGA/circle.py | 124 | 3.921875 | 4 | # Area de un circulo
from math import pi
r = 2
area = pi * r ** 2
print('The area of a circle with radius', r, 'is', area)
|
df7911328fd4b62321d98a88f8399978c053c5d0 | CertifiedErickBaps/Python36 | /Manipulacion de textos/Practica 6/username.py | 2,277 | 4.3125 | 4 | # Authors:
# A01379896 Erick Bautista Pérez
#Write a program called username.py. Define in this program a function called username(first, middle, last)
#that takes the first name, middle name, and last name of a person and generates her user name given the above
#rules. You may assume that every first name... |
5af607504652e3240c32ecfb8a764987e5e58786 | Exclusive1410/practise3 | /pr3-4.py | 231 | 4.34375 | 4 | #Write Python program to find and print factorial of a number
import math
def fact(n):
return (math.factorial(n))
num = int(input('Enter the number:'))
factorial = fact(num)
print('Factorial of', num, 'is', factorial) |
f14a298f9b623616b2e81fe80aa2d1860e707bf4 | StephenJonker/python-sample-code | /sort-list/sort-list-of-integer-list-pairs.py | 1,780 | 4.25 | 4 | # uses python3
#
# Written by: Stephen Jonker
# Written on: Tuesday 19 Sept 2017
# Copyright (c) 2017 Stephen Jonker - www.stephenjonker.com
#
# Purpose:
# - basic python program to show sorting a list of number pairs
#
# - Given a list of integer number pairs that will come from STDIN
# - first read in n, the number o... |
aef9193f4019edf38a90edec7e4e5c38d1e0ce3f | little-riffle/python-programming-exercises | /repeating-numbers/repeating_numbers.py | 495 | 3.640625 | 4 | def find_repeating_numbers(n, input):
repeating_numbers, hashmap = [], dict()
for number in input.split(" "):
number = int(number)
hashmap[number] = 1 if number not in hashmap.keys() else hashmap[number] + 1
if hashmap[number] > 1 and number not in repeating_numbers:
repea... |
cf5a25d897a55ed3ffe9cf4b70c7a3f352b16c56 | sylviocesart/Curso_em_Video | /Desafios/Desafio10.py | 1,205 | 4.15625 | 4 | """
Crie um programa que leia quanto dinheiro
uma pessoa tem na carteira e mostre quantos
Dólares ela pode comprar
Considere US$ 1,00 = R$ 3,27
"""
dolar = 3.27
print('\nAtualmente o valor do dólar é: {}\n'.format(dolar))
valor = float(input('Quanto de dinheiro você tem na carteira? '))
qnt_dolar = valor // 3.27
qnt_c... |
1b375309de4cc80c8e6908c0b02cf90b20912d5a | mauricioguim/Curso | /ex006.py | 172 | 4.125 | 4 | n = int(input('Digite um número: '))
print('O número digitado foi {} e o seu dobro é {}, o seu triplo é {} e sua raiz quadrada é {}'.format(n, n*2, n*3, pow(n, 1/2))) |
2a3066a9ae5e4b726fe86008fc7f5a83acfc7a9e | salsafadhilah/UAS-salsa1- | /tugas3.py | 181 | 3.8125 | 4 | def sc():
print("modul nilai random")
import random
n = input('jumlah n?')
for i in range(n):
while 1:
a = random.random()
if a < 0.5:
print(a)
|
6d93f12ee35d4494416310c08860b115d5b9fb05 | egemensert/AoI | /env.py | 699 | 3.859375 | 4 | class Environment:
def __init__(self):
pass
def reset(self):
"""This method should reset the environment and return the current
state (list of float(s))"""
return state
def step(self, action):
""" Main function of the environment. The method
simulates the en... |
29d3c15ad8e6c09dfbefe199dada2c43b7881501 | grihanemo/php | /zad4.py | 319 | 3.671875 | 4 | print("Введите слово или фразу")
x = str(input())
y1 = len(x) - 1
y2 = 0
for i in range (0,len(x)-1):
if x[y1] == x[y2]:
y1 = y1 - 1
y2 = y2 + 1
else:
print("не является палиндромом")
quit()
print("это палиндром")
|
e6b38846ceed488f1334a77279b1220c31a4d21d | jeansabety/learning_python | /frame.py | 608 | 4.25 | 4 | #!/usr/bin/env python3
# Write a program that prints out the position, frame, and letter of the DNA
# Try coding this with a single loop
# Try coding this with nested loops
dna = 'ATGGCCTTT'
for i in range(len(dna)) :
print(i, i%3 , dna[i]) #i%3 -> divide i (which is a number!) by i, and print the remainder
for ... |
632a36b7c686db27cfee436935eecfc9ba74be30 | jeansabety/learning_python | /xcoverage.py | 1,902 | 4.15625 | 4 | #!/usr/bin/env python3
# Write a program that simulates random read coverage over a chromosome
# Report min, max, and average coverage
# Make variables for genome size, read number, read length
# Input values from the command line
# Note that you will not sample the ends of a chromosome very well
# So don't count the ... |
d1673b7fb62aff8e24672e6788c293a85c9668aa | sokratisathancsd/programmingLanguageDesign-csdauth | /calc.py | 2,391 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jub 6 13:44:08 2020
@author: Sokratis Athanasiadis
"""
import ply.lex as lex
import ply.yacc as yacc
import sys
#tokens
tokens = [
'INT',
'FLOAT',
'NAME',
'PLUS',
'MINUS',
'DIVIDE',
'MUL',
'EQUALS'
'RBRAC'
'LBRAC'
]
t_PLUS ... |
105a283f43df55a685f063d7f9b5c85790ddc22e | bensenberner/ctci | /printAllPossibleSentences.py | 338 | 3.5 | 4 | def allSentences(allWords, currString, index):
if index == len(allWords):
print(currString)
return
for word in allWords[index]:
newString = currString + word + ' '
allSentences(allWords, newString, index + 1)
w = [['you', 'we'], ['have', 'are'], ['sleep', 'eat', 'drink']]
allSe... |
e12a20a149a71a98b8a204c8a8c7241c6c5c7b52 | bensenberner/ctci | /python_datastructs/DoublyLinkedList.py | 2,370 | 4.03125 | 4 | class Node():
def __init__(self, val):
self.val = val
self.nextNode = None
self.prevNode = None
class LinkedList():
def __init__(self):
self.head = None
self.tail = None
def insertFront(self, node):
if not self.tail:
self.tail = node
if... |
d8d7f31a6afb6c9e0a5ac222ac5fb8b05bd6cba0 | bensenberner/ctci | /strings_arrays/longestIncreasingSubsequence.py | 724 | 3.6875 | 4 | def lis(arr):
n = len(arr)
dp = [1]*n
maximum = 0
for i in range(1, n):
for j in range(0, i):
# first part sees if the current index is greater than the j
# index, i.e. that the sequence is increasing up until i.
# the second part sees if the LIS up until j... |
74b3099c0e855613d580861e2449259de4df6e3d | bensenberner/ctci | /python_datastructs/SinglyLinkedList.py | 906 | 3.59375 | 4 | from time import time
class Node():
def __init__(self, val):
self.val = val
self.nextNode = None
class LinkedList():
def __init__(self):
self.head = None
self.hour = None
self.minute = None
self.second = None
def pushToFront(self, node):
if not self... |
16cd2bf34e64a65fdf79ebd6d466f46ced9d7e43 | bensenberner/ctci | /strings_arrays/minimumWindowSubstring.py | 2,423 | 3.96875 | 4 | from collections import Counter
'''
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the empty ... |
7cb752e2f804347c50c12fb617c16783c69144ba | bensenberner/ctci | /strings_arrays/subsetSumWith3Ints.py | 1,592 | 3.5625 | 4 | from collections import Counter
def main():
arr = [2, 2, 2, 3, 5, 7, 2, 4, 8, 2]
targetSum = 6
print(pointerSolution(arr, targetSum))
def compare(x, y):
return Counter(x) == Counter(y)
def checkIfListInList(smallList, bigList):
for l in bigList:
if compare(l, smallList):
retur... |
985cad86ce3de12ea470b2464728af9a5edb3a0d | bensenberner/ctci | /skylineProblem.py | 1,350 | 3.765625 | 4 | def getSkyline(raw_buildings):
buildings = sorted({(x, y, z) for x, y, z in raw_buildings})
res = set()
for idx, (l, r, h) in enumerate(buildings):
left_corner_above_all = True
# loop through all buildings and confirm the left corner is above all
# exit if you go past the current idx... |
2bf9621350f70e81680aaaf972e80fe3de5ac5e4 | bensenberner/ctci | /sorting_searching/sortedSearchNoSize.py | 600 | 3.953125 | 4 | '''
Sorted Search, No Size:
You are given an array-like data structure Listy which
lacks a size method.It does, however, have an elementAt(i) method that returns
the element at index i in 0(1) time. If i is beyond the bounds of the data
structure, it returns -1. (For this reason, the data structure only supports
posit... |
be163b7fc4cba2478f24a54134d177ed642d4409 | bensenberner/ctci | /test/hard/count_of_smaller_nums_after_self_315.py | 538 | 3.546875 | 4 | import unittest
from hard.count_of_smaller_nums_after_self_315 import countSmaller
class MyTestCase(unittest.TestCase):
def test_something(self):
nums = [5, 2, 6, 1]
expected = [2, 1, 1, 0]
self.assertEqual(expected, countSmaller(nums))
def test_negatives(self):
nums = [-1, -... |
eaae9e505533b44875d0a29572e0ceee5c93f1d6 | bensenberner/ctci | /hard/longest_consecutive_sequence.py | 1,295 | 3.90625 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
"""
from collections... |
56dca60febd2201eb98acc666d82c0c9c9a038b6 | bensenberner/ctci | /magicIndex2.py | 613 | 3.671875 | 4 | '''
if values are distinct
'''
def magicIndex(arr, low, high):
if low > high: return -1
mid = (low + high) // 2
leftExists = -1
rightExists = -1
if arr[mid] == mid:
return mid
elif arr[mid] < mid:
rightExists = magicIndex(arr, mid, high)
else:
leftExists = magicInd... |
bcc3efb2b006c7e532529a08739005c28761813d | bensenberner/ctci | /oneAway.py | 1,512 | 3.984375 | 4 | '''
Given the three edit operations: insertion, removal, and deletion, write a function to check
if two strings are one or zero edits away
abcde
abcXde
'''
def isOneEditAway(strtup):
str1, str2 = strtup
'''
three cases: str1 is shorter, the same length, or longer than str2
'''
shortStr, longStr = s... |
b8c06621794eb405eca4eb29211d3060c23f914b | bensenberner/ctci | /python_datastructs/LRU.py | 1,860 | 3.6875 | 4 | class Node():
def __init__(self, k, v):
self.key = k
self.val = v
class LRUCache():
def __init__(self, capacity):
self.capacity = capacity
self.mapping = {}
head = None
tail = None
def get(self, key):
if key in self.mapping:
n = self.ma... |
a73294a6fd3b68d0032a81faa7d01d8ed0747111 | bensenberner/ctci | /binode_17.2.py | 878 | 3.78125 | 4 | class BiNode:
def __init__(self, node1, node2, data):
self.node1 = node1
self.node2 = node2
self.data = data
def __repr__(self):
return str(self.data)
def treeToList(root):
if not root:
return None, None
leftHead, leftTail = treeToList(root.node1)
rightHead,... |
c21b34a5591caebafde8312f4c4082f73c16c1b5 | bensenberner/ctci | /numStairs.py | 565 | 3.953125 | 4 | # counts the number of possible ways to climb n stairs if you can go 1, 2, or 3
# stairs at a time
def countStairs(n, memo):
if n < 1:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 6
else:
if (memo[n] == None):
memo[n] = ... |
d91c2f6c9635cea1b0a8bc767ea5604d13cadd26 | bensenberner/ctci | /babyNames.py | 974 | 3.796875 | 4 | class nameCount:
def __init__(self, name):
self.count = 0
self.visited = False
self.name = name
names = {
"john": 15,
"jon": 12,
"chris": 13,
"kris": 4,
"christopher": 19
}
synonyms = [
("jon", "john"),
("john", "johnny"),
("chris", "kris"),
("chris", "... |
7efe190f957eec5b5c7a62adb1e45b520066f33f | bensenberner/ctci | /peaksAndValleys.py | 638 | 4.40625 | 4 | '''
in an array of ints, a peak is an element which is greater than or equal to the adjacent integers.
the opposite for a valley. Given an array of ints, sort it into an alternating sequence of peaks and valleys.
'''
def peakSort(arr):
for i in range(1, len(arr), 2):
# make sure indices don't go out of bou... |
094398b2ac711cf8d232d513c8f40fbf7cd9c766 | bensenberner/ctci | /minesweeper.py | 1,998 | 3.5625 | 4 | import random
def isValid(i, j, m, n):
return i >= 0 and i < m and j >= 0 and j < n
def reveal(i, j, board, visited, visible, flags, setFlag, m, n):
if not isValid(i, j, m, n) or visited[i][j]: return False
visited[i][j] = True
if setFlag:
visible[i][j] = "f"
flags.add((i, j))
... |
f8441cb584ee5b4647db0635cc11d05fef73bb58 | bensenberner/ctci | /trackFromStreamLinkedList.py | 1,113 | 3.6875 | 4 | # TODO: finish this
class Node():
def __init__(self, val, rank):
self.val = val
self.rank = rank
self.nextNode = None
def sortedLinkedList():
def __init__(self):
self.head = None
def insert_node(self, newNode):
if not self.head:
self.head = newNode
... |
2ae7717e802791945194d017d24b1833cce2c6b8 | bensenberner/ctci | /strings_arrays/allPalParts.py | 893 | 3.625 | 4 | def main():
string = "nitin"
allPalPartitions(string)
def allPalPartitions(string):
n = len(string)
allPart = [[]]
currPart = []
allPalPartUtil(allPart, currPart, 0, n, string)
for i in range(len(allPart)):
for j in range(len(allPart[i])):
print(allPart[i][j])
def isP... |
2da56bed173d0488f2bc4e7b1f62df9bb244947e | bensenberner/ctci | /sudoku.py | 3,431 | 3.84375 | 4 | from collections import namedtuple
from copy import deepcopy
MAX_BOARD_VALUE = GRID_LENGTH = 9
UNASSIGNED = 0
Position = namedtuple("Position", ["row", "col"])
class GridSolver:
def __init__(self, grid):
self.grid = deepcopy(grid)
def solve(self):
"""
Finds an unassigned position on ... |
3b9bbbbe42cd120e985ec69509811e82e4613c86 | bensenberner/ctci | /moderate/pattern_matching.py | 2,708 | 4.09375 | 4 | """
You are given two strings, pattern and value. The pattern string consists ONLY of the letters a and b, describing a pattern.
For example, catcatgocatgo matches the pattern aabab (cat is a, go is b). It also matches patterns like a, ab, and b.
Write a method to determine if value matches pattern.
-------------------... |
b27de5be5db6b7dd0b2ee7c1f13bcbad5d3bcc76 | bensenberner/ctci | /countAllWaysMakeChange.py | 253 | 3.515625 | 4 | def countWays(amount, coins):
coins = sorted(coins)
dp = [1] + [0] * amount
for coin in coins:
for i in range(coin, amount + 1):
dp[i] += dp[i - coin]
print(dp)
return dp[amount]
print(countWays(4, [1, 2, 3]))
|
ecfdb4ddff71280db5b0943ee3ef469650ab2007 | bensenberner/ctci | /test/hard/shortest_supersequence.py | 553 | 3.5625 | 4 | import unittest
from hard.shortest_supersequence import shortest_supersequence
class Test(unittest.TestCase):
def test_something(self):
short = [1, 5, 9]
long = [7, 5, 9, 0, 2, 1, 3, 5, 7, 9, 1, 1, 5, 8, 8, 9, 7]
self.assertEqual((7, 10), shortest_supersequence(short, long))
def test... |
3559ace9fe63307597bf924f37bc080da3490e00 | GabyPopolin/Estrutura_Sequencial | /Estrutura_Sequencial_exe_07.py | 278 | 4.125 | 4 | '''Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.'''
n = float(input('Digiite o valor de um dos lados do quadrado: '))
a = (n**2) * 2
print('')
print('O dobro do valor da área do quadrado é: {}' .format(a)) |
f28956d14fb2d0b41b40cda2042d43b28ac500ab | GabyPopolin/Estrutura_Sequencial | /Estrutura_Sequencial_exe_06.py | 231 | 4.125 | 4 | import math
'''Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.'''
r = float(input('Digite o raio do círculo: '))
a = (r**2) * 3.14
print('')
print('Á área do círculo é: {}' .format(a)) |
c45caa3ba300591bd77625f4c0858a3224bee4fa | Ewalk21/CS_510_computing | /midterm-Ewalk21/midterm.py | 7,894 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#import cplane_np_midterm
import sys
import cmath
#import csv
from cplane_np_midterm import ArrayComplexPlane
###
# Name: Evan A Walker
# Student ID: 001932978
# Email: walke208@mail.chapman.edu
# Co... |
c426f56cffb4a80d9214f864c32f48c6f9ad6205 | Dibmar/DAANMO_Project | /main/src_libs/cross_index_funcs.py | 6,099 | 4.28125 | 4 | def genre_corresponder (df, df_genres):
"""
---What it does---
This function creates a dataframe that relates a count of the number of male and female actors in any of the given film genres identified.
It must be said that because any given film genre has more than one film genre, the count is done mult... |
af4bb69d50c4096e7e0a3221c97c9b302590b0a0 | fcoclavero/textpreprocess | /case_cleaner.py | 1,353 | 3.515625 | 4 | __author__ = ["Francisco Clavero"]
__description__ = "Text cleaner functions that deal with casing."
__email__ = ["fcoclavero32@gmail.com"]
__status__ = "Prototype"
import re
def clean_cases(text: str) -> str:
"""Makes text all lowercase.
Arguments:
text:
The text to be converted to all ... |
0a9b4ffc48334e09e1ba122d3d522895c9c2c495 | pinkston4/project_euler_challenges | /smallest_multiple/main.py | 286 | 3.546875 | 4 | #! /usr/bin/env python3
def solution(n, check):
for num in range(n, 999999999, n):
if all((num % j == 0 for j in check)):
return num
return None
if __name__ == "__main__":
checklist = [11, 13, 14, 16, 17, 18, 19, 20]
print(solution(20, checklist))
|
01bf6d6e54cbbf560e6d321a8108f4904203c8ea | smitparmar33/cicd_python | /python_test.py | 52 | 3.796875 | 4 | list1=[1,2,3,4,5,6]
list1.reverse()
print(list1)
|
1fd0333e5dacfb2b76b63f1b71a8da239b5a7f52 | sharduln30/Machine-Learning-ForskLabs | /Code Challenge/CC36_SLR/LinearReggression1.py | 1,495 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 09 18:04:52 2018
@author: Shardul Negi
"""
# Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Foodtruck.csv')
features = dataset.iloc[:, :-1].values
labels = dataset.iloc[:, -1].values
# Splittin... |
4e9e52ab1ad428a483cea51c27d52c2e09c9adc2 | jerryhanhuan/LearnPython | /function/do_reduce.py | 1,316 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#File Name:do_reduce.py
#Created Time:2019-07-16 07:06:43
# reduce 把一个函数作用在一个序列上,这个函数必须接收 2 个 参数,reduce 把结果继续和序列的下一个元素做累计计算
# reduce(f,[x1,x2,x3,x4]) = f(f(f(x1,x2),x3),x4)
# eg 对一个序列求和,就可以使用 reduce 实现
from functools import reduce
def add(x,y):
return x + y
... |
2ee76971239226d0b15460b4cd22f20edd8ea83b | jerryhanhuan/LearnPython | /basic/do_hex.py | 447 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import codecs
def str2hex(s):
b = codecs.decode(s,'hex_codec')
return b
def hex2str(b):
s = codecs.encode(b,'hex_codec')
return s
def main():
s = input("请输入一串十六进制字符串::")
print('s is:',s)
b = str2hex(s)
print('b is:',b,'len is:',len(b... |
fb3093bba1d2f7d55fe6d2da842170dbe41a4faa | jerryhanhuan/LearnPython | /built_in_module/do_datetime.py | 1,633 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#File Name:do_datetime.py
#Created Time:2019-07-20 10:01:45
from datetime import datetime
import time
def main():
now = datetime.now()
print(now) #2019-07-20 10:15:09.476397
#构造一个 date
date = datetime(2014,7,1,12,3,34)
print(date) #2014-07-01 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.