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 |
|---|---|---|---|---|---|---|
181f9bb8e3876bd15fcb91b2ac9b6da02669ce40 | titusjan/pepeye | /examples/small.py | 552 | 3.546875 | 4 | from __future__ import print_function
from time import sleep
def myfun1():
print (" myfun1")
sleep(0.25)
myfun3()
def myfun2(n):
print (" myfun2")
sleep(0.15)
if n == 0:
return
else:
myfun3()
myfun2(n-1)
def myfun3():
print (" myfun3")
sleep(... |
bf533cf98e56396f5e9696ac237af5cf4586d06a | harsha-94/harsha-project | /harsha-project/data_stream/twitter/tweet.py | 1,110 | 3.609375 | 4 | __author__ = 'thecreator232'
from exceptions import UserNotFoundException
class Tweet(object):
def __init__(self, tweet):
self.tweet = tweet
@staticmethod
def text(self):
"""Returns the text of a tweet.
Returns:
unicode formatted string.
"""
return se... |
660848ae5488cb9326331d9aa4ac4aab71d73632 | Kpsmile/Learn-Python | /Basic_Programming/ListsComprehension_basics.py | 951 | 4.125 | 4 | sentence='My Name is Kp Singh'
def eg_lc(sentence):
vowel='a,e,i,o,u'
return''.join(l for l in sentence if l not in vowel)
print"List comprehension is" + eg_lc(sentence)
"""square of only even numbers in the list
def square_map(arr):
return map(lambda x: x**2, arr)
print ["List comprehension i... |
832de19c8b9ab75f412d3f0ebc57f6791bc0d15f | Kpsmile/Learn-Python | /Basic_Programming/Collections.py | 1,580 | 4.53125 | 5 | a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that return... |
d9b3cbdec02329fadaa14cab8a17bd253a14469a | supermitch/Advent-of-Code | /2016/21/twenty_one.py | 3,185 | 3.609375 | 4 | from collections import deque
def parse(line):
parts = line.split()
if 'move' in parts:
return ('move', int(parts[2]), int(parts[5]))
elif 'swap letter' in line:
return ('swap', parts[2], parts[5])
elif 'swap position' in line:
return ('swap_pos', int(parts[2]), int(parts[5]))
... |
49f3e309c00eb4717e7485595e5c2cbc745ec112 | supermitch/Advent-of-Code | /2017/23/twenty_three.py | 523 | 3.671875 | 4 | #!/usr/bin/env python
def not_prime(n):
for i in range(2, n): # Ignoring 1 * n
if n % i == 0:
return True
return False
def run(debug=True):
if debug:
b = 65
c = 65
return (b - 2) * (c - 2)
else:
return sum(not_prime(b) for b in range(106500, 12350... |
6d07ddc90e53979b46f87fe9e4cf48a602499476 | supermitch/Advent-of-Code | /2020/05/five.py | 829 | 3.53125 | 4 | def seat_id(seat):
rows = list(range(128))
for k in seat[:7]:
n = len(rows)
if k == 'F':
rows = rows[:n // 2]
elif k == 'B':
rows = rows[n // 2:]
cols = list(range(8))
for k in seat[7:]:
n = len(cols)
if k == 'L':
cols = cols[:n... |
f30a4352bf060c56a1e1f623da96e35eeb6671ad | supermitch/Advent-of-Code | /2017/06/six.py | 789 | 3.75 | 4 | def reallocate(memory):
n = len(memory)
blocks = max(memory)
i = memory.index(blocks) # Returns first high bank
memory[i] = 0 # Reset current bank
while blocks > 0:
memory[(i + 1) % n] += 1
blocks -= 1
i += 1
return memory
def redistribute(memory):
count = 0
s... |
1b238cbf45478268d686289cdcf11751401b07c0 | supermitch/Advent-of-Code | /2019/03/three.py | 1,852 | 3.921875 | 4 | #!/usr/bin/env python
deltas = {
'R': (1, 0),
'L': (-1, 0),
'U': (0, 1),
'D': (0, -1),
}
def get_steps(moves, grid, junctions):
""" Calculate the steps it takes to get to each junction. """
x, y = 0, 0
steps = 0
taken = {}
for d, dist in moves:
dx, dy = deltas[d]
... |
7535941f17a2579cfa862b4587e7603e6d425a22 | aakashpatel12345/FDMMLTraining | /CreatingMyOwnLinearRegressor4.py | 1,727 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 18:16:35 2020
@author: Aakash
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv("./Datasets/admissions.csv")
#create independent and dependent variables
x=np.array(data["TOEFL Score"])
y=np.array(data["CGPA"... |
c986753668e3402c48f04c040db3b6f2b600a5a6 | craignicol/adventofcode | /2022/day.13.py | 3,284 | 3.609375 | 4 | #!/usr/bin/env python3
def execute():
with open('2022/input/day.13.txt') as inp:
lines = inp.readlines()
data = [l for l in lines]
is_in_order, is_correct, score = check_order(data)
return is_correct, score, decoder_key(data)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global te... |
5bbd579a75b947034e9bd1c8fde3f05bcb311315 | craignicol/adventofcode | /2020/day.8.py | 1,831 | 3.578125 | 4 | #!/usr/bin/env python3
example = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6"""
def execute():
with open('2020/input/8.txt') as inp:
lines = inp.readlines()
code = [l.strip() for l in lines if len(l.strip()) > 0]
return run_until_loop_or_exit(code)["accumulator"], flip_until... |
3bb34ee077779049883bb8b24e9a3919cac6ccab | craignicol/adventofcode | /2015/day.9.py | 2,084 | 3.921875 | 4 | #!/usr/bin/env python3
def execute():
with open('2015/input/9.txt') as inp:
lines = inp.readlines()
data = create_graph([l.strip() for l in lines if len(l.strip()) > 0])
return shortest_distance(data), longest_distance(data)
tests_failed = 0
tests_executed = 0
distances = """London to Dublin = 46... |
04f9c78547a4933543f5cc523883668eca04a5bd | craignicol/adventofcode | /2022/day.3.py | 1,859 | 3.53125 | 4 | #!/usr/bin/env python3
def execute():
with open('2022/input/day.3.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
return total_priority(data), total_badge_priority(data)
tests_failed = 0
tests_executed = 0
sample_input = """
vJrwpWtwJgWrhcsFMMfFFhFp
jq... |
526467e551c21f70ecd9cc7a09f42db83f74c965 | craignicol/adventofcode | /2021/day.13.py | 2,159 | 3.5 | 4 | #!/usr/bin/env python3
def execute():
with open('./input/day.13.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
paper = fold_paper(parse_origami(data))
render(paper)
return count_dots(paper)
tests_failed = 0
tests_executed = 0
def verify(a, b)... |
7e33ff5032f25a4a6963b7bfb42a72597dc96d4e | 59090939/ClassProjects | /Programming220/homeowrk10/CardSOLUTION.py | 706 | 3.515625 | 4 | # CardSOLUTION.py
# Author: RoxAnn H. Stalvey
# Modified by Pharr
class Card:
def __init__(self, value, suit):
if value >= 1 and value <= 13:
self.value = int(value)
else:
self.value = 1
if self.validSuit(suit):
self.suit = suit
else:
... |
8f7b4c6fb7836cffe5535ac1dec6cc55e8f90808 | 59090939/ClassProjects | /Programming220/salarytable.py | 518 | 3.890625 | 4 | def main():
startyear = input("What year did you start teaching? ")
currentyear = input("Up to what year would you like to calulate your salary? ")
salary = input("What was your starting salary? ")
percent = input("What is the percent increase of your annual salary? ")
years = currentyear - startyea... |
8ef71a1e59510cec01da5391765d439d40272f28 | 59090939/ClassProjects | /Programming220/ch. 2/conversion(cu-ml).py | 381 | 4.09375 | 4 | ## Conversion.py
## David Schirduan
## This code converts cups (input) to ml (output)
def main():
print "This program converts cups to Ml."
units = raw_input ("what are the resultant units: ")
cups = input ("How many cups does the recipe require: ")
ounces = cups * 8
milliliters = ounces * 2... |
eb79d415a647e67158ab5061466868ee339e626f | 59090939/ClassProjects | /Programming220/ch. 2/lab2/convertable.py | 350 | 4.0625 | 4 | # convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell (actually Zelle; see p. 28)
def main():
celsius = 0
for i in range(11):
fahrenheit = (9.0 / 5.0) * celsius + 32
print celsius,"degrees in Celsius is", fahrenheit, "degrees Fahrenheit."
... |
ae990b74675bc00138a6d6daf574aefa7181342b | wildfox24/Python | /klek_learn.py | 858 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
class Square(object):
width=0
height=0
def __init__(self, width, height):
self.width=width
self.height=height
def area(self):
return self.width * self.height
@staticmethod
def get_area(width, height):
return width *... |
8a3abf1a0099ab461244f251316de824c2012c0c | fernandotonon/Estrutura_Dados | /memoria.py | 1,405 | 3.9375 | 4 | class No:
def __init__(self, dado):
self.dado = dado
self.prox = None
def getDado(self):
return self.dado
def setDado(self, dado):
self.dado = dado
def getProx(self):
return self.prox
def setProx(self, prox):
self.prox = prox
class ListaE... |
88783965e0dd86b8a91c436d16b4f89267cdfa26 | surya-lights/Python_Cracks | /Random.py | 383 | 3.921875 | 4 | # To import random numbers within the range of 1 to 100
import random
print(random.randrange(1, 100))
# Conversion of numbers
x = 5 # int
y = 7.2 # float
z = 4j # complex
# convert from int to float:
a = float(x)
# convert from float to int:
b = int(y)
# convert from int to complex:
c = complex(x)
print(a)
p... |
3cace7075d865c99c2efb281d09234af707aff73 | surya-lights/Python_Cracks | /loop types.py | 409 | 3.859375 | 4 | # Inner loop
nums = [1, 2, 3]
for num in nums:
for letter in 'abc':
print(letter, nums)
# Build in function Range
for i in range(10):
print(i)
for i in range(1, 11):
print(i)
# While loop
x = 0
while x < 10:
print(x)
x += 1
# Break
x = 0
while x < 10:
if x := 5:
breakpoint()
... |
50febd52f27da540cc858944a37969ed932090c6 | surya-lights/Python_Cracks | /math.py | 293 | 4.15625 | 4 | # To find the highest or lowest value in an iteration
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
# To get the positive value of specified number using abs() function
x = abs(-98.3)
print(x)
# Return the value of 5 to the power of 4 is (same as 5*5*5*5):
x = pow(5, 4)
print(x)
|
0aee5541a76e0bca960fb14ebeb7177802d35c11 | surya-lights/Python_Cracks | /Key Func.py | 333 | 3.890625 | 4 | # Keys
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. keys())
# To show values
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. values())
# To display items
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(stude... |
72b3fa8b3d95a06f0c5f03e9f5601f43ba3ee843 | ajamesl/Exercises | /exercises1.py | 1,830 | 3.6875 | 4 | import math
c = "Come"
d = "home"
print c + " " + d
for i in range(10):
print "Hello"
for i in range (10):
print i
for i in range(1,11):
print i
for i in range(1,21):
print i**2
for i in range(1,100):
if i**2 < 1000:
print i**2
for i in range(1,200):
if i%3.0 == 0 and i%5.0 == 0:
... |
f8bbfd6363010700b233934b7392629138d29e66 | sanazjamloo/algorithms | /mergeSort.py | 1,395 | 4.4375 | 4 | def merge_sort(list):
"""
Sorts a list in ascending order
Returns a new sorted List
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time... |
a5630e21ec26ed53258db76f7a138f3fc520373e | hemanthsoma/BigData | /Assignment01/prime_numbers.py | 213 | 3.625 | 4 | def primeNumbers(limit):
for i in range(2,limit+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
limit = int(input())
primeNumbers(limit) |
1a60361248c7c4e56f5b5ee3ab04c0945ed94b2a | hemanthsoma/BigData | /Assignment02/ReverseInteger.py | 118 | 3.75 | 4 | number=int(input())
rev=0
while number!=0:
digit=number%10
rev=(rev*10)+digit
number//=10
print(rev) |
e60dddb767568b9c23308441b7c7016f6fc64554 | hemanthsoma/BigData | /Assignment02/ConvertTempCentToFahren.py | 113 | 3.75 | 4 | c = int(input('Enter temperature in Centrigrade'))
f = ((9*c)/5)+32
print('Temperature in Fahrenheit is: ',f)
|
c6b77a3fd1fa2d9140df334354dde84a3e58036a | hemanthsoma/BigData | /Assignment02/LinearSearch.py | 239 | 4.03125 | 4 | List=[1,2,3,4,5,6,7,8]
flag=0
search=int(input('Enter num to search'))
for i in range(len(List)):
if List[i]==search:
print('Element is found')
flag=1
break
if flag==0:
print('Element is not found') |
5febd76579e8ba3ba0619081584e7b1f0db970c0 | hemanthsoma/BigData | /Assignment01/sumOfMultiples.py | 251 | 3.71875 | 4 | def sumOfMultiplesOf3and5(limit):
l = []
i = 1
while True:
l.extend([3*i,5*i])
if 3*i==limit or 5*i==limit:
break
i+=1
return sum(l)
limit = int(input())
print(sumOfMultiplesOf3and5(limit)) |
8486feacc41df6f6930874661fddedee07114648 | Mahoro752/PROGRAM-THAT-ACCEPTS-THE-DIFFERENCE-OF-NUMBERS | /Defference of any number.py | 209 | 4.03125 | 4 | first_number = int(input("Enter first Number: "))
second_number = int(input("Enter Second number: "))
x = first_number - second_number
print()
print("The Diffrence between first and second number is: ", x) |
73631147ca4cc0322de2a68a36290502ee230907 | ytgeng99/algorithms | /Pythonfundamentals/FooAndBar.py | 1,040 | 4.25 | 4 | '''Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000.
For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither prin... |
44a002f5ed28792f31033331f79f49b24d6bc3ef | ytgeng99/algorithms | /Pythonfundamentals/TypeList.py | 1,320 | 4.375 | 4 | '''Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At t... |
478c988bb167a129631e2c8b0f3d07c51b65574b | Sacharya1/Basic-Python-Tutorials | /runnerUp.py | 600 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 19:10:34 2019
@author: SampadAcharya
"""
if __name__ == '__main__':
n = 5
arr = [-7,-7,-7,-7,-6]
index=[]
def indexVal(arr, maxVal,n):
for i in range(n):
if arr[i]==maxVal:
# print(i)
m=i
... |
a0f8368674545ca6a45d715afbc9bbaadf062c08 | huynguyen120390/CrackingCodingProblem | /ArrayandStrings/return_permutationStrings.py | 1,337 | 3.75 | 4 | def __is_permutation(string1, string2):
if len(string1) != len(string2):
return False
set = {}
#stock chars of string1 with positive occurency
for i, v in enumerate(string1):
v = v.lower()
if v not in set:
set[v] = 1
else:
set[v] += 1
#stock c... |
ff1ce1557342706b401042efc6b213e0e1bbd9ef | chrisgzf/AoC | /2019/Day06_Part2.py | 1,047 | 3.515625 | 4 | from collections import defaultdict
with open("Day06_Input") as f:
orbits = f.readlines()
orbits = list(map(lambda x: x.strip(), orbits))
print(len(orbits))
edges = defaultdict(list)
vertices = set()
for orbit in orbits:
orbitee, orbiter = orbit.split(")")
edges[orbiter].append(orbitee)
vertices... |
569202e0b336f912e1e9dbfa29a5f2aea7c8f2b5 | JiHoon-JK/Sparta_py | /list.py | 290 | 3.609375 | 4 | a = ['사과','감','감','배','사과','포도','딸기','사과','배']
def count_list(a_list):
result={}
for element in a_list:
if element in result:
result[element] += 1
else:
result[element] = 1
return result
print(count_list(a)) |
c8bc084cc06c30404dbb8d5cd6653dd74d007405 | KatePavlovska/python-laboratory | /laboratory1&2update/Lab2_Task2_calculation_pavlovska_km_93.py | 640 | 4.25 | 4 | print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool... |
2e1addf3b25bf2df65ff1bcf6d223d5b5520e32b | KatePavlovska/python-laboratory | /laboratory1/task2.py | 1,125 | 4.09375 | 4 | print('Павловська Катерина. КМ-93. Варіант №14.')
print('You are welcomed by the guessing program')
Petails=int(input("Number of petails: "))
while Petails<=3:
print("The given values are incorrect, which flower does not exist, please try again")
Petails=int(input("Number of petals: "))
Version=int(input("... |
7b573852d78943dc327ecdb8d9a87fb987dffae9 | fingerroll/wip | /strobogrammatic-number-II/s1.py | 847 | 3.5 | 4 | # Forget '00' can be a number
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
sbg = ['69', '88','11', '96', '00']
if n == 0:
return []
if n == 1:
return ['0', '8', '1']
if n == 2... |
25e72fea728d1df3fef1c0a0378c355144ed4536 | fingerroll/wip | /count-univalue-subtree/s1.py | 1,285 | 3.734375 | 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 countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if ... |
92c83d1a0b882aa143205809bfecbbaeac395118 | karishma347/gas-modules | /bisection.py | 477 | 3.65625 | 4 | # a python module to calculate bisection method
# Karishma Bharti, Srisha Rao M V, IISc, July 2020
# Global conventions and variables
# a,b are guessing values
# func is the function
def bis(a,b,func):
if (func(a) * func(b)>=0):
print("wrong assumption")
return
c=a
while((b-a)>=0... |
661937904645917e033c55f797121b6a05a543d0 | dm-fedorov/python3book | /2-ed/ch12/class_fun.py | 779 | 3.734375 | 4 | # class_fun.py
# Обновленная функция, которая обрабатывает объект типа (класса) Address.
# Вывести адрес на экран:
def print_address(address):
print(address.name)
if len(address.line1) > 0:
print(address.line1)
if len(address.line2) > 0:
print(address.line2)
print(address.city + ", " + a... |
e7c5bc523427257158b6eab611d28d05775c7962 | dm-fedorov/python3book | /3-ed/ch4/mypr.py | 221 | 3.59375 | 4 | # mypr.py
def func(x):
return x ** 2 + 7
#x = int(input("Введите значение: "))
#print(func(x))
if __name__ == "__main__":
x = int(input("Введите значение: "))
print(func(x))
|
746562d02ebf880a258e307948343b656e417076 | dm-fedorov/python3book | /3-ed/ch10/exception_08.py | 258 | 3.6875 | 4 | # exception_08.py
try:
x = int(input("Введите число: "))
print(5/x)
except ZeroDivisionError:
print("Ошибка деления на ноль!!!")
except ValueError:
print("Ошибка преобразования типа!!!")
|
21a2fbe709284990b8d486f7aabd79ddc269d4bf | AlexChesser/CIT590 | /04-travellingsalesman/cities.py | 2,041 | 4.28125 | 4 | def read_cities(file_name)
"""Read in the cities from the given file_name, and return them as a list
of four-tuples: [(state, city, latitude, longitude), ...] Use this as your
initial road_map, that is, the cycle Alabama → Alaska → Arizona → ... → Wyoming → Alabama."""
pass
def print_cities(road_map... |
5b4f1d86618af532f251f8c6381cc351196dd215 | VictorMacleury/Questionario | /Questionario.py | 1,689 | 4.03125 | 4 | print()
print('Digite a letra respectiva à resposta que você considera como correta.')
print()
perguntas = {
'pergunta 1' : {
'pergunta' : 'Quanto é 1 + 1?',
'respostas' : {'a' : '1', 'b' : '2', 'c' : '3', 'd' : '4' },
'resposta certa' : 'b',
},
'pergunta 2' : {
'pergunta' ... |
0f723850be01c3ca714cabe90672bc83cbfe09ee | mrbilal4972/Number-Guessing-Game | /main.py | 1,076 | 4.09375 | 4 | import random
randNo = random.randint(1,100)
userGuess = None
totalGuesses = 0
# Loop runs until guess matched
while randNo!=userGuess:
try: # Try box handle the invalid input from user, like: alphbet or special character
userGuess = int(input("Guess the number between 1 to 100: "))
if randNo != u... |
d6395521d2f7816d6d0329e8feefad2e373a2397 | ml4026/Assignment1-Answer | /RLalgs/pi.py | 4,432 | 3.84375 | 4 | import numpy as np
from RLalgs.utils import action_evaluation
def policy_iteration(env, gamma, max_iteration, theta):
"""
Implement Policy iteration algorithm.
Inputs:
env: OpenAI Gym environment.
env.P: dictionary
P[state][action] is list of tuples. Each tuple contains... |
93081ee785e71c16e56f78767a316b99038b4b25 | Nerhox1983/studio_python | /capitulo02/Reto0203.py | 920 | 3.734375 | 4 | #Ejercicio 2.1. Aplicando las reglas matemáticas de asociatividad, decidir cuáles de las siguientes
#expresiones son iguales entre sí:
import FuncionesNumeros02
Numero10 = 10.0
Numero100 = 100.0
Numero1000 = 1000.0
resultado1 = FuncionesNumeros02.CalcularReto0201PuntoA(Numero10, Numero100, Numero1000)
resultado2 = Fu... |
6c094694aa448680ad878943075247641e79d744 | ooobsidian/shu_spider | /thread.py | 532 | 3.6875 | 4 | # coding=utf-8
import threading
import time
class myThread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
def run(self):
time.sleep(2)
print('Thread {} is running.'.format(self.i))
time.sleep(2)
return
if __name__ == '__m... |
c8721544d8d9cb6e3835f59d2a7bd14a36dee70b | dortmans/ComputerVision | /VideoCapture.py | 1,521 | 3.609375 | 4 | import numpy as np
import cv2
#we are capturing image from the standard cameras
# 0,1,2,... (since we are using the laptop capera , we use 0 , else we use 1,2..)
#Note: we need to create a VideoCapture object to capture video in OpenCV
cap = cv2.VideoCapture(0) #this will create a streaming video via the lappy cam
... |
024213abf18bf6c878a42111c221612f12cce7b3 | dortmans/ComputerVision | /trainCV/gaussianBlue_Color.py | 953 | 3.5 | 4 | #Gaussian Blur Example using scipy
#Color
#We individually apply the filter to individual channels
from PIL import Image
from numpy import *
from scipy.ndimage import filters
from pylab import *
im = array(Image.open("riaz.jpg"))
#Note: Here is the standard deviation value
#more the sigma , more the blur
blur2 = z... |
8ae0d4ef38c6072949606f126e9ba9ae16f9a183 | dortmans/ComputerVision | /trainCV/unsharp_mask.py | 526 | 3.515625 | 4 | #Program to demonstrate unsharp masking
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from scipy.ndimage import filters
im = np.array(Image.open("lena_noisy.png").convert("L"))
blur = filters.gaussian_filter(im,10)
sharp = im - blur
plt.figure("Unsharp masking Example")
plt.gray()
p... |
40db83e086d8857643c10447811873e55740797b | kajalubale/PythonTutorial | /While loop in python.py | 535 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
#... |
a991a9d07955fe00dad9a2b46fd32503121249e8 | kajalubale/PythonTutorial | /For loop in python.py | 1,891 | 4.71875 | 5 |
################### For Loop Tutorial ###############
# A List
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
# To print all elements in list
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can do same thing easily using for loop
# for ... |
2a3ca27dd93b4c29a43526fa2894f79f38280b82 | kajalubale/PythonTutorial | /41.join function.py | 971 | 4.34375 | 4 | # What is the join method in Python?
# "Join is a function in Python, that returns a string by joining the elements of an iterable,
# using a string or character of our choice."
# In the case of join function, the iterable can be a list, dictionary, set, tuple, or even a string itself.
# The string that separates... |
767fc168ca7b5c78be91f3aa94302fc009d73e49 | kajalubale/PythonTutorial | /35.Recursion.py | 1,457 | 4.5625 | 5 | # Recursion: Using Function inside the function, is known as recursion
def print_2(str):
print("This is",str)
print_2("kajal")
# output: This is kajal
# but if i used print_2("str") inside the function it shows Recursion error.
# def print_2(str):
# print_2(str)
# print("This is",str)
# print_2... |
08e1c60124239203af2859a726c052e5775c2836 | alin719/cs221-project | /tokenscanner.py | 21,454 | 3.578125 | 4 | """
* File: tokenscanner.cpp
* ----------------------
* Implementation for the TokenScanner class.
*
* @version 2014/10/08
* - removed 'using namespace' statement
"""
import string
"""
* File: tokenscanner.h
* --------------------
* This file exports a <code>TokenScanner</code> class that divides
* a strin... |
da7bb658e7fbd4f41c8c8bc95977a90d5c0e8e04 | mondler/leetcode | /codes_python/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py | 1,851 | 3.96875 | 4 | # https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/
#
# 452. Minimum Number of Arrows to Burst Balloons
# Medium
#
# 706
#
# 38
#
# Add to List
#
# Share
# There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end ... |
1e852d48e55224e0054364b0ea6379f21e7f922c | mondler/leetcode | /codes_python/0098_Validate_Binary_Search_Tree.py | 3,211 | 4.25 | 4 | # https://leetcode.com/problems/validate-binary-search-tree/
# 98. Validate Binary Search Tree
# Medium
#
# 3220
#
# 458
#
# Add to List
#
# Share
# Given a binary tree, determine if it is a valid binary search tree(BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with ke... |
060eb25956088487b27ab6fe31077f73b6691857 | mondler/leetcode | /codes_python/0006_ZigZag_Conversion.py | 1,866 | 4.15625 | 4 | # 6. ZigZag Conversion
# Medium
#
# 2362
#
# 5830
#
# Add to List
#
# Share
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by... |
50b1e950818bf56fc22197c075e2d69cd6604e84 | mondler/leetcode | /codes_python/0093_Restore_IP_Addresses.py | 2,289 | 3.59375 | 4 | # https://leetcode.com/problems/restore-ip-addresses/description/
# 93. Restore IP Addresses
# Medium
#
# 1032
#
# 460
#
# Add to List
#
# Share
# Given a string containing only digits, restore it by returning all possible valid IP address combinations.
#
# Example:
#
# Input: "25525511135"
# Output: ["255.255.11.135",... |
48a7ced84d9937622fe9a9d1bad59a127789a204 | mondler/leetcode | /codes_python/0435_Non-overlapping_Intervals.py | 2,914 | 4.09375 | 4 | # https://leetcode.com/problems/non-overlapping-intervals/description/
#
# 435. Non-overlapping Intervals
# Medium
#
# 782
#
# 28
#
# Add to List
#
# Share
# Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
#
#
#
# Example 1:
#
#... |
da765a0a6123eb2623100ace81ff60feec44138f | mondler/leetcode | /codes_python/0074_search_a_2_d_matrix.py | 1,673 | 3.828125 | 4 | #
# @lc app=leetcode id=74 lang=python3
#
# [74] Search a 2D Matrix
#
# https://leetcode.com/problems/search-a-2d-matrix/description/
#
# algorithms
# Medium (45.32%)
# Likes: 8267
# Dislikes: 285
# Total Accepted: 856.7K
# Total Submissions: 1.9M
# Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,60]]\n3'
... |
826f7fa5964a0e98a70f4f28b80a6c9d90ad9e32 | mondler/leetcode | /codes_python/0139_Word_Break.py | 1,881 | 3.78125 | 4 | # 139. Word Break
# Medium
#
# 8835
#
# 404
#
# Add to List
#
# Share
# Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
#
# Note that the same word in the dictionary may be reused multiple times in the segmentation... |
502900e5c65ea2c9ba230f5b063fa2f679d34ee5 | mondler/leetcode | /codes_python/0611_Valid_Triangle_Number.py | 1,443 | 3.765625 | 4 | # 611. Valid Triangle Number
# Medium
#
# 2074
#
# 134
#
# Add to List
#
# Share
# Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
#
#
#
# Example 1:
#
# Input: nums = [2,2,3,4]
# Output: 3
# Explanation: Valid combi... |
4d04a766fc39870a8c8ea190150eced1325d39b8 | ohmahgawditbob/py-projects | /kinetic_energy_calculator.py | 201 | 3.875 | 4 | import math
vel = float(input("Velocity (m/s): "))
mass = float(input("Mass (kg): "))
energy_kinetic = 0.5*mass*(math.pow(vel, 2))
print("The Kinetic Energy is " + str(energy_kinetic) + " Joules.")
|
69c3d6752d504a08cf06c2ad8374e823f4e3f206 | srankur/PythonUtil | /MultiProcess/MultiThreading.py | 602 | 3.5625 | 4 | import time
import threading
def calc_square(num):
print("Calculating squares")
for n in num:
print("Square", n*n)
def calc_cube(num):
print("Calculating Cubes")
for n in num:
print ("cube", n*n*n)
number = [1,2,3,4]
t = time.time()
t1 = threading.Thread(target = calc_square,args=(ra... |
d7fbbf8edf9b1748f59f7269641cb14a9f65529f | jakubna/IML-MAI20Z | /w1/algorithms/dbscan.py | 2,771 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
def find_eps(x):
""" this function aims to plot the epsilon by calculating the distance to the nearest two points and index.
the optimal value will be fou... |
8e910da5e978a08b5be147fac493495144b76be2 | basu-sanjana1619/python_projects | /lists_to_dic.py | 146 | 3.65625 | 4 | #convert list to dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
dic = {}
for k,v in zip(keys,values):
dic[k] = v
print(dic)
|
4decf52cae21f429395dbb079c3bada56f7bf326 | basu-sanjana1619/python_projects | /gender_predictor.py | 683 | 4.21875 | 4 | #It is a fun program which will tell a user whether she is having a girl or a boy.
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate abov... |
8d37f294b27d2b0438b78c4ac726170312cd32d2 | yousufahmad/Stock-Price-Predictor | /python-stock-predictor.py | 2,554 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 15:33:08 2019
@author: yousuf
"""
import numpy as np
from datetime import datetime
from sklearn.linear_model import LinearRegression
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
'''
predictLinear takes in a ticker, a sta... |
7ca7431e7c1c9fc28e859181da989f6d81b293b4 | thegrafico/coding-challenges | /python_challenge/zigzag2.py | 651 | 3.859375 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows
like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
================================================
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINA... |
6d1df73ee15581838b77a690311b9189489e537d | thegrafico/coding-challenges | /python_challenge/statistist_10days/day_1_quartiles_range.py | 1,678 | 3.78125 | 4 | # tam = input()
# values = input()
values = '6 12 8 10 20 16'
frequency = '5 4 3 2 1 5'
values = values.split()
frequency = frequency.split()
values = [float(x) for x in values]
frequency = [float(x) for x in frequency]
# print(values)
# print(frequency)
index_median = 0
def create_list(values, frequency):
arr ... |
bdde0bdf932547d4fc2e02379deebe6e47fa22ae | cookcodeblog/python_work | /ch08/describe_city.py | 307 | 3.84375 | 4 | # 8-5 describe_city() function
def describe_city(city, country="China"):
print(str(city).title() + " is in " + country.title())
describe_city("Shanghai")
describe_city("Beijing")
describe_city(city="Chongqing")
describe_city("London", "England")
describe_city(city="California", country="America")
|
ab5cc8e8e5bc954b31b8a9334fb03af157fea522 | cookcodeblog/python_work | /ch10/guest.py | 457 | 4.09375 | 4 | # 10-3 Guest
# name = input("What is your name please ? ")
# # Don't forget add "w" to identify you want to write sth into the file
# with open("guest.txt", "w") as file_obj:
# file_obj.write(name)
with open("guest.txt", "a") as file_obj:
while True:
name = input("What is your name please? ")
... |
0c26588a8506eb7d6bb5fa7d675451a607f5a3ab | cookcodeblog/python_work | /ch06/favorite_places.py | 366 | 3.796875 | 4 | # 6-9 Favorite Places
favorite_places = {
'William': ["Hainan", "Guangzhou", "Yunnan"],
'Sunna': ["Shanxi", "Greece", "London"],
'Wilson': ["Shanghai", "Beijing", "Hong Kong"]
}
for name, places in favorite_places.items():
print(name.title() + " likes following places:")
for place in places:
... |
9d77a0ee4b5f9d90d48c67fcc19a686f6cb3b508 | cookcodeblog/python_work | /ch07/visit_poll.py | 543 | 4.125 | 4 | # 7-10 Visit Poll
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place # It is like map.put(key, value)
repeat = input("Would you like to let another perso... |
4f6f9d0dbcbf0baad2c94fa8a1aa5fd26e2a8f0f | cookcodeblog/python_work | /ch10/survey_programming.py | 283 | 3.84375 | 4 | # 10-5 Survey of Programming
with open("survey.txt", "a") as survey:
while True:
reason = input("Why do you want to learn Python? ")
survey.write(reason + "\n")
repeat = input("Continue? (yes / no) ")
if repeat.lower() == "no":
break
|
9bf8b21b2776a14fc8abc84c51549b3baff7385e | cookcodeblog/python_work | /ch09/restaurant.py | 1,155 | 4.03125 | 4 | # 9-1 Restaurant class
class Restaurant:
def __init__(self, restaurant_name, cuisine_type, number_served=0):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = number_served
def describe_restaurant(self):
print(self.restaurant_name + ... |
2e1679facc189bf53edfc0c74160c0cecaa5b194 | cookcodeblog/python_work | /ch06/river.py | 316 | 4.25 | 4 | # 6-5 River
rivers = {
'Nile': 'Egypt',
'Changjiang': 'China',
'Ganges River': 'India'
}
for river, location in rivers.items():
print("The " + river + " runs through " + location + ".\n")
for river in rivers.keys():
print(river)
print()
for location in rivers.values():
print(location)
|
5d9d7e969d5200c7cab614e09c5dd5914a567609 | jhgdike/leetCode | /leetcode_python/201-300/213.py | 485 | 3.53125 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def _rob_range(nums, i, j):
last = now = 0
for x in range(i, j):
last, now = now, max(now, last + nums[x])
return now
if not num... |
0bb7fe5ad689ae77131bf184ddb4933995217a4c | jhgdike/leetCode | /leetcode_python/301-400/328.py | 856 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
... |
c85b4dc755e367a5e8b1a554ebea5b74ee5f3b6f | jhgdike/leetCode | /leetcode_python/801-900/860.py | 706 | 3.578125 | 4 | class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
bil = [0, 0]
for b in bills:
if b == 5:
bil[0] += 1
elif b == 10:
if bil[0] < 1:
return Fal... |
5f17c8f1ec2f340bdb38a58e045c18dff521c787 | jhgdike/leetCode | /leetcode_python/101-200/143.py | 1,018 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
... |
ed83eebfc06efbb76af1baf6f9996f4389556824 | jhgdike/leetCode | /leetcode_python/1-100/43.py | 686 | 3.578125 | 4 | class Solution(object):
"""
Python can do it directly by str(int(num1)*int(num2))
"""
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = [0] * (len(num1) + len(num2))
lengh = len(res)
for i, n1 in en... |
93f70311fcc86ee8a6fc47edc27da22cd085f77d | jhgdike/leetCode | /leetcode_python/301-400/374.py | 943 | 3.5625 | 4 | # The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
def guess(num: int) -> int:
if num == 6:
return 0
elif num > 6:
return -1
return 1
class Solution:
def guessNumber(self, n: int) -> int:
l = 1
r ... |
24cd99d037e3115ef980d5a035601d5ac745f634 | jhgdike/leetCode | /others/qsort.py | 249 | 3.578125 | 4 | # coding: utf-8
def ugly_qsort(seq):
if not seq:
return []
pivot = seq[0]
lesser = ugly_qsort([x for x in seq[1:] if x < pivot])
greater = ugly_qsort([x for x in seq[1:] if x >= pivot])
return lesser + [pivot] + greater
|
2a638fb07799491d5e2bdbcc5462e4507e089fff | jhgdike/leetCode | /leetcode_python/101-200/166.py | 1,312 | 3.734375 | 4 | class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
string_buffer = []
if numerator == 0:
return "0"
if (numerator < 0) ^ (denominator < 0):
... |
869a9d9c98a9ca7ecd1bc1d3eccf57e1195d0a52 | jhgdike/leetCode | /leetcode_python/__init__.py | 1,955 | 3.5 | 4 | import json
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
... |
ba1970ff9331aca918aedc3fc019585970fc78a9 | jhgdike/leetCode | /leetcode_python/601-700/623.py | 880 | 3.96875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def addOneRow(self, root, val, depth):
"""
:type root: TreeNode
:ty... |
6d8cea9f81c3d3d6714e8f6c613c95ce16b36ad2 | jhgdike/leetCode | /leetcode_python/1-100/56.py | 719 | 3.734375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
from operator import attrgetter
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
... |
0b44347123649993c9b6c56d3dd2a0594d19f83b | hunny123/Python-cpcode | /codeforces/CF677-D2-A.py | 322 | 3.71875 | 4 | def findwidth(n,h):
sum1=0
i=0
while i<len(n):
if(n[i]>h):
sum1 = sum1+2
else:
sum1 = sum1+1
i=i+1
return sum1
t = input()
t = list(map(int ,t.split(" ")))
li = input()
li = list(map(int,li.split(" ")))
print(findwidth(li,t[1]))... |
6d7d18fcd11e749140128f267f289f90bcd3023e | hunny123/Python-cpcode | /codeforces/CF102-D2-B.py | 154 | 3.5625 | 4 | def spell(n):
return sum(list(map(int,n)))
n = (input())
count=0
while len((n))!=1:
count =count+1
n=str(spell(n))
print(count)
|
b6f24db742408390a6125fd53ea58e20340246e1 | azdoherty/learners | /learners/TFtest.py | 517 | 3.53125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
from scipy.io import loadmat
import numpy as np
#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#res = mnist.test.next_batch(batch_size=100)
#print(res[0].shape)
#print(res[1].shape)
trainfile = "datasets/housenumbers/train_32x32.mat"
trainset... |
045c4403c1babccb954fe09af19829d25aef3724 | zhenhao/phello | /src/utils/container/list.py | 506 | 3.609375 | 4 | __author__ = 'wangzhenhao'
class List:
def __init__(self):
self.l = []
def append(self, x):
self.l.append(x)
def insert(self, i, x):
self.l.insert(i, x)
def pop(self):
return self.l.pop()
def __str__(self):
return str(self.l)
def empty(self):
... |
859b5a09dc0a055963c28780a6fc9e93ae186747 | zhenhao/phello | /src/utils/helper.py | 239 | 3.953125 | 4 | __author__ = 'wangzhenhao'
def hanoi(a='A', b='B', c='C', n=1):
if n < 1:
pass
elif n == 1:
print(a + ' -> ' + c)
else:
hanoi(a, c, b, n - 1)
print(a + ' -> ' + c)
hanoi(b, a, c, n - 1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.