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 |
|---|---|---|---|---|---|---|
5d82d08b88d08badb587b28927abfecd61e20c0f | rajasekaran36/GE8151-PSPP-2020-Examples | /unit3/basic-if.py | 123 | 3.96875 | 4 | print("Voting eligibility in india")
age = int(input('Enter your age:'))
if(age>=18):
print('you are eligible to vote') |
fc30d1810bf3ab7a883ca3581edce2d0b8c0a7b4 | stefanoborini/quantum-chemistry | /code/wavemol/wavemoldb/lib/chemistry.py | 782 | 3.59375 | 4 | def hillFormula(element_list):
"Returns the Hill's formula out of a list of Element objects"
brute = {}
for symbol in element_list:
if brute.has_key(symbol):
brute[symbol] += 1
else:
brute[symbol] = 1
brute_string = ""
if brute.has_key("C"):
brute_st... |
37b56ce6f5529b7f620e62d28584e70cd956d94e | AgustinDoige/FrogProbabilityProblem | /frogProblemLeg.py | 2,124 | 3.6875 | 4 | from time import time as t
from random import randint
from itertools import combinations
NUMBER_OF_ITERATIONS_IN_SIMULATION = 500000
def prod(ite):
# returns the product of an iter, like the product of a list.
ans = 1
for elem in ite:
ans *= elem
return ans
def getE_simulation(n,amount=NUMBER_OF_ITERATIONS_IN_... |
9a5c19374b77c6acc896313fea669ca5e15d5382 | ethan-jiang-1/hello_ai | /exam_nn/snn/snn_1.py | 1,787 | 3.9375 | 4 | #!/usr/bin/env python
# encoding:utf8
from numpy import exp, array, random, dot
# A single neuron, with 3 inputs connections and 1 output connection.
# The weight is 3 x 1 matrix, with value in the range of -1 to 1 (mean is 0)
class NeuralNetwork():
def __init__(self):
#seed the random number generator, so ... |
081838a95b0b0bccb82df0ef51e61fad5734bbb6 | toshic/mp4viewer | /src/tree.py | 1,137 | 3.921875 | 4 |
class Attr(object):
def __init__(self, name, value, display_value=None):
if type(name) is not str:
raise Exception("name should be string")
self.name = name
self.value = value
self.display_value = display_value
class Tree(object):
def __init__(self, name, desc):
... |
2528eef32d526d21201252ed2256a842c5f2216c | NikheelP/Spark_ | /spark/widget/sample/sample_color_variable.py | 9,494 | 3.625 | 4 |
class COLOR_VARIABLE_CHILD():
def __init__(self, value):
self._color_value = value
@property
def set_value(self):
'''
return the color value
'''
return self._color_value
def get_value(self):
'''
return the color value
'''
return ... |
5d1ec95952b1ec26718a4f5423a500b179fad362 | LouisGi33/Algo-Project | /Trajet/livraison.py | 2,434 | 3.65625 | 4 | from math import floor
# Dictionnaire
ville = {
"Biarritz-Dax": 59,
"Biarritz-Marmande": 231,
"Biarritz-Pau": 119,
"Biarritz-Poitiers": 442,
"Biarritz-Tours": 540,
"Dax-Marmande": 175,
"Dax-Pau": 85,
"Dax-Poitiers": 398,
"Dax-Tours": 496,
"Marmande-Pau": 193... |
fbb4dd3dced038cd6b1153077ea516e7fd93b422 | ACBozzi/Machine-Learning-para-classifica-o-de-corais | /coral_slicer/coral_slicer.py | 2,058 | 3.65625 | 4 | # este código vai pegar um valor x e y e cortar o coral em epdaõs desse tampnho
# https://coderwall.com/p/ovlnwa/use-python-and-pil-to-slice-an-image-vertically
from __future__ import division
from PIL import Image
import math
import os
def has_transparency(img):
if img.mode == "P":
transparent = img.info... |
cd88c9fd226f7b9f23cd4698e30b4890786255eb | yinnyC/leetcode-questions | /addTwoNumbers.py | 467 | 3.671875 | 4 | """Problems 2. Add Two Numbers"""
def addTwoNumbers(l1, l2)
ret = cur = ListNode(0)
takeAway = 0
while l1 or l2 or takeAway:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
total = v1 + v2 +... |
9530cd9094afb4da7557b63626578058fa125f8c | yinnyC/leetcode-questions | /Remove Nth Node From End of List.py | 1,422 | 3.78125 | 4 | """Problems 19. Remove Nth Node From End of List"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def removeNthFromEnd(self, head, n):
"""
singly-linked-list
1. traverse
pointer point to c... |
4dbd0dc749c18157cf3959c41f87293d11ce0cab | pali101/basic-training | /hello.py | 150 | 4.28125 | 4 | print("Hello World!")
num = int(input("User input: "))
if num > 5:
print(num, "is greater than 5")
else:
print(num, "is not greater than 5") |
095bd19c1f4d4dbb39a657d1826c88ebe0673bf0 | Aamir-Meman/BoringStuffWithPython | /old learning/stronglytype.py | 163 | 3.71875 | 4 | def main():
my_str = "Hello, World "
my_num = 42
print(my_str + str(my_num)) # int has to be convert to string
if __name__ == '__main__':
main()
|
70d0f8c4cc2fc8bb64513fa5b4350501a0812ad7 | Aamir-Meman/BoringStuffWithPython | /sequences/reduce-transforming-list.py | 646 | 4.15625 | 4 | """
The reduce function is the one iterative function which can be use
to implement all of the other iterative functions.
The basic idea of reduce is that it reduces the list to a single value.
The single value could be sum as shown below, or any kind of object including a new list
"""
from _functools import reduce... |
a790fa3675dd9073b777f094c70b4c8de0ae35e1 | Aamir-Meman/BoringStuffWithPython | /old learning/lists.py | 165 | 3.796875 | 4 |
# list can have any type in there chain i.e. str, int
nums = [1, 2, 3, 4, "5", "Aamir"]
print(nums[0])
print(nums[1])
nums.append(6)
print(nums)
print(type(nums))
|
7a76d722565041671f5acbad3ec7fb18b26b5431 | LPompe/thesis_demand_response | /software/simulation_enviroment.py | 7,562 | 3.625 | 4 | import math
from random import choice
from pricing_generators import BasePricingGenerator
import pandas as pd
from noise_functions import identity
import matplotlib.pyplot as plt
class DemandResponseEviroment():
"""
Base enviroment to run cooling/heating simulations.
The demandResponseEviroment will run ep... |
978e0d28bcfbf89b9c980e76cfba9fc974adde29 | tnir/pandas | /pandas/tests/copy_view/util.py | 719 | 3.5 | 4 | from pandas import Series
from pandas.core.arrays import BaseMaskedArray
def get_array(obj, col=None):
"""
Helper method to get array for a DataFrame column or a Series.
Equivalent of df[col].values, but without going through normal getitem,
which triggers tracking references / CoW (and we might be t... |
92d6d5760989b847093df1e93b027e3e09e6a7f2 | lucasdavid/convolutional | /convolutional/networks/utils/one_hot.py | 556 | 3.75 | 4 | import numpy as np
def one_hot_encoding(y, n_classes=None):
"""Return a n_classes-dimensional unit vector with a 1.0 in the
j'th position and zeroes elsewhere.
This is used to convert a digit (0...9) into a corresponding desired
output from the neural network.
:param y: 1-ranked tensor.
T... |
5ad3a6412440d9e635168be30ad9eee48d61b6e1 | dormanh/Evolving-Titles | /experience.py | 2,141 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
from idea import generator
from encode import clean, encode, flatten
import numpy as np
import requests
import pandas as pd
import string
import nltk
'''Function searches for a random book title related to a given word.'''
def title_search(word):
books = pd.read_html(r... |
8162656dd123d61e6ce1f0651427cd7418bf7975 | EmsDz/EmsDominoGame | /Clases/ClassToken.py | 499 | 3.703125 | 4 |
# this class is the principal of the game, is the token
class token(object): # token = ficha
"""docstring for token"""
def __init__(self, num):
self.number = num # which number is in the token, is a string
def changeOrientation(self):
self.number = self.number[1] + self.number[0]
... |
45c99755f65b2189994a39ddcc71823034ac7aa7 | EmsDz/EmsDominoGame | /Clases/ClassPlayer.py | 2,828 | 3.703125 | 4 |
# this class contend all the actions that can be do by the player
class player(object):
"""docstring for player"""
def __init__(self, name):
# super(player, self).__init__()
self.name = name # player name, is a string
self.tokens = {} # player tokens, is a dictionary not a list
... |
bcc9720f4eadc14d577f196a0efca17209ae2048 | Tiger-a11y/PythonProjects | /For loop.py | 736 | 3.828125 | 4 | list1 = [["harry",1], ["Larry",2], ["Avi",4], ["Gaurav",7] ]
dict1 = dict(list1)
print(dict1)
for item, lollipop in dict1.items():
print(item, "have lollypop ",lollipop)
for x,y in list1:
print (x,"lolly pop",y)
#Quizz
list2 = ["nana",67,"llaj",5,8,4,"kaka"]
for item in list2:
if str(item).isdigit():... |
d90b479f378d5c80a3d6324931e85d2ab394365d | Tiger-a11y/PythonProjects | /Array.py | 824 | 3.921875 | 4 | # from numpy import *
# arr = array('i',[])
# n = int(input("enter the lenght of array :"))
#
# for i in range(n):
# x = int(input("enter the value :"))
# arr.append(x)
# print(arr)
#
# val = int(input("Enter the value you wanna search :"))
# k = 0
# for e in arr:
# if e == val:
# print(k)
# ... |
067c7fea36ae0de1ac94277db2f3215270a1040d | Tiger-a11y/PythonProjects | /dict Exercise.py | 479 | 4.21875 | 4 | # Apni Dictionary
dict = { "Set" : "Sets are used to store multiple items in a single variable.",
"Tuples" : "Tuples are used to store multiple items in a single variable.",
"List" : "Lists are used to store multiple items in a single variable.",
"String" : "Strings in python are surrounded b... |
9dd6a77da2dd27b6e06e17dcbc0e3e02c18aed89 | huynhhoanghuy/AI | /AStar.py | 3,328 | 3.546875 | 4 | import heapq
class Map:
def __init__(self,width, height):
self.width = width # N
self.height = height # N
self.obstacles = [] # 1
def is_valid(self, point):
(x,y) = point
return 0 <= x < self.width and 0 <= y < self.height
def is_wall(self, point):
... |
15ffea41699c0726bbf4f2833df96be454d5c4d5 | Jgwentworth/pyramid-slide | /initials/initials.py | 335 | 4.03125 | 4 | def get_initials(fullname):
fullname = fullname.upper()
fullname = fullname.split()
new_name = ''
for char in fullname:
new_name = new_name + char[0]
return new_name
def main():
fullname = input("What is your full name?")
print(get_initials(fullname))
if __name__ == '__main__' ... |
eae9fa8d0b927559339d282cc09ab806e4f9e272 | afk-echo/ConsoleToStr | /examples/example_2.py | 614 | 3.515625 | 4 | from ConsoleToStr import ConsoleToStrConverter
conv = ConsoleToStrConverter()
# The inbuilt help() function only prints the output on the console, rather than returning a string.
# We can use help() to demonstrate an application of the converter.
conv.start()
help(list.pop)
result = conv.stop()
print(result) # Pr... |
4e5d85942415adb43d3f402bad4693ecba52ab01 | zachariahsharma/learning-python | /numbers/51.py | 318 | 3.765625 | 4 | mylist1 = [1, 2, 4, 5, 10, 20, 25, 50, 100]
mylist2 = [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200]
commonfactor=[]
for num1 in mylist1:
for num2 in mylist2:
if num1 == num2:
commonfactor.append(num1)
# Greatest common factor is the last entry of the list commonfactor
print(commonfactor[-1])
|
e6dd483cc36f30e58d629cb0936ce4ef10c7e840 | zachariahsharma/learning-python | /numbers/6.py | 1,313 | 4.40625 | 4 | #this is telling python to remmember the types of people
types_of_people=10
#this is showng us a sentance that tells us how many types of people
x=f"there are {types_of_people} types of people"
#this is telling python to remmember the word binary under the word binary
binary='binary'
#this is telling python to remmemb... |
4d1fa4d3ea1fbbde6fdca231ebcc5ba530962d91 | zachariahsharma/learning-python | /numbers/48.py | 473 | 3.5625 | 4 | def createListofFactors(num):
print("TODO: Don't bug me. I am busy")
return [1,2,3]
def askforNumbers():
num1=int(input('give me a number:'))
num2=int(input('give me another number:'))
return num1, num2
if __name__ == '__main__':
number1, number2 = askforNumbers()
print(number1, number2)... |
b8f7401236a54d04c2fb6d09789979b68674d3d0 | SCAUapc/sentiment-analysis | /EmotionSystemUI/ExtractEmoji.py | 2,066 | 3.859375 | 4 | import emoji
import csv
from collections import Counter
def contains_target_emoji(tweet):
"""Returns True if at least one of the target emojis appears in a tweet.
Returns False otherwise."""
emojis = set(c for c in tweet if c in emoji.UNICODE_EMOJI)
targets = {'😨', '😱', '😍', '❤', '😳', '😮', '😡', ... |
f09575dfff643738ace64a908daa7641761e717f | tamotsuhirai0708/GW | /Q6.py | 3,029 | 3.890625 | 4 | import random
mylife = 20
myattacklist = [3,5,7,9,11,20,100]
enemylifelist = [5,10,15,20]
enemyattacklist = [1,2,3,4,5,6,7,8,9,10,15,20]
heallist = [1,3,5,7,9,11,13,15]
next = "1歩進んだ"
walk = 6
while walk >= 2 :
if(walk >= 2):
walk -= 1
print("出口まで"+str(walk)+"歩")
print("HP"+str(mylife))
... |
5806c883c530b1997dc1e2e8c8d474c2626f32a4 | hm-du/pythonLeetCode | /dhm/sort.py | 1,830 | 3.703125 | 4 | import time
import numpy
def display_time(func):
def wrapper(*args):
stime = time.time()
func(*args)
etime = time.time()
print "cost time:"+str(etime -stime)
print "------------------------------"
return wrapper
@display_time
def bubbleSort(arr):
len... |
0d19edda62a7a9a5d74f0cd59405eb82cbaa924f | sankalpg10/GAN_Even_Num_Generator | /dataset.py | 1,240 | 4.125 | 4 | import math
import numpy as np
def int_to_bin(number: int) -> int:
# if number is negative or not an integer raise an error
if number < 0 or type(number) is not int:
raise ValueError("only positive integers are allowed")
# converts binary number into a list and returns it
return [... |
9a2f090e85ad0d2dce0cf5a8b77a8251951b79c5 | tr1503/LeetCode | /Tree and Graphs/closestKValues.py | 915 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
... |
730ead5ecbe02ff56b1ad035d2334297b7983a86 | tr1503/LeetCode | /Depth First Search/floodFill.py | 661 | 3.515625 | 4 | # time is O(n), space is O(n)
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
n = len(image)
m = len(image[0])
color = image[sr][sc]
if color == newColor:
return image
def dfs(r, c):
if i... |
3783788cad214827cc26534480c077b50d08145f | tr1503/LeetCode | /Union Find/minMalwareSpread.py | 1,437 | 3.53125 | 4 | # Use Union Find to solve this question
# Check https://www.cnblogs.com/seyjs/p/9811590.html
class Solution:
def minMalwareSpread(self, graph, initial):
"""
:type graph: List[List[int]]
:type initial: List[int]
:rtype: int
"""
parent = [i for i in range(len(graph))]
... |
86af6a12ba28011877a820adada9290100efa1e3 | tr1503/LeetCode | /Tree and Graphs/uniqueBST_II.py | 1,008 | 4 | 4 | '''Use dfs recursion to get the left tree and right tree separately.'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generate(self, start, end):
res = []
... |
acde81c4de0082f4b383d81af42a4df4a718005c | tr1503/LeetCode | /Design/insertDeleteRandomDuplicate.py | 1,629 | 4.0625 | 4 | class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = collections.defaultdict(set)
self.arr = []
def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not alread... |
574a0f52175c58e5751965750edddc2cec39b5ba | tr1503/LeetCode | /Two Points/palindromeLinkedList.py | 917 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True... |
51102d73493a6fd6fb2ad4e458872a254aed39eb | tr1503/LeetCode | /Depth First Search/leafSimilarTrees.py | 650 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
... |
ec9eebaa0c92c557b817e40f1d2fce57be2a58d3 | tr1503/LeetCode | /Tree and Graphs/BSTtoSortedDoublyList.py | 914 | 3.703125 | 4 | '''Use in-order to travelsal BST to get an array.
Transfer this array to doubly linked list. Time is O(n).'''
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def tr... |
b8f4c47e1a1866a8618a78c35ce72254c7917a33 | tr1503/LeetCode | /Stack/basicCalculator.py | 1,350 | 3.5 | 4 | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
res = 0
num = 0
sign = 1
for i in range(len(s)):
#If it is digit, add to temp variable num
if s[i].isdigit():
nu... |
8a6421271f682e822e913dd5738a50cb24e67fd1 | tr1503/LeetCode | /Breadth First Search/shortestDistanceFromAllBuildings.py | 1,656 | 3.515625 | 4 | class Solution:
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# for each building 1, run bfs and return for each 0
n = len(grid)
m = len(grid[0])
buildings = sum(grid[x][y] for x in range(n) for y in range(m) if grid... |
d40bac64daf3930676bd4213e7df34305ef87a9b | tr1503/LeetCode | /arrayAndString/search2DMatrix.py | 877 | 3.875 | 4 | '''Iter each row's first element and compare to target.
If the first element is larger than target, the target must be at the last line.
If there is only one row in matrix, search that row.
If the last row's first element is still smaller than target, search the last row.'''
class Solution(object):
def searchMatr... |
ef158b2438ec4f914aea8f5a5c35072a6ea96f5f | tr1503/LeetCode | /Backtracking/wordSearch_II.py | 1,653 | 3.671875 | 4 | class Trie(object):
def __init__(self):
self.children = {}
def insert(self,word):
temp = ""
for c in word:
temp += c
if temp not in self.children:
self.children[temp] = False
self.children[word] = True
def search(self, word):
... |
b17b0bb67983e0999826e0d8affccc87f4c4f99d | tr1503/LeetCode | /arrayAndString/validAnagram.py | 624 | 3.71875 | 4 | # use an array to reprent the number of each character in string
# if one character's number is more than or missing in other string, they are not anagram
# time is O(n), space is O(1)
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
... |
2ae747d078060df380ef07b7a8296e3836967980 | tr1503/LeetCode | /Dynamic Programming/allPossbileFBT.py | 706 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
if N % 2 == 0:
return []
dp = [[] for _ in range(N + 1)]
... |
775356a20a5f744a1f4c2835efa0d3ccc9863776 | tr1503/LeetCode | /Stack/indexDiff.py | 582 | 3.625 | 4 | # get the index difference of first number after this element that is larger than this element
# if there is no number larger than this element, return -1
def indexDiff(nums):
if len(nums) == 0:
return []
res = [-1 for _ in range(len(nums))]
stack = [] # add [number, index]
for i, num in enumerate(nums):
while... |
48e17f098b61bc06eea3398386a182fbdfe00ca3 | tr1503/LeetCode | /linkedList/copyListwithRondomPointer.py | 1,618 | 3.96875 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
4e4f67dbcac87da798101e87f43cfe72f9bbf750 | tr1503/LeetCode | /Tree and Graphs/recoverBST.py | 995 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify... |
57c284f34bb1f7288bf089139eb5a151f4fd64d1 | tr1503/LeetCode | /arrayAndString/findWordExtension.py | 182 | 3.671875 | 4 | def findWordExtension(s):
i = 0
res = []
while i < len(s):
j = i + 1
while j < len(s) and s[j] == s[i]:
j += 1
if j - i >= 3:
res.append([i, j-1])
i = j
return res
|
aafeeeba3458c7666bd37331fb11b7cef80a718e | tr1503/LeetCode | /Breadth First Search/pacificAtlanticWaterFlow.py | 1,417 | 3.671875 | 4 | # use bfs to search from the boundary to the extrances of two oceans
# if both of them get to oceans, then they should be the result
class Solution:
dirs = [[0,-1],[0,1],[-1,0],[1,0]]
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""... |
20b73d00f16c8cebcfc92df4c81d4434a81d6a4a | tr1503/LeetCode | /Two Points/linkedListCycle_II.py | 1,307 | 3.890625 | 4 | '''Use Floyd's Algorithm to solve this question. Set one slow pointer and one fast pointer firstly.
If fast pointer reaches null, this linked list is not cycle, return None. If slow and fast intersect,
return this intersect node. Set two new pointer, one is head another is the intersect node.
Track these two nodes, ge... |
4bd7d10262544ecb96c7dfa9205171a85eea87df | tr1503/LeetCode | /Math/countPrimes.py | 504 | 3.59375 | 4 | class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0 or n == 1:
return 0
num = [True] * (n - 1)
num[0] = False
res = 0
limit = int(math.sqrt(n))
for i in range(2, limit + 1):
if nu... |
4fb4803dee3c1e945fcec3b91fe1f1fc45334dfd | EricSchles/HeriReligion | /freshman/heri2.py | 3,724 | 3.515625 | 4 | """This file contains code used in "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import matplotlib.pyplot as pyplot
#import myplot
import csv
#import Cdf
#import correlation
#import heri
import math
impor... |
4d21c1abf5bc2343a441a4c50f6efc243cf511ad | christopherc1331/cs-sprint-challenge-hash-tables | /hashtables/ex1/ex1.py | 1,103 | 3.5625 | 4 | def get_indices_of_item_weights(weights, length, limit):
"""
YOUR CODE HERE
"""
# Your code here
matched_weights = ()
idx_1 = None
idx_2 = None
my_dict = {}
for i in range(length):
# print("hello")
# print(weights[i])
if weights[i] not in my_dict:
... |
c24d3769f1cc2c4263b9dacd502db025c8533cc3 | Arnacels/fora | /split_date.py | 855 | 3.640625 | 4 | from datetime import datetime
class SplitDate(object):
def __init__(self, df):
self._df = df
self._dates = {
'year': [],
'month': [],
'day': [],
'weekday': []
}
def split(self):
for index, series in self._df.iterrows():
... |
bf09b2cec97accf10a810e06add3404029f897a0 | CobraCoral/recursive_square | /recursive_square_unittest.py | 1,323 | 3.71875 | 4 | #!/bin/env python3
"""Test recursive square algorithm implementation."""
import unittest
from recursive_square import iterative_square, recursive_square, recursive_square_tail
class SquareTestCommon():
def setUp(self):
self.range_start = -100
self.range_end = 100 + 1
self.function = None
... |
d3f2f4698175bf23018a5eaf7f453efaa713c3c3 | AnastasiiaDm/Py_ThirdtProject | /IntDegreeOf2.py | 4,116 | 4.0625 | 4 | # По данному натуральному числу N найдите наибольшую целую степень двойки, не превосходящую N.
# Выведите показатель степени и саму степень.
# Операцией возведения в степень, а так же функцией возведения в степень пользоваться НЕЛЬЗЯ!
#
# Например:
# 50 5 32 2 ** 5 = 32
# 10 3 8 ... |
31364ee319b85253abb2e6fa62f0c0b05985f371 | 504703038/Linux | /study/大二下/Python/课本代码/1-8.py | 122 | 3.765625 | 4 | n = input("请输入整数N: ")
sum = 0
for i in range(int(n)):
sum += i + 1
print("1 到N 求和结果: ", sum)
|
461337d963ca253ef7191cc9d9d499c24bd38408 | 504703038/Linux | /study/大二下/Python/实验/实验4/习题4.2.py | 325 | 3.765625 | 4 | # 习题4.2
s = input("请输入一行字符:")
num = space = word = 0
for i in s:
if i >= '0' and i <= '9':
num += 1
elif i >= 'a' and i <= 'z' or i >= 'A' and i <= 'Z':
word += 1
else:
space += 1
print("英文字符有{}个,数字有{}个,空格有{}个".format(word, num, space))
|
0e2891b39ef4d54aae64c668ce6a7962d62906ac | clusterking/clusterking | /clusterking/util/cli.py | 2,220 | 3.546875 | 4 | #!/usr/bin/env python3
"""Utils for the command line interface (CLI)."""
def yn_prompt(question: str, yes=None, no=None) -> bool:
"""Ask yes-no question.
Args:
question: Description of the prompt
yes: List of strings interpreted as yes
no: List of strings interpreted as no
Retur... |
4354b110ce7da268a27c9c9bc3c42333c6fc25ad | controlling-robots/controlling_omni_robots | /scripts/ControlLaws.py | 3,701 | 3.703125 | 4 | from numpy import sqrt, sin, cos, pi
class CircleControlLaw:
k = 2
def __init__(self, v, R):
"""
Constructor of Circle control law class.
:param v:
:param R:
"""
self.v = v
self.R = R
def getControl(self, x, y, alpha, center=(0, 0)):
"""
... |
2baed855097cf6284403315197af77f04a4e9e8b | yafanman/python | /20210503.py | 6,360 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print('hi')
# In[4]:
user_input_a = input("정수 입력> ")
if user_input_a.isdigit():
number_input_a = int(user_input_a)
print("원의 반지름:", number_input_a)
print("원의 둘레:", 2* 3.14 * number_input_a)
print("원의 넓이:", 3.14 * number_input_a * number_input_a... |
6c2e67452294f7674821d41c032e019932eb1cd1 | Coder481/Data_Structure_And_Algorithm | /Functions/To print first N prime numbers.py | 369 | 3.921875 | 4 | #Print first N prime numbers(TSRN)
def f1(a):
count=0
x=1
while True:
x+=1
for i in range(2,x):
if x%i==0:
break
else:
count+=1
print(x)
if count==n:
break
n=int(input("Enter how many... |
07cc63a902618b0085e6f5913fc15c309b4867d8 | Coder481/Data_Structure_And_Algorithm | /Recursion/10.HCF of two numbers.py | 270 | 4 | 4 | #TO find HCF of two numbers
def f(a,b,i):
if a%i==0 and b%i==0:
return i
else:
return f(a,b,i-1)
y,z=int(input("Enter first number")),int(input("Enter second number"))
x=f(y,z,min(y,z))
print("The HCF of the two numbers is",x)
|
4682e7095effa3c1084cee173f4ccfbb87ac3af8 | Coder481/Data_Structure_And_Algorithm | /Recursion/10.Reverse of cubes of first N natural numbers.py | 138 | 3.9375 | 4 | #Reverse of cubes of first n natural numbers
def f(n):
if n==1:
return print(n**3)
return print(n**3),f(n-1)
f(5)
|
25e18dbe9406ba41d43abea86d195d6814a24ce4 | Coder481/Data_Structure_And_Algorithm | /Recursion/7.Squares of first N natural numbers.py | 114 | 3.640625 | 4 | #Squares of first N natural numbers
def f(i,n):
if i<=n:
print(i**2)
f(i+1,n)
f(1,10)
|
740330063ef3b7869f197e8bf5271c8afa11c999 | Coder481/Data_Structure_And_Algorithm | /Recursion/8.Reverse of squares of first N natural numbers.py | 140 | 3.9375 | 4 | #Reverse of squares of first n natural numbers
def f(n):
if n==1:
return print(n**2)
return print(n**2),f(n-1)
f(5)
|
b23438d702424628a7ab55a230ec415ff435c986 | Coder481/Data_Structure_And_Algorithm | /Dictionary/Dict_items.py | 78 | 3.640625 | 4 | d=eval(input("Enter a dict(key:value)"))
for x in d:
print("\n",x ,d[x])
|
5b641f0feccbec150f1bb8d2eca75543a3c6985a | Coder481/Data_Structure_And_Algorithm | /Recursion/5. N odd natural numbers.py | 115 | 4.09375 | 4 | #To print first N odd natural numbers
def f(i,n):
if i<n:
print(2*i+1)
f(i+1,n)
f(0,5)
|
700c48c702fb046f4e3825379d86a60eb926641a | Xatnagh/100-picture-mosaic | /5imgs.py | 820 | 3.6875 | 4 | def pixilImg(imagename, l, h): # high def image -> 5 images of lower quality/ file names from order from highest quatity to lowest - YOUR_FILENAME1, ... YOUR_FILENAME5 by pixels/4
from PIL import Image
im = Image.open(imagename)
x = imagename
for i in range(5):
im.thumbnail([h/2, l/2]) # ... |
74084bf18bd502c9c1335f460bc8a63ea4be8a0b | yh3715/coding-for-younjong | /week-01-python/1-2-hw.py | 402 | 3.671875 | 4 |
class Person:
def __init__(self, name, old, gender):
self.name = name
self.old = old
self.gender = gender
class Colleague(Person):
# position = "대리"
def __init__(self, name, old, gender, position):
super().__init__(name, old, gender)
self.position = position
coll... |
13e0eeb6d35514f70ce5fe99624131a8df873bd8 | bocaletm/cs325-algorithms | /week1/sortingAnalysis/mergeTime.py | 3,287 | 3.640625 | 4 | # Mario Bocaletti
# CS325 Fall 2018
# 09/22/18
# Merge Sort
##################
# merge()
##################
def merge(leftSide = [], rightSide = []):
if not leftSide:
return rightSide
if not rightSide:
return leftSide
mergedSubData = []
while leftSide and rightSide:
if leftSi... |
1bcfeb334441f1cf865aba25d07c61447e4372d5 | bocaletm/cs325-algorithms | /week6/wrestler.py | 2,945 | 3.640625 | 4 | ##################
# Mario Bocaletti
# cs325 - week6
# 11/4/18
# wrestler
##################
# wrestler class has a list of rivals
class Wrestler:
def __init__(self):
self.rivals = set()
self.team = ""
def addRival(self,rival):
self.rivals.add(rival)
def hasRival(self,rival):
... |
fa3da93f96c84901bc9b403e0ff79ec9212aec0a | chesswiz16/TopCoder | /SRM635_quadratic_law.py | 443 | 3.546875 | 4 | __author__ = 'Tiger'
def BinarySearch(lo, hi, f):
# f(lo) is true
# f(hi) is false
# returns the largest x such that f(x) is true
while lo + 1 < hi:
ha = (lo + hi) / 2
if f(ha):
lo = ha
else:
hi = ha
return lo
class QuadraticLaw:
def getTime(sel... |
da7a253122514fc8dee817a6ad354597ad607328 | ridolenai/Day_3 | /worksheet day 3 (bonus).py | 1,401 | 3.8125 | 4 |
# import statistics
# from statistics import mode
# from collections import Counter
list_of_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
# arbitrary_number = 5
# secondlist_of_numbers = [1,1,1,4,2,2,3,3,5]
# keepy_tracky_number = 0
# first_list_names = ['Jimbob', 'Bubba', 'Jeremiah']
# second_list_names = ['Bubba', 'Johnny... |
d490ee22f26eee6328f223fff47894322ef54de6 | hsvoen/Simulated_annealing | /pseudo.py | 2,418 | 3.546875 | 4 | import random
class Basket:
N = 0
M = 0
#eggs = []
def __init__(self, n,m):
self.M = m
self.N = n
self.eggs = []
def set_eggs(self, table):
self.eggs = table
def init_start_eggs(self):
row = [0]*self.N
for i in range(self.M):
self.egg... |
1c47069ec9b961188f78e0fe1da675c3c35c7407 | allengour/Tweetalytics | /Ad_author.py | 654 | 3.5625 | 4 | import json
import nltk
def get_author(tweet):
'''
parameter: tweet json object
return: the author of that tweet (the retweeter, in case of a retweet)
'''
return tweet['user']['screen_name'] # the @ name
def all_authors(filename):
'''
parameter: string filename
return: list of all auth... |
c182d4143f41cdb030e5b6fa0fad9ed2ea71e581 | Bishalf/bishal | /ColorChoice.py | 239 | 3.859375 | 4 | color=input("enter your favorite color\n ")
if color=="blue":
print("you beileve in Deepness")
elif color=="black":
print("You are classy")
elif color =="red":
print("Nice choice")
else:
print("Nice choice") |
0f6cf6ba290ae4598fb144bf387d17c5a211cba4 | villancikos/realpython-book2 | /flask-hello-world/app.py | 754 | 3.59375 | 4 | # --- Flask Hello World --- #
#import the Flask class from the flask module
from flask import Flask
#create the application object
app = Flask(__name__)
#error handling
app.config["DEBUG"] = True
#use decorators to link the function to a url
#@app.route("/")
#@app.route("/hello")
#dynamic route
@app.route("/")
@a... |
accfba75d21fa6f8be14940ed65bde941ea3d609 | Aston-Bishop/210CW | /Coding Exercises/Exersize 9.py | 454 | 3.6875 | 4 | def binaryInterval(l, low, high):
first = 0
last = len(l)-1
found = False
while first<=last and not found:
mid = (first + last)//2
if l[mid] >= low and l[mid] <= high:
found = True
else:
if low < l[mid]:
last = mid-1
... |
16e62e5f6127703df436195c7d10e03b71a3555c | Aston-Bishop/210CW | /Coding Exercises/Exersize 1.py | 584 | 4.03125 | 4 |
import random
def swap(n1, n2): # simple function to swap two numbers
return n2, n1
def shuffle (ordered_list): # Base on the Fisher–Yates shuffle
for x in range(0, len(ordered_list)-1):
j = random.randint(0,x)
... |
8c21874aba1081b07ffcf0c1f7b09113d9a6302b | justawho/Python | /vampire2.py | 353 | 4.0625 | 4 | print ('Please enter your name.')
name = input()
print ('Please enter your age.')
age = input()
if name == 'Alice':
print('Hi, Alice')
elif int(age) < 12:
print('You are not Alice, kiddo.')
elif int(age) > 100:
print('You are not Alice, grannie.')
elif int(age) > 2000:
print('Unlike you, Alice is not an... |
75764f96681592643f63082b017aa4c1a64d5e56 | justawho/Python | /TablePrinter.py | 620 | 4.25 | 4 | ## A function named printTable() that rakes a list of lists of strings and
## displays it in a well-organized table
def printTable(someTable):
colWidths = [0] * len(someTable)
for j in range (len(someTable[0])):
for i in range(len(someTable)):
colWidths[i] = len(max(someTable[i], key=len))
... |
aab57cbd87343b9c124164e08e7ce293a1527a9e | Nincy11/Tic-Tac-Toe-Game | /main.py | 5,648 | 3.515625 | 4 | import pygame
import sys
#****************************************************functions******************************************************************
def map_mouse_to_board(x, y):
if x < gameSize / 3:
column = 0
elif gameSize / 3 <= x < (gameSize / 3) * 2:
column = 1
else:
colu... |
4ab7d7ea392ed1f2a35d7cd145bb120c1d02c4b8 | alexoliveirah/cod_python | /1_fibonacci.py | 501 | 3.90625 | 4 | """Sequência de Fibonacci
os números seguintes serão a soma dos dois números anteriores
ex: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584..."""
try:
term = int(input('Quantos termos você quer ver? '))
t1 = 0
t2 = 1
t3 = 0
print(f'{t1} - {t2}', end=' ')
f... |
e608f3918ea42c32ac5bb8f29b15c4a61b3475ba | raj-khare/Advent-of-Code | /Day5/day5.py | 761 | 3.515625 | 4 | import re
import string
data = open("input.txt").read()
# PART 1
def react(polymer):
i = 0
while i != len(polymer)-1:
if abs(ord(polymer[i]) - ord(polymer[i+1])) == 32:
polymer.pop(i)
polymer.pop(i)
if i != 0: i -= 1
else: i += 1
return len(polymer... |
39e5a96a886152df39bdf2d37b6240627d857ee6 | eshthakkar/coding_challenges | /heaps.py | 1,350 | 3.9375 | 4 | import math
def max_heapify(A,i,n):
l = 2 * i + 1
r = 2 * i + 2
if l < n and A[l] > A[i]:
largest = l
else:
largest = i
if r < n and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A,largest,n)
#O(n) ... |
99684d3f327cd662d85f4f4239c882ef3b130bf5 | eshthakkar/coding_challenges | /closing_paran_index.py | 2,161 | 4.0625 | 4 | def get_closing_paran_index(sentence, open_paran_index):
""" Problem : Return the closing paranthesis index from the input string
Complexity Analysis: O(n) time and O(1) space
Tests:
>>> sentence = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get c... |
92f7400e1ffa24879e1626c42e1e5c21c2e4eda8 | eshthakkar/coding_challenges | /bit_manipulation.py | 1,108 | 4.125 | 4 | # O(n^2 + T) runtime where n is the total number of words and T is the total number of letters.
def max_product(words):
"""Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
You may assume that each word will contain only l... |
3e6f61f56ba8f3973be04896b5827c9bf99f664b | eshthakkar/coding_challenges | /rectangle_overlap.py | 1,895 | 4.1875 | 4 | # Overlapping rectangle problem, O(1) space and time complexity
def find_rectangular_overlap(rect1, rect2):
""" Find and return the overlapping rectangle between given 2 rectangles"""
x_overlap_start_pt , overlap_width = find_range_overlap(rect1["x_left"], rect1["width"], rect2["x_left"], rect2["width"])
y... |
49421b3c6d6cd17108c8a9ef1c58130c2c531d3e | eshthakkar/coding_challenges | /kth_largest_from_sorted_subarrays.py | 676 | 4.125 | 4 | # O(k) time complexity and O(1) space complexity
def kth_largest(list1,list2,k):
""" Find the kth largest element from 2 sorted subarrays
>>> print kth_largest([2, 5, 7, 8], [3, 5, 5, 6], 3)
6
"""
i = len(list1) - 1
j = len(list2) - 1
count = 0
while count < k:
if list1... |
274ce90a027f65c845bea0b6edc41f3aea728edb | tahentx/plan-evaluation-tools | /evaltools/mapping/drawgraph.py | 2,495 | 3.6875 | 4 |
import matplotlib.pyplot as plt
import networkx as nx
def drawgraph(
G, ax=None, x="INTPTLON20", y="INTPTLAT20", components=False, node_size=1,
**kwargs
):
"""
Draws a gerrychain Graph object. Returns a single Axes object (for dual
graphs drawn whole) and lists of `(Figure, Axes)` pai... |
4345f43ceebfae6bf9b4514241a243202d936d70 | wyolum/Alex | /scripts/packages/mylistbox.py | 1,551 | 3.609375 | 4 | #https://tk-tutorial.readthedocs.io/en/latest/listbox/listbox.html
import tkinter as tk
def listbox(parent, items, item_clicked, item_selected, n_row=40):
def myclick(event=None):
idx = lb.curselection()
if idx:
out = lb.get(idx)
search.delete(0, tk.END)
search.... |
a7c92c7d490e5f37eacc2b0e7efde08131b8241e | anshulsharma111/Advance-Billing-Software | /App/Backend/patterns_validations.py | 1,540 | 3.90625 | 4 | import re
class PatternsValidations:
"""Below are all the regular expressions"""
@classmethod
def v_gst(cls, e):
if e == '':
return True
pattern = re.compile(
'^([0][1-9]|[1-2][0-9]|[3][0-5])([a-zA-Z]{5}[0-9]{4}[a-zA-Z][1-9a-zA-Z][zZ][0-9a-zA-Z])+$')
if re.s... |
9a41c9a514d61a35306de193da9bb97ada3153cb | FelixWessel/SimpleSnakeGame | /SimpleSnakeGame.py | 5,653 | 4.0625 | 4 | # This is a work in progress - not finished and not working yet
import pygame
import sys
from random import randint
pygame.init()
#Definition of variables for the game
run = True # As long as run equals true the game runs
screen_width = 600 # Setting the widt... |
660721b46bf39fcd86baf4ac1c7c0d8f5d53cb1d | tgphelps/bj-trainer | /Shoe.py | 1,461 | 3.59375 | 4 |
import random
from Card import Card
SUITS = ['spade', 'heart', 'diamond', 'club']
FACE_CARDS = ['jack', 'queen', 'king']
class Shoe:
def __init__(self, num_decks: int, card_size=1) -> None:
deck = create_deck(card_size)
self.shoe = num_decks * deck
self.shoe_size = 52 * num_decks
... |
dae286a5def2f293a32b12a2aa05b5f43a78fe7c | cladjevardi/SHAE | /jump_game.py | 5,948 | 3.84375 | 4 | """
Main module for platform scroller example.
"""
import pygame
import constants
import levels
from player import Player
def main():
""" Main Program """
pygame.init()
# Set the height and width of the screen
size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
screen = py... |
49b4ed16afeba9afd7d24351ae89f038a4e210dc | FabianArancibiaM/ApiRes-HebHub_to_Heroku | /model/ClassUsers.py | 376 | 3.546875 | 4 | class User:
def __init__(self,name, password):
self.__name =name
self.__password = password
def printUser(self):
print('name: {} and password {}'.format(self.__name,self.__password))
def validar(self):
if self.__name == 'admin' and self.__password == 'admin':
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.