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 |
|---|---|---|---|---|---|---|
d3b1ceff2e207895ca92c5e825daa990e3c339e1 | jang010505/Algorithm | /BOJ/10423.py | 776 | 3.53125 | 4 | def find(num):
if parent[num]==num:
return num
parent[num]=find(parent[num])
return parent[num]
def union(num1, num2):
a=find(num1)
b=find(num2)
if a!=b:
parent[b]=a
def parentFind(num1, num2):
a=find(num1)
b=find(num2)
if a!=b:
return 0
else:
retu... |
023b2fd11b8854427d5653385254cb61b14caf15 | jang010505/Algorithm | /BOJ/10768.py | 151 | 4.15625 | 4 | a=int(input())
b=int(input())
if a<2 or (a==2 and b<18): print("Before")
if a>2 or (a==2 and b>18): print("After")
if a==2 and b==18: print("Special")
|
9b54a71a33f2d9c0427dd7c273bf6eedf8113bcc | jang010505/Algorithm | /BOJ/5522.py | 58 | 3.75 | 4 | res=0
for i in range(5):
res+=int(input())
print(res)
|
7f529cb4745565b57599482bfd3cc8c53d027da8 | jang010505/Algorithm | /BOJ/1774.py | 924 | 3.59375 | 4 | def find(num):
if parent[num]==num:
return num
else:
parent[num]=find(parent[num])
return parent[num]
def union(num1, num2):
a=find(num1)
b=find(num2)
if a!=b:
parent[b]=a
def parentFind(num1, num2):
if find(num1)==find(num2):
return 1
else:
re... |
3cef4008c9c59c71f7c4c18c1ba1156938b204fd | jang010505/Algorithm | /BOJ/10179.py | 86 | 3.6875 | 4 | n=int(input())
for i in range(n):
x=float(input())
print("$%.2f" %(x*80/100))
|
cae0951dcb0aaed9aa287c1e924211365b6bcf80 | Lynch08/pands-problem-sheet | /squareroot.py | 1,061 | 4.3125 | 4 | #Programme that uses a function so when you input a number it will return the square root
#Author Enda Lynch
#REF https://medium.com/@sddkal/newton-square-root-method-in-python-270853e9185d
#REF https://www.youtube.com/watch?v=WsQQvHm4lSw - Understand Calculas
#REF https://www.homeschoolmath.net/teaching/square-root-al... |
9bbf035b5e759603277ab311b08da9172cf22559 | suhjohn/Asyncio-Study | /asyncio_study/event_loop/utils.py | 585 | 3.796875 | 4 | from functools import wraps
from time import time
def log_execution_time(func):
"""
Decorator function that prints how long it took to execute the function
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time()
return_value = func(*args, **kwarg... |
9ad76f1d88a7eebaee0a06a3ace1fdcd161e1cda | diaahassouna/My-Python-2014 | /pygame makings/basic 4.py | 895 | 3.734375 | 4 | #importing modules
import pygame
import sys
from pygame.locals import *
#initialization
pygame.init()
#defining colors and custom colors in RGB mode
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,255,0)
cyan = (0,255,255)
magenta = (255,0,255)
#set variable of the... |
aaff2840112da2ff60a32ba852d181885249aa3c | CrissDefaz001/03_DesktopApps | /04_Python/01_Formas/Rombos.py | 656 | 3.53125 | 4 | print('Rombo normal:')
num = 8
if(num%2 == 0):
num2 = int(num/2)
else:
num2 = int((num+1)/2)
for i in range(num2, 0, -1):
for j in range(i, num2):
print('* ', end="")
print('')
for i in range(0, num2):
for j in range(i, num2):
print ('* ',end="")
print('')
print('\nRombo con forma:\n')
if(num%2... |
81a9451d1581fdedf766a439f4744a78e0feb8a0 | perennialAutodidact/algorithms_and_data_structures | /data_structures/trees/filter_range.py | 611 | 3.6875 | 4 | from BinarySearchTree import BST, BSTNode
'''
Given a BST and a valid range of keys, remove nodes
from the BST that have keys outside that range.
'''
def truncate(root, low, high):
if root is None:
return root
root.left = truncate(root.left, low, high)
root.right = truncate(root.right, low, ... |
74c9dfa20d2a168810f07b75fb525a836741b4d3 | perennialAutodidact/algorithms_and_data_structures | /algorithms/searching/python/binary_search.py | 527 | 3.703125 | 4 | from random import randint
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
elif arr[mid] > target:
hi... |
8d37650fc1728a38f41a5e70d4a560f19eef0631 | perennialAutodidact/algorithms_and_data_structures | /data_structures/singly_linked_list/SLL_has_cycle.py | 1,000 | 3.8125 | 4 | from SLinkedList import SLinkedList, Node
def has_cycle(head):
slow = head
fast = head.next
# while pointers aren't None
while slow and fast:
# if the slow and fast pointers land
# on the same node, a cycle exists
if slow == fast:
return True
# pr... |
b96c473a1b366efebf30f888dcfe9aba5e53b2c6 | VladKrupin/DemoGit | /Calculator v1.0.py | 419 | 4.1875 | 4 | from math import pow
a = float(input("Enter the first number:"))
op = input("Input the operation:")
b = float(input("Enter the second number:"))
result = None
if op == "+":
result = a+b
elif op == "/":
result = a/b
elif op == "-":
result = a-b
elif op == "*":
result = a*b
elif op == "pow":
result=po... |
cf2c3ca1da7e03150375bb6b51ad4047c4b87a77 | adrian-lux/coffeeMachine | /main.py | 3,129 | 3.875 | 4 | emoticons = {
"hot_beverage": "☕",
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0
}
beverages = {
"espresso": {
"water": 100,
"milk": 0,
"coffee": 16,
"money": -1.5
},
"latte": {
"water": 100,
"milk": 100,
"c... |
cd707f93116cd0c4cc73b1e32e1997b6201fe90d | indraneel76/learning | /python/inda/tensorflow_example.py | 1,442 | 3.578125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("/tmp/data/",one_hot=True)
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
plt.imshow(np.reshape(mnist.train.images[8],[28,28]),cmap='gray')
#plt.show()
learning_rate=0.1
num_steps=500
batch_size=128
... |
559b75f012f9d21fd0367942558cf768d20226de | KennyBarza/Machine-Learning | /Data Preprocessing/Data Cleaning/DroppingColumnsWith1Value.py | 728 | 3.59375 | 4 | #Now that we found them, we could drop the columns!
# delete columns with a single unique value
from pandas import read_csv
# define the location of the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/oil-spill.csv'
# load the dataset
df = read_csv(path, header=None)
print(df.shape)
... |
247253beb89aa039ba57841502a950ed0e120cda | KennyBarza/Machine-Learning | /Data Preprocessing/Data Cleaning/VarianceThreshold.py | 901 | 4.0625 | 4 | #In this section, we will be removing columns that have a low variance uisng VarianceThreshold()
# example of apply the variance threshold. Note that our data is full of numerical data. So if we got
#a value of 2, it would be reasonable for a categorical variable, but unreasonable for a numerical value!
from pandas ... |
044d8b6e56aa03a3ccb1103faa0fa3bf33a3af0b | botchains/Lattice-Based-Signatures | /Fiat-Shamir-based/Gaussian_sampling.py | 2,704 | 3.640625 | 4 | '''
Transcedental function Bernoulli sampling, Gaussian sampling
used for embedded devices where floating point computations
are not native and memory is limited.
'''
from math import exp
import random
import util
def Bernoulli_rv(c):
'''
c is a parameter of Bernoulli distribution
'''
return 1 if random.random() ... |
c8ecbd9bc33cd0fb448d3c791f904bfe2dd19ddf | VeryBigCorp/dataset_analyzer | /analyze.py | 3,575 | 3.71875 | 4 | """
Input: the ith domain
Output: key-value dictionary will successful missions in those domains (successful >= 3)
"""
def checkOneDomain(i): \
array1 = {}
successArray = {}
# fill list with all possibilities of domain
for row in data:
array1[row[i]] = array1.get(row[i], 0) + 1
for key in array1:
for row i... |
975304d34b9cb77d774a555aee184667dafd4da6 | yoloshao/yolowork | /排序/自定义排序函数03.py | 894 | 3.625 | 4 |
l = [{'name':'Tom', 'age':10},
{'name':'liming', 'age':30},
{'name':'guoguo', 'age':50},
{'name':'rose', 'age':18}]
count = len(l)
for i in range(0, count - 1):
for j in range(0, count - 1 -i):
if l[j]['age'] > l[j + 1]['age']:
l[j],l[j + 1] = l[j + 1],l[j]
print(l)
sorted(... |
d5488c9f1d38f687fceb7f8e7bf40a454655fddc | yoloshao/yolowork | /spiderdemo/10买汉堡 演示协程.py | 407 | 3.734375 | 4 | def buy():
result = ""
while True:
# yield 调用result 返回给r
n = yield result
if not n:
return None
result = '{n}购买成功'.format(n=n)
def make(buy):
next(buy)
n = 0
while n < 5:
n = n + 1
# 协程工作
r = buy.send(n)
print(r)
buy.clo... |
9d0e3f9388d797713fab494b88a538b652526c6b | neerajkumarTTN/lambda_error_handeling | /Q2.py | 275 | 3.796875 | 4 | def is_prime(num):
if num >= 2:
for y in range(2,num):
if num%2==0:
return False
else:
return True
else:
return False
return True
#num=[5,3,4,6,7]
num=[33]
print(list(filter(is_prime,num))) |
10f29b6e424800fb5c9ba4360b7e59c79c46b36c | sheelabhadra/LeetCode-Python | /1023_Camelcase_Matching.py | 1,639 | 3.921875 | 4 | """PROBLEM:
A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query.
(We may insert each character at any position, and may insert 0 characters.)
Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and onl... |
39f113cd4bdb08992ec39fecbcccb3ae324ac9d9 | sheelabhadra/LeetCode-Python | /849_Minimize_Distance_To_Closest_Person.py | 1,935 | 3.9375 | 4 | # In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
# There is at least one empty seat, and at least one person sitting.
# Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
# Return that maximum distanc... |
53b9d3683feff9adfa34c88be6c856db960072ad | sheelabhadra/LeetCode-Python | /1033_Moving_Stones_Until_Consecutive.py | 2,232 | 4.21875 | 4 | """PROBLEM:
Three stones are on a number line at positions a, b, and c.
Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it
to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions
x, y, z with x < y < z. Y... |
22e6457a4791af6292a17bbb294566aefdb9834e | sheelabhadra/LeetCode-Python | /728_Self_Dividing_Numbers.py | 1,425 | 4.125 | 4 | #A self-dividing number is a number that is divisible by every digit it contains.
# For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
# Also, a self-dividing number is not allowed to contain the digit zero.
# Given a lower and upper number bound, output a list of every ... |
b23bb16fc13e163d5bb072af1eb860775160dfee | sheelabhadra/LeetCode-Python | /1080_Insufficient_Nodes_in_Root_to_Leaf_Paths.py | 980 | 3.8125 | 4 | """PROBLEM:
Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf.
(A leaf is a node with no children.)
A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.
Delete all insufficient nodes simultaneously, and return... |
7b86c9772df7b4eb4937944c5f238636ce55ec8f | sheelabhadra/LeetCode-Python | /130_Surrounded_Regions.py | 2,183 | 4.0625 | 4 | # Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
# Example:
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
# X X X X
# X X X X
# X X X X
# X O... |
3c3f302ecbbfff3b2c4598312564e97a63a58cd7 | sheelabhadra/LeetCode-Python | /532_K-diff_Pairs_in_an_Array.py | 1,089 | 3.828125 | 4 | """PROBLEM:
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array.
Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their
absolute difference is k.
"""
"""SOLUTION:
Similar to 2 sum. We need to check if (n... |
c03f4d6e278b3fe1591d9bfae8e45eda6c1d5134 | sheelabhadra/LeetCode-Python | /1004_Max_Consecutive_Ones_III.py | 590 | 3.5 | 4 | """Problem:
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
"""
"""Solution: #copied
For each A[j], try to find the longest subarray.
If A[i] ~ A[j] has zeros <= K, we continue to increment j.
If A[i] ~ A[j] has ze... |
5339ae2ade971686c99ed0fe0e00d6dd677c3989 | sheelabhadra/LeetCode-Python | /279_Perfect_Squares.py | 666 | 3.59375 | 4 | #Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...)
#which sum to n.
#For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
## SOLUTION: Dynamic Programming
import sys
class Solution(object):
def numSquares(... |
d84cfd420337859a86786c927cd586f02c3ee210 | sheelabhadra/LeetCode-Python | /852_Peak_Index_Mountain_Array.py | 667 | 3.859375 | 4 | #Let's call an array A a mountain if the following properties hold:
#A.length >= 3
#There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
#Given an array that is definitely a mountain, return any i such that
#A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > ... |
327a7c221e670ed0344b4799f0c8a51488acd5c7 | sheelabhadra/LeetCode-Python | /637_Average_of_Levels_in_Binary_Tree.py | 1,128 | 3.78125 | 4 | """PROBLEM:
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.... |
cb8173fb6620cc6fac4e09ede07412690f44f4fc | sheelabhadra/LeetCode-Python | /695_Max_Area_Island.py | 1,206 | 3.828125 | 4 | # Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land)
# connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
# Find the maximum area of an island in the given 2D array. (If there is no island, the maximum are... |
eb07d07f5391fa4e7e21b05c3ce0daacc818ad69 | sheelabhadra/LeetCode-Python | /840_Magic_Squares_In_Grid.py | 1,876 | 4.03125 | 4 | #A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column,
#and both diagonals all have the same sum.
#Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
#Example 1:
#Input: [[4,3,8,4],
# [9,5,1,9],
# ... |
ab1c0726e560bf17869613cda64f30cc8a0f0ec1 | sheelabhadra/LeetCode-Python | /15_3Sum.py | 2,034 | 3.859375 | 4 | """PROBLEM:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets
in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0,... |
37eefb7c19eb1bc64c2c4a2dc5cde53fef56708d | sheelabhadra/LeetCode-Python | /35_Search_Insert_Position.py | 893 | 4 | 4 | """PROBLEM:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would
be if it were inserted in order.
You may assume no duplicates in the array.
"""
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(... |
68e3931f77614f3d07225b9d6d1b29cf76baff67 | sheelabhadra/LeetCode-Python | /783_Minimum_Distance_Between_BST_Nodes.py | 1,138 | 3.625 | 4 | """PROBLEM:
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two
different nodes in the tree.
"""
"""SOLUTION:
Consider the min difference between the current node and its children. Also consider the min difference between the
left/right child and floo... |
824edd750eb15c4707a7d1fcc25b091af5e5eb36 | sheelabhadra/LeetCode-Python | /787_Cheapest_Flights_Within_K_Stops.py | 1,383 | 3.625 | 4 | """PROBLEM:
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 flights, 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. If there is no such route, out... |
7260281520c1da66044945d54c46aacfc9dfd831 | sheelabhadra/LeetCode-Python | /739_Daily_Temperatures.py | 2,177 | 3.96875 | 4 | """PROBLEM:
Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days
you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73],
y... |
f5547f0f2f8c43fec70049b94783f862f9b9ff3d | rosette99/LearnPython | /NumpyTest_A/NumpyTest1.py | 201 | 3.625 | 4 | __author__ = 'linma'
import numpy as np
array = np.array([1,4,5,8],float)
print array
print ""
array = np.array([[1,2,3],[4,5,6]],float) # a 2D array/Matrix array; [[1. 2. 3.]\n[4. 5. 6.]]
print array |
2919cb4ed21c77e5ae149b371c85774b7da1982a | sirex/python-pamokos | /S01E01/T12.py | 239 | 3.578125 | 4 | LONGNESS = [
(5, 'short'),
(8, 'medium'),
(10, None),
(None, 'long'),
]
def howlong(word):
for n, name in LONGNESS[:-1]:
if len(word) < n:
print(name)
return
print(LONGNESS[-1][1])
|
174c1655ae4e136aa68b3f0875b40b4aef7c54e5 | AngelaAsatryan/Homework | /class example.py | 633 | 3.78125 | 4 | class Dog:
def __init__(self, name, age, bread, sex, body, head, tail, legs, hair):
self.name = name
self.age = age
self.bread=bread
self.sex=sex
self.body=body
self.head=head
self.tail=tail
self.legs=legs
self.hair=hair
#methods
def bark(arg):
print("haf haf h... |
697935b825edf22f663c9ee800a912a09301682b | gfajardo95/CrackingPython | /array_questions/question_3.py | 1,106 | 3.859375 | 4 | def urlify_string_v1(str, true_len):
URL_STR = "%20"
spaces = (len(str) - true_len) / 2 # this returns a double!
i = 0
urlified_string = ""
while i < len(str) and spaces != 0:
if str[i] is " ":
# str.insert(i, URL_STR) ERROR: str.insert does not work because insert is for lists... |
1d373a68942a5448fbd82f4797049c14f98c5647 | Chetve007/file_manager | /games/guess_number.py | 1,089 | 4 | 4 | import random
number = random.randint(1, 100)
user_number = None
count = 0
levels = {1: 10, 2: 5, 3: 3}
level = None
while 1:
level = int(input('Select difficulty level: '))
if level not in levels.keys():
print('You have only three difficult levels: 1, 2, 3')
continue
break
max_count = lev... |
2e419591913ee8fefccab8ff8f6956ca867ce554 | LiuFlying/Z_LeetCode_Python | /074_Search_a_2D_Matrix.py | 2,371 | 3.71875 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) <= 0 or len(matrix[0]) <= 0:
return False
rows, columns = len(matrix), len(matrix[0])
row, column = ... |
2b996ea141af4c9bda48e0b90e4b1350f58de69d | tcd1558/ASMLCodingQuestion | /ProcessCheck.py | 3,011 | 3.78125 | 4 | import re
logStrings=["abcdeabcde", "abacdebcde", "abcdeabcce", "abcdeabcd", "ababcdcee", "aaabbbcccdddeee", "aaabcdebcdebcde"]
def firstEntryCheck():
""" The first letter in a logString has to be 'a'. """
def LastEntryCheck():
""" The first letter in a logString has to be 'e', Otherwise the process can not ... |
accbec6a2d851b8e78e25a2042b1a889cf3ebc78 | pappasam/npd | /c3_advanced_python/python/c03/s01/ex03.py | 393 | 3.546875 | 4 | class ImAnIterator(object):
def __init__(self, limit):
self.limit = limit
self.cnt = 0
def next(self):
if self.cnt > self.limit:
raise StopIteration()
try:
return self.cnt
finally:
self.cnt +=1
class ImIterable(ImAnIterator):
def __iter__(self):
return self
for i in ... |
159076f943c24c297dd3011c0546d74bc64cd141 | pappasam/npd | /c3_advanced_python/python/c03/s01/ex05.py | 730 | 3.671875 | 4 | class ImAnIterator(object):
def __init__(self, limit):
self.limit = limit
self.cnt = 0
def next(self):
if self.cnt > self.limit:
raise StopIteration()
try:
#Now we will only return self, which will have a string value.
return self
finally:
self.cnt +=1
def __str__(se... |
906f06c45600cb0ad90d308aa757daf2fbfba5fd | zahraaassaad/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/3-forward.py | 1,408 | 3.84375 | 4 | #!/usr/bin/env python3
"""Function that performs the forward algorithm for a hidden markov model"""
import numpy as np
def forward(Observation, Emission, Transition, Initial):
"""Returns: P, F, or None, None on failure
P: likelihood of the observations given the model
F: numpy.ndarray of shape (N... |
a92014b710494f1583f6488a045e75b73def5b8b | zahraaassaad/holbertonschool-machine_learning | /math/0x00-linear_algebra/101-the_whole_barn.py | 1,285 | 3.828125 | 4 | #!/usr/bin/env python3
"""
Module for add_matrices.
"""
def matrix_shape(matrix):
"""Finds shape of matrix."""
dimensions = []
len_matrix = len(matrix)
dimensions.append(len_matrix)
while type(matrix[0]) == list:
matrix = matrix[0]
len_matrix = len(matrix)
dimensions.appen... |
d5fec83b09015c6cab7330df67ecd64a71f10cec | zahraaassaad/holbertonschool-machine_learning | /unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | 812 | 3.59375 | 4 | #!/usr/bin/env python3
"""Class GaussianProcess that represents
a noiseless 1D Gaussian process"""
import numpy as np
class GaussianProcess:
"""Class GaussianProcess"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Constructor"""
self.X = X_init
self.Y = Y_init
self.l... |
6701d5e6e7a31f5167fd35f8e94ac44f09b62b47 | zahraaassaad/holbertonschool-machine_learning | /unsupervised_learning/0x01-clustering/1-kmeans.py | 2,045 | 3.828125 | 4 | #!/usr/bin/env python3
"""Function that performs K-means on a dataset"""
import numpy as np
def kmeans(X, k, iterations=1000):
"""X is a numpy.ndarray of shape (n, d) containing the dataset
n is the number of data points
d is the number of dimensions for each data point
k is a positive intege... |
8a25987ba534fe52bc1bc1bba8991ec834481884 | zahraaassaad/holbertonschool-machine_learning | /unsupervised_learning/0x01-clustering/5-pdf.py | 1,340 | 3.78125 | 4 | #!/usr/bin/env python3
""" Calculates the probability density function of a Gaussian distribution """
import numpy as np
def pdf(X, m, S):
"""
X is a numpy.ndarray of shape (n, d) containing the data points whose PDF
should be evaluated
m is a numpy.ndarray of shape (d,) containing the mean of the... |
8f977472fd05fb250e180589c6545a545805a2ac | zahraaassaad/holbertonschool-machine_learning | /math/0x06-multivariate_prob/0-mean_cov.py | 854 | 4.28125 | 4 | #!/usr/bin/env python3
""" calculates the mean and covariance of a data set """
import numpy as np
def mean_cov(X):
"""
X is a numpy.ndarray of shape (n, d) containing the data set:
n is the number of data points
d is the number of dimensions in each data point
Returns: mean, cov:
mean num... |
9bc3f91763ca1527d32d18365524c08b0ba27f0e | zahraaassaad/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/4-inverse.py | 3,459 | 3.828125 | 4 | #!/usr/bin/env python3
"""
4-inverse.py
calculates the inverse of a matrix
"""
def inverse(matrix):
"""Returns: the inverse of matrix, or None if matrix is singular"""
deter_mat = determinant(matrix)
adj_mat = adjugate(matrix)
if deter_mat is 0:
return None
inv_mat = []
for i in range... |
c014af16eb2bf4f58f83c5dc447f2c7d13d98981 | schorlet/pacman | /filter_email_address.py | 210 | 3.609375 | 4 | import re
n = int(raw_input())
mails = list(raw_input() for _ in range(n))
def valid_email(mail):
return re.match("^[a-z0-9_-]+@[a-z0-9]+\.[a-z0-9]{1,3}$", mail)
print sorted(filter(valid_email, mails))
|
3142de4f237c7aca06045ca9d45450cb9706f859 | Cobrette/i21 | /tp3.py | 2,509 | 3.8125 | 4 | '''
^ XOR
| or
~ not
& and
'''
#exo 1 :Operateurs bit a bit
#question 1:
#retourne la valeur dui-`eme bit de l’entiern.
def bit(n,i):
x= n & 2**i
return x>>i
"""
ou en 1 ligne :
def bit(n,i):
return (n&2**i)>>i
"""
#question 2 :
#retourne l’entier x pour lequel le bit de poids i a été modifier en val
de... |
2bd28581cab1b0666deda9be61f938ef5c8e6b40 | martin-v-ottesen/SDA_Wookieepedia | /Old Files/Lecture1.py | 2,128 | 3.96875 | 4 |
# coding: utf-8
## Lecture 1
### Part 1
#### Ex 1B
# A list with elements from 1 to 100
# In[1]:
a = range(1,101)
# We slice the array to get the elements from 42 to 79
# In[2]:
b = a[41:79]
# We now define a simple function using def
# In[3]:
def f(x):
return x*x+2
# We use this on each element of... |
b965f10cce1cc500c559ccf66520ee5c51f8930f | BartekDzwonek/PracaDomowa3 | /Zadanie2.py | 311 | 3.984375 | 4 | #!/usr/bin/env python3
def check():
number = input("Put your number: ")
number2 = 0
number = int(number) # obie wartosci musza byc typu int dla operacji is
if number is number2:
print("Hero zero")
else:
print("Your number is {}.".format(number))
check()
|
17039f019f507455b54f7c3a7414c1a16b9c9515 | lcc728/python | /bubble.py | 268 | 3.71875 | 4 | # 氣泡排序 Bubble Sort
# https://www.george.tw
my_list= [16,62,93,94,65,96]
for i in range (len(my_list) -1):
for j in range(len(my_list)-1):
if my_list[j] < my_list[j+1]:
my_list[j],my_list[j+1] =my_list[j+1],my_list[j]
print (my_list)
|
35720ff21ac78d83973c32960f1048111541ed7d | lcc728/python | /magicBall.py | 1,370 | 3.78125 | 4 | # Magic Ball
#https://www.george.tw/2020/05/01/python-dict-magic-8-ball/
import random
# https://zh.wikipedia.org/wiki/神奇八號球
magicMap={
1:'It is certain (這是必然)',
2:'It is decidedly so (肯定是的)',
3:'Without a doubt (不用懷疑)',
4:'Yes, definitely (毫無疑問)',
5:'You may rely on it (你能依靠它)',
... |
657c5eaa278f64328e55cb0317402211421192f2 | dtran2108/permutations | /permutations.py | 485 | 3.75 | 4 | def permute(nums):
res = []
_permuteHelper(nums, 0, res)
return res
def _permuteHelper(nums, start, results): #helper method
if start >= len(nums):
results.append(nums[:])
else:
for i in range(start, len(nums)):
nums[i], nums[start] = nums[start], nu... |
3d4ab039e71cd29e99869411e85843626f8cc95f | Forrest-Z/learngit | /code/moro_code/python/legend.py | 541 | 3.625 | 4 | # -*- coding:utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 11, 1)
# plt.plot(x, x * 2, label = "First")
# plt.plot(x, x * 3, label = "Second")
# plt.plot(x, x * 4, label = "Third")
# # loc 设置显示的位置,0是自适应
# # ncol 设置显示的列数
# plt.legend(loc = 0, ncol = 2)
# 也可以... |
6957186f092bd22fcb6016c566be14c6c7504c52 | 1Nput/BuilDD | /pyCalc.py | 3,184 | 4.09375 | 4 | print ('Bem Vindo a calculadora de expressões, leis e equações matemáticas totalmente automatizada. Para saber quais operações automatizadas nos fazemos, aperte enter!')
import math
def deltanegativo (x):
if (x < 0):
print ('')
print ('Por favor insira um número que o valor de Delta seja > ou = 0')
... |
241630704fd83337ecac9ef435d09e9a90633515 | punith369/Cup-game | /main.py | 300 | 3.90625 | 4 | import random
print("welcome to the game Rock Predictor in the cup\n Pick a cup")
a = int(input("what's your choice: '0' or '1' or '2' "))
flip = random.randint(0, 2)
print(flip)
if (flip == a):
print("hurray! you won")
else:
print("sorry you lost, better luck next time")
|
81c55915e271308b548ffd70c4d50a4749329cd0 | calmahn/jump_to_python | /2. 자료형/02-6-01.py | 192 | 4.03125 | 4 | s1 = set([1,2,3])
s2 = set("Hello")
print(s2)
#집합 자료형
#중복 허용X, 순서X
l1 = list(s1)
print(l1)
print(l1[0])
t1 = tuple(s1)
print(t1)
print(t1[0])
t2 = tuple(s2)
print(t2) |
f35025afe817908dd6131765379bd37464147117 | calmahn/jump_to_python | /2. 자료형/02-4-01.py | 166 | 3.53125 | 4 | t1 = (1,2,'a','b')
print(t1[0])
print(t1[3])
print(t1[1:])
t2 = (3,4)
print(t1 + t2)
print(t2*3)
print(len(t1))
t3 = (1,2,3)
t4 = (4,)
print(t3+t4)
print(t3+(4,)) |
5aab2e5c754200317caf1f35399d7d9e57ae32f0 | calmahn/jump_to_python | /3. 제어문/03-2-05.py | 249 | 4.0625 | 4 | #continue: while문을 빠져나가지 않고 맨 처음(조건문)으로 다시 돌아가는 방법
a = 0
while a < 10:
a = a + 1
if a%2 == 0: continue
print(a)
b = 0
while b < 10:
b = b + 1
if b%3 == 0: continue
print(b) |
4e93a276e2b0c8c3b72448dfa05fda413ac91b7c | calmahn/jump_to_python | /4. 입력과 출력/04-1-04.py | 84 | 3.6875 | 4 | def add(a,b):
return a+b
result = add(a=3, b=7)
print(result)
print(add(3,7)) |
d3188328685d9129205d70903d82aa3fa0f5898d | calmahn/jump_to_python | /5-7. test/05-test-q01.py | 311 | 3.703125 | 4 | class Calculator:
def __init__(self):
self.value = 0
def add(self, val):
self.value += val
return(val)
class UpgradeCalculator(Calculator):
def minus(self, val):
self.value -= val
return(val)
cal = UpgradeCalculator()
print(cal.add(10))
print(cal.minus(7)) |
f49aa22682be17046465b0d4eefce90fb48e0c38 | larsh101/FinalDAO | /classes/transaction.py | 431 | 3.671875 | 4 | from collections import OrderedDict
from util.printable import Printable
class Transaction(Printable):
def __init__(self,sender,recipient,amount,kind):
self.sender = sender
self.recipient = recipient
self.amount = amount
self.kind = kind
def to_ordered_dict(self):
retu... |
f024d287fb1525b452314fb0d523020745636270 | srclayton/Python-uDemy | /aula22_arquivos.py | 937 | 3.9375 | 4 | # -*- coding: utf-8 -*-
'''
r == somente leitura
w == escrita (caso o arquivo ja exista, ele sera apgado e um noovo arquivo vazio sera criado)
a == leitura e escrita(adiciona o novo conteudo ao fim do arquivo)
r+ == leitura e escrita
w+ == escrita (o modo w+, assim como o w, tambem apaga o conteudo anterior do arquivo)... |
4e8b71067820b1dced1a2cf88ae3143f60d029c6 | srclayton/Python-uDemy | /aula10_comparacao.py | 167 | 3.96875 | 4 | # -*- coding: utf-8 -*-
x=3
y=3
z=2
print(z == y or x == z)
'''
==
>=
<=
!=
>/<
Retornam sua comparação no print!
And e Or operadores logicos and==&& e or==||
''' |
1fb919cec3ee8153cb619e78f07b13abe65aa662 | bardia52/LeetCode | /Algorithms/game_of_life.py | 1,695 | 3.65625 | 4 | class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: None Do not return anything, modify board in-place instead.
"""
def neighbors(b,i,j,m,n):
ret = 0
# check above rows
if i > 0:
# a... |
30f2836b509dbf7c746835ebbc3ac0ab6de0d0aa | YoYolops/URI | /Iniciante/Sequência lógica.py | 169 | 3.796875 | 4 | x = int(input())
n = 1
y = int((x*2)/2)
for i in range(y):
print("%d %d %d"%(n, pow(n,2), pow(n,3)))
print("%d %d %d"%(n, pow(n,2)+1,pow(n,3)+1))
n = n + 1
|
8bba0b1ba06c9a9914bedbf792398269d910e9e0 | YoYolops/URI | /Iniciante/Sort Simples - 1042.py | 172 | 3.5625 | 4 | a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
leitura = [a,b,c]
ordem = sorted(leitura)
for j in ordem:
print(j)
print()
for i in leitura:
print(i) |
5b428bf8b0e1e03a5c2e6138f5e81203cfae8bde | SC-Coder-Dojo/Pygame-Scratch | /PGS_racing.py | 2,738 | 3.6875 | 4 | import random
import pygame
from pygame import Color
from pygame.locals import *
from ScratchSprite import *
#####################################################################
# DESIGN YOUR SPRITES #
#####################################################################
class Stage(Stage):
def __init__... |
5651f25d4501ffe56b8fe9a6b3d7ebb9f848e209 | marpy1990/Code | /Python/block/Block.py | 1,707 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
"""用于管理一定资源并实现某些功能的一种模型
模块是占有资源的最小单位,对模块资源的访问只能采用申请应答机制。
在这种架构体系下,一种资源只能被一个模块唯一占有,全局资源是不被允许的。
Basic usage::
>>> block = Block(name)
"""
__docformat__ = "restructuredtext en"
__all__ = [
"Block"
]
__author__ = "marpy"
__version__ = "1.0.0"
__date__ = "$Date: 2013-10-13$"
# exception... |
b719c7dc5ba949343702aeb25addde11007478de | kwierman/Cards | /Source/Deck.py | 2,264 | 4.03125 | 4 | ## @package Deck
# Deck definition in the cards simulation
import Card
## Private implementation of the deck type in the cards simulation
class _Card_List:
def __init__(self):
self.cards = []
def __str__(self):
tmp_string = ""
for i in self.cards:
tmp_string+="\t"+str(i)+"\n"
return tmp_string
## Class... |
e4a322de533519abc12a1819ef9bcea84113c488 | kwierman/Cards | /Source/Shuffle.py | 1,032 | 4.125 | 4 | """ @package Shuffle
Performs shuffling operations on decks
"""
import Deck
## splits the deck into two decks
# @param deck The deck to be split
# @param split_point how many cards from the top of the deck to split it
def split_deck(deck, split_point=26):
deck_1 = Deck.Deck()
deck_2 = Deck.Deck()
for x, card in ... |
68a9d15962f3ad6785e5b4d8cb8abc1023b9e46e | gustavodfaguiar/list-exercises-python-br | /estrutura_sequencial/ex04.py | 232 | 3.71875 | 4 | nota1 = int(input("Informe a nota 1: "))
nota2 = int(input("Informe a nota 2: "))
nota3 = int(input("Informe a nota 3: "))
nota4 = int(input("Informe a nota 4: "))
media = (nota1 + nota2 + nota3 + nota4) / 4
print("Media:", media)
|
cee08b421339d7583b0490e7f0c1a75fb91f268b | Cocktailpy/spiderRepository | /1.commonUrllibAPI.py | 1,614 | 3.5 | 4 | import urllib.request
# >>>urlopen()
def urllib_urlopen():
# 打开并爬取一个网页
file = urllib.request.urlopen("http://www.baidu.com/")
# 读取全部内容
data = file.read()
# # 读取全部内容
# dataline = file.readline()
# 将网页保存在本地
fhandle = open("./doc/1.html", "wb")
fhandle.write(data)
fhandle.close... |
239231b60672f68f0c8c58d6d7e5b3334d43edca | denise-sanders/BrainTeasers | /rotator.py | 1,316 | 4.03125 | 4 | """Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here
So we are given a list, that is in alphabetical order, but started somewhere random in the a... |
6001aea202b565bbbecd7c06a5ec5514318c77a8 | denise-sanders/BrainTeasers | /simpleCalculator.py | 1,708 | 3.578125 | 4 | class Stack:
def __init__(self):
self.data = []
def pop(self):
return self.data.pop()
def push(self, value):
self.data.append(value)
def isEmpty(self):
return len(self.data) == 0
class Solution:
@staticmethod
def resolve_op(last_op, re... |
4aee96d18563f1291574806fc9e1734964c95121 | denise-sanders/BrainTeasers | /string_permutations.py | 821 | 3.90625 | 4 | # Write a recursive function for generating all permutations of an input string. Return them as a set.
def permutate(string):
if len(string) == 0:
return {}
if len(string) == 1:
print string
return { string }
if len(string) > 1:
current = permutate(string[1:])
for c ... |
b74a1c4d34d77696547cc76539975a99b7ee9133 | ashish88sharma/market_analysis | /download_required_data.py | 1,786 | 3.515625 | 4 | ''' this code downloads delivery data of today. it is assumed to be working on windows
so, downloaded file goes to downloaded. It then renames this file and move it to
our target folder for further processing'''
import sys
import pandas as pd
import numpy as np
import shutil
import os
import time
import random
from se... |
9e5965b726a190a0ce8b36424870b6aa050f9f34 | simiyub/python | /interview/practice/tests/dynamic_programming/TestMinimumCoinsForChange.py | 333 | 3.875 | 4 | import unittest
from interview.practice.code.dynamic_programming.MinimumCoinsForChange import coins_for_change
class TestMinimumCoinsForChange(unittest.TestCase):
def test_coins_for_change(self):
self.assertEqual(3,coins_for_change(7, [1, 5, 10])) # add assertion here
if __name__ == '__main__':
uni... |
5fd87282bd2429a43a83feb00c542b07da1a4259 | simiyub/python | /interview/practice/code/arrays/SortedSquareFromSortedArray.py | 642 | 4.28125 | 4 | """
Given an array of sorted integers, this function returns a sorted array of the square of the numbers
"""
def sorted_square_array(array):
result = [0 for _ in array]
smaller_value_index = 0
larger_value_index = len(array) - 1
for index in reversed(range(len(array))):
smaller_value = array[... |
6e713b61bedbe73121c1326b8d17ae7cd5d1ef06 | simiyub/python | /interview/practice/code/recursion/Permutations.py | 1,724 | 4.15625 | 4 | """
Requirement:This function will receive an array of integers and
create an array of unique permutations or ordering of integers
that can be created from the integers in the array.
Implementation: We build all permutations for the array within the array in place using pointers.
We select the first element in the arra... |
b38061008c428376be3fd297a5896102960bed62 | simiyub/python | /interview/practice/code/arrays/MinimumChangeCannotCreate.py | 1,205 | 3.828125 | 4 | """
Requirement: Given an array of integers that represent a set of coins,
write a function that returns the minimum amount of change that cannot be created with the set of coins.
Given no coins [ ], the minimum change that you cannot create would be 1 and given [1, 2, 5],
you cannot create 4.
Implementation: We sort ... |
08d233abb3e53e06f9a156929d047feddc00173b | simiyub/python | /interview/practice/code/bst/FindClosestValueInBST.py | 802 | 4.09375 | 4 | """
This example uses iteration to find the closest value to a target value
in a BST with Worst and Average case O(n) T and O(1) S
"""
import copy
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def find_closest_value_in_bst(tree, target):
... |
61066f828ffa00dd2652b07ea8e546e255682cf8 | simiyub/python | /interview/practice/code/linked_lists/ReverseLinkedList.py | 1,248 | 4.15625 | 4 | """
Requirement: Given a linked list where each node points to the next node,
this function will return the linked list in reverse order
Implementation: Conceptually, a node is reversed when the next pointer points to the previous node.
However, as this is a singly linked list, we do not have a pointer to the previous ... |
bdcdc5e5b8478d2d5a3f07b274d793553fe86d03 | Badhan-abhishek/python-scripts | /mongo_json_collection.py | 841 | 3.71875 | 4 | import os
import sys
# To be tested with CSV data
# file_type = int(input('''
# Please choose file type
# 1) JSON
# 2) CSV
# Type down number as option:
# '''))
# if file_type != 1 and file_type != 2:
# sys.exit('Wrong selection')
# Get directory path
directory = input("Please enter valid directory where json... |
ccdd5f0c988ba45fd34cd898c36bd5fcf2135afa | shorya97/AddSkill | /DS & Algo/Week 2/Sorting/Largest Number.py | 883 | 3.5 | 4 | class Solution:
def largestNumber(self, nums: List[int]) -> str:
if not any(map(bool, nums)): # this is , if we encounter just zeroes, edge case
return '0'
nums = list(map(str, nums)) # converting it into a string
if len(nums) <2:
... |
fe1c5e5cea9e34e329b658982acd5bd7fd8f23af | shorya97/AddSkill | /DS & Algo/Week 2/Stack/Implement Stack using Queues.py | 1,420 | 4.15625 | 4 |
from queue import Queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = Queue() #inbuilt queues
self.q2 = Queue()
self.cur_size = 0 #contains number of elements
def push(self, x: int) -> None... |
be1b56dc341fc45d7c0d017bc979c4d1426f7afa | prabhu30/Python | /Strings/Set - 1/maketrans_translate.py | 743 | 4.5625 | 5 | """
maketrans() :-
It is used to map the contents of string 1 with string 2 with respective indices to be translated later using translate().
translate() :-
This is used to swap the string elements mapped with the help of maketrans().
"""
# Python code to demonstrate working of
# maketrans() and translate()
from ... |
1feaf630e326d9ed22aa164e6874e477681504ad | prabhu30/Python | /Strings/string_functionalities_2.py | 1,241 | 4 | 4 | s = "geeksforgeeks"
print("\nindex method :")
ind = s.index("g") #First occurence of "g"
print(ind)
ind = s.index("for")
print(ind)
# ind = s.index("gfg") ---> This raises index error, as gfg is not present in the string
print("\nisspace method :")
string = 'Geeksforgeeks'
print(string.isspace())
string = '\n \n \n... |
bdbfdd41268b98866a0eb26d1d335267b1a4f0b9 | prabhu30/Python | /Lists/Set - 1/indexing_negative.py | 666 | 4.375 | 4 | """
Negative indexing :-
In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last it... |
9b76ccde2b4bbc6c9ace5d7669202869ef2775a2 | spandanb/insight-coding-challenge | /src/hashlist.py | 5,088 | 4.15625 | 4 | """
This module defines the hashlist class.
"""
class hashlist(dict):
"""
This class provides an ordered dictionary with
an age based eviction policy.
The keys are sorted (in increasing order) by the corresponding value.
When an insert happens the entry is inserted
in order to maintain or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.