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 |
|---|---|---|---|---|---|---|
9c3a98dc0117de376277591b5ac77807d2b2cf86 | vmgabriel/async-python | /src/async_func.py | 1,031 | 4.125 | 4 | """Async function"""
# Libraries
from time import sleep
async def hello_world():
"""Print hello world"""
sleep(3)
return 'Hello World'
class ACalculator:
"""Class Async Calculator"""
async def sum(self, a, b):
"""function sum a + b"""
sleep(2)
return a + b
async def... |
bebb0bfed98f10287b6f5a430ceeb194faebfa15 | SeriousBlackMage/Python_References | /Files/Files.py | 737 | 3.859375 | 4 |
def main():
#Open() öffnet eine File oder erstellt sie falls sie noch nicht vorhanden ist
f = open("textfile.txt","w+") #Das Erste Argument ist die zu behandelnde Datei und das zweite ist "was gemacht werden soll"
for i in range(10):
f.write("This is line %d \r \n" % (i+1))
f.close()
f ... |
e27326c7043fdaac069d9961294d40aa7bfcc476 | SeriousBlackMage/Python_References | /Ok_Stuff/Classes.py | 779 | 3.984375 | 4 |
class myClass():
def method1(self): #Self-Argument weist auf das Object an sich hin.
print("myClass Method1")
def method2(self, someString):
print("myClass Method2 " + someString)
class anotherClass(myClass): #anotherClass wird inheritiert von myClass
def method2(self): #Methoden werden ... |
0d869792e4cab79fd6ae7750db17aa24b4ed22c2 | GregSzopinski/nn-from-scratch | /nn/metrics.py | 741 | 3.609375 | 4 | import numpy as np
def mae(y_true: np.ndarray, y_pred: np.ndarray):
"""
Compute mean absolute error for a neural network.
"""
return np.mean(np.abs(y_true - y_pred))
def rmse(y_true: np.ndarray, y_pred: np.ndarray):
"""
Compute root mean squared error for a neural network.
"""
return... |
6356e4616995463a16cacb7873efdeba2bd9438b | kawatmp/program_sample1 | /program_sample1.py | 228 | 3.609375 | 4 | # coding: Shift_JIS
import datetime
d1 = datetime.datetime.today()
print('now:', d1)
# 10[vŖ150b
for n in range(1000000000):
if n == 5000:
print("5000")
d2 = datetime.datetime.today()
print('now:', d2)
|
252b7c015b09d4ca2e4850050d5df8091bae1abf | pinwei67/computational-thinking-and-program-design | /week14_A108060032林品慰.py | 300 | 4.0625 | 4 | weight = float(input("Enter Your Weight(KG)? "))
height = float(input("Enter Your height(M)? "))
bmi = weight / (height * height)
print("BMI指數為",bmi)
n = 0
left = 0
while n < 10:
n = n + 1
left = 10 - n
print("這是第", n, "次的hello", "還有",left, "次機會") |
e04e266dcc7a71bb4a6086040566e9f125f7e025 | JEMeyer/advent-of-code | /2019/01/fuelThing.py | 1,259 | 3.53125 | 4 | #!/usr/bin/env python
import functools
"""
Module Docstring
"""
__author__ = "Joe Meyer"
__license__ = "MIT"
def fuelAndExtra(mass):
fuel = 0
currentFuel = mass / 3 - 2
while currentFuel > 8:
fuel = fuel + currentFuel
currentFuel = currentFuel / 3 - 2
if currentFuel > 0:
fuel =... |
4d0d77186d37abc53efbccd2554cd14c9b54062d | legmartini/python-def | /ex098.py | 878 | 3.6875 | 4 | from time import sleep
# Funções
def linha():
print('-=' * 20)
def contador(ini, fim, pas):
print('-=' * 20)
print(f'Contagem de {ini} até {fim} de {pas} em {pas}')
sleep(1.5)
if pas < 0:
pas *= -1
if pas == 0:
pas = 1
if ini < fim:
cont = ini... |
2de23de09d321817ccb2d024ee653fc1f9cda8e1 | SujahathMSM/GlobalAIHubPythonCourse | /Homeworks/Hw_D02_01.py | 344 | 3.828125 | 4 | My_list=[1,4,9,16,25,36,10,20,30,40,50,60] #Creating a list with some Numbers
New_List=[] # Creating empty list
first_Half=My_list[0:6] #Extracting the first half elements from My_list
Second_Half=My_list[6:] #Extracting the second half elements from My_list
print(Second_Half+first_Half) # Swapping first and... |
be2903c65f890e828c81649a0857f31d271acdff | liupzone/CrowdNet | /scripts/lr.py | 693 | 3.5625 | 4 | # -*- coding: utf-8 -*-
''' linear regression '''
import sys
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
if len(sys.argv) < 3:
print 'Usage: python lr.py x.txt y.txt'
sys.exit(-1)
x = np.loadtxt(open(sys.argv[1],'r')).reshape(-1,1)
y = np.loadtxt(open(sys.argv[2],'r... |
fedaa4e5c7f56cc9016215c0dde3bc0264e796ca | n0thingchanged/xipilao | /water-flower.py | 158 | 3.578125 | 4 | num = 100
while num <= 999:
a = num // 100
b = num // 10 % 10
c = num % 10
if a ** 3 + b ** 3 + c ** 3 == num:
print num
num += 1 |
8378d2d4a0ad48eda5503348daf2f3499b863589 | william0829/learn-pyhon | /sample/basic/do_while.py | 517 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding utf-8 -*-
#打印从9,7,5,3,1每次相加值
sum=0
n=9
while n>0:
sum=sum+n
n=n-2
print(sum)
exit()
#打印hello+名字
L=['Bart','Lisa','Adam']
n=0
while n<=2:
print('Hello,',L[n])
n=n+1
exit()
#打印n每个数,当n>20时停止
n=1
while n<=100:
if n>20:
break
print(n)
n=n+1
print('END')
exit()
#打印n,... |
02362f40af96faceb2a158805cc93ca5bc7ba488 | CrystalSixone/AssignmentProblem_with_Hungarian_and_AntColonyAlgorithm | /hungarian.py | 15,641 | 3.5 | 4 | # -*- coding: utf-8 -*-
'''
@Date: 2021/05/30
@Author:w61
@Brief: Using imporved Hungarian algorithm to solve balanced and unbalanced assignment problems.
'''
import math
import numpy as np
import copy
import time
from matplotlib import pyplot as plt
from costMatrix import getDistance,randomMatrix,loadMatrix,randomMa... |
9f07ed5d96bbc9e2ef23c0d8e0c76c80e9c67144 | jackylee328/Practice-Problems | /Divisors.py | 146 | 3.671875 | 4 | # 04 Divisors
num = input("Give me a number: ")
intNum = int(num)
for i in range(1, intNum+1):
if (intNum % i == 0):
print(str(i))
|
a24ef4f30b9d6ec767e9f3ef29582c53d6013272 | spring-2019-csc-226/a03-master | /a03_ovezovs.py | 3,478 | 3.875 | 4 | ######################################################################
# Author: Shageldi Ovezov TODO: Change this to your name, if modifying
# Username: ovezovs TODO: Change this to your username, if modifying
#
# Assignment: A03: A Pair of Fully Functional Gitty Psychedelic Robotic Turtles
# Link... |
58fd0a7e36292e7d562ec9034ef30409a6ff6184 | spring-2019-csc-226/a03-master | /a03_Sandesh-l.py | 4,298 | 4.28125 | 4 |
# Name: Sandesh Lamichhane
# Doc Link: https://docs.google.com/document/d/1x5rX6GzEgg-MPuUwYkVoDDZmU4mmbn1UQ6iu19AcTMg/edit?usp=sharing
import math
import turtle
wn = turtle.Screen()
def draw_house(house_color, house_height, roof_color):
"""""
this function will draw a simple square house with a triangl... |
88345beeb086c9d131752adf48554fdf38fec98b | spring-2019-csc-226/a03-master | /A03_westj2.py | 2,316 | 3.5 | 4 | ######################################################################
# Author: Johnathan West
# Username: westj2
#
# Assignment: A03
# Doc:https://docs.google.com/document/d/1iQCxEhiEbdHSGWJ16A9AC4E5ViTDvvYHfBGZpW7KiEQ/edit?usp=sharing
######################################################################
import turt... |
24b050abb0b427c84ccecb6696becf7043601a13 | spring-2019-csc-226/a03-master | /a03_mupotsal.py | 3,440 | 3.984375 | 4 | #################################################################################
# Author: Liberty Mupotsa
# Username: mupotsal
# Google document link to the file :
# https://docs.google.com/document/d/1LkTHFrehbfiPwt7vFb3iw_GgT8vMh2vvjSVyskBteDg/edit?usp=sharing
# Assignment:A Pair of Fully Functional Gitty Psychedel... |
4a6c563fdb6f4afef644783d2f787500dab30e4c | ajay286/DS_problems | /trie_solution.py | 1,218 | 3.65625 | 4 | class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isLastWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _chatIndex(self,ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
len_key = len(key)... |
25405511319bff04521132f09d027eb1bedc6e7a | MahidharMannuru5/DSA-with-python | /dictionaryfunctions.py | 1,826 | 4.5625 | 5 | 1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values.
2. items() :- This method is used to return the list with all dictionary keys with values.
# Python code to demonstrate working of
# str() and items()
# Initializing dictionary
dic = { 'Name' : 'Nandini', 'Ag... |
d02e4dc0b560b586717edee185b7b5ff8cf25c6a | fbjxu/Algorithm-Specialization | /DijkstraHeap.py | 2,318 | 3.796875 | 4 | #create a graph in list format. Each element is a list of lists. The element index indicate the node identity/number/
#the element is of the format [[node(x), length(x)], [node(y), length(y)]]
g = [[] for x in range(201)] #note that g[0] is useless
with open('Dijkstra.txt', 'r') as f:
for line in f.readlines():
... |
561518912ea2f178dc1d02cf25d791afe47fdcdd | stephanephanon/head_first_design_patterns | /chapter04.py | 3,522 | 4.53125 | 5 | """
Chapter Four -- Factory Pattern
SimpleFactory.
Encapsulate object creation, have one place to make modifications
when the implementation changes
"""
class PizzaBase(object):
"""
Base pizza class. This pizza only has tomato sauce
"""
def __init__(self):
self.toppings = ['tomato sauce']
... |
a04221dcf409fec4074c4ec2cf2d5be4bb085c33 | octavian-stoch/Practice-Repository | /Daily Problems/Spetember 18th Microsoft [Easy].py | 384 | 3.59375 | 4 | #Author: Octavian Stoch
#Date: 9/18/2019
#Using a read7() method that returns 7 characters from a file,
#implement readN(n) which reads n characters.
#For example, given a file with the content “Hello world”,
#three read7() returns “Hello w”, “orld” and then “”.
def read7():
#test file string
inf = "Hello wor... |
0bfff01de4d4b739f08c6d5499734d9039df55fc | octavian-stoch/Practice-Repository | /Daily Problems/July 21 Google Question [Easy] [Matrix].py | 1,618 | 4.15625 | 4 | #Author: Octavian Stoch
#Date: July 21, 2019
#You are given an M by N matrix consisting of booleans that
#represents a board. Each True boolean represents a wall. Each False boolean
#represents a tile you can walk on.
#Given this matrix, a start coordinate, and an end coordinate,
#return the minimum number... |
6e069574a3730ab0efdc298aea352c7bf0d9f5c8 | samarin1/python-challenge | /PyBank.py | 1,682 | 3.6875 | 4 | import os
import csv
budget_data_csv = os.path.join('..' , 'python-challenge' , 'budget_data.csv')
Number_of_Months = 0
Net_Total = 0
Average_Change = 0
Previous = 0
Net_Change = 0
Total_Net_Change = 0
Greatest_Change = 0
Greatest_Decrease = 0
with open(budget_data_csv,'r') as csvfile:
csvreader = csv.reader(csv... |
1fc6aa6bbdb3aab80cc5efbe764fe55ae06c1a34 | mahdisesmaeelian/Python-Basic | /assignment 4/4-7.PY | 448 | 3.890625 | 4 | listnum1=[]
listnum2=[]
num1 = int(input(" Enter the first number : "))
num2 = int(input(" Enter the second number : "))
for i in range(1,num2+1):
listnum1.append(num1*i)
for i in range(1,num1+1):
listnum2.append(num2*i)
print(listnum1)
print(listnum2)
for i in range(1,len(listnum1)):
i... |
ba918967545f4a59010f46f0a1d4f0a3dead810c | mahdisesmaeelian/Python-Basic | /assignment 3/4.py | 177 | 4.03125 | 4 | n= int(input("Enter length of the snake : "))
for i in range(n):
if (i %2 )==0 :
print("*", end="")
else:
print("#", end="")
|
23aa363c467f6ea8270974d101e84df35af4b3b0 | PMARINA/ImageRecognition | /EdgeDetection/CameraProcessor.py | 4,249 | 3.71875 | 4 | '''
Author: Pridhvi Myneni
Version: Python 2.7.13
Instructions:
1) Read all the instructions before you do anything
2) Change the preferences below to match your personal preferences and the
machine on which you will be running the script
3) Run the program
4) Use 'q' and 'e' keys to play with the gaussian blur se... |
1292e48e98813dbddd7bd3f1a9fe434163435d84 | elishen/leetcode | /730_MyCalendarII.py | 1,035 | 3.703125 | 4 | class MyCalendar:
def __init__(self):
self.booking = []
self.overlaps = []
self.res = []
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
for x, y in self.overlaps:
if not (
(st... |
3f130dd1b6860be60070f46a50f12708ed118236 | sephpace/game-engine | /entity.py | 4,282 | 3.53125 | 4 |
from abc import ABC
from glumpy import gl, gloo
import numpy as np
from constants import SCREEN_WIDTH, SCREEN_HEIGHT, ZOOM
class Entity(ABC):
"""
An abstract entity class.
An entity is an object that can move.
Attributes:
position (ndarray): The position of the entity in 3D space.
velocit... |
91e23da6642bbe412c49391e5aed2180525d9d86 | Nicoo1230/pyalgo | /manip_tableau.py | 2,201 | 3.828125 | 4 | """
@name manip_tableau.py
@author Aélion
@version 1.0.0
Algorithme spécifique sur collection
"""
"""
getLowerOf function
return the lowest value of two params
"""
def getLowerOf(firstVal, secondVal):
if firstVal < secondVal:
return firstVal
else:
return secondVal
"""
getGreaterOf function
r... |
a4819757786e3e1faa59ae55263ba75b1f4b2b3a | Utheau/CodeWars | /The shell game.py | 165 | 3.578125 | 4 | def find_the_ball(start, swaps):
for a, b in swaps:
if a == start:
start = b
elif b == start:
start = a
return start
|
9b71f9c338f6c92d5018bf39eef53f9563bac4a9 | GinnyGaga/PY-3 | /ex21-1.py | 95 | 3.65625 | 4 | def add(a,b):
print ("add:%d+%d" % (a,b))
return a+b
age=add(3,9)
print("Age:a+b=%d" % age)
|
a8e4ebf81c13e2036f680da9104105c11417f026 | GinnyGaga/PY-3 | /ex21.py | 955 | 4.03125 | 4 | def add(a,b):
print ("ADDING %d+%d" % (a,b))
return a+b
def subtract(a,b):
print("SUBTRACTING %d - %d" % (a,b))
return a-b
def multiply(a,b):
print("MULTIPLYING %d * %d" % (a,b))
return a*b
def divide(a,b):
print("DIVIDING %d / %d" % (a,b))
return a/b
print ("Let's do some math with just functions!")
age=a... |
7b7221d1a38b3b3472880821bb12ce454e2130f5 | lrx0014/PythonStudy | /EXP 01/a.py | 198 | 3.875 | 4 | import math
ax=int(input('input ax:'))
ay=int(input('input ay:'))
bx=int(input('input bx:'))
by=int(input('input by:'))
print('distance: {0}'.format(math.sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by))))
|
b8abc8ad43ce2cae9f9d773acb9879383bf4c5b3 | lrx0014/PythonStudy | /HW 01/BinaryTree.py | 1,406 | 4.03125 | 4 | # BinaryTree
class BinaryTree(object):
def __init__(self, value):
self.__left = None
self.__right = None
self.__data = value
def insertLeftChild(self, value):
if self.__left:
print('Left Child Tree Already Exists!')
else:
self.__left = BinaryTre... |
91ef8bc1ea1b963fb0197d6faa1ecb2f93c93d23 | dimapanfilov/2Dto3D | /depthMap.py | 3,906 | 3.59375 | 4 | import numpy as np
import cv2
from matplotlib import pyplot as plt
import math
def depth_map(imgL, imgR, numDisparities, blockSize, location, scaleValue = 0.7):
"""
This function creates a disparity map using semi-global block matching (SGBM). Given two
stereo images and the parameters to SGBM, a... |
9bf2c2a9970021f7579803379323debb1843df10 | punitsakre23/Python-Essentials | /Day2-Assignment-Answers/Assignment-Answers.py | 1,685 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Q1. List and it's default functions
# In[1]:
lst = ["Keyboard", 23.123, "ESP8266", 789, .007]
# In[2]:
lst.append("Keyboard")
lst
# In[3]:
lst.count("Keyboard")
# In[4]:
lst.index(789)
# In[5]:
lst.reverse()
lst
# In[6]:
lst.clear()
lst
# # Q2. Dictio... |
8426f2cfd180c75e0d22b6c72d1b1bd2dc1b7fb0 | MadhushreeBardhan/python-script | /weeklist.py | 594 | 3.90625 | 4 | # 1) week_list = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun']
# input = {day: 'mon', 'number': 2}
# output = 'wed'
#
# input = {'day': 'fri', 'number': 28}
# output = ?
def finding(i,week_list,inputt):
if inputt['num']>(len(week_list)-1):
n=inputt['num']%7
i=i+n
else:
i=i+inputt... |
c85dc9b4248d76e757d67f5d2491861d736a4bb2 | Anchals24/Book-Series | /Bookseries Ques2 - Sorting Topic.py | 1,058 | 3.90625 | 4 | #Bookseries : Ques2
#Which element in array is repeating maximum times?
#Approach1 : Time Complexity : O(n ** 2) , Space Complexity : O(1)
A = [ 1 , 2, 1, 3, 1, 2, 4 ,5]
counter = 0
maxcounter = 0
candidate = A[0]
l = len(A)
maxcountelement = A[0]
for i in range(l):
candidate = A[i]
counter = 1
... |
3512a2f70c9d2c21fa9004e3d311238729286339 | DmytroBartoshchuk/algorithms | /quick_sort.py | 351 | 4 | 4 | # quick sort
our_list = [1,2,3,4,5,6,8,9,10,7]
def quick_sort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater... |
4d45ebaf7d0781ad37777b7ed36630b300740c34 | rctcwyvrn/advent | /advent2020/day9/cleaned.py | 834 | 3.5625 | 4 | def check(buf, val):
for x in buf:
for y in buf:
if x + y == val:
return True
return False
def find_xmas_weakness(nums):
buf = []
ctr = 0
invalid = None
for x in nums:
if ctr >= 25:
if not check(buf, x):
invalid = x
... |
f7ceba24d80f6f3bc4d93e245bc19379135c5f27 | tonycao/CodeSnippets | /python/homework/Archive/A6/A6_shan_slow.py | 966 | 3.546875 | 4 | import numpy as np
from datetime import date
def average_rain( data ):
week = np.zeros(len(data))
for i in xrange(len(data)):
week[i] = date(int(data[i,0]),int(data[i,1]),int(data[i,2])).weekday()
weekday = np.logical_and(week >= 1, week <= 3)
weekend = np.logical_or(week == 5, week == 6)
... |
8ed67ae3d95f7ab983bd9b4d2374ac60bf1d44cb | tonycao/CodeSnippets | /python/1064python/test.py | 1,882 | 4.125 | 4 | import string
swapstr = "Hello World!"
result = ""
for c in swapstr:
if c.islower():
result += c.upper()
elif c.isupper():
result += c.lower()
else:
result += c
print(result)
string1 = input("Enter a string: ")
string2 = input("Enter a string: ")
string1_changed ... |
0c58e1426767399c16999612d0a3d13096bd0cbc | tonycao/CodeSnippets | /python/1064python/inclass.py | 980 | 3.5625 | 4 | import smtplib
import email.mime.text
passwd = "tony19841211%" # TODO remove me when you submit
# TODO add prompts add the rest of the prompts
# prompt for "from"
emailfrom = input("From: ")
# prompt for "to"
emailto = input("To: ")
# prompt for "subject"
subject = input("Subject: ")
msg = input("Enter message: ")
... |
8e8f88499e37730afca505b61b44894d90c854f0 | tonycao/CodeSnippets | /python/1064python/hw2.py | 367 | 3.90625 | 4 | import math
principal_str = input("Please enter the principal:")
principal_flo = float(principal_str)
year_str = input("Please enter the number of year:")
year_int = int(year_str)
rate_str = input("Please enter the interest:")
rate_flo = float(rate_str)
rate = rate_flo/100
balance = principal_flo * (1 + rate)** yea... |
c0dc3edff15947038d179a0175c394400cee6b93 | tonycao/CodeSnippets | /python/homework/Archive/A3/A3_shan.py | 5,501 | 3.8125 | 4 | #######################################################################################
## Assignment 3 ##
## Discussion is allowed. ##
## Copying or sharing code is prohibited. ... |
d4cc17b886593011903bda1b28a0da4152a7c352 | Mytsa/Mytsa | /HW-5(sum_of_number).py | 866 | 3.8125 | 4 | num = raw_input("input numbers: ")
action = raw_input("input 'y' if you need cycle 'for': ")
n = 0
res1 = 0
i = 0
res2 = 0
rg = int(len(num))
if action == 'y':
for n in range(rg):
res = int(num[n])
res1 = res1 + res
for i in range(len(num)):
num = int(num)
res_... |
513395003f137ef66efe4836152bccf2aa72f88e | Mytsa/Mytsa | /HW-4(year_leap).py | 115 | 4.15625 | 4 | year = int(raw_input("input year:"))
print("It's a leap year!" if (year % 4 == 0) else "This is not a leap year!") |
aae80e394d43e2c64e604c3dfa9110530d2a29cb | Hitesh1912/Machine-Learning | /linear_reg_gd.py | 3,587 | 3.875 | 4 | # this code runs linear regression on housing price dataset
import numpy as np
import pandas as pd
import time
from random import shuffle
import matplotlib.pyplot as plt
# Function importing Dataset
def importdata():
train = pd.read_csv(
'http://www.ccs.neu.edu/home/vip/teach/MLcourse/data/housing_train.... |
0a3a4b685075794e5e5e53a055e558c25a9a5ec1 | nathan-pichon/Eternity2-research | /algorithm.py | 2,998 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import csv, random, copy
from piece import Piece
from board import Board
## algorithm
## for our program it's like one island
## self.boards is an array of boards
## self.best is the best board
class algorithm:
def __init__(self, numberOfBoards):
... |
a0da07e7ac24a6d8f3f146b6023594194d108682 | JordanHoover/algorithms | /find_two_ints_that_multiply_to_x.py | 375 | 4.09375 | 4 | # Given an Array of numbers, find 2 integers that multiple to a certain
# value
# naive solution
def find_two_ints(input_array, target_value):
for n in input_array:
for x in input_array[1:]:
if x*n==target_value:
return x,n
# put in the Array
arry = [1,4,1,6,5,9,20,-3,20]
# print out the 2 n... |
85eda34dc6d393bbe38e1497943cbed06249a03d | ulido/stochastictoolkit | /stochastictoolkit/external_drift.py | 1,800 | 3.515625 | 4 | '''external_drift.py
Classes
-------
ExternalDrift - base class for all external drift objects
ConstantDrift - generic class to apply a constant drift
'''
from abc import ABC, abstractmethod
import numpy as np
__all__ = ['ExternalDrift', 'ConstantDrift']
class ExternalDrift:
'''Base class for all external drift ... |
78312f75f286846a2ce181fc585c4391b7c49d04 | edoardovivo/algo_designII | /Assignment6/two_sat.py | 5,343 | 3.875 | 4 | """
In this assignment you will implement one or more algorithms for the 2SAT problem. Here are 6 different 2SAT instances:
The file format is as follows. In each instance, the number of variables and the number of clauses is the same, and this number is specified on the first line of the file. Each subsequent line sp... |
3ef8ae836387bc3b46cbe18d9f2189cf90f27d78 | nagasudhirpulla/wrldc_metering_warehouse | /app_utils.py | 247 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 11:45:02 2019
@author: Nagasudhir
"""
# derive intersection of 2 lists
def intersection(lst1, lst2):
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
return lst3 |
d1a3d0dab1033089576b31a71b0c27bc72314111 | lyloster/MathAdventuresWithPyhon | /Chapter1/1.3triAndTri.py | 255 | 4.03125 | 4 | from turtle import *
shape('turtle')
#for the turn use the external angle which the turtle turns,not the internal
def triangle(sidelength=100):
for i in range(3):
forward(sidelength)
right(120)
speed(0)
triangle(50)
|
4302d5fd7b255d536fe473924b428d6c14a9e9d4 | lyloster/MathAdventuresWithPyhon | /Chapter3/wander.py | 440 | 3.921875 | 4 | from turtle import *
from random import randint
shape('turtle')
speed(0)
#turtle wanders on screen, press X to exit
def wander():
while True:
#forward
fd(3)
#x and y coordintes are from -300 to 300 by default
if xcor() >= 200 or xcor() <= -200 or ycor() <= -200 or ycor() >= 200:
#left turn
... |
1a37e1907d92d5ddda4fadf925d8c5f299ad09c3 | WeijiaMa123/chapter-4 | /4_5.py | 305 | 3.703125 | 4 | import turtle
wn=turtle.Screen()
wn.bgcolor("lightgreen")
frank = turtle.Turtle()
frank.speed(10)
frank.color("blue")
def draw_spiral(turt,sz,space):
turt.right(90)
for i in range(98):
turt.forward(sz)
sz = sz+space
turt.right(90)
draw_spiral(frank,10,2) |
20da679b389b1a104ddb866b04e56087eed7c893 | fahadun/pygame_tutorial | /ex02.py | 645 | 3.9375 | 4 | import pygame # Imports pygame package
pygame.init() #Initializes pygame
screen = pygame.display.set_mode((600, 400)) #Creates a screen
green = (0,128,0) #RGB for color green
red = (255,0,0) #Rgb for color red
running = True
while running:
for event in pygame.event.get(): #get events from the queue
if ev... |
a516ab11706af66b8f140f6703d6ef21feaf7ca2 | jenifa0421/30-days-of-python | /day13.py | 5,234 | 3.734375 | 4 | class CoffeeMachine:
water = 300
milk = 400
coffee = 150
money = 0
def __init__(self, opt):
self.value = opt
def report(self, opt):
print("Water:", self.water, "ml\nMilk:", self.milk, "ml\nCoffee:", self.coffee, "g\nMoney:$", self.money)
def makecoffee(self, op... |
757076bb40e37eba3b62ab831df3df37e2ed602e | DShmunk/h3_homework | /pingpong.py | 1,107 | 3.5 | 4 | from multiprocessing import Process, Pipe
from time import sleep
from os import getpid
# receive a message
# print it as f"Process{getpid()} got message: {msg}"
# sleep before responding
# send response message back
def ponger(receiver, sender, response):
while True:
response = receiver.recv()
prin... |
40f7c39f57a052189d8341d56e9ee441e502e6d0 | DShmunk/h3_homework | /HW_on_09.11.2020_decor2.py | 1,820 | 3.703125 | 4 | # Напишите декоратор для превращения функции print в генератор html-тегов
# Декоратор должен принимать список тегов italic, bold, underline
# Результатом работы декоратора с аргументами italic, bold должно быть преобразование из строки вида "test string" в "<i><b>test string</b></i>"
def str_to_html(tags):
de... |
adf4d247f1f4be159fab8e71413e7edcc3bd3d3d | ToDevelopersTeam/DS-Algos | /codeforces/practice/HQ9+.py | 122 | 3.84375 | 4 | s = raw_input()
check = ["H","Q","9"]
match = [i for i in check if i in s]
if len(match)>0:
print "YES"
else:
print "NO" |
9d17b47acae875eb2168ec89378c18576f179a2a | ToDevelopersTeam/DS-Algos | /codeforces/practice/Word.py | 138 | 3.734375 | 4 | s = raw_input()
low=0
high=0
for i in s:
if i.islower():
low+=1
else:
high+=1
if low>=high:
print s.lower()
else:
print s.upper()
|
c4c8eebc18df3f107b6b540fc4a8a29062603a57 | ToDevelopersTeam/DS-Algos | /codechef/practice/beginner/Piece_of_Cake.py | 235 | 3.53125 | 4 | from collections import Counter
t = int(raw_input())
while t>0:
string = str(raw_input())
flag = "NO"
freq = Counter(string).values()
total = sum(freq)
for i in freq:
if i*2 == total:
flag = "YES"
break
print flag
t-=1
|
b25f5c8f6adea7c0f6f0ecc045c8eb76718ee48a | mrspockengineering/Spracherkennung_de | /pyaudio_aufnehmen.py | 1,682 | 3.78125 | 4 | '''
Created on 17.11.2019
speech_recognition -> funktioniert mit headset SilverCrest SKBA -> tests
https://www.youtube.com/watch?v=BWFc9JsSELw
https://www.youtube.com/watch?v=vSzjnUS8u8k
https://realpython.com/python-speech-recognition/#how-speech-recognition-works-an-overview
Funktionen:
- diktiert TExt
- Funktion... |
8bbb66040ced7643ffd910104c75d0c3f486f89a | vlad-user/log-linear-pos-tagger | /main.py | 1,554 | 3.703125 | 4 | """Trains, evaluates model1 and stores two models."""
import pickle
import train_and_eval
def main():
"""Trains, evaluates and stores two model2.
To test the model during training, use `store_intermediate=True`
flag as in following example:
```python
# start training from one script:
# ...
... |
6b95c30f0b8f865433c4a442bafa8f0b27c1b619 | joelsewhere/qc_opportunity_youth | /src/data/sql_utils.py | 6,119 | 3.625 | 4 | import psycopg2
import pandas as pd
import os
DBNAME = "opportunity_youth"
def create_database_and_tables():
create_database()
create_tables()
print("Successfully created database and all tables")
print()
def create_database():
"""
This function assumes that you have an existing database cal... |
d7f42953edff49b748c99be05a79759fa6b994fc | zk18051/ORS-PA-18-Homework02 | /task2.py | 361 | 4.125 | 4 | print('Convert Kilometers To Miles')
def main():
user_value = input('Enter kilometers:')
try:
float(user_value)
print(float(user_value),'km')
except:
print(user_value, 'is not a number. Try again.')
return main()
user_miles = float(user_value) * 0.62137
print(user_val... |
e773b604dc7d40060804ffa4aa0255141648396a | KristiGourlay/tipsy | /scratch_pads/tipsy2.py | 1,376 | 3.65625 | 4 | import pandas as pd
import numpy as np
def df_maker():
names = input('Who worked?').split(',')
times = input('How many hours?').split(',')
monies = input('How much in tips?').split(',')
new_times = []
money = []
for n in times:
new_times.append(int(n))
for m in monies:
mo... |
e45ab4b4955bf394866275d21450fc2d6e6ca881 | Cloudxtreme/lensmoorbookgenerator | /bookclasses.py | 1,157 | 3.578125 | 4 | #!/usr/bin/python
import pdb
class Book:
def __init__(self):
self.title = None
self.author = None
self.keyword = None
self.colors = {'header': '{c',
'subheader': '{D',
'body': '{x',
'footer': '{c'}
self.sections = []
def set_title(self,t... |
1b2e59962a6972c3ea5e48f21f2882cc0e531eef | kshitijdesai99/DSA | /Trees.py | 5,359 | 4.03125 | 4 | class Node:
def __init__(self, data = None):
self.data = data
self.left_node = None
self.right_node = None
class BinaryTree:
def __init__(self):
self.root = None
def inorder(self):
if self.root == None:
print("Tree is Empty..")
else:
... |
6828501a48c9359b03499b328479da597bc7e126 | shenjie1983/Study-Python | /Day01-15/code/Day01/variable1.py | 458 | 3.5625 | 4 | '''
@Descripttion:使用变量保存数据并进行操作
@version: 0.1
@Author: 沈洁
@Date: 2019-09-17 15:39:20
@LastEditors: 沈洁
@LastEditTime: 2019-10-14 11:30:02
'''
a = 321
b = 123
print('a + b = ', a + b)
print('a - b = ', a - b)
print('a * b = ', a * b)
print('a / b = ', a / b)
print('a // b = ', a // b) # 返回乘法的整数部分
print('a % b = ', a % ... |
a2205d35d8b88482ba4f040542a3960dfaeb4e9a | shenjie1983/Study-Python | /study_1/sj_4/c2.py | 167 | 3.5625 | 4 | import re
a = 'C|C++|Java|C#|Python|Javascript'
# re.findall('正则表达式', a)
r = re.findall('Python', a)
if len(r) > 0:
print('字符串中包含Python')
|
11d0d0b58a3afa9f22c0b743fe01bc5ef91bbbaa | shenjie1983/Study-Python | /study_1/sj_4/c16.py | 387 | 3.671875 | 4 | # 反序列化
import json
json_str1 = '{"name":"qiyue", "age":18}'
json_str2 = '[{"name":"qiyue", "age":18, "flag":false}, {"name":"qiyue", "age":18, "flag":false}]'
# loads函数将json数据类型转化为python数据类型
# 反序列化
student1 = json.loads(json_str1)
print(type(student1))
print(student1)
student2 = json.loads(json_str2)
print(type(stu... |
4c5f19c84ea74db5b488796d5d7538256d08fa2d | shenjie1983/Study-Python | /study_1/sj_5/c1.py | 314 | 3.640625 | 4 | # 类型
# 腾讯各种砖——1、绿钻、黄钻、红钻、黑钻等,通常存储数据,可读性弱
# python提供枚举
# 导入引用枚举类
from enum import Enum
# 枚举定义的标识,建议使用大写
class VIP(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
print(VIP.YELLOW)
|
5ddf83bfc722ca7ebb53d5a5f10b83a9416fded3 | shenjie1983/Study-Python | /Day01-15/code/Day01/is_leap.py | 333 | 3.65625 | 4 | '''
@Descripttion:输入年份 如果是闰年输出True 否则输出False
leap:闰年
@version: 0.1
@Author: 沈洁
@Date: 2019-06-12 11:20:07
@LastEditors: 沈洁
@LastEditTime: 2019-10-12 10:39:48
'''
year = int(input('输入年份:'))
is_leap = (year % 4 == 0 and year % 100 != 0 or
year % 400 == 0)
print(is_leap)
|
bc804b3e034f77bc80d88796f6879f092598d9ee | E-Tsubo/Procon | /aoj/ALDS1_7_B_BinaryTrees.py | 3,825 | 3.8125 | 4 | # -*- Coding: utf-8 -*-
from math import *
#無理やり作ったので汚い。。
class Node(object):
"""A Node for BinaryTree"""
"Constructor"
def __init__(self, parent = -1, left = -1, right = -1):
self.parent = parent
self.parentIdx = -1
self.left = left
self.leftIdx = -1
self.right = right
self.right... |
ae4a4aab6da45d5a6356d33df9f77423a2ba00c6 | E-Tsubo/Procon | /aoj/ALDS1_2_A(BubbleSort).py | 680 | 3.78125 | 4 | # -*- Coding: utf-8 -*-
#競技プログラミング用
from decimal import *
import sys
#バブルソート(安定なソート)
def bubbleSort(a,n):
sw = 0
for i in range(0,n-1,+1):
#右端から、隣同士の値を比較して、入れ替えを実施
#1ループ終わるごとに、左端にソート済みの数値がおかれるので、探索範囲が狭まる
for j in range(n-1,i,-1):
if a[j-1] > a[j]:
tmp = a[j-1]
a[j-1] = a[j]
a[j]... |
7bcef89710589fbe569e6a9cb711264cd0b95546 | E-Tsubo/Procon | /aoj/ALDS1_6_B_Partition.py | 862 | 3.5625 | 4 | # -*- Coding: utf-8 -*-
from math import *
# Partitionは、ある値を基準に小さいか大きいかで並び替えを行うアルゴリズム
# クイックソートは分割統治法に基づくが、この技術を分割の部分に利用している。
def Partition(A, p, r):
x = A[r]
i = p - 1
#jは0-番兵ひとつ前まで(j<rが条件)
for j in range(p, r):
if A[j] <= x:
i = i + 1
A[i], A[j] = A[j], A[i]
#最後に基準としていた最後尾の数値を、A[i... |
4feb41a341721fbeb2fd463560d8385af1eb3929 | Nagarjune1/Genetic-Pathfinding-Processing | /Vehicle.py | 3,631 | 3.609375 | 4 | class Vehicle(object):
# how many moves have been made by this vehicle
lifetime = None
# the closest this vehicle has gotten to the goal cell
lowestDistance = None
# how long it took the vehicle to make it to the goal cell
timeArrived = None
# if the vehicle has arrived to the goal cell
... |
84c07ddcb310aaaaba2b5fad42058c9feadb3490 | manali1312/pythonsnippets | /HR_Sets.py | 280 | 3.765625 | 4 | FirstSet = set([3,1])
SecondSet = set([5,1])
ArrayForSearch = [1,5,2]
count = 0
for num in ArrayForSearch:
print(num)
if num in FirstSet:
count +=1
print(count)
if num in SecondSet:
count -=1
print(count)
print("Final count: ",count)
|
61fffd675337476f9d8242dfb83450372af25d2c | manali1312/pythonsnippets | /HR_finding_Percentage.py | 511 | 4.03125 | 4 | def student(name):
marks = {"manali":(88,78,89),"utkarsha":(98,72,91),"devang":(71,72,94),"sohini":(89,82,78)}
if name in marks:
markes_new = marks.get(name)
print(markes_new)
result = 0
for num in markes_new:
result += num
print(result)
ave... |
cdf34aa97f087889a3b0d12e05246955b2522a32 | manali1312/pythonsnippets | /reduce_example.py | 132 | 3.625 | 4 | a=[1,2,3,4]
'''
def add(a,b):
return a+b
ans = reduce(add,a)
print(ans)
'''
ans = 0
for i in a:
ans = ans + i
print(ans)
|
7a15ba5ec8fbfc22d569193c326f5b50aef40f63 | manali1312/pythonsnippets | /HR_Func_leapyr.py | 336 | 4.1875 | 4 | def leapYear():
year = int(input("Enter an year:"))
if year%4==0 or year%400==0:
if year%100==0 and year%400!=0:
print("Not a leap year")
else:
print("It is a leap year")
else:
print("This is not a leap year")
if __name__ == '__main__':
leap... |
0b71eb4902fe32e3bc0d7dc6de86722cd3720fc7 | manali1312/pythonsnippets | /reduce_string.py | 107 | 3.6875 | 4 | a = ['a','b','c','d']
def concatStr(l1,l2):
return l1 + " " + l2
ans = reduce(concatStr,a)
print(ans) |
df21edc96a6b4570ea06736177b946c486d1b333 | ssh6189/2019.12.10 | /dictionery.py | 1,945 | 3.765625 | 4 | #key는 unique해야 하며, 불변 이다 , value 는 가변(변경 가능)
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Alice']: ", dict['Alice']) #존재하지 않는 키로 요소에 접근할 경우?
dict['Age'] = 8; #요소의 val... |
44079e3a2a5403f63d14e3b7075a5d021a33102f | ssh6189/2019.12.10 | /이진수 변환 제작.py | 98 | 3.71875 | 4 | num = int(input("수를 입력하시오."))
str
while num > 0:
a = num//2
b = num%2
|
78fbc1ea4c6022da0b30d94175129fb3240727b2 | Amartya-vats/API-request | /api request.py | 798 | 3.578125 | 4 | # simple api requesting and posting a rough sketch
import requests
import json
# easiest way to manupilate json data is to use class and then run loops through it
URL_getting ='__'
URL_posting ='__'
#function to get from the url supplied in the main
def getting ():
r = requests.get(URL_getting)
return r.jso... |
e8db5377932f021ca4f58ca489e5015e69b91058 | saikumar176/pro | /21.py | 318 | 3.75 | 4 | def avgr(lst_ab):
return sum(lst_ab)//len(lst_ab)
inp = int(input())
lst = [int(x) for x in input().split()]
lst1 = []
for i in range(len(lst)-1):
if avgr(lst[0:i+1]) == avgr(lst[i+1:inp]):
lst1.append('yes')
else:
lst1.append('no')
if 'yes' in lst1:
print('yes')
else:
print('no')
|
916046b72056056b21889a785cec39379d14462d | skieffer/py3dm | /q5.py | 2,548 | 3.75 | 4 |
"""
Question 5
Give a polynomial-time reduction from 3DM to SAT.
In other words, given a 3DM problem T (a set of triples), we must convert it into
an equivalent SAT problem P, i.e. a formula P in conjuctive normal form that is
satisfiable if and only if there exists a solution S for the problem T.
TASK 1: Implement... |
c3b96ecc497ebc3be6fd6ea1b389085220ec22f5 | Tianhao-Shao/CIS-2348-Homework | /Homework #1/5.19 main.py | 1,176 | 3.78125 | 4 | # Tianhao Shao
# 1781421
print("Davy's auto shop services")
print('Oil change -- $35\nTire rotation -- $19\nCar wash -- $7\nCar wax -- $12\n')
user_service = {'-':0,'Oil change':35, 'Tire rotation':19, 'Car wash':7, 'Car wax':12}
user_service1 = input('Select first service:\n')
user_service2 = input('Select second s... |
7843ece86756b4e0a7c95ab8da1434bc24908bfd | Tianhao-Shao/CIS-2348-Homework | /Homework 2/9.10 main.py | 395 | 3.703125 | 4 | # Tianhao Shao
# 1781421
import csv
#Enter the file name:
file = input()
#make dic for frequency
frequency = {}
with open(file, 'r') as csvfile:
csvfile = csv.reader(csvfile)
for row in csvfile:
for word in row:
if word not in frequency.keys():
frequency[word] = 1
else:
frequency[word] =frequency... |
c6586b03278f0cc365a8c67ecc10d5fe4c66d002 | navvenkumar/navenkumar | /program8.py | 125 | 3.609375 | 4 | dict1 = {"naveen": 29, "chinnu": 10}
dict2 = {"teja": 13, "bannu": 7}
dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)
|
e99c5c9be98da1ea30586e596d0418bebd418d92 | rowiki/wikiro | /robots/python/geo/mapillary.py | 1,737 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script tries to obtain images from Mapillary based on how a set of
coordinates and other information.
TODO: Pagination in responses
"""
import json
import requests
def get_images_looking(api_key, lat, lon, radius=100, limit=1000):
"""
Function that obtain... |
cb2fc7f4fb4645112a504dca8e3de85b7c0b4af4 | 8story8/python | /18_inheritance.py | 1,004 | 3.859375 | 4 | class User:
def __init__(self, name, phone):
self.__name = name
self.__phone = phone
print("User object initialized!")
def get_name(self):
return self.__name
def get_phone(self):
return self.__phone
def __del__(self):
print("User object destroye... |
25e19ba52815976722636e5422868a7de6ece725 | 8story8/python | /24_try_except.py | 223 | 3.625 | 4 | # x = 1
try:
print(x)
except NameError:
print("Variable x is not defined!")
except:
print("Something else went wrong!")
else:
print("Nothing went wrong!")
finally:
print("The 'try except' is finished!") |
335b126081e6128784cad9b52692003f31a75808 | 8story8/python | /23_regex.py | 210 | 3.640625 | 4 | import re
string = "Hello, I am Kiske!"
x = re.findall("am", string)
print(x)
x = re.search(r"\s", string)
print(x.start())
x = re.split(r"\s", string, 3)
print(x)
x = re.sub(r"\s", "777", string)
print(x) |
537343d89b8f0d1565fbdf398feacef5ea4b6fe7 | grihanotpresent/15-112-Coursework | /week9/lab9.py | 10,078 | 4.1875 | 4 | #################################################
# Lab9
#Derek Li (derekl1)
#Trevor Arashiro (tarashir)
# No iteration! no 'for' or 'while'. Also, no 'zip' or 'join'.
# You may add optional parameters
# You may use wrapper functions
#
#################################################
import cs112_f17_week9_linter
im... |
c0d3b865ccb4f5bbdbd58e76c6b1dc5e6e3227ad | sakshamsin09/Tic-Tac-Toe | /tic_tac_toe.py | 4,796 | 4.09375 | 4 | from IPython.display import clear_output
import random
#1 function for displaying board
def display_board(b):
clear_output()
print(b[1]+'|'+b[2]+'|'+b[3])
print(b[4]+'|'+b[5]+'|'+b[6])
print(b[7]+'|'+b[8]+'|'+b[9])
#2 function that take user input and assign their markers
def player_input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.