blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
46b164ad9c3a01ee945fee69cd8ec8676fc2f154 | vthomas1908/yahtzee | /functions.py | 4,616 | 3.828125 | 4 | # Copyright (c) 2014 Thomas Van Klaveren
# create the function for Yahtzee game. This will evaluate dice and
# determine the points eligible for the score card item selected
#function checks the values of dice and returns a list containing the numbers
#of same valued dice (ie dice 6,2,6,6,2 would return [3,2])
def ... |
96720afe434563414e5a8167964e4759a4696186 | tadteo/nnn | /src/utils.py | 835 | 3.53125 | 4 | #select the best two individuals
def select_best_two(population):
if population[0].score >= population[1].score:
mx=population[0].score
best = population[0]
second_best_value = population[1].score
second_best = population[1]
else:
mx=population[1].score
best = pop... |
3bcd2fad9fbb8028a7b92da712c3c3f5f13c3f84 | spoofdoof/2018 | /SP/assign3/decrypt.py | 2,302 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from collections import defaultdict, Counter
def read_file(filename):
with open(filename) as lines:
for line in lines:
yield line.strip().decode('hex')
def xor_combinations(data):
"""
Returns all posible combinations of XORs ... |
e7caaeace5bfd268d90db767c2d8df6d1539fca6 | JuDePom/algooo | /lda/prettyprinter.py | 2,077 | 3.9375 | 4 | class PrettyPrinter:
"""
Facilitates the making of a properly-indented file.
"""
# must be defined by subclasses
export_method_name = None
def __init__(self):
self.indent = 0
self.strings = []
self.already_indented = False
def put(self, *items):
"""
Append items to the source code at the current ind... |
5ecae8a199ce0b5e87bb6d57f4386a5c8ba29d31 | Riableo/analisis | /Ejercicios/insercion.py | 396 | 3.921875 | 4 | def Insercion(Vector):
for i in range(1,len(Vector)):
actual = Vector[i]
j = i
#Desplazamiento de los elementos de la matriz }
while j>0 and Vector[j-1]>actual:
Vector[j]=Vector[j-1]
j = j-1
#insertar el elemento en su lugar
Vector[j]=... |
63d77f48f26c15c1d060ba2f50b82386016a6389 | Riableo/analisis | /Ejercicios/Multiplos.py | 367 | 3.890625 | 4 | tr=0
while tr == 0:
try:
Num=int(input("Ingresar numero: "))
Num_I=int(input("Ingresar numero: "))
N=Num%Num_I
N1=Num_I%Num
if N == 0 or N1 == 0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos")
except ValueError:
print("Solo números por favor")
tr=int(input("Volver... |
331a82a167fd30e270ec8db699145caba71a80d3 | skyhuge/python-demo | /muti_params.py | 1,204 | 4.0625 | 4 | def calc(nums):
sum = 0
for n in nums:
sum += n
return sum
# 可变参数
def add_nums(*nums):
sum = 0
for n in nums:
sum += n
return sum
# 关键字参数
def print_nums(name, age, **kw):
# kw.clear() # 对kw的操作不会改变extra的值
print('name is %s , age is %s , other is %s' % (name, age, kw)... |
f19d3a39693428d4ff85fc65e8cdc734c1b8f5d0 | 6Kwecky6/PyForProggers | /Lecture4/TimeTableDraw.py | 1,224 | 4.0625 | 4 | import turtle
import math
step = 0
def drawCircle(rad, num_points, pen):
# placing the circle down by rad to make the center of it origo
pen.up()
pen.goto(0,-rad)
pen.down()
# Drawing the circle
pen.circle(rad)
pen.up()
#Moves along the circle to yield points
for it in range(num_po... |
eac82a0b61c8bee65c15b3078150af5f711c45d5 | pinpin3152/python | /Assignment_cointoss.py | 837 | 3.78125 | 4 | import random
def coin(toss):
if toss == 0:
return "head"
else:
return "tail"
head = 0
tail = 0
i = 1
while i < 5001:
X = random.randint(0,1)
if X == 0:
head += 1
else:
tail += 1
print "Attempt #" + str(i) + ": Throwing a coin... It's a " + coin(X) + "! ... Got " + str(head) + " head(s) so far and " + s... |
63a21b76e45777b7fa2b333df3bf46b56920c304 | Tornike-Skhulukhia/Principles-of-data-science-book-working-files | /scripts/chapter 10/point_estimates.py | 1,168 | 3.625 | 4 | from import_helpers import (
np,
pd,
plt,
)
from scipy import stats
from scipy.stats import poisson
# why do they use loc > 0 in the book???
long_breaks = poisson.rvs(loc=0, mu=60, size=3000)
short_breaks = ... |
f4034f05130cfa6c9d6f1af443f1651da5534e28 | stoicswe/CSCI315A-BigData | /HW6_NathanBunch/Boltzman Machine Example/rbm.py | 14,152 | 3.828125 | 4 | from __future__ import print_function
import numpy as np
class RBM:
def __init__(self, num_visible, num_hidden):
self.num_hidden = num_hidden
self.num_visible = num_visible
self.debug_print = True
# Initialize a weight matrix, of dimensions (num_visible x num_hidden), using
# a uniform distri... |
ff66222e7d4764345f053a966e2b0cd81255667f | adhed/shortest-path | /shortest_path.py | 1,002 | 4.0625 | 4 | from point import Point
from algorithm import Algorithm
def ask_for_points():
points = []
points_counter = int(input("Podaj proszę liczbę punktów jaką będziesz chciał przeliczyć: "))
for idx in range(points_counter):
x = int(input("Podaj współrzędną X dla punktu nr {0}: ".format(idx+1)))
... |
0e69f61ef23bc9b2dc698670ed063a51fe8fb2c1 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/653_div_3/b.py | 1,358 | 3.546875 | 4 | from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
n = int(input())
nummoves = 0
flag = 0
while n!=1:
if n%3!... |
9336374508ea58e1706637d9d20636ab94d08b4c | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/644 Div 3/C.py | 1,094 | 3.96875 | 4 | # A pair (x, y) is similar if they have same parity, i.e., x%2 == y%2 OR they are consecutive |x-y| = 1
t = int(input())
for _ in range(t):
# n is even (given in question, also a requirement to form pairs)
n = int(input())
arr = list(map(int, input().split()))
# There are only two cases: no.of... |
fad5fe4ca3e87197c4d7204999ed5fef4f81220a | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codechef/ANSLEAK.py | 439 | 3.59375 | 4 | from collections import Counter
def get_most_frequent(solns):
return Counter(solns).most_common()[0][0]
if __name__ == "__main__":
T = int(input())
for _ in range(T):
ans = []
n, m, k = list(map(int, input().split()))
for _ in range(n):
solns = list(map(int... |
9e364b774c5ccd44d3897cd98983a4d7bf072cd7 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Atcoder/172/d.py | 1,294 | 3.828125 | 4 | n = int(input())
# Check out atcoder editorial for this, beautifully explained. Same as geothermal's but it also shows how this idea was thought
# https://img.atcoder.jp/abc172/editorial.pdf
def sieve(n):
# 1.9 seconds.
# 1 and n are divisors for every n.
is_prime = [2]*(n + 1)
is_prime[0], ... |
a1c657c309fabf23cd2f255e0431ec673c2d8470 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/Educational Round 88/C.py | 1,885 | 3.671875 | 4 | # If there are even number of cups, the attained temperature is always: (h+c)/2. If there are odd number of total cups (let it be 2*x - 1). There are x hot cups and (x-1) cold cups. The attained temperature is given by (h*x + c*(x-1))/2*x-1 = t_attained ---- EQN 1
# In the odd no. of cups case, the no. of hot cups i... |
f05605470e60d9342fc96dca170bc90e9418cac4 | Mustafa-pnevma-galinis/Basic-Algorithms | /Agorithms.py | 11,412 | 4.34375 | 4 | #بسم اللّه و الصلاة و السلام على جميع الأنبياء و المرسلين و آل بيوتهم الطاهرين المقربين و على من تبعهم بإحسانٍ إلى يوم الدين
# ◙◙ (α) Merge Sort Algorithm
count = 0
lst = [4,6,8,1,3,2,5,7]
sectorA = lst[0:4]
sectorB = lst[4:8]
# ◘◘@Note: to allocate the size of the array before initialisation.
#sortedArray =... |
93981da08850dd74b5752556d1b8f0ede9c75d1d | 6qos/CSE | /notes/venv/Semester 2 Note.py | 346 | 3.921875 | 4 | print("Hello World")
# Cookies
cars = 5
driving = True
print("I have %s cars" % cars)
age = input("How Old Are You?")
print("%s?? Really??"% age)
colors = ["Red", "Blue", "Black", "White"]
colors.append("Cyan")
print(colors)
import string
print(list(string.ascii_letters))
print(string.digits)
print(string.punctuation... |
a284d342205f358abf46a778680e060ac193cc3d | senthilkumarr2212/python | /Day1.py | 876 | 3.96875 | 4 | # Task 1
names = ["john", "jake", "jack", "george", "jenny", "jason"]
for name in names:
if len(name) < 5 and 'e' not in name:
print('Printing Unique Names : ' +name)
# Task 2
str = 'python'
print('c' + str[1:])
# Task 3
dict = {"name": "python", "ext": "py", "creator": "guido"}
print(dict... |
6e12c901e0706b05f3ac67dd2e0c5df3215855bf | gothaur/the_game | /projectile.py | 2,174 | 3.9375 | 4 | import pygame
from pygame.sprite import Sprite
from penguin import Enemy
class Projectile(Sprite):
def __init__(self, settings, penguin, f_img, b_img):
"""
:param penguin: penguin which fired projectile
:param f_img: image faced forward
:param b_img: image faced backward
"... |
8e4078ae8d366d00cc83fdb60acfed096f252a1e | VINITHAKANDASAMY/python_programming | /hunter/upper.py | 74 | 3.890625 | 4 | list = ['vibi','john','peter']
for item in list:
print(item.upper())
|
90472457e00f25dfca4f589b398a60f47cd311c8 | VINITHAKANDASAMY/python_programming | /player/vowel.py | 151 | 4.03125 | 4 | v1=input("enter an alphabet")
if v1 in ('a','e','i','o','u'):
print("given alphabet is vowel")
else:
print("given alphabet is consonant")
|
ce9090dbbbc2431d045c37550b6704403938a23b | justinchoys/learn_python | /ex43.py | 2,904 | 3.75 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This is not a configured scene, use a subclass")
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.... |
3ff0b5ab4f45e5763fcc28aef525111e513cd5e9 | maisuto/address | /takeaddress.py | 929 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
from makeaddress import MakeAddress
class TakeAddress(MakeAddress):
def make_new_csv(self, csvdic):
newcsv = []
top_list = [
'name',
'phone',
'mobile_pyone',
'zip code',
... |
edace158002f255b7bbfd8d5708575912ab065d9 | Varsha1230/python-programs | /ch4_list_and_tuples/ch4_lists_and_tuples.py | 352 | 4.1875 | 4 | #create a list using[]---------------------------
a=[1,2,4,56,6]
#print the list using print() function-----------
print(a)
#Access using index using a[0], a[1], a[2]
print(a[2])
#change the value of list using------------------------
a[0]=98
print(a)
#we can also create a list with items of diff. data types
c=[45,... |
ccade5b4083c03f67193c304ed68f470f91ec980 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_3_multiple_inheritance.py | 496 | 3.875 | 4 | class Employee:
company = "visa"
eCode = 120
class Freelancer:
company = "fiverr"
level = 0
def upgradeLevel(self):
self.level =self.level + 1
class Programmer(Employee, Freelancer): #multiple inheritance
name = "Rohit"
p = Programmer()
print(p.level)
p.upgradeLevel()
print(p.leve... |
a12737d07ea5a4ac4268d50070a09be8018fd499 | Varsha1230/python-programs | /ch2_variables_and_dataType/ch2_prob_04_comparision_operator.py | 138 | 3.796875 | 4 | # use comparision operator to find out whether a given variable 'a' is greater than 'b' or not... take a=34 and b=80
a=34
b=80
print(a>b) |
194b4560ae2532e13e65a0f4b3664149578c3293 | Varsha1230/python-programs | /ch13_advance_python2.py/ch13_3_format.py | 265 | 3.640625 | 4 | name = "Harry"
channel = "Code with harry"
type = "coding"
#a = f"this is {name}"
#a = "this is {}" .format(name)
# a = "this is {} and his channel is {}" .format(name, channel)
a = "this is {0} and his {2} channel is {1}".format(name, channel, type)
print(a) |
360ec7c1039125c324248437f72dc44eb56d59a5 | Varsha1230/python-programs | /ch8_functions_and_recursion.py/ch8_prob_04.py | 580 | 3.953125 | 4 | # n! = (n-1)! * n
# sum(n) = sum(n-1) + n
#-- there is no exit/stop statement in this loop------------------------------------------------
# def sum(n):
# return (sum(n-1) + n)
# num = int(input("please enter a no.: "))
# add = sum(num)
# print("the sum of n natural numbers is: " + str(add))
#----------------... |
2765a047df4e0eace928604f2d0dd53cafb7e36f | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_prob_05.py | 181 | 3.984375 | 4 | l1 = ["varsha", "ankur", "namrata"]
name = input("please enter your name:\n")
if name in l1:
print("your name is in the list")
else:
print("your name is not in the list") |
e05e4075af111c11cfe2b2f55dfc46ae0c13aa3d | Varsha1230/python-programs | /ch11_inheritance.py/ch11_6_class_method.py | 508 | 3.703125 | 4 | class Employee:
company = "camel" # class-attribute
location = "Delhi" # class-attribute
salary = 100 # class-attribute
# def changeSalary(self, sal):
# self.__class__.salary = sal # dunder class (we can use this for same task,but it is related to object, here oue motive ... |
5e8c0be79943cb840b77adfc98efbb1664d09972 | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_5_logical_operator.py | 229 | 3.96875 | 4 | age=int(input("enter your age: "))
if(age>34 and age<56):
print("you can work with us")
else:
print("you can't work with us")
print("Done")
if(age>34 or age<56):
print("you can with us")
else:
print("djvbvjnd") |
c43b35b690a329f582683f9b406a66c826e5cabf | Varsha1230/python-programs | /ch3_strings/ch3_prob_01.py | 435 | 4.3125 | 4 | #display a user entered name followed by Good Afternoon using input() function--------------
greeting="Good Afternoon,"
a=input("enter a name to whom you want to wish:")
print(greeting+a)
# second way------------------------------------------------
name=input("enter your name:")
print("Good Afternoon," +name)
#---... |
5b3ef497693bc27e3d5fee58a9a77867b8f18811 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_1_inheritance.py | 731 | 4.125 | 4 | class Employee: #parent/base class
company = "Google"
def showDetails(self):
print("this is an employee")
class Programmer(Employee): #child/derived class
language = "python"
# company = "YouTube"
def getLanguage(self):
print("the language is {self.language}")
def s... |
d6fd821221299ad77efb685c4c82b4b485bec16d | vivek-2000/DSA | /Array/K_sorted_array.py | 401 | 3.53125 | 4 | from heapq import heappop, heappush, heapify
def sort_k(arr,n,k):
heap=arr[:k+1]
heapify(heap)
tar_ind=0
for rem_elmnts_index in range(k+1,n):
arr[tar_ind]=heappop(heap)
heappush(heap, arr[rem_elmnts_index])
tar_ind+=1
while heap:
arr[tar_ind]=heappop(heap)
tar_ind+=1
k=3
ar... |
4d669245dc188f77447bac45eaa554bba7feab52 | BestNico/Leetcode_answer | /1431/1431.py | 288 | 3.625 | 4 | from typing import List
class Solution(object):
def kidWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
biggestEle = max(candies)
subList = [biggestEle - i for i in candies]
return [True if i <= extraCandies else False for i in subList] |
b4591e299bcaa0f177ab2da26aaa98dd3599321f | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no21reOrderOddEven.py | 1,064 | 3.640625 | 4 | def reOrderOddEven_1(str):
length = len(str)
if length == 0:
return
i = 0
j = length - 1
while i < j:
#前面的为奇数,遇到偶数停止
while i < j and (str[i] & 0x1) != 0:
i += 1
while i < j and (str[j] & 0x1) == 0:
j -= 1
if i < j:
temp = ... |
dff95a393d887cc6f44d3480f02dc8064e71bdc0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no40getLeastNumbers.py | 538 | 3.75 | 4 | import maxHeap
def getLeastNumbers(arr,k):
if not k or not arr or k < 1 or len(arr) < k :
return
heap = maxHeap.MaxHeap(arr[:k])
for item in arr[k:]:
if item < heap.data[0]:
heap.extractMax()
heap.insert(item)
for item in heap.data:
print(item)
if __name... |
40ceb70ecc8460fff034f6bbc53cc7cba2267938 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no42findGreatestSumOfSubArray.py | 400 | 3.640625 | 4 | def findSubarray(nums):
invalidInput = False
if not nums or len(nums) <= 0:
invalidInput = True
return 0
invalidInput = False
curSum = 0
greastestSum = float('-inf')
for i in nums:
if curSum < 0:
curSum = i
else:
curSum += i
if ... |
fc39fba8f6f26ad7ed138dd93379482053578c20 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no53getFirstK.py | 1,411 | 4 | 4 | # 巧用二分查找在排序数组中找一个特定数字
def getNumberOfK(data,length,k):
number = 0
if data and length > 0:
first = getFirstK(data,length,k,0,length-1)
last = getLastK(data,length,k,0,length-1)
if first > -1 and last > -1:
number = last - first +1
return number
def getFirstK(data,leng... |
29d80bdd038da385e916ebd1a02a0e200f9b7378 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no7reconstructBiTreev2.py | 4,501 | 3.75 | 4 | class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.rightChild = None
self.leftChild = None
def insertLeftChild(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
... |
a806ec1eaa2bd542dda64e9dfee12847b32771c1 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no14cutstring.py | 1,020 | 3.609375 | 4 | #大问题->小问题->小问题最优解组合->大问题最优解----->可以用动态规划
def maxProductAfterCutting_DP(length):
if length <2:
return 0
if length == 2:
return 1
if length == 3:
return 2
products = [0,1,2,3]
max = 0
for i in range(4,length+1):
max = 0
products.append(0)
for j in ... |
b03562bddb37cc22ce4c2aba658d8c368becb2c0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no39moreThanHalfNum_1.py | 499 | 3.546875 | 4 | def MoreThanHalfNum(numbers,length):
# 判断输入符合要求
if not numbers and length<=0:
return 0
result = numbers[0]
times = 1
for i in range(1,length):
if times == 0:
result = numbers[i]
times = 1
elif numbers[i] == result:
times += 1
else:... |
266cab3b9773bbca24a1449cd305e27e3b82ab59 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no55isBalanced2.py | 531 | 3.78125 | 4 | def isBalanced(proot,depth):
if not proot:
depth = 0
return True
leftDepth = rightDepth = -1
# 递归,一步步往下判断左右是否是平衡树,不是就返回,是的话记录当前的深度
if isBalanced(proot.left,leftDepth) and isBalanced(proot.right,rightDepth):
diff = leftDepth - rightDepth
if diff <= 1 and diff >= -1:
... |
4d834531037456b1cac14a8fb3d72df707764355 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no17print_n_num_v2.py | 1,616 | 3.625 | 4 | def PrintToMAxDIgits(n):
if n <= 0:
return
number = [0]*(n)
while(not Increment(number)):
PrintNumber(number)
def Increment(number:[int]):
isOverflow = False
nTakeOver = 0
length = len(number)
#每一轮只计一个数,这个循环存在的意义仅在于判断是否有进位,如有进位,高位就可以加nTakeove
# 以isOverflow判断是否最高位进位,最高... |
a2dc98deb96601ebc3b9643d539a31d7835853cc | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no34findPath.py | 1,041 | 3.703125 | 4 | # 找到二叉树中某一值和的路径
def findPath(root,expectedSum):
if not root:
return []
result = []
def findPathCore(root,path,currentSum):
currentSum += root.val
path.append(root)
ifLeaf = not (root.left or root.right)
# 是叶子节点,且和为目标和
if ifLeaf and currentSum==expectedSum:
... |
f1e92e70cfd8d1757967e5ff3d56883ac269227a | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no16pow.py | 1,535 | 3.796875 | 4 | class Solution:
g_Invalid_input = False
def power(self,base,exponent):
if base == 0 and exponent < 0:
self.g_Invalid_input = True
return 0
absExponent = exponent
if exponent < 0:
absExponent = -exponent
result = self.powerCal_2(base,absExpon... |
1c424c81442732b5b5c2d7616919ac81bc4dfcd2 | mittgaurav/Pietone | /power_a_to_b.py | 637 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 13:57:40 2019
@author: gaurav
cache half power results. O(log n)
"""
def power(a, b):
"""power without pow() under O(b)"""
print("getting power of", a, "for", b)
if a == 0:
return 0
if b == 1:
return a
elif b == 0:
return... |
0042a3255312843743e1e257face5599acc063d8 | mittgaurav/Pietone | /skyline.py | 5,927 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 22:56:07 2019
@author: gaurav
"""
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
def skyline(arr):
"""A skyline for given
building dimensions"""
now = 0
while now < len(arr):
start, height, end = arr[now]
print(start, height)... |
7d4cb2013282e283ff91dd0762490ff962b5eeec | mittgaurav/Pietone | /common_elem_n_arrays.py | 1,938 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 02:00:55 2019
@author: gaurav
"""
def common_elem_in_n_sorted_arrays(arrays):
"""find the common elements in
n sorted arrays without using
extra memory"""
if not arrays:
return []
result = []
first = arrays[0]
for i in first: # f... |
7bad8a4482385e6b355d8cd9bd3e303c6c8e8ed5 | mittgaurav/Pietone | /sudoku.py | 2,787 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 02:12:35 2020
@author: gaurav
"""
import math
from functools import reduce
from operator import add
board = [
[4, 3, 0, 0],
[1, 2, 3, 0],
[0, 0, 2, 0],
[2, 1, 0, 0]
]
def _check(board, full=False):
N = len(board)
def ... |
853936e6f2e717da65ad845d1e7cfef1b52d630d | mittgaurav/Pietone | /wildcard_pattern_matching.py | 2,518 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 19:24:26 2018
@author: gaurav
"""
def wildcard_matching_no_dp(string, pat):
"""tell whether pattern represents
string as wildcard. '*' and '?'"""
if not pat:
return not string
if not string:
for i in pat:
i... |
9119084ee6a7f510f481c56f72d6524edbaefe58 | mittgaurav/Pietone | /battleship.py | 1,820 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 13:05:37 2020
leetcode.com/discuss/interview-question/538068/
@author: gaurav
"""
def get_tuple(N, this):
"""given row digits and col char
returns the unique tuple number"""
row, col = get_row_col(this)
return get_tuple_2(N, row, col)
def get_row_c... |
51dcdbe9d528b1c4f5de18838e678b24ccff3a07 | mittgaurav/Pietone | /largest_square_submatrix.py | 4,727 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 01:26:49 2018
@author: gaurav
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
for each elem, collect four values:
* Continuous true horizontally
* C... |
eb1bf679c48940bbc2bf157675287e9c71f14e7a | mittgaurav/Pietone | /tree.py | 6,327 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
tree.py
- Tree (Binary Tree)
- Bst
"""
class Tree():
"""Binary tree"""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def max_level(self):
"""height of tree"""
return max(self.l... |
e586a1f9e60722c8aa1949a9c1aa9f2404fa683e | PhirayaSripim/Python | /Week2/test2.6.py | 1,019 | 3.765625 | 4 | price=[[25,30,45,55,60],[45,45,75,90,100],[60,70,110,130,140]]
car = [" 4 ล้อ "," 6 ล้อ ","มากกว่า 6 ล้อ "]
print( " โปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์\n---------------")
print(" รถยนต์ 4 ล้อ กด 1\nรถยนต์ 6 ล้อ กด 2\nรถยนต์มากกว่า 6 ล้อ กด 3\n")
a=int(input("เลือกประเภทยานพหนะ : "))
print(car[a-1])
print("ลา... |
2abbde87690a9670e0dd672daa22ae9e4c7afeb7 | PhirayaSripim/Python | /Week2/test2.3.py | 126 | 3.609375 | 4 | friend= ['jan','cream','phu','bam','orm','pee','bas','kong','da','james']
friend[9]="may"
friend[3]="boat"
print (friend[3:8]) |
184bc3285b8669680b305faafcb8099d2464b9cd | renatomayoral/ClickAutomation | /WAtest.py | 1,558 | 3.75 | 4 | #WhatApp Desktop App mensage sender
import pyautogui as pg
import time
print(pg.position())
screenWidth, screenHeight = pg.size() # Get the size of the primary monitor.
currentMouseX, currentMouseY = pg.position() # Get the XY position of the mouse.
pg.moveTo(471, 1063) # Move the mouse to XY coordinates.
pg.click(... |
e0e4e39fd90e6e7bb8024ff3636229043ae63b40 | eddylongshanks/repl-code | /Week 1 Example Code/_week1-program.py | 1,984 | 4.125 | 4 |
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __str__(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __repr__(self):... |
40f6f3affe328fbe149f7766be75a7774acbf709 | careywalker/networkanalysis | /CommunityEvaluation/utilities/calculate_modularity.py | 1,118 | 3.984375 | 4 | """This uses Newman-Girwan method for calculating modularity"""
import math
import networkx as nx
def calculate_modularity(graph, communities):
"""
Loops through each community in the graph
and calculate the modularity using Newman-Girwan method
modularity: identify the set of nodes that inte... |
c174f8baea2ae06e4772c33599bc0de062bef842 | robertvari/pycore-210612-alapok-1 | /07_lists.py | 620 | 4 | 4 | my_name = "Tom"
my_age = 34
# indexes: 0 1 2 3
my_numbers = [23, 56, 12, 46]
# mixed list
my_list = [
"Robert",
"Csaba",
"Christina",
32,
3.14,
my_name,
my_age,
my_numbers
]
# print(my_list[7][-1])
# print(my_list[0])
# add items to list
my_numbers.append("Csilla")
print(m... |
c5b88df5ed908065732058806f386d7b9f723d7e | robertvari/pycore-210612-alapok-1 | /12_list_comprehension.py | 190 | 3.5 | 4 | number_list = [1, 2, 3, 4, 5]
# result_list = []
#
# for i in number_list:
# result_list.append(i+100)
result_list = [ i*i for i in number_list ]
print(number_list)
print(result_list) |
2fc3dc75d5a35af8a8890e8b2f7613ef00bcefbd | robertvari/pycore-210612-alapok-1 | /08_sets.py | 405 | 3.828125 | 4 | # cast list into a set
my_list = [1, 2, 3, "csaba", 4, "csaba", 2, 1]
my_set = set(my_list)
# print(my_set)
# add items to set
new_set = {1, 2, 3}
# print(new_set)
new_set.add(4)
# print(new_set)
# add more items to set
new_set.update([5, 6, 7, 8])
# print(new_set)
new_set.remove(5)
new_set.discard(7)
# print(new_... |
d0bad2d90258f1654b588b956d926a2203ea59a3 | dinoivusic/Python-Challenges | /day17.py | 351 | 3.515625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
longest = ""
if len(strs) < 1:
return longest
for index, value in enumerate(strs[0]):
longest += value
for s in strs[1:]:
if not s.startswith(longest):
return longest[... |
a9f01e9a879b0b939d1a8ec99915cc0ec7999fb9 | dinoivusic/Python-Challenges | /day55.py | 275 | 3.515625 | 4 | def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
if len(strs) == 0:
return ans
for i in range(len(min(strs))):
can = [s[i] for s in strs]
if (len(set(can)) != 1):
return ans
ans += can[0]
return ans
|
2d3f6ad78b0fccadc9cb575780e9268d9fa94680 | dinoivusic/Python-Challenges | /day24.py | 597 | 3.578125 | 4 | #One line solution
def cakes(recipe, available):
return min(available.get(k, 0)/recipe[k] for k in recipe)
#Longer way of solving it
def cakes(recipe, available):
new = []
shared = set(recipe.keys() & set(available.keys()))
if not len(shared) == len(recipe.keys()) and len(shared) == len(available.keys()... |
03e81f455a5d2bab66078ff4c210da966c8958de | dinoivusic/Python-Challenges | /day35.py | 222 | 3.609375 | 4 | def overlap(arr,num):
count = 0
for i in range(len(arr)):
if arr[i][0] == num or arr[i][1] == num:
count+=1
if num > arr[i][0] and num < arr[i][1]:
count+=1
return count
|
b220260f33cd97cb8f1216bdad813af73adc0137 | dinoivusic/Python-Challenges | /day64.py | 527 | 4.03125 | 4 | #Create a function that return the output of letters multiplied by the int following them
import re
def multi(arr):
chars = re.findall('[A-Z]', arr)
digits = re.findall('[0-9]+', arr)
final= ''.join([chars[i]* int(digits[i]) for i in range(0,len(chars)-1)]) + chars[-1]
return final
print(multi('A4B5C2')... |
1ccb257f02a30bb948940670626b3a713e863934 | dinoivusic/Python-Challenges | /day18.py | 173 | 3.515625 | 4 | class Solution:
def isPalindrome(self, strs):
s = [c.lower() for c in strs if c.isalnum()]
if s == s[::-1]:
return True
return False
|
dd054af1ca07948f20cc5e126da501ad227da02e | aqueed-shaikh/submissions | /7/islam_yaseen/app.py | 741 | 3.5 | 4 |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """<h1>This is the home page </h1>
<p><a href="/about">about</a> page</p>
<p><a href="/who">who</a> page</p>
<p><a href="http://www.youtube.com/watch?v=unVQT_AB0mY">something</a> to watch</p>
"""
@app.route("/who")
@app.route("/wh... |
c12604df95e476146dd984c1b6ddf7ae3453492d | aqueed-shaikh/submissions | /7/han_jason/HW1.py | 1,130 | 3.53125 | 4 | #!/usr/bin/python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello World.</h1>\n<h2>More headings</h2>\n<b>Bold stuff</b>"
@app.route("/about")
def about():
return "<h1>I am cookie monster. Nom nom nom nom.</h1>"
@app.route("/color")
def color():
return """
<bo... |
bdeab1439c982ce0a142980a1bd868a00caac17f | aqueed-shaikh/submissions | /6/lin_jing/HW1.py | 449 | 4.0625 | 4 | #!/usr/bin/python
#Factorization of Input Number
def main():
try:
a = int(raw_input("Enter a number: "))
except ValueError:
print("That is not a number!")
return 0
String = "The Factors of %d are " % (a)
Counter = int(a**.5)
for i in range(2, Counter):
if(a == (a ... |
362923f31d00353c0ddd2640101ae9d80e427e77 | aqueed-shaikh/submissions | /6/kozak_severyn/3_madlibs/app.py | 871 | 3.609375 | 4 | #!/usr/bin/python
"""
Team: Severyn Kozak (only)
app, a Python Flask application, populates a template .html
file's empty fields with a randomized selection of words.
Think madlibs.
"""
from flask import Flask, render_template
from random import sample
app = Flask(__name__)
#dictionary of word arrays, by type
word... |
865e77608165c48b254aa4fbbfbcee48e65c79c2 | aqueed-shaikh/submissions | /6/kurtovic_benjamin/stuff.py | 2,061 | 3.9375 | 4 | #! /usr/bin/env python
# I'm not sure how to demonstrate my knowledge best, so here's an example of
# some really esoteric concepts in the form of metaclasses (because I can).
import sys
import time
class CacheMeta(type):
"""Caches the return values of every function in the child class."""
def __new__(cls, n... |
66d0e4aed34979127e18bf88bd2010461028acc4 | aqueed-shaikh/submissions | /7/herman_hunter/hermanroar.py | 433 | 3.71875 | 4 | import random
<<<<<<< HEAD
for x in range(0, random.randrange(0, 999)):
print "I AM HERMAN HEAR ME ROAR"
print "meow"
=======
total_fear = 0
for x in range(0, random.randrange(1, 999)):
print "I AM HERMAN NUMBER %i HEAR ME ROAR"%(x*x)
num = random.randrange(100, 450)
print "fear level: %i"%num
to... |
2ca884ecd48eb25176d5f0a315371e9464710f89 | aqueed-shaikh/submissions | /7/chung_victoria/test.py | 576 | 3.625 | 4 | #!/usr/bin/python
def problemOne():
sum = 0
i = 1
while i < 1000:
if i % 3 == 0 or i % 5 == 0:
sum += i
i+=1
print sum
def problemTwo():
sum = 2
a = 1
b = 2
term = 2
while term <= 4000000:
term = a + b
a = b
b = term
if term % 2 == 0:
sum += term
print sum
def problemThree():
answe... |
34067bf118ee70d6f07d4499db7015d3b4dee808 | aqueed-shaikh/submissions | /6/Luo_Jason/Hello.py | 414 | 3.890625 | 4 | #!/usr/bin/python
def fact (n):
if n == 0:
return 1
else:
return n * fact(n-1)
print fact (5)
def fib (n):
count = 0
if n == 1:
return count + 0
elif n == 2:
return count + 1
else:
return count + fib(n-1) + fib(n-2)
print fib(10)
def isPrime(n):
l... |
c25ee297552465456ca50c12ce5df934c9d399bf | IsaacMarovitz/ComputerSciencePython | /MontyHall.py | 2,224 | 4.28125 | 4 | # Python Homework 11/01/20
# In the Monty Hall Problem it is benefical to switch your choice
# This is because, if you switch, you have a rougly 2/3 chance of
# Choosing a door, becuase you know for sure that one of the doors is
# The wrong one, otherwise if you didnt switch you would still have the
# same 1/3 chance... |
d5abb3795766226e51caba8f079af04c9c5cb7cf | IsaacMarovitz/ComputerSciencePython | /IfStatements2.py | 1,219 | 3.921875 | 4 | # Python Homework 09/16/2020
import sys
try:
float(sys.argv[1])
except IndexError:
sys.exit("Error: No system arguments given\nProgram exiting")
except ValueError:
sys.exit("Error: First system argument must be a float\nProgram exiting")
user_score = float(sys.argv[1])
if user_score < 0 or user_score > ... |
155a6195c974de35a6de43dffe7f1d2065d40787 | IsaacMarovitz/ComputerSciencePython | /Conversation2.py | 1,358 | 4.15625 | 4 | # Python Homework 09/09/2020
# Inital grade 2/2
# Inital file Conversation.py
# Modified version after inital submisions, with error handeling and datetime year
# Importing the datetime module so that the value for the year later in the program isn't hardcoded
import datetime
def userAge():
global user_age
us... |
bf00b432183b7c83bed5de8f1f78ce59322e1889 | IsaacMarovitz/ComputerSciencePython | /Minesweeper.py | 10,535 | 3.59375 | 4 | # Isaac Marovitz - Python Homework 02/10/20
# Sources: N/A
# Blah blah blah
# On my honour, I have neither given nor received unauthorised aid
import sys, random, os, time
# Declaring needed arrays
mineGrid = []
gameGrid = []
# Clear the terminal
def clear():
if os.name == "nt":
os.system('cls')
else... |
6cad478212cb9a345107e33659dd716f49e674a0 | daniromero97/Python | /e025-StringMethods/StringMethods.py | 1,049 | 3.75 | 4 | print("##################### 1 #####################")
sequence = ("This is a ", "")
s = "test"
sentence = s.join(sequence)
print(sentence)
sequence = ("This is a ", " (", ")")
sentence = s.join(sequence)
print(sentence)
"""
output:
This is a test
This is a test (test)
"""
print("##################### 2 ###... |
00e97c511c9114dd8cb32f68a3ce3323cfd7ebf4 | daniromero97/Python | /e004-Tuples/Tuples.py | 1,380 | 3.875 | 4 | print("########################### 1 ############################")
my_tuple = ("value 1", "value 2", "value 3", ["value 4.1", "value 4.2"], 5, ("value 6.1", "value 6.2"))
print(my_tuple)
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[2:5])
"""
Output:
('value 1', 'value 2', 'value 3', ['value 4.1', 'value... |
ddbeef1a26cb8b570434e5e595dd1421a81a5625 | daniromero97/Python | /e013-Encapsulation/OOP.py | 728 | 4.03125 | 4 | class Person(object):
def __init__(self, name, height, weight, age):
self.__name = name
self.__height = height
self.__weight = weight
self.__age = age
def properties(self):
print("Name: %s, height: %.2f m, weight: %.1f kg, age: %d years old" % (self.__name, self.__height... |
a5eaef2210158228b7681822194cb4ae04dfd677 | daniromero97/Python | /e006-ControlFlowStatements/ControlFlowStatements.py | 1,780 | 3.9375 | 4 | print("########################### 1 ############################")
a = 0
while a<5:
print(a)
a+=1
"""
Output:
0
1
2
3
4
"""
print("########################### 2 ############################")
a = 0
while True:
a += 1
print(a)
if a == 3:
break
"""
Output:
1
2
... |
7dcde1f414b5214079c7516810a9d96094538107 | daniromero97/Python | /e033-Datetime/Main.py | 3,097 | 3.734375 | 4 | import datetime
print("###################### 1 ######################")
print(datetime.MINYEAR)
"""
output:
1
"""
print("###################### 2 ######################")
print(datetime.MAXYEAR)
"""
output:
9999
"""
print("###################### 3 ######################")
print(datetime.date.today())
pr... |
b574c115fc9c68ca068880dfb5b2a247f985d8c2 | xiong-zh/Arithmetic | /sort/radix.py | 685 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020/6/15
# @Author: zhangxiong.net
# @Desc :
def radix(arr):
digit = 0
max_digit = 1
max_value = max(arr)
# 找出列表中最大的位数
while 10 ** max_digit < max_value:
max_digit = max_digit + 1
while digit < max_digit:
temp = [[] for... |
774ce49dd157eca63ab05d74c0d542dd33b4f14a | Nyame-Wolf/snippets_solution | /codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py | 629 | 4.5 | 4 | Summation
Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer
greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
tests
test.describe('Summation')
test.it('Should return the correct t... |
389b09b0bcc2596b3847791765a47127b4f97f13 | McBonB/text01_lf | /t.py | 1,958 | 3.65625 | 4 | """
最远足迹
莫探险队对地下洞穴探索
会不定期记录自身坐标,在记录的间隙中也会记录其他数据,探索工作结束后,探险队需要获取到某成员在探险过程中,对于探险队总部的最远位置
1.仪器记录坐标时,坐标的数据格式为 x,y
x和y——》0-1000
(01,2)(1,01)
设定总部位置为0,0
计算公式为x*(x+y)*y
"""
import re,math
s = "abcccc(3,10)c5,13d(1$f(6,11)sdf(510,200)adas2d()(011,6)" #原始字符串
#print(re.findall(r'[^()a-z]+', s))
pattern = re.compile(r'\(([0-9]{1... |
a1e2cbfe73c8889bca05dd05a02ef1789bb61a68 | Bellroute/python_class | /day0911/example2_6.py | 304 | 4.09375 | 4 | def sumDigits(n):
result = 0
while(n != 0):
result += n % 10
n //= 10
return result
def main():
n = int(input('Enter a number between 0 and 1000 : '))
result = sumDigits(n)
print('The sum of the digits is', result)
if __name__ == "__main__":
main() |
483a180d35ed99b23cd82163b47fe2f78e18148c | Bellroute/python_class | /day1002/example5_19.py | 253 | 3.703125 | 4 | inputValue = int(input("Enter the number of lines: "))
for i in range(1, inputValue + 1):
line = " "
for j in range(i, 0, -1):
line += str(j) + " "
for j in range(2, i + 1):
line += str(j) + " "
print(line.center(60))
|
282434fc39e19a79f8ce6b7ca4b142a9a61aed9d | Bellroute/python_class | /someday/factorize.py | 457 | 3.765625 | 4 | import prime
def factorize(n):
factor = []
while True:
m = prime.isPrime(n)
if m == n:
break
n //= m
return factor
def main():
n = int(input('type any number : '))
result = prime.isPrime(n)
if result:
print(n, '은 소수야!')
else:
print(n... |
d920f009c5aa6209e9daf681197d9de7ca73a1f5 | acttx/Python | /Comp Fund 2/Lab4/personList.py | 1,811 | 3.59375 | 4 | import csv
from person import Person
from sortable import Sortable
from searchable import Searchable
"""
This class has no instance variables.
The list data is held in the parent list class object.
The constructor must call the list constructor:
See how this was done in the Tower class.
Code ... |
e96466aa5575c4b719780a0c2585c270e6f2fb16 | acttx/Python | /Comp Fund 2/Lab9/road.py | 8,547 | 3.859375 | 4 | import math
from edge import Edge
from comparable import Comparable
"""
Background to Find Direction of Travel:
If you are traveling:
Due East: you are moving in the positive x direction
Due North: you are moving in the positive y direction
Due West: you are moving in the negative x direction
Due South: you are mo... |
5fbadcc16da279332b3cf317155a683f3744e93d | acttx/Python | /Comp Fund 2/Lab4/person_main.py | 3,160 | 4.1875 | 4 | from comparable import Comparable
from personList import PersonList
from person import Person
from sort_search_funcs import *
def main():
"""
This main function creates a PersonList object and populates it
with the contents of a data file containing 30 records each
containing the first name and birthda... |
6b789ec1822bfeef3b0518c2114a51dee2425424 | acttx/Python | /Comp Fund 2/Lab8/charCount.py | 530 | 3.75 | 4 | from comparable import Comparable
class CharCount(Comparable):
def __init__(self, char, count):
self.char = char
self.count = count
def get_char(self):
return self.char
def get_count(self):
return self.count
def compare(self, other_charCount):
if self.char <... |
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f | DanielOram/simple-python-functions | /blueberry.py | 2,627 | 4.625 | 5 | #Author: Daniel Oram
#Code club Manurewa intermediate
#This line stores all the words typed from keyboard when you press enter
myString = raw_input()
#Lets print out myString so that we can see proof of our awesome typing skills!
#Try typing myString between the brackets of print() below
print()
#With our stri... |
15cc2f889516a57be1129b8cad373084222f2c30 | viniciuschiele/solvedit | /strings/is_permutation.py | 719 | 4.125 | 4 | """
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Question:
Given two strings, write a method to decide if one is a permutation of the other.
"""
from unittest import TestCase
def is_permutation(s1, s2):
if not s1 or not s2:
return False
if ... |
9332ac35cb63d27f65404bb86dfc6370c919c2be | viniciuschiele/solvedit | /strings/is_permutation_of_palindrome.py | 1,117 | 4.125 | 4 | """
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Palindrome is a word or phrase that is the same forwards and backwards.
A string to be a permutation of palindrome, each char must have an even count
and at most one char can have an odd count.
Question:
Given ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.