blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
622750c767c0da2a154488c0ee329de58b466bc7
sergokov/batch_gradient_descent
/src/gradient descent_vectorized.py
1,765
3.515625
4
import random import matplotlib.pyplot as plt import numpy as np from sklearn import datasets # Load dataset diabetes = datasets.load_diabetes() # Use only one feature X = diabetes.data[:, np.newaxis, 2] # Split the data into training/validation sets X_train = X[:-20] X_val = X[-20:] # Split the targets into trai...
bccf3e842b365bce42c037fe72df853ab52663ed
WenJuing/scrapy-douBan
/C2-PythonBasis/2.11-colorPrint.py
968
3.640625
4
import sys class ColorPrint(object): def __init__(self): self.color = "red" self.msg = "cao" self.cPrint() def cPrint(self): colors = { 'black': '\033[1;30;47m', 'red': '\033[1;31;47m', 'green': '\033[1;32;47m', 'yellow': '\033[1;...
16406432b9a40bf9ace5f7d950d9774df9466784
WenJuing/scrapy-douBan
/study/类.py
2,871
4.0625
4
# 创建Dog类 class Dog(): '''一只可爱的小狗''' def __init__(self, name, age): # 使用类时自动运行,接收参数并返回实例 self.name = name self.age = age def sit(self): '''坐下命令''' print(self.name.title(), "is now sitting!") def describe_dog(self): '''输出小狗信息''' print("Dog's name is", s...
886f2ef9c4e72f8d501ac83fb5dce28bb25be583
WenJuing/scrapy-douBan
/C3-ComPythonScript/3.2-fibonacci.py
477
3.828125
4
# 输出斐波那契数列 def bibon(n): n1 = 0 n2 = 1 print("%d %d " % (n1, n2), end='') for i in range(0, n+1): n3 = n2 + n1 print(n3, end=' ') n1 = n2 n2 = n3 listLenStr = input("请输入fibonacci数列的长度(3~50):") try: listLen = int(listLenStr) except ValueError: print("输入值类型不正确!") ...
ca69299c324e6cb290ab2bb9e9d530b1d0eefbdb
WenJuing/scrapy-douBan
/C2-PythonBasis/2.4.1-ComSysFunc.py
1,321
4
4
# 常用内置函数 n = -5 li = [1, 2, 3] tu = ("a", "b", "c") print("n的值:%d" % n) print("list的值:%s" % li) print("tuple的值:%s" % list(tu)) # abs()取绝对值 print("n的绝对值为:%d" % abs(n)) # max()取最大值 print("list的最大值:%d" % max(li)) # min()取最小值 print("list的最小值:%d" % min(li)) # divmod()取模 print("7除3=%s" % list(divmod(7, 3))) # len()计算长度 prin...
e3a9207b7e744a154172adbe83474a745c2d998e
WenJuing/scrapy-douBan
/C2-PythonBasis/2.4-showTuple.py
1,075
4.40625
4
class showTuple(object): def __init__(self): self.T1 = () self.createTuple() # 创建元组 self.subTuple(self.T1) # 元组分片 self.tuple2List(self.T1) # 元组、列表转换 def createTuple(self): print("创建元组:") self.T1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(self.T1) ...
f8436e698dcb4edc9d9b673dba088654b51ac696
rajatvd/ProjectTemplate
/training_functions.py
3,690
3.546875
4
""" Train on batch function for training a ConvNet on MNIST """ import torch from torch import nn from torch import optim import logging from tqdm import tqdm import pytorch_utils.sacred_trainer as st def train_on_batch(model, batch, optimizer): """One train step on batch of MNIST data. Uses CrossEntropyLoss. ...
3c094ed93a9cb3cd3b530b6992293831b9584fa5
ngrvineeth/Simple-bank-application
/bank_app.py
1,066
4.03125
4
#bank apllication import sys class customer: bankname="ngr's bank" def __init__(self,name,balance=0): self.name=name self.balance=balance def deposit(self,amt): self.balance=self.balance+amt print('After deposit the balance:',self.balance) def withdraw(self,amt): ...
67001758a40dac78880aa950252d25fdfc6fa1eb
jd45p8/Primes-counter
/test.py
323
3.59375
4
from count_primes import count_primes_up_to from find_primes import find_primes #n = int(input('Digite el n: ')) for i in range(1,1000): print("n = " + str(i)) print(" " + str(count_primes_up_to(i)) + " - " + str(len(find_primes(i)))) if count_primes_up_to(i) != len(find_primes(i)): brea...
93f10e194d4ee1bdf7f6da98f619bbcf346ece04
numanonur/hesapMakinesi
/hesapMakinesi.py
2,608
3.578125
4
while True: cal=input("""------------------------------------------- | Hesap makinesine hoş geldin | | Tooplama İşlemi için-----------------1 | | Çıkarma İşlemi için------------------2 | | Çarma İşlemi için--------------------3 | | Bölme İşlemi için--------------------4 | | Üslü işlemler için------------...
113f0f61ccc2e1dd465bbc2f6fa7b1b8f8d78d47
sywangs/python-learning
/dictionary/many_users.py
515
3.765625
4
# define nested dic users = { 'aeinstein':{ 'first':'albert', 'last':'esnstein', 'location':'princeton', }, 'mcurie':{ 'first':'marie', 'last':'cuire', 'location':'paris', } } #access to the dic inside for user_name,user_value in users.items(): print...
5c00dd06e2d47e479d1414ec53f1a3fd44bfdbb2
Guiyed/user-signup
/validators.py
952
3.90625
4
def validateUsername(username): if username == "": return 'User is empty' elif " " in username or not username.isalpha() or len(username) > 20 or len(username) < 3: return 'User must contains between 3 and 20 alphanumeric characters' return '' def validatePassword(password): if password == "": ...
3a3acc7714728e1a183c222bfe5d109d360682b0
kosemMG/python_avratech
/exercise-6-calculator-oop.py
1,839
3.703125
4
class Operation: def __init__(self, input_obj): self.arg1 = input_obj.arg1 self.arg2 = input_obj.arg2 class Add(Operation): def __init__(self, input_obj): Operation.__init__(self, input_obj) def run(self): return self.arg1 + self.arg2 class Subtract(Operation): def _...
f4793c84c1cd21a9b162927514b9e0469ef3b6f8
kosemMG/python_avratech
/exercise-2-multiples.py
111
3.890625
4
number = input('Enter a number: ') for i in range(1, 11): print('%s * %s = %s' % (number, i, number * i))
1495d71aad82337c3002d566f5d7548ed1387e81
xaviBlue/curso_python
/tuples.py
191
3.765625
4
x = (1,2,3,4,5) print(type(x)) y=tuple((1,2,3)) print(y) print(x[0]) #usamos del para eliminer la tupla locations={ (34.56,6431.4):"tokyo", (34.6,641.4):"orlando" } print(locations)
54ee9334ece78806d560a622d228da9fd2a4eab5
xaviBlue/curso_python
/variables.py
248
3.546875
4
name = "Xavier" print(name) number=100 print(number) x=100 book="Juntos Solos" print(x, book) #Convenciones book_name="El principito" bookName="Hola" BookName="Estoy bien" #Constante PI = 3.1416 #Mayusculas book_name="I robot" book_name=121112
a49e6a4e39b2cac1b756204784bb394f97e24760
Jaculabilis/horsay
/horsay.py
3,350
3.90625
4
#!/usr/bin/env python3 from argparse import ArgumentParser from sys import stdin, stdout def parse_args(): parser = ArgumentParser(description="Displays input straight from the horse's mouth.") parser.add_argument("-u", "--unicode", action="store_true", help="Use fancier lines for the text bubble") parser.add_...
b3063f4cb40bd85ca0e31f9061b6a3fb11174eff
zhsheng26/PythonLesson
/基础语法/8_set.py
713
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/12 14:12 # @Author : zhangsheng # set 没有重复的元素 # 创建一个set a_set = {6, 3, 4, 2} print(isinstance(a_set, set)) # 将list转为set a_list = [5, 1, 3, 6, 5, 6] print(a_list) a_set = set(a_list) # 重复元素在set中自动被过滤 print(a_set) s1 = set([1, 1, 2, 2, 3, 3]) print(s1)...
76eec6db49c0b260ed7536563322920e80395c6e
zhsheng26/PythonLesson
/面向对象/4_获取对象信息.py
1,492
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/18 11:30 # @Author : zhangsheng # 判断对象类型,使用type()函数:返回对应的Class类型 import types print(type('abc') == type('123')) def fun(): pass print(type(fun) == types.FunctionType) print(type(abs) == types.BuiltinFunctionType) print(type(lambda x: x) == ty...
21d46e6dd097d54b3854d66fbd73ad8ca96f9d5e
zhsheng26/PythonLesson
/面向对象高级/6_使用元类.py
907
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/19 08:58 # @Author : zhangsheng # type()函数可以查看一个类型或变量的类型 class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name) h = Hello() # Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello print(type(h)) print(type(Hello)) ...
dcd5d70bb8eed2f4ead275f53a5b49c64940de32
zhsheng26/PythonLesson
/基础语法/5_tuple.py
924
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/12 11:13 # @Author : zhangsheng # @Site : # @File : 5_tuple.py # @Software: PyCharm # tuple 元组,是有序的列表,一旦初始化,不能修改 classmates = ('Michael', 'Bob', 'Tracy') # 没有append(),insert()这样的方法 # 因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。 # 定义一个空的tup...
e5971846f436b77afc6e90e504c2af759f72085e
zhsheng26/PythonLesson
/常用内建模块/日期datetime.py
557
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/27 21:07 # @Author : zhangsheng from datetime import datetime # 获取当前日期和时间 print(datetime.now()) # 获取指定日期和时间 print(datetime(2017, 9, 27, 12, 20)) # 时间戳 :如果有小数位,小数位表示毫秒数。 print(datetime.timestamp(datetime(2017, 9, 27, 12, 20))) # str转换为datetime cday = ...
7903efa7f03af0f25ee49877d9734f3990cd66a3
SAGAR-DAM/assignment-4-semester-2
/problem 6.py
957
3.5
4
''' Assignment 4 problem 6 generating gaussian data from uniform random numbers using Rejection method NAME: SAGAR DAM; DNAP''' import numpy as np from matplotlib import pyplot as plt #generating random numbers and rejecting according to given distribution y=[] for i in range(1000000): x1=4*np.random.random() ...
625f0ce31d4fecc9cf0bbf1a41f4769ed7463546
MattJ-UK/mit_course
/600.1x/Week 2/polysum.py
370
3.796875
4
import math def polysum(n,s): """ :param n: number of sides of polygon (int) :param s: length of those sides :return: area of polygon + perimeter of polygon squared. Rounded to 4dp. """ # calculate and return area (left of '+') and add the square of the perimeter (right of '+') return roun...
59001c21f00e72840d8538a747fb88324f8be84c
MattJ-UK/mit_course
/600.1x/Week 1/Problem 1 - Vowels.py
175
3.828125
4
s = 'dahhurfvkiaatugb' vowels = 'aeiou' count = 0 for i in s: for v in vowels: if i == v: count = count + 1 print('Number of vowels: ' + str(count))
14e1b922d9266986c8687513ea03ca761beb2c3c
divyasanchana/divyastrove
/arabic_to_roman.py
343
3.5625
4
num=input() num=int(num) if (num<4): print('I'*num) elif num==4: print('IV') elif num==5: print('V') elif num<=9 and num>5: print('V'+('I'*(num-5))) elif num>=10 and num<=13: print('X'+('I'*(num-10))) elif num==14: print('XIV') elif num>=15 and num<=18: print('XV'+('I'*(num-15))) elif num==19: print('XIX') elif...
7c53bd4f14ed486f1dc34c249133dfcb7772ad40
divyasanchana/divyastrove
/reverse_of_string.py
64
3.84375
4
string=input() reverse=''.join(reversed(string)) print(reverse)
fd753ee9845d4ca220639191102d37f11dd3e983
saigagan/python
/28-01-2020/withrtn_witharg.py
108
3.59375
4
def Addition(a, b): Sum = a + b return Sum print("After Calling the Function:", Addition(25, 45))
9cb3f03aabf6f425e4e9c65672ad54efc1dffcaa
vicentedr96/Fundamentos-de-python
/Ordenamientos/02-ordenamiendo-quickSort-1.py
1,271
3.5625
4
import time class Ordenamiento(): #constructor def __init__(self,arr=[]): self.arr=arr self.comp=0 self.tiempoFinal=0 self.cambios=0 def orden_creciente(self,arr=None): if(arr!=None): self.arr=arr if(len(self.arr)<1): return [] ...
692743b98aa8c722949becfdef412c349839bd26
Kontari/MapGen
/MakeMap.py
7,158
3.53125
4
from PIL import Image import random as r import math h=100 w=100 known_islands = [] def create_grid(height=10, width=10, populate=True): ''' Creates a height x width array. If populate is true randomizes numbers placed in list. ''' grid = [] for _ in range(height): temp = [] ...
0468cfac7c0cf8a8e101acb74b1f203509e1e88a
810Teams/atm-problem-generator
/atm.py
3,081
3.875
4
''' `atm.py` ATM Problem Generator Information System Security and IT Laws class, IT KMITL. by Teerapat Kraisrisirikul Getting Started - Just run this code file. - Global variable(s) can be edited to your liking. ''' from random import randint DISPLAY_COLUMNS = 5 def main(): ''' Mai...
bfef831b497e5fa0adebd7ad0d3c08fb2f23c37a
the-fanan/python-algorithms-practice
/tutorial/dsap-rance-d-necaise/queues-pad.py
1,970
3.625
4
#Python Algorithms and Data Structures from array import Array # First In First Out (FIFO) # has worst caserunning time of O(n) class ListQueue : def __init__(self): self.items = list() self.size = 0 def __len__(self): return self.size def isEmpty(self): return self.size == 0 def enque(self,item): se...
d99c21e13bef5abf91cace232f05272fb6470f5d
the-fanan/python-algorithms-practice
/challenges/hackerrank/golsmansachs-interview-1.py
2,819
3.90625
4
mapping = [1,2,4,5,6,8,9,3,7,0] num = ['990', '034', '16','116', '34','09'] #geberate the correct value and the oder 'num' in ascending order according p their actual values. If two actual values are same then follow order of occurrence in 'num' def createListOfLists2(mapping, num): listOflists = list() if len(num) >...
8bba654d46dee2ac08bd57a21de5feb09986cbb2
the-fanan/python-algorithms-practice
/challenges/hackerrank/array-manipulation.py
584
3.859375
4
# Hard # you are given # arrayManipulation has the following parameters: #n - the number of elements in your array #queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k. def arrayManipulation(n, queries): e = [0] * (n + 1) for query in queries: e[query[0] - 1] += ...
02d0c0621085e799b2dd5f780a11fad230fbef0e
rupeshvkm/Python
/aasgn2-2007.py
194
3.703125
4
a={'emp1':{'name':'rup','salary':20000},'emp2':{'name':'raj','salary':21000}} flag=a['emp1']['salary']; for i in a: if(a[i]['salary']>flag): flag=a[i]['name'] print(flag) help
ec0461f53d2711abdede0da03382738f9076f24a
rupeshvkm/Python
/assgn51707.py
88
3.640625
4
c=3.62 c-=int(c) print(c) if(c==0): print('No decimal') else: print("Decimals")
a5845bb3c70cdc0276e4a094ca583e260b0fef19
Rahandi/college
/naivebayes/del.py
724
4.03125
4
def bubblesort(list, id): # Swap the elements to arrange in order for iter_num in range(len(list)-1,0,-1): for idx in list.keys(): next = int(idx)+1 next = str(next) if next not in list: # print(next) continue if list[idx]<list[...
8689dd0c8dc5af68c1f05c67b75f4af659c35fdf
sfranzmann/CS-127-HUNTER-
/Turtle programming/clover.py
312
3.734375
4
#name: steven franzmann #email: steven.franzmann70@myhunter.cuny.edu #date: 9/1/2020 import turtle A = turtle.Turtle() A.color("purple") for i in range(15): A.forward(50) A.left(24) A.left(125) for i in range(15): A.forward(50) A.left(24) A.left(125) for i in range(15): ...
2041d0347991f953f740f8214ec039767df1e431
kinjaljain/QA_SDP
/src/spell_checker/levenshtein.py
1,345
3.875
4
from spellchecker import SpellChecker spell = SpellChecker(distance=1) spell.word_frequency.load_words(['riki']) def calculate_hamming_distance(str1, str2): distance = 0 if len(str1) != len(str2): return -1 for ch1, ch2 in zip(str1, str2): if ch1 != ch2: distance += 1 retur...
f39612a84d3c3c641d79571e16e22273067e0aa7
AimeeLiu01/Project-BAK
/DataMining/scikit-learn-model.py
6,060
3.546875
4
#!/usr/bin/python # -*- coding: UTF-8 -*-# import numpy as np import urllib url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" # download the file raw_data = urllib.urlopen(url) #load the CSV file as a numpy matrix dataset = np.loadtxt(raw_data, delimiter...
9b20a080a49a34a8c8fb05257e4dd04b1b7e9beb
TouffeTouffe/Projet_Info
/backtrack.py
1,800
3.640625
4
from solver import Solver class Backtrack(Solver): """auteur: Léopold Poquillon""" def __init__(self,g): super().__init__(g) def test_complet(self): """Renvoie True si toutes les cases ont une valeur solution affectée""" n = self.grille.x * self.grille.y for i in range(n):...
a0598a5cecf8fc2447b52461447f0d4ba9e7b2ff
Aifedayo/Python-Crash-Course-7
/Test.py
275
4.21875
4
first_name="Tayo" last_name="Tunji" print(f"my first name is {first_name} and my last name is {last_name}") name=str(input("enter your first name")) age=int(input("enter your age")) print(f"his first name is {name} and his age is {age}") string= "pepsi" print(string.upper)
4708811fef632ea93d8d554a0b72d98fd2656006
OMGfox/adventofcode_2020
/day_7/day_7_part_1.py
1,526
3.59375
4
from collections import defaultdict def split_input_line(line): raw_bag_name, raw_bag_content = line.split("contain") bag_name = raw_bag_name.strip() if "bags" in bag_name: bag_name = bag_name[:-1] if "no other bags" in raw_bag_content: bag_content = None else: bag_content ...
332bb7230c5da7ed9168d53db269e6cf32654080
enkore/asynker
/examples/oversimplified_qt.py
1,079
3.703125
4
""" This is a very simplified example showing how Asynker can be used in conjunction with the Qt event loop. """ import sys from PyQt5.QtCore import QCoreApplication, QObject, QTimer, QEventLoop from asynker import Scheduler, Future, suspend app = QCoreApplication(sys.argv) done = False def quit(): global don...
d44e5deaab1a87062d1e92cd6ec9d64403a1729d
LucasMarchi/MIT_6.00.1x_Python
/ProblemSet_2/Problem_2.py
1,173
4.15625
4
#Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. #By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. def calculateLowestPayment(balanc...
aa5b7dfdef1f3a046984c90622e16380e6641d32
ABUBAKR-YAHIA/ImageProcessingLab
/Lab-List.py
12,825
4.40625
4
# program to display grayscale image using read and write operations # Description:grayscale # Grayscaling is the process of converting an image from other color spaces e.g RGB, CMYK, HSV, etc. to shades of gray. #It varies between complete black and complete white. #Importance of grayscaling – # Dimension reduction:...
963c221fb2cca635348e7b63e43041fc4ac11063
OpenJ92/hyperSphere
/probabilityTheory.py
689
3.625
4
import numpy as np import matplotlib.pyplot as plt # https://newonlinecourses.science.psu.edu/stat504/node/209/ def factorial(n): if n > 1: return n * factorial(n - 1) else: return 1 def permutation(n, r): return factorial(n) / factorial(n-r) def combination(n, r): return permu...
1bcf72379ea5b08a78ad0e37ed01104ae00377d2
Linkaan/pythonchallenge-solutions
/10.py
386
3.71875
4
start = "1" def look_and_say(start): looking_at = start[0] count = 0 next_item = '' for item in start: if item == looking_at: count += 1 else: next_item += str(count) + looking_at count = 1 looking_at = item next_item += str(count) + looking_at return next_item for...
8c461ebda4f3907c0a9ff477d1b63c1957f292c1
Linkaan/pythonchallenge-solutions
/11.py
428
3.5625
4
from PIL import Image im = Image.open("cave.jpg") rgb_im = im.convert('RGB') pix = rgb_im.load() width, height = rgb_im.size image = Image.new('RGB', (width / 2, height / 2)) image_pix = image.load() for x in range(0, width, 2): for y in range(0, height, 2): if x+1 > width or y+1 > height: continue value =...
fa826ff0542a76c3a76c8f5e878bbd47fd5e8272
Jaroslav-Pol/UzduotisPaskolos
/modules/loan.py
2,032
3.703125
4
class Loan: def __init__(self, loan_sum, term, interest): self.loan_sum = int(loan_sum) self.term = int(term) self.interest = int(interest) # self.total_interest = self.loan_calc() def loan_info(self): 'Atvaizduoja paskolos informaciją' print(f'Paskolos suma: {s...
40762b6ebac29eef3ab4d259f4135689c1dd07de
FishBobYuYanqiu/learnpython
/learn/extract_character.py
316
4.09375
4
# 6.5 Write code using find() and string slicing (see section 6.10) to # extract the number at the end of the line below. Convert the extracted # value to a floating point number and print it out. text = "X-DSPAM-Confidence: 0.8475"; index=text.find(".") number=text[index-1:] number=float(number) print(number)
d2a16b3b8ebb6c42efbaac9330208367dfc44b38
FishBobYuYanqiu/learnpython
/learn/email.py
797
4.3125
4
# 8.5 Open the file mbox-short.txt and read it line by line. When you # find a line that starts with 'From ' like the following line: # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line using split() and print out the second # word in the line (i.e. the entire address of the pers...
5c33053eb40c8d191067cba3904dc4c29510bed4
potstar/optometry
/window/test3.py
182
3.90625
4
sight=['4.5','4.6','1'] suitable=['',''] if sight[0]<='4.7' or sight[1]<='4.7': if suitable[0]>='5.0' and suitable[1]>='5.0': print(1) else:print(0) print(sight[0:1])
ae2d3c3785671246adbe309e77d9d110e95725c8
vollcheck/mleco
/mleco/core.py
3,542
3.78125
4
from itertools import combinations from math import sqrt from typing import List, Union, Dict from mleco import Numbers def average(xs: Numbers) -> float: """ Calculates an arithmetic average. """ return sum(xs) / len(xs) def variance(xs: Numbers) -> float: """ Calculates a variance. ""...
853ca6b207e3e0c0f15a7e6f167364273943bcaa
manikanta-MB/IPL-Dataset-Analytics
/Code/bangalore_batsmen_score.py
2,423
3.953125
4
"""This program shows the bar chart of Top 10 bangalore batsmen over IPL history """ # importing all the required libraries to deal with csv files and to plot the data. import csv import os from matplotlib import pyplot as plt def get_bangalore_batsmen_and_score(file_path): """It will create and return a dictiona...
02277c2bfb1c6ac676a5c0d9562daa0f75a6881d
panjacob/Enigma2.0
/md5.py
1,752
3.6875
4
import hashlib from algorithm import Algorithm """ Title ----- MD5 Hash algorithm Author ------- Jakub Kwiatkowski Description ----------- MD5 - The MD5 message-digest algorithm is a widely used hash function producing a 128-bit hash value. Although MD5 was initially designed to be used as a cryptogra...
9f9b9ba2869ee7139d5cb05ffcd258f98db2e02a
sunglassman/U4_Lesson5
/problem5/problem5.py
177
3.578125
4
from turtle import * skye = Turtle() skye.color("black") skye.pensize("4") skye.shape("arrow") skye.speed(0) for x in range(5): skye.forward(150) skye.left(144) mainloop()
444659e28362084922d3f21aa8e0030eeb36346a
quynhanhvl/finalProj
/finalGradeCalc.py
1,617
4.0625
4
''' Created on Mar 7, 2020 @author: ITAUser ''' #statements welcoming and explaining program print ("Welcome to the final grade calculator!") print ("Use this resource to calculate what grades you need on your finals for the grades you want (:") userChoice = input("press 's' to start: ") #while loop so that program r...
71e396e8f8a950f014451dd9a65f5df00d3a97fc
drtierney/pythonTrainingSep20
/tasks/task1.py
68
3.53125
4
print("Hello' How 'Are' you") a = "Hello' \"How 'Are' You" print(a)
0b4058a0232392be8242780dfd97638174381b5c
drtierney/pythonTrainingSep20
/tasks/task4.py
218
3.609375
4
a = [[1, 2, 3], ['hi', 'Iam', 'python','language'], [100, 200, 300, 400],{"java":"language"}] print(a) print("a[1][2] = " + a[1][2]) print("a[1][1][0] = " + a[1][1][0]) print("a[3].get(\"java\") = " + a[3].get("java"))
24998d5d8c0b8a0b2584baa8651b2060270d5cd9
syedarehaq/python_learn_and_teach
/teaching/class_00.py
2,158
4.625
5
## lets start using python3 from here. ## https://github.com/jerry-git/learn-python3 ## Lets print a string, a number ## lets print the lower case of a string, check if isalpha, isalphanum, isnum ## Assign something to variable ## see the type of the variable ## get help about a function (e.g. .lower function of the s...
e950aa89c62964e7f7ebbc21197f6a9a8eacbbce
Rnazx/Assignment-04
/library.py
4,717
3.65625
4
#function for storing the augmented matrix matrix(A) from a file def store(st,rows): X=[] T=[] rows=int(rows) with open(st,'r+') as file: i=0 while i<rows: s=file.readline() p=s.split() j=0 while (j<len(p)): T....
7b144538679eedc44f81154aa49c00e7e6415f36
ankitgupta123445/python
/day.py
1,272
3.953125
4
date=int(input("enter the date")) month=int(input("enter the month")) t=365 if month==1: rem=(31-date)+(t-31) print("no. of remaining days=",rem) elif month==2: rem=(28-date)+(t-31-28) print("no. of remaining days=",rem) elif month==3: rem=(31-date)+(t-31-28-31) print("no. of remainin...
396d9082ea492878133729c1f42e843cbd7aeaa5
lazidge/maps
/algorithms.py
6,270
3.765625
4
""" import math from heapq import heapify, heappop, heappush from collections import defaultdict from store import Node def length_haversine(p1, p2): lat1 = p1.lat lng1 = p1.lng lat2 = p2.lat lng2 = p2.lng lat1, lng1, lat2, lng2 = map(math.radians, [lat1, lng1, lat2, lng2]) dlat = lat2 - lat1 ...
71990935271fea1e475c8e12604ddfcdb24b4c77
mattvonrocketstein/spock
/spock/belief.py
2,394
3.671875
4
""" spock.belief """ from datetime import datetime from spock.simplex import symbol ALWAYS = always = symbol._belief_always NEVER = never = symbol._belief_never class BadBelief(ValueError): pass class Belief(object): """ a belief is a artifact in temporal logic. see Shoham:1993 for more information. ...
5ae7233418de02362c1d84c68516441964e95cdb
Jacob-Brink/game
/lib/modules/physics/vector.py
7,615
3.859375
4
import math from lib.modules.gui.rectangle import Point class Vector: '''Vector class used for velocity, force, and acceleration in physics stuff''' def __init__(self, position_point, **keywords): '''Constructs a new vector given direction (degrees :0 for facing right) and magnitude (any num type)''' ...
732f8f8ff0bba4ef768404f5149b98b3f32eabcc
Jacob-Brink/game
/lib/modules/physics/line.py
4,405
3.921875
4
from lib.modules.gui.rectangle import Point class Line: def __init__(self, slope, point, x_range, y_range): # check invariants for slope being a number or infinite if slope == 'infinite' or self.isnumber(slope): self._slope = slope else: raise ValueError('Slope must...
a88a1e02e5f208f6b587d748cb0b7bd2f845f4a9
mirianfsilva/code-challenges
/hackerrank/Stack-balanced_brackets.py
808
3.875
4
#!/bin/python3 import math import os import random import re import sys # Complete the isBalanced function below. def isBalanced(s): open_brackets = ["(", "[", "{"] close_brackets = [")", "]", "}"] stack = [] for bracket in s: if (bracket in open_brackets): stack.append(bracket) ...
3120482cb7f537553de34affd9557323f9941829
codingtrivia/PythonLabs
/Lab5/Lab5.py
337
3.84375
4
# Question 1: Write a program that defines a function: average and that function calculates average of numbers from 0 to 100 # Question 2: We have a dictionary as follows. nameAndAge = {"Joe": 18, "Katie": 21, "John": 23, "Jack": 24} # How would you print entries (or items) from the above dictionary where the names (k...
aa2869d40590d518560d3e365d62e94104598c6b
codingtrivia/PythonLabs
/Lab2/lab2.py
1,184
4.15625
4
a = 5 b = 2 # 1. how will i get value 2.5 on division of a/b in 2 ways hint: int to float # 2. how will i get 2 on division of a/b # 3. how will i get 25 i.e. 5^2 from a and b # 4. how will i get decimal value of bits '101' a = ['aaa'] b = ['bbb', "ccc"] # 5. after applying what operation on a can i get a list ['a...
e3f36fbed65c4406ee5895aab8a48a0beb03fa8b
khadak-bogati/python_project
/countdown.py
186
4.09375
4
#countdown function # Print the numbers from 1 to i # on a single line def countdown(i): for j in range(1, i +1): print(j, end = " ") print() countdown(10) countdown(5) countdown(2)
18c95ad98dd2425042d8995b54890495fc098934
khadak-bogati/python_project
/Selection_model.py
305
3.53125
4
def Selection_model(a_list): for i in range(len(a_list)): minIndex = i for j in range(i + 1, len(a_list)): if a_list[minIndex] > a_list[j]: minIndex = j minValue = a_list[minIndex] del a_list[minIndex] a_list.insert(i, minValue) return a_list print(Selection_model([6, 5, 4, 3, 2, 1]))
3eb6e677dc602df36905ca31182db3f20a82b7d0
khadak-bogati/python_project
/numpyAttribute.py
2,851
3.9375
4
#import numpy import numpy as np print("==========================================================") print("Create a numpy array") a = np.array([0, 1, 2, 3, 4]) print(a) print("==============================================================") print("The attribute size is the number of element in the array: ") print(...
be225e80d37b6c2aed1360c9dcb6225ba1217f3d
getanotherone/secondtry
/Guess.py
206
3.625
4
import random number = random.randint(1, 10) for i in range(10): playernumber = int(input()) if playernumber == number: print("win") else: print("lose") print("that's all folks")
dd7ab0749049f8d63a8c81bdb37b7fb3b1ab264a
HoanVanHuynh/decision-tree-15-10
/break_de2.py
2,229
3.8125
4
# Toy dataset. # Format: # Each row is an example . # The first two columns are features # The last column is the label. # Feel free to play with it by adding more feature and examples. # Interesting note: # I've written this so the 2nd and 5th examples # have the same features, but different labels # so we can see ...
53a107d4c8ee1d82685ecc3f2f111d0edbda96b1
rishilss99/Intro-to-Python-Udacity-course-
/rating_function.py
1,331
4.375
4
def scores_to_rating(score1,score2,score3,score4,score5): """ Turns five scores into a rating by averaging the middle three of the five scores and assigning this average to a written rating. """ #STEP 1 convert scores to numbers score1 = convert_to_numeric(score1) score2 = convert_to_num...
dd7f17bc8ae463e2aa470e683124ecbb30182f04
andersschuller/palindromes
/test_palindromes.py
1,327
3.609375
4
from palindromes import is_palindrome, all_substrings, longest_palindrome import unittest palindrome_strings = {"", "A", "AA", "ABA", "ABBA", "tattarrattat", "deleveled", "redivider"} random_strings = {"ABC", "palindrome", "something", "wordswordswords"} class PalindromesTestCase(unittest.TestCase): def test_is_...
73d08ac369b84b7377d815a51c26ded62c3f3fdf
GabrieleMaurina/workspace
/python/Graphics/GraphicsFirst.py
708
4.03125
4
from graphics import * win = GraphWin('Draw a Triangle', 350, 350) win.setBackground('yellow') message = Text(Point(win.getWidth()/2, 30), 'Click on three points') message.setTextColor('red') message.setStyle('italic') message.setSize(20) message.draw(win) # Get and draw three vertices of triangle p1 = win.getMouse()...
3da1f5cf0b106284e7242d914fe599beb533e2fa
GabrieleMaurina/workspace
/python/PA/people.py
2,283
3.59375
4
from datetime import date, timedelta class Person: def __init__(self, name, lastname, birthday): self.name = name self.lastname = lastname self.birthday = birthday def __str__(self): return '{} {}'.format(type(self).__name__, self.__dict__) class Student(Person): def __init...
524971cf1c28edcbc9c296b2d5a2d8fe5828b865
RoliqueSuperSonic9000/blackjack_terminal
/src/deck_class.py
1,063
3.703125
4
from card_class import Card from random import randint """ Deck Class """ class Deck(object): def __init__(self, u_id): self._unique_id = u_id self._cards = [] for suit in Card.suits: for rank in Card.ranks: card = Card(suit, rank) self._cards.append(card) @property def unique_id(self): return ...
d7e600d08dd5f79b7bdcc081abaea30fff7f1ce3
Hamzah101/Square
/square.py
488
3.984375
4
import turtle # Window Design window=turtle.Screen() window.bgcolor("black") window.title("Ball Animation") # Shape Design shape=turtle.Turtle() shape.shape("square") shape.shapesize(4) shape.color("white") shape.penup() shape.speed(0) shape.goto(0,200) # Animation shape.y=2 down=0.2 while True:...
8c400c18d01cd3bee0d115a95152a71b867780f6
aravindbattaje/MLND_Capstone
/mnist_multi_digit.py
10,582
3.734375
4
"""Model for MNIST multi-digit recognition. Four convolutional layers, interspersed with max pooling, followed by fully connected net with two hidden layers. The final hidden layer branches into several softmax layers: one for predicting the length of the sequence and the rest for each digit. """ import tensorflow as...
f45c93885dc290ad6eaf3011543734da7b68ddd4
jfost00/LPTHW
/ex18.py
443
3.703125
4
# This is like the argv def printtwo(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # okay that *args is not needed def printtwoagain(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def printone(arg1): print "arg1: %r" % arg1 # this takes nothing ...
26c79ebb505ca01dd7e1597fcbfc5f55c2ca3432
ConnorWorrell/WeatherDataCollector
/LatterSim.py
875
3.640625
4
import random import time winstreak = 0 rank = 25 stars = 0 wins = 0 losses = 0 for i in range(100): win = random.randint(1, 2) if(win == 1): wins = wins + 1 stars = stars + 1 winstreak = winstreak + 1 if(winstreak > 2): stars = stars + 1 if(rank <= 0): ...
1fbd9f59ea73444b7579662986489a8a40efd695
twenta/pdftables
/pdftables/linesegments.py
3,825
4.09375
4
""" Algorithms for processing line segments segments_generator Yield segments in order of their start/end. [(1, 4), (2, 3)] => [(1, (1, 4)), (2, (2, 3)), (3, (2, 3)), (4, (1, 4))] histogram_segments Number of line segments present in each given range [(1, 4), (2, 3)] => [((1, 2), 1), ((2, 3), 2), ...
dd2687c957783ada28c80d5b5627168168b46bde
adrielyeung/computational-physics
/Interpolation_3.py
3,588
3.5625
4
import numpy as np import Matrix_2 as M2 """ lin - Linear interpolation Input: inp = a matrix containing all the x and y values (columns 0 and 1), sorted in ascending order in x. Output: array f whose elements i provide the y values for any x between x_i and x_i+1 using a linear interpolation method. """ d...
2b1aa1c52ef6d1e2ccbd4065ffb83136bad68df2
genuineBuildMonkey/advent-2019
/day1/solve.py
525
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import math masses = open('input.txt', 'r').readlines() def part1(): return sum([((int(i.strip()) / 3) - 2) for i in masses]) def part2(): total = 0 for m in masses: m = int(m.strip()) requires = math.floor((m / 3) - 2) total += re...
91c3a5cdeed6fd076559c6be7df9f81ef65b1ca7
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 10/10-1. Learning Python.py
530
4.21875
4
filename = 'learning_python.txt' print('--Reading in the entire file--') with open(filename) as file_object: contents = file_object.read() print(contents) print('\n--Reading by looping over the file object--') with open(filename) as f: for line in f: print(f"In Python you can {line.strip()}") print('\n--Reading...
ab5defa7e3dbd12be52016a69a8d5c959306f883
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 6/6-8. Pets.py
432
4.125
4
pets = [] # make each of the dictionary for each pet pet ={ 'kind': 'loro', 'owner': 'que andas de sapo', } pets.append(pet) pet ={ 'kind': 'dog', 'owner': 'quico', } pets.append(pet) pet ={ 'kind': 'elefante', 'owner': 'bart simpson', } pets.append(pet) # now loop for each pet dictionary and print its infor...
b61a65019ed312804f521ffa47fce5b7af5a9051
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 3/3-10. Every Function.py
681
3.875
4
movies=['fight club', 'el padrino', 'la sirenita'] sorted(movies) print("alphabetical temporarly") print(sorted(movies)) print("\n original order") print(movies) print('\n Reverse alphabetical sorted order') print(sorted(movies, reverse=True)) print('\n Original reverse order') movies.reverse() print(movies) print(...
40820e3163c82b9cf98980381731ae6d09cfb05f
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 11/employee.py
294
3.84375
4
class Employee: """A class to represent an employee.""" def __init__(self, first, last, salary): """Initialize the employee.""" self.first = first self.last = last self.salary = salary def give_raise(self, amount=5000): """Give a raise to the employee.""" self.salary += amount
b48f68e3f14764a19755a87ee3eeb35af198f8cd
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 10/10-13. Verify User.py
782
3.5625
4
import json def get_stored_user(): """Get stored username if available.""" filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: return None else: return username def get_new_username(): """Prompt for a new username.""" username = input("What is yo...
e320155c17ca88c97d8dadbb2c988e7823058310
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 6/6-11. Cities.py
520
3.859375
4
cities = { 'portoviejo': { 'country': 'ecuador', 'population':'16 000 000', 'fact': 'its the Manabís capital', }, 'new york': { 'country': 'Unites States', 'population': '10e6', 'fact': 'worlds capital', }, 'crucita': { 'country': 'ecuador', 'population': 'no se mi yabe', 'fact': 'uno se puede bañar en su...
f5db29608c910621bbd44ac6587ddd3520c4fb1e
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 6/6-1. Person.py
208
3.59375
4
batman = { 'first name': 'bruce', 'last name': 'wayne', 'age': 40, 'city': 'gotam', 'blood type': 'y yo que voy a saber?', } for key, value in batman.items(): print(f"\n{key}: ") print(value)
08b86652bc1f0522a38d5e0341a74ec2f66d8ad8
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 8/8-7. Album.py
457
3.90625
4
def make_album(artist, album, nsongs=0): """Show an artist's name and one of his album""" album = {'artist': artist.title(), 'album': album.title()} if nsongs: album['Number of songs'] = f"{nsongs.title()} songs" return album album= make_album('the beatles', 'revolver', '13') print(album) artist_album= make_al...
07d5d65fbd6510b7a906de5d4b9799a2aedff23e
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 7/7-9. No Pastrami.py
576
4.125
4
sandwich_orders = ['chicken', 'pastrami','meet', 'cheese', 'pastrami', 'tuna', 'mortadella', 'pastrami'] finished_sandwiches = [] print("There are no pastrami sandwich anymore, we run out of it.") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') print('\n') while sandwich_orders: finished_sa...
14703ffb741791bef4078864f37ec21bbe85873b
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 9/9 -11. Imported Admin.py
772
3.9375
4
from user import User class Admin(User): """.""" def __init__(self, first_name, last_name, age): """ Initialize the admin. """ super().__init__(first_name, last_name,age) # Initialize an empty set of privileges. self.privileges = Privileges([]) class Privileges(): """.""" def __init__(self, privile...
858317d46717a1e483d9114143c9855cc5265fd9
Alec-Vis/Machine_Learning_Reference-main
/templates/regression/Random_Forest_Regression.py
2,183
3.828125
4
""" @author Alec Vis, 2/28/2021 Random Forest Regression step 1: pick a random selection of K data points from the data set step 2: Build the decision tree associated to these K data points step 3: choose the number of trees you want to build and repeat steps 1 & 2 step 4: given a new data point, have ...
8f2c5dc65bfb9b4809b1b52401b03b404e9d2df6
codinglzc/liaoxuefengLearnPython
/build_in_module_collections.py
2,885
4.25
4
# coding=utf-8 # 内建模块 ################################################ # collections # collections是Python内建的一个集合模块,提供了许多有用的集合类 # namedtuple # namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定量tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print p...
13057e39e20c8f07e20cca559834e39ada388785
codinglzc/liaoxuefengLearnPython
/dict.py
405
3.953125
4
# coding=utf-8 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print d['Michael'] # 向字典中添加元素 d['Adam'] = 67 print d # 修改字典中的元素 d['Adam'] = 77 print d # 避免key不存在的错误 if 'Adam' in d: print d['Adam'] # 如果存在key为'Adam'的元素,则返回值;反之,返回默认值-1 print d.get('Adam', -1) print d # 删除一个key-value d.pop('Adam') print d