blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
30147dabc029bca90db082f94e97e6dbced0a392 | btoll/howto-algorithm | /dynamic-programming/permutations/perm-class.py | 424 | 3.828125 | 4 | class Permutation:
def __init__(self):
self.perms = []
def permute(self, arr):
self.backtrack(arr, [])
return self.perms
def backtrack(self, arr, path):
# Base case.
if not arr:
self.perms.append(path)
for n in range(len(arr)):
self.... |
db4f257d0446276a05aca77f46a4d7b095cc4a06 | btoll/howto-algorithm | /python/puzzles/truthTables.py | 772 | 3.6875 | 4 | def bitwiseAnd(a, b):
return a & b
def bitwiseOr(a, b):
return a | b
def bitwiseXor(a, b):
return a ^ b
table = {
'&': {
'text': 'AND',
'fn': bitwiseAnd
},
'|': {
'text': 'OR',
'fn': bitwiseOr
},
'^': {
'text': 'XOR',
'fn': bitwiseXor
... |
cecadf1255c04ef20bd919aad273cb93b28954ac | btoll/howto-algorithm | /python/sort/insertion/insertion.py | 376 | 3.8125 | 4 | def move(arr, i, k):
num = arr[i]
while k > -1:
if num < arr[k]:
arr[i] = arr[k]
i -= 1
k -= 1
arr[k] = num
def insertion(arr):
k = 0
for i in range(1, len(arr), 1):
if arr[i] < arr[i - 1]:
move(arr, i, k)
k += 1
retu... |
1f16e3ed6c1eb435cd04de36dffc38354e0cfc9a | btoll/howto-algorithm | /python/algorithms/binary_search/binary_search.py | 471 | 3.5 | 4 | nums = [-99, -1, 1, 3, 4, 5, 7, 9, 188, 7777]
def binary_search(p, r, n):
if p > r:
return -1
q = (p + r) >> 1
if nums[q] == n:
return q
if nums[q] < n:
return binary_search(q + 1, r, n)
else:
return binary_search(p, q - 1, n)
def main():
# for i in range(len(... |
c07fbcef4cb7c0699bc4ed6a3cb97bf8c1ae2225 | btoll/howto-algorithm | /pascals_triangle.py | 390 | 3.734375 | 4 | # Iterative (dynamic programming b/c not adding the outside 1s every time)
def pascals_triangle(n):
triangle = []
for i in range(n):
row = [None] * (i + 1)
row[0], row[-1] = 1, 1
for j in range(1, len(row) - 1):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
... |
542160a343ac4a91aef401ccecd8ae160ad6ab34 | btoll/howto-algorithm | /array/hourglass_sum.py | 1,056 | 3.734375 | 4 | matrix = [
# [1, 1, 1, 0, 0, 0,],
# [0, 1, 0, 0, 0, 0,],
# [1, 1, 1, 0, 0, 0,],
# [0, 0, 2, 4, 4, 0,],
# [0, 0, 0, 2, 0, 0,],
# [0, 0, 1, 2, 4, 0,],
[-1, -1, 0, -9, -2, -2],
[-2, -1, -6, -8, -2, -5],
[-1, -1, -1, -2, -3, -4],
[-1, -9, -2, -4, -4, -5],
[-7, -3, -3, -2, -9, -9],
[-1, -3, -1, -2, -... |
fa5df91b7a0db298d161da4719b7d1c3bbfce142 | btoll/howto-algorithm | /cracking-the-code-interview/VII_technical-questions/technique1/duplicate_work.py | 444 | 3.953125 | 4 | # Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3
# where a, b, c and d are integers between 1 and 1000.
r = range(1, 1001)
a = 1
b = 1
c = 1
d = 1
m = {}
for c in r:
for d in r:
res = c**3 + d**3
m[res] = [c, d]
#for a in r:
# for b in r:
# res = a**3 + b**3
... |
b32e81f1ecbdf4720a7cf21932239fa48e80dc07 | btoll/howto-algorithm | /python/tree/symmetric_tree.py | 1,242 | 4.1875 | 4 | from Tree import Tree
# Approach 1.
def preorder(node, visited=[]):
if not node:
return
visited.append(node.value)
preorder(node.left, visited)
preorder(node.right, visited)
return visited
def postorder(node, visited=[]):
if not node:
return
postorder(node.left, visited... |
b3044b2a39097d0e60f721f6559cf44cda204815 | btoll/howto-algorithm | /python/tree/maximum_depth.py | 953 | 3.875 | 4 | from Tree import Tree
# Bottom up.
def maximum_depth(root):
if root is None:
return 0
return max(maximum_depth(root.left), maximum_depth(root.right)) + 1
# Top down.
ans = 0
def maximum_depth(root, depth=1):
if root is None:
return 0
if not root.left and not root.right:
retu... |
b3958de4b006440951de455db07eb8e64964137b | btoll/howto-algorithm | /python/tree/path_sum.py | 969 | 4 | 4 | from Tree import Tree
# Recursive
def path_sum(root, current_sum):
current_sum -= root.value
if not root.left and not root.right:
return current_sum == 0
if root.left or root.right:
return path_sum(root.left, current_sum) or path_sum(root.right, current_sum)
# Iterative
def path_sum(ro... |
9cae42dd5e6c56915edf546b3bc9fceff5e616da | btoll/howto-algorithm | /python/array/find_duplicate_number.py | 404 | 3.875 | 4 | #def find_duplicate_number(arr):
# for i in range(len(arr)):
# for j in range(len(arr)):
# if i != j and arr[i] == arr[j]:
# return arr[j]
def find_duplicate_number(arr):
k = 0
for num in arr:
if k & (1 << num) > 0:
return num
else:
k... |
20fbfd3547e11cf63906d388e5969b3f6ace08b5 | btoll/howto-algorithm | /python/75-leetcode-questions/two_sum_2.py | 309 | 3.765625 | 4 | def two_sum2(nums, target):
l, r = 0, len(nums) - 1
while l < r:
summed = nums[l] + nums[r]
if summed < target:
l += 1
elif summed > target:
r -= 1
else:
return [l, r]
return []
nums = [2, 7, 11, 15]
print(two_sum2(nums, 26))
|
04f55d6da3edc4777cf4bb5318c4084f2c73cf94 | prekshabutani17/Binary-Search-4 | /MedianOfTwoSortedArrays.py | 2,134 | 3.78125 | 4 | """
Time Complexity : O(logn) where n is length of smaller array of nums1 and nums2
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
"""
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(... |
3f4a6dc3328eedc16ae79700e68d9c1c4470f65e | xoancg/sapientia | /es_primo.py | 376 | 4.28125 | 4 | number = int(input('Type a number: '))
if number > 1:
isprime = True
divisor = 2
while divisor < number:
if number % divisor == 0:
isprime = False
break
divisor += 1
else:
isprime = False
if isprime:
print('{0} is a prime number! ;)'.format(number))
else:
... |
1f88e989a9467e987776ed337319dc08bfcc1e03 | xoancg/sapientia | /potencias.py | 230 | 4.28125 | 4 | number = int(input('Type a number: '))
#for power in [2, 3, 4, 5]:
# Note: 'b' parameter is not included in range(a, b)
for power in range(2, 5):
print('{0} to the power of {1} is {2}'.format(number, power, number ** power)) |
839c92d3ec545625d24cd075a33b9d0386950e17 | therealmaxkim/Playground | /SPOJ/ SMPSEQ3 - Fun with Sequences.py | 2,312 | 3.796875 | 4 | '''
SMPSEQ3 - Fun with Sequences
You are given a sorted sequence of n integers S = s1, s2, ..., sn and a sorted sequence of m integers Q = q1, q2, ..., qm. Please, print in the ascending order all such si that does not belong to Q.
Input data specification
In the first line you are given one integer 2<=n<=100, and in... |
f7ab2d11fd06cd9866bc7f371d8efb15c9030297 | therealmaxkim/Playground | /Codesignal/Arcade - Intro/common_character_count/code.py | 1,207 | 4.125 | 4 | '''
Questions
1. What types are in the strings?
2. Can a string be empty?
Observations
1. Order does not matter. Just the knowing how many of a character exists in entire string and comparing.
2. all lowercase letters - only 26 possible characters
3. Need a fast way to check how many characters are in string A in orde... |
8833e23ea48467e0babbe22ca5d18a2d97777ce2 | therealmaxkim/Playground | /Codesignal/Arcade - Intro/avoid_obstacles/code.py | 1,964 | 3.953125 | 4 | '''
Questions
1. Can there be no obstacles?
2. is the list of obstacle coordinates sorted? No
Observations
1. Only given coordinates of obstacles. All other points are open
2. You are only allowed to make jumps of the same length
3. We want to minimize the length of the jump
4. The destination that we want to go to is... |
ed66e421c4688e28a47857babb543b2b8051d45a | therealmaxkim/Playground | /SPOJ/PT07Y - Is it a tree.py | 1,010 | 3.765625 | 4 | '''
Input
The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).
Output
Print... |
f47ae0e7212bdc4a0e6c26c8f119d9c517a3b841 | therealmaxkim/Playground | /Codesignal/Arcade - Intro/shape_Area/code.py | 1,252 | 3.8125 | 4 | '''
Questions
1. can n be zero?
Observations
1.
n=0, area=0,
jump=0
n=1, area=1,
jump=4
n=2, area=5,
jump=8
n=3, area=13,
jump=12
n=4, area=25,
jump=16
n=5, area=41,
2. is there a formula to getting the area based on n?
3. the way t... |
5acb1fe102aff989a905730b2a28a9a2073f2d29 | pjoseph3/coding-challenges | /recursion/PalindromicCombos.py | 1,078 | 3.71875 | 4 | def generate_palindromic_decompositions(s):
result = []
helper(s, 0, '', result)
return result
def helper(s, count, word, result):
if count == len(s):
isPalin = True
string = ''
print(word)
for i in range(len(word)):
if word[i] == '|':
# p... |
91342a715df3e3262bee951c20da288e9acee9cd | pjoseph3/coding-challenges | /sorting/findZeroSum.py | 992 | 3.65625 | 4 | def findZeroSum(arr):
# Write your code here.
output = []
arr.sort()
for i in range(len(arr)):
if i > 0 and arr[i] == arr[i - 1]:
continue
start = i + 1
end = len(arr) - 1
target = 0 - arr[i]
while (start < end):
if arr[start] + arr[end]... |
395fe1100ec0ab977ef52b7089fe51de256e3adf | Facial-Micro-ExpressionGC/CapsAttnNet | /gen_images.py | 7,254 | 3.53125 | 4 | '''
image_generator provides a keras generator for images (X) and class+pose(y).
The images contain a single object of a given class.
default_objects defines how to compose the objects from
the graphics primatives (boxes,triangles and circles)
'''
import random
from gym.envs.classic_control.rendering import Transform... |
bc004c51a1c632d1de568490aa0b55afa38e9fa0 | Alialmanea/Data-Structures | /find the sum of the 3 nums from array.py | 761 | 3.59375 | 4 | import random
def threesum(arr, n):
result = []
arr.sort()
for i in range(len(arr)-3):
if i == 0 or arr[i] > arr[i-1]:
start = i+1
end = len(arr) - 1
while(start < end):
if arr[i] + arr[start] + arr[end] == n:
result.append([arr[i], arr[start], arr[end]])
if arr[i]... |
e070a450691df4ee244c33ffec397c5b3c5cc5b6 | Alialmanea/Data-Structures | /First Recurring.py | 199 | 3.640625 | 4 | def first_recurring(str):
counts = {}
for char in str:
if char in counts:
return char
counts[char] = 1
return None
str = 'ABCAB'
print(first_recurring(str))
|
d5edf9accb891219a9bc5c6e70e358ef7a552098 | JinhaoPlus/LiaoxuefengPython | /ch10_IO/10.4-pickling.py | 1,103 | 3.703125 | 4 | import pickle, json
d = dict(name='Bob', age=20, score=88)
print(pickle.dumps(d))
# with open('/Users/jinhaoplus/Desktop/pickling.txt', 'wb') as f:
# pickle.dump(d, f)
with open('/Users/jinhaoplus/Desktop/pickling.txt', 'rb') as f:
dump = pickle.load(f)
print(dump)
d = dict(name='Bob', age=20, score=88)
pr... |
21570ae0a13147b3503ff51e90fdce09d4a49a8a | JinhaoPlus/LiaoxuefengPython | /ch7_OOP/7.5-get-instance-info.py | 1,054 | 3.78125 | 4 | class Animal:
def run(self):
print('Animal is running...')
animal = Animal()
print(type(animal))
print(type(animal.run))
def fn():
pass
print(type(fn))
print(type(abs))
class Dog(Animal):
pass
class Husky(Dog):
pass
husky = Husky()
dog = Dog()
print(type(husky))
print(isinstance(hu... |
b103ab62974f522a9e6115c9126ebedc5259a830 | tomlionne/algo-Tom-L | /Fibo.py | 1,077 | 3.96875 | 4 | class Node :
def __init__(self, value) :
self.value = value
self.child = self.left = self.right = self.parent = None
class LinkedList :
def __init__(self) :
self.tail = None
self.head = None
class FibonacciHeap(Heap):
def __init__ (self, min) :
self.min =... |
7fdc08d21cb40622fe81c2f0b8ce9ae926e0181d | vanphuong12a2/tuenti_challenge5 | /challenge7.py | 3,064 | 3.703125 | 4 | import sys
from sets import Set
def get_friends(girl):
"""Find all friends of the girl through chains"""
fchain = Set([])
for chain in chains:
if girl in chain:
fchain |= chain.copy()
fchain.discard(girl)
return fchain
def get_friends_of_friends(girl):
"""Find all friends of friends o... |
65515de93ff4d28f9bcb3ef238edc2371216516d | madheat/ATLS1300 | /PC04/PC04_20200214_Heath.py | 4,437 | 3.5625 | 4 | #
# PC04 Interactive robot
#
# 02192020
#
# Madi Heath
#
# Dwarf fortress robot friends will move around and dominate all dwarves in their
# fortress
#
# Not really but they will move around and their eyes will change colors because anger
#
'''
PSUEDOCODE
import pygame and random
set colors and variables
create bac... |
6f4cd31ba977b43f52094e2f86753ca82d3a3eb9 | 17671367716/demo | /Python/demo/demo_15.py | 561 | 3.78125 | 4 | # creation time:2021/7/15 10:37
# theme: 元组
# 不可变序列
t1 = ('a','b','b','c')
print(t1,type(t1))
t1 = 'A','B','B','B'
print(t1,type(t1))
t2 = tuple(('hello','python','!'))
print(t2,type(t2))
# 如果只有一个元素,需要使用,和()
t3 = 'a',
print(t3,type(t3))
t3 = ('a',)
print(t3,type(t3))
t4 = tuple(('hello python !',))
print(t... |
25101185c54f5473deb92c6ed495ecbf3ffb797c | sumitAggarwal416/lengthOfString | /lab4-1.py | 774 | 3.734375 | 4 | #I, Sumit Aggarwal, student number 000793607, certify that all code submitted is
#my own work and I have not copied from any source. I also certify that I have
#not allowed anyone else to copy my work
user_input= input("Enter any string ")
string_length= len(user_input)
if string_length%2==0:
print("The input... |
9a91dbe5e25f279c5c86387e1787f630171bf01b | SinKonn/PythonBasics | /Basic Number Operations.py | 1,168 | 3.890625 | 4 | def task1():
x = 1
y = 0
while x <100 :
y = x + y
x = x + 1
print("The total is: %d" %y)
def task2():
x = 25
y = 0
while x <50 :
y = x + y
x = x + 1
print("The total is: %d" %y)
def task3():
x = 0
y = 0
while x <99 :
x = x + 1
if x % 2 == 0:
y = x + y
else:
c... |
5bb18b49d42a6130ce1e45b9afd705aef1316cbd | vasigabi86/first_project | /dictionary.py | 481 | 4 | 4 | products = {"orange": 30, "apple": 50, "bread": 10}
print(products["orange"])
products["orange"] = 29
print(products)
products["milk"] = 16
print(products)
my_products = {}
print(products)
my_products["bread"] = 88
print(my_products)
del(products["orange"])
print(products)
for (key, value) in products.items():
... |
43f12d5601d1863797409e786e4fe95c93d857ff | vasigabi86/first_project | /maxnumbers.py | 415 | 3.5625 | 4 | t = []
i = 0
while i < 5:
ti = int(input("Irj be 1 szamot"))
t.append(ti)
#szam1 = int(input("Irj be 1 szamot"))
#szam2 = int(input("Irj be 1 szamot"))
#szam3 = int(input("Irj be 1 szamot"))
#szam4 = int(input("Irj be 1 szamot"))
#szam5 = int(input("Irj be 1 szamot"))
#t = [szam1, szam2, szam3, szam4, szam5]... |
f9f2b29a3a314a3c7c40a034da3ecb07b43acf21 | Srujana6188/sdet | /python/python/Activity8.py | 262 | 4.03125 | 4 | numbers = list(input("Enter a sequence of comma separated values: ").split(","))
#print the list
print("Numbers is list is : ",numbers)
firstnum = numbers[0]
lastnum = numbers[-1]
if(firstnum == lastnum):
print("True ")
else:
print("False") |
9bc79e2ef7f4241fa44d005780177d7e96535086 | korkeatw/pythainlp | /pythainlp/summarize/__init__.py | 799 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Summarization
"""
from typing import List
from pythainlp.tokenize import sent_tokenize
from .freq import FrequencySummarizer
def summarize(
text: str, n: int, engine: str = "frequency", tokenizer: str = "newmm"
) -> List[str]:
"""
Thai text summarization
:param str text... |
d597c3cdae5eb58808525688e78d0b87e793a23b | korkeatw/pythainlp | /pythainlp/util/wordtonum.py | 2,865 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Convert number in words to a computable number value
Adapted from Korakot Chaovavanich's notebook
https://colab.research.google.com/drive/148WNIeclf0kOU6QxKd6pcfwpSs8l-VKD#scrollTo=EuVDd0nNuI8Q
"""
import re
from typing import Iterable, List
from pythainlp.tokenize import Tokenizer
_THAI... |
d5479def4ba032a2824d0491110c2afb59f95578 | satyampatidar/Intermediate-Coding-Assignment | /Solution 1.py | 671 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 22:41:17 2020
@author: Satyam Patidar
Win Cartell
"""
dictName = {}
def task():
while True:
nname1 = input("Give the nick name of your friend:")
if ("q" == nname1 or "Q" == nname1):
print("Ok Bye")
break
for key, va... |
3780f8ef0563d817a59a8c7c748c475108ba6929 | vivian2943/01 | /20 space1.py | 550 | 4.21875 | 4 | '''
使用%s %d 控制列印位置 這個是舊的方法未來可能會不支援
'''
print('姓名 座號 國文 數學 英文')
print('%5s %3d %3d' % ('林大名', 1, 80))# %4的意思是4個字元,沒有字元就會填上空白字元
print('%3s %3d %3d' %('小花',130,40))#''中的空白也會被印出來
print('%3s %3d %3d' %('小貓', 25, 46))
ch = int(input("請輸入國文成績:"))
ma = int(input("請輸入數學成績:"))
en = int(input("請輸入英文成績:"))
sum... |
584823f543d3d71c6031003ea85cb0c657a0b87f | Covee/Algorithm_Prac_Python | /algorithm_python/insertion_sort(삽입 정렬).py | 744 | 3.984375 | 4 | # 모두의 알고리즘(길벗) / 문제 09
# 문제: 삽입 정렬(insertion sort)
# 주어진 리스트 안의 자료를 작은 수부터 큰 수 순서로 배열하는 정렬 알고리즘을 만들어 보세요.
def i_sort(nums):
for i in range(1, len(nums)):
val = nums[i]
j = i-1
while j >= 0 and nums[j] > val:
nums[j+1] = nums[j]
nums[j] = val
j = j-1
print("정렬을 마쳤습니다! " + str(nums))
n_list = list(... |
a8629716f0084c5c9537e13aa6f76d75670059be | Covee/Algorithm_Prac_Python | /algorithm_python/단어의_갯수.py | 1,004 | 3.53125 | 4 | # 백준 / 1152
# 정답 비율: 22.20%
# 문제: 단어의 갯수
# 영어 대소문자와 띄어쓰기만으로 이루어진 문장이 주어진다. 이 문장에는 몇 개의 단어가 있을까? 이를 구하는 프로그램을 작성하시오.
# 문장의 길이는 100자를 넘지 않는다. 단어는 띄어쓰기 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다.
# 첫째 줄에 단어의 개수를 출력한다.
sentence = input("입력하신 문장을 이루고 있는 단어의 갯수를 알아보기 위해 문장을 입력해 주세요: ")
if len(sentence) < 0 and len(sentence) > 100:... |
07c8b0a477474c6711e8157578150e20a2383716 | Covee/Algorithm_Prac_Python | /algorithm_python/단어_뒤집기.py | 1,376 | 3.734375 | 4 | # 백준 / 9093
# 정답 비율: 45.02%
# 문제: 단어 뒤집기
# 문장이 주어졌을 때, 단어를 모두 뒤집어서 출력하는 프로그램을 작성하시오. 단, 단어의 순서는 바꿀 수 없다. 단어는 영어 알파벳으로만 이루어져 있다.
# 단어의 길이는 최대 20, 문장의 길이는 최대 100이다. 단어와 단어 사이에는 공백이 하나 있다.
import sys
def reversing(sentence, ch):
for i in range(0, len(ch)):
dh = list(ch[i])
dh.reverse()
for j in range(0, len(dh)... |
ca2ba4b3c509d3e2a33b8b8c8430d248664fce6c | oopsiamgopi/algorithm | /bubble_sort.py | 620 | 4.3125 | 4 | import sys
def bubble_sort_practice(source_list):
source_length = len(source_list)
for i in range(source_length):
for j in range(source_length-i-1):
if source_list[j] > source_list[j+1]:
source_list[j],source_list[j+1] = source_list[j+1],source_list[j]
return source_list... |
83f1f720987a9fc10c22868dd0ab17864a5eeb69 | oopsiamgopi/algorithm | /graph/greedy/prims-minimum-spanning-tree-mst.py | 3,208 | 4.3125 | 4 | # A Python program for Prim's Minimum Spanning Tree (MST) algorithm.
'''
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree
for a weighted undirected graph. This means it finds a subset of the edges
that forms a tree that includes every vertex, where the total weight of all
the edges in the t... |
527ebe88551120a7507539492bfe8ef65106c1e8 | xuanxuan03021/machine-learing- | /excercise01_LinearRegression.py | 3,288 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as op
from mpl_toolkits.mplot3d import Axes3D
#print(np.eye(5))
data=np.loadtxt("ex1data1.txt",delimiter=",")
x=data[:,0]
y=data[:,1]
plt.scatter(x,y)
plt.xlabel('Population of city in 10000s')
plt.ylabel("Profit in $10000")
plt.show()
print('R... |
5ff395bc8286b9645d1f49d6dc7a43f9a50018c5 | xuanxuan03021/machine-learing- | /ex3.py | 4,470 | 4.21875 | 4 | ## Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all
import matplotlib.pyplot as plt
import scipy.io
import numpy as np
from matplotlib import use
use('TkAgg')
import math
import scipy.optimize as op
np.set_printoptions(threshold = 1e6)#设置打印数量的阈值
# Instructions
# ------------
#
# This file contains... |
0d6cb145bb7561b4161ba434fdbb3d59e5d54a8a | myo-kun/AtCoder | /ABC/ABC077-A.py | 107 | 3.703125 | 4 | c1 = input()
c2 = input()
if (c1 == c2[::-1]) and (c2 == c1[::-1]):
print('YES')
else:
print('NO')
|
11b82eda48ac41bd5e08d2374fb2e3a64ed9abaa | jan-kelemen/project-euler | /problem_solutions/009_py_special_pythagorean_triplet/_009_py_special_pythagorean_triplet.py | 258 | 4 | 4 |
def pythagorean_triplet():
for a in range(1, 998 + 1):
for b in range(a + 1, 998):
for c in range(b + 1, 998):
if a + b + c == 1000 and a*a + b*b == c*c:
return a*b*c
print(pythagorean_triplet())
|
97c56c3e6f68d80185e11225de18ec4967c0cd39 | Sravanthi-cb/Crypto | /vigenere.py | 1,041 | 3.703125 | 4 | """
Module for Ceaser encryption.
"""
import sys
import helpers
usage = 'usage: python3 ceaser.py n'
def encrypt(text, key):
"""
Ceaser encryption.
"""
if type(text) != type(''):
raise TypeError
if type(key) != type(''):
raise TypeError
if not key.isalpha():
raise TypeEr... |
5657643d587001273db6e7e8172f5ffefe5171cc | macchino/python_algorithmetc | /sort/selection_sort.py | 458 | 3.671875 | 4 | list_a = [5, 7, 4, 5, 1, 2, 3, 2, 9, 1, 4]
# i:0=>list_aの長さ-1までループしたインデックス
for i in range(len(list_a)):
# min_idx:i以上のインデックスでlisit_aに最小値の入っているもの
min_idx = i
# j:i+1=>list_aの長さ-1
for j in range(min_idx + 1, len(list_a)):
if list_a[min_idx] > list_a[j]:
min_idx = j
list_a[i], list... |
07204102591099092dbedd673d190aa95c950cf5 | liangyf22/test | /01_函数/闭包.py | 333 | 3.84375 | 4 | # 闭包条件
# 1、函数里嵌套了函数
# 2、外层函数返回的是嵌套函数名
# 3、嵌套函数引用外层函数非全局的变量
def func1(n):
def func2():
return 2*n
return func2
res = func1(10)
print(res.__closure__) #被引用的的外部变量会被保存到__closure__属性中
print(res())
|
75d4da2637fa69ad9beb2c7849f1709587a2b688 | liangyf22/test | /01_函数/filter_fun.py | 283 | 3.5625 | 4 | # filter()参数为一个函数、一个为迭代对象。
# 遍历可迭代对象依次传入函数,将为ture数据放入的一个可迭代对象中并返回
# 做过滤作用
lis = [1,23,2,3,546,33,5,7]
def func(n):
return n>10
res =filter(func,lis)
print(list(res))
|
ce4799d60c22df3d7feefec0d92f4434e3be13ad | jgasyna/security-utils | /recursive_file_dups.py | 2,282 | 3.609375 | 4 | #
# This function identifies files (Can be different names) with identical contents within a folder
# TODO Modify to store hashes and identify duplicates in the entire file system
import hashlib, os, sys
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f... |
24253c3fa982f6d6552ba1f40ef5746c6d8b0018 | douqianqing/muqing | /第11章/listing_11-1.py | 445 | 3.671875 | 4 | # Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Printing three multiplication tables at once
for multiplier in range (5, 8): #B
for i in range (1, 11): #A #B
print i, "x", multiplier, "=", i... |
2343fdc84967389bc6b3041d151bbf2c96260246 | chrisowensdev/july_2020_python_functions | /f_to_c.py | 213 | 4.1875 | 4 | def fahrenheit_to_celsius(temp):
celsius = (temp - 32) * 5/9
return celsius
user_input = float(input("Temp to Celcius? "))
temp_conversion = fahrenheit_to_celsius(user_input)
print(int(temp_conversion))
|
b950ca99acac16029ab0fc22c522b6da649d69ea | CalderLund/ChessVariantMaker | /pieces/pawn.py | 5,553 | 3.671875 | 4 | from pieces.piece import Piece
from typing import Tuple, Union, List
from board import Board
from constants import NORTH, SOUTH, EAST, WEST
from pieces.squares import EmptySquare
class Pawn(Piece):
"""
Pawn is a Piece in chess.
"""
def __init__(self, direction: int, colour: str, team_colours: List[str... |
4c5f494b80644904c63d65ac52206e32cac4c45c | catize/Alien_Invasion | /Files/ship.py | 1,427 | 3.6875 | 4 | # creates the starship
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
# manages the ship
def __init__(self, ai_game):
# initializes ship and starting position
super().__init__()
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
... |
4bb4ad9c6aac1358b29b4bc40901c9e1beee23b1 | QinDie/wave-1 | /Roots of Quadratic .py | 334 | 3.78125 | 4 | a = int(input())
b = int(input())
c = int(input())
import math
if b * b - 4 * a * c > 0:
print("two root", (-b +(math.sqrt((b * b) - 4 * a * c))) / 2 * a, (-b -(math.sqrt((b * b) - 4 * a * c))) / 2 * a)
elif b * b - 4 * a * c == 0:
print("one root", (-b +(math.sqrt((b * b) - 4 * a * c))) / 2 * a)
else:
pr... |
4694110788988705a57c575779579a676bfeb403 | miaolin/time_series_modelling | /stats_method/fourier_transforms.py | 1,546 | 3.515625 | 4 | # coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def fourier_transformation(data, target_column):
"""
As you see in Figure 3 the more components from the Fourier transform we use the closer the approximation
function is to the real stock price (the 100 components tran... |
77dfe5b7263466dc667f47aaca7a109aefe36f62 | HIT-jixiyang/offer | /合并链表.py | 2,006 | 3.953125 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if not pHead2:
return pHead1
if not pHead1:
return pHead2
if pHead1... |
9618db604e2ea7fa8787c6f52884239fcf1231ae | HIT-jixiyang/offer | /剑指offer/56-找到链表中环的入口.py | 463 | 3.59375 | 4 | # -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#还有一种方法是使用快慢指针,快指针跑得快一定能追上慢指针
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
d={}
while pHead:
if id(pHead) in d.keys():
r... |
4af5497f9f59c3144f2dfbd2a9a4e5c188b368b5 | HIT-jixiyang/offer | /reorderArray.py | 700 | 3.953125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
left=0
right=len(array)-1
odd=[]
even=[]
for i in range(len(array)):
if array[i]%2==1:
odd.append(array[i])
if array[i]%2==0:
... |
c8ad19696ed8e954b5ca98802587a67310c5b991 | HIT-jixiyang/offer | /剑指offer/7-斐波那契.py | 232 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
a=[]
a.append(0)
a.append(1)
for i in range(2,n+1):
a.append(a[i-1]+a[i-2])
return a[n] |
8f6fabebf7a634dfdcb1f25b0b85d5a2131ab95e | HIT-jixiyang/offer | /整数除法.py | 1,517 | 3.71875 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
flag = 0
if (divisor < 0 and dividend > 0):
divisor = -divisor
flag = 1
elif (divisor > 0 and dividend < 0):
dividend = -dividend
flag = 1
elif (divisor < 0 and divi... |
42200b8ed2aa10ab52a05a3dae27f49d8f61753f | HIT-jixiyang/offer | /choujiang.py | 159 | 3.546875 | 4 | print("%.4f" % 0.1)
l=input().split(' ')
m=int(l[1])
n=int(l[0])
if n==2 and m==3:
print("%.4f" % 0.6000)
if n == 1 and m == 3:
print("%.4f" % 0.5000)
|
89529540e8ec6028fa1b00f66ed0f1f7e0488b69 | Galaton/Python | /Learning/01 - Basic.py | 3,130 | 4.0625 | 4 | # Assinalando multiplas variáveias a o mesmo valor
a = b = c = d = 10
print(a,b,c)
# Assinalando multiplos valoser a multiplas variáveis
e,f,g = 12,13,14
print(e,f,g)
# Python não usa {} para delimitar blocos de código
# ele usa a identação para fazer isto
#Exemplo de if
# O primeiro passo é pegar um int em vez de s... |
1f1aea14fb73cf02a6a0187fd6067c85b0a4ad95 | jaisekhar/Python-icp2 | /icp2_1.py | 337 | 3.96875 | 4 | inpList=[]
outList=[]
numElem=int(input("Enter the Number of Elements should be in Input List:"))
for i in range(numElem):
tempElem=float(input("Enter Number {} for Input List:".format(i+1)))
inpList.append(tempElem)
outList=[i*0.453592 for i in inpList]
print("Input list(lbs): {}\nOutput List(kgs): {}".format(... |
097afa0eeafffff310d7ed268bddb1312afa5dc0 | thejosmeister/advent-of-code-2020 | /src/day5/day5part2.py | 371 | 3.546875 | 4 | # Day 5 part 2
from day5.day5common import produce_list_of_seat_nos
# Sort the output
sorted_list = sorted(produce_list_of_seat_nos())
# Look for a difference larger than 1 for adjacent seat numbers.
for i in range(1, len(sorted_list)):
if sorted_list[i] - sorted_list[i - 1] != 1:
print(' ')
print... |
a9537dda3326c083a9e5d7f5a65fc337048936c2 | thejosmeister/advent-of-code-2020 | /src/day6/day6part2.py | 1,077 | 3.6875 | 4 | # Day 6 part 2
# Does what it says on the tin.
def number_of_q_everyone_answered_yes(answers: str) -> int:
list_of_answers = answers.split()
common = list_of_answers[0]
# If there is only one lot of answers
if len(list_of_answers) == 1:
return len(common)
for answers_for_person in list_... |
cc79d9df08f02bf2aa710735ae3c326b7593bc0f | thejosmeister/advent-of-code-2020 | /src/day20/Tile.py | 3,296 | 3.96875 | 4 | """
This class meant I had an easy way of rotating, flipping and accessing the properties of the tiles.
"""
class Tile:
def __init__(self, id: str, tile: list, sides: dict, edge_sides: list, internal_sides: list):
self.id = id
self.tile = tile
self.sides = sides
self.edge_sides ... |
3dc52b61e20b755645d8e765c18827fb11160fcb | thejosmeister/advent-of-code-2020 | /src/day10/day10part2.py | 1,477 | 3.53125 | 4 | # Day 10 part 2
chargers = [0, 158]
f = open("day10input.txt", "r")
for file_line in f:
chargers.append(int(file_line.rstrip()))
f.close()
# We want out sorted list of chargers again
sorted_chargers = sorted(chargers)
# To get the total permutations of chargers it centres around the fact that we only have gaps ... |
7fcc58f4485e75e9f7271076ebcfeb00db11e0fc | thejosmeister/advent-of-code-2020 | /src/day8/GameConsole.py | 1,263 | 3.734375 | 4 | # Probably 2020's Intcode machine
class GameConsole:
# Constructor takes the list of input commands.
def __init__(self, _input: list):
self.input = _input
self.state = 0
self.accumulator = 0
self.states_entered = [0]
# Process each instruction, will probably call out to oth... |
922b6d3a83c83b2a03345c4a2674cfd71264d772 | jeffroche/pycalc-js-poc | /calc.py | 350 | 3.921875 | 4 | import math
import numpy as np
def add_two_numbers(num1=6, num2=3):
return num1 + num2
def sine_wave(magnitude=2, period=math.pi/2):
"""Returns the x and y values of a sine wave"""
x = np.arange(0, 2 * math.pi, 2 * math.pi/100)
x = x * period
y = magnitude * np.sin(x / period)
r... |
e58be1b4b63adc2e9ce4c43d675327f1959c17f7 | tejamupparaju/LeetCode_Python | /leet_code423.py | 1,800 | 3.828125 | 4 | """
423. Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.
Note:
Input contains only lowercase English letters.
Input is guaranteed to be valid and can be transformed to its original digits. That mea... |
ccc01e39cf4fc80a1230de60993a05f2cbc0bf73 | tejamupparaju/LeetCode_Python | /leet_code485.py | 969 | 3.734375 | 4 | """
485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain ... |
d592360d10f05704d5ce2fc1107556f50da04dfc | tejamupparaju/LeetCode_Python | /leet_code526.py | 2,505 | 3.59375 | 4 | """
526. Beautiful Arrangement
Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array:
The number at the ith position is divisible by i.
i is divisible b... |
07c95ce1e117fb4e1a6fa47f310c72a3027e0b82 | tejamupparaju/LeetCode_Python | /leet_code244.py | 1,702 | 4.03125 | 4 | """
244. Shortest Word Distance II
This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and ... |
a20a1b734bce17cd4c234ed7160d55757ba58e84 | tejamupparaju/LeetCode_Python | /leet_code389.py | 1,015 | 3.578125 | 4 | """
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the lette... |
c693e63e28f4ffc5837041bd9d30332c747a647b | tejamupparaju/LeetCode_Python | /leet_code102.py | 1,736 | 3.890625 | 4 | """
102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15... |
d65cd4a2ca7fb10c66e3a7121dfe5b57ed8bddbf | tejamupparaju/LeetCode_Python | /leet_code542.py | 1,806 | 3.71875 | 4 | """
542. 01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given... |
431ec3835da0be25d20edafce922e5d40dbeced1 | tejamupparaju/LeetCode_Python | /leet_code346.py | 1,395 | 3.90625 | 4 | """
346. Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
Hide Compan... |
e66fd868a5f6b5df76a71a00944a7362725f8d8c | tejamupparaju/LeetCode_Python | /leet_code294.py | 1,264 | 3.75 | 4 | """
294. Flip Game II
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner... |
343d73d2e022171279ca95247da5bef054c4a098 | tejamupparaju/LeetCode_Python | /leet_code658.py | 2,263 | 3.8125 | 4 | """
658. Find K Closest Elements
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,... |
c8f159e31e3f225c5006055dbdc6c2ddc8be8535 | tejamupparaju/LeetCode_Python | /leet_code524.py | 2,534 | 3.90625 | 4 | """
524. Longest Word in Dictionary through Deleting
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If the... |
f85debbfbad22380ffb654048fc2bd9ba9e75041 | tejamupparaju/LeetCode_Python | /leet_code199.py | 2,067 | 4.28125 | 4 | """
199. Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should re... |
6802d5920558d7e3c10b8401c2ce4e396b4f542a | tejamupparaju/LeetCode_Python | /leet_code463.py | 1,894 | 3.859375 | 4 | """
463. Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells)... |
81b365ada21f4979a9fd1753f92e30e4a089af88 | tejamupparaju/LeetCode_Python | /leet_code781.py | 1,959 | 3.84375 | 4 | """
781. Rabbits in Forest
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them.
Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.
Examples:
Input: answers = [1, 1, 2]
... |
67e3b04f90b16c49b312d8bf87f09e4392f00474 | tejamupparaju/LeetCode_Python | /leet_code750.py | 5,354 | 4 | 4 | """
750. Number Of Corner Rectangles
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
A corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.
Example 1:
Inp... |
56f5f24c840099926f3cf61a1efa631c974314b3 | tejamupparaju/LeetCode_Python | /leet_code655.py | 2,900 | 4.15625 | 4 | """
655. Print Binary Tree
Print a binary tree in an m*n 2D string array following these rules:
The row number m should be equal to the height of the given binary tree.
The column number n should always be an odd number.
The root node's value (in string format) should be put in the exactly middle of the first row it ... |
6b30c75dccc298c42b4431bffd007304ec5ee9c0 | tejamupparaju/LeetCode_Python | /leet_code802.py | 1,925 | 4.03125 | 4 | """
802. Find Eventual Safe States
bv, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal
(that is, it has no outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node.
M... |
ddd7f80fa359ae546571ad9c936a1c62bab8f210 | tejamupparaju/LeetCode_Python | /leet_code150.py | 1,216 | 4.09375 | 4 | """
150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) ->... |
24dc301204c57557bcb2ebf1f67c08c478b43c17 | tejamupparaju/LeetCode_Python | /leet_code401.py | 2,568 | 4.03125 | 4 | """
401. Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n wh... |
f00c2eddcb77463b13dd612ed38600040e3913d9 | tejamupparaju/LeetCode_Python | /leet_code462.py | 1,071 | 4.03125 | 4 | """
462. Minimum Moves to Equal Array Elements II
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
I... |
a5a42bc66482731661804906e219ce431cdfef19 | tejamupparaju/LeetCode_Python | /leet_code152.py | 1,758 | 4.15625 | 4 | """
152. Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
class Solution(object):
def maxProduct(self, nums):
"""
... |
ced6a970f3dd3514fb933a55835ac3cabea96d2d | tejamupparaju/LeetCode_Python | /leet_code23.py | 1,192 | 4.125 | 4 | """
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Companies
Amazon 22 Facebook 11 Google 8 Microsoft 5 Apple 4 Alibaba 4 Tencent 4 Uber 3 Bloomberg 3 Paypal 2... |
a9a5db08f764c3e5a4ad21b855cab681800463fd | tejamupparaju/LeetCode_Python | /leet_code286.py | 1,538 | 4.03125 | 4 | """
286. Walls and Gates
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty... |
440c0d9fb88e994a504c38d0dfada9b3fe79e37e | tejamupparaju/LeetCode_Python | /leet_code428.py | 2,156 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
428. Serialize and Deserialize N-ary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another comput... |
7b2c3c40bdc702dc22b8d13a68181f19f24b9da2 | tejamupparaju/LeetCode_Python | /leet_code787.py | 3,269 | 3.78125 | 4 | """
787. Cheapest Flights Within K Stops
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.
Now given all the cities and fights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. I... |
62e3d9632827568ad12444ddb42757189196904d | profharimohanpandey/GA_Implementation | /Evolution.py | 1,881 | 3.671875 | 4 | def evolve(self, pop):
"""Evolve a population of networks.
Args:
pop (list): A list of network parameters
"""
# Get scores for each network.
graded = [(self.fitness(network), network) for network in pop]
# Sort on the scores.
graded = [x[1] for x in sorted(graded, key=lam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.