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
629f3b7d45f6e30779aa0636192927b33b7c3eae
slsteven/python_fundamentals
/selection_sort.py
1,030
4.09375
4
#selection sort #start with linear selection #iterate through array and find minimum value #swap variable position with minimum value import time start_time = time.time() my_list = [6, 5, 2, 8, 3, 1, 4, 7, 9] print "length of list %s" % len(my_list) def selection_sort(my_list): leng = len(my_list) for i in range(l...
6ee0fe2ed84e5197e77e1fb131a003a3be62ded8
accountor-finago/stovokor-xml
/util/randomization.py
630
3.921875
4
""" File contains randomization utilities. """ import random import string __author__ = 'michal.toporowski' choice = random.choice def random_with_chars(length: int, allowed_chars: str): return ''.join(random.choice(allowed_chars) for i in range(length)) def random_numeric(length: int) -> str: return rand...
05b72faac13f324605cb62bf3c1fff7258260e28
itsamanyadav/Python
/unittest使用.py
2,237
4.4375
4
#断言 编写代码时,我们总是会做出一些假设,断言就是用于在代码中捕捉这些假设,可以将断言看作是异常处理的一种高级形式。 #assert代表断言,假设断言的条件为真,如果为假诱发AssertionError #assert 断言的条件,错误的提升 # a = 0 # assert a,"a is false" # print(a) #上面的断言代码类似下面的if语句 # a = 1 # if not a: # raise AssertionError("a is false") # print(a) # import unittest # # #unittest使用的方法 # class OurTest(unittest....
d74d586afbc38a2ff57ee5d24fccdcc75ff694a2
JasirDonte1/TESU_Python_Projects_and_Assignments
/COS-205_assignment_4b.py
340
3.90625
4
def wordCount(): file = open("/Users/JasirDonte/Documents/infile.txt","r") file_single_line = file.readlines() word_count = 0 for x in file_single_line: line_array = x.split(" ") word_count = len(line_array) + word_count return word_count print("this file contains:", wor...
5a0e4b7c1c6111ce948c098836892ca3f9a5e4c2
JasirDonte1/TESU_Python_Projects_and_Assignments
/COS-205_assignment4a_.py
870
3.6875
4
dictionary = { 'A': 1, 'a' : 1, 'B': 2, 'b' : 2, 'C': 3, 'c' : 3, 'D': 4, 'd': 4, 'E': 5, 'e': 5, 'F': 6, 'f': 6, 'G': 7, 'g': 7, 'H': 8, 'h': 8, 'I': 9, 'i': 9, 'J': 10,'j': 10, 'K': 11,'k': 11, 'L': 12,'l': 12, 'M': 13,'m': 13, 'N': 14,'n': 14, 'O': 15,'o':...
d16c9eb1179f026658bb93d04ceb7c021371ad09
iurii-milovanov/pymlclass
/machine-learning-ex2/solutions/costFunction.py
940
3.734375
4
# COSTFUNCTION Compute cost and gradient for logistic regression # J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the # parameter for logistic regression and the gradient of the cost # w.r.t. to the parameters. import numpy as np from solutions.sigmoid import sigmoid def costFunction(the...
5de240a83e1c4cf9a4f5254ea18dcaa23e108347
iurii-milovanov/pymlclass
/machine-learning-ex1/solutions/ex1_multi.py
3,289
4.3125
4
#!/usr/bin/env python3 # # Machine Learning Online Class # Exercise 1: Linear regression with multiple variables # import numpy as np import matplotlib.pyplot as plt import os from featureNormalize import featureNormalize from gradientDescentMulti import gradientDescentMulti from normalEqn import normalEqn if __name...
1460f7fcea2755bcad0eaa481cd33d2752e9d7e4
iurii-milovanov/pymlclass
/machine-learning-ex5/polyFeatures.py
712
4.03125
4
# POLYFEATURES Maps X (1D vector) into the p-th power # X_poly = POLYFEATURES(X, p) takes a data matrix X (size m x 1) and # maps each example into its polynomial features where # X_poly[i, :] = [X[i], X[i] ** 2, X[i] ** 3 ... X[i] ** p] # import numpy as np def polyFeatures(X, p): # You need to return t...
2d9ca18c7b90af0ac266f5f8b8b684492c2bbc4e
laurendayoun/intro-to-python
/homework-2/answers/forloops.py
2,846
4.40625
4
""" Reminders: for loop format: for ELEMENT in GROUP: BODY - ELEMENT can be any variable name, as long as it doesn't conflict with other variables in the loop - GROUP will be a list, string, or range() - BODY is the work you want to do at every loop range format is: range(start, stop, step) or range(st...
e8412e95f1b1b094e5d24c286c18f240e72401be
taruntalreja/Training_Toppr
/Python Basics/OOPs Concepts/class_object.py
700
4.25
4
class Sparrow: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age #instance method def eats(self,food): return "{} eats {}".format(self.name,food) # instantiate the Parrot class fanny = Sparrow("Fanny...
5c5f0ac6d09a02a6ef628ae8849837f488b2ba4d
alex-stephens/aoc2020
/23/b.py
1,683
3.625
4
class Circle(object): def __init__(self, string, size=None): vals = list(map(int, list(string))) if size: vals += [x for x in range(max(vals)+1, size+1)] self.nxt = {} self.n = len(vals) self.cur = vals[0] for i in range(len(vals)): ...
cfbba8090330cc79419582fae8be3387958c083d
brit228/DS-Unit-3-Sprint-1-Software-Engineering
/sprint-challenge/acme.py
2,669
3.953125
4
"""Product classes for Acme corporation.""" import random class Product: """Standard product class for Acme corporation. Assigns name, price, weight and flammability. Also randomly creates identifier attribute between 1000000 and 9999999, inclusive. Args: name (str): name of product p...
9b23886f2bc2aacb5d8e8fee1a5cdf4d0d808c92
AugustoOspal/Calculadora-para-potencias
/calculadora with py/calculadora_de_potencia.py
1,955
3.65625
4
import math import helpers print("\n24/12/2019") print("E-Mail: AugustoOspal@icloud.com\n") print(" /| | | |''' | | |''' '''|''' |'''|") print(" / | | | | __ | | |___ | | |") print(" /__| | | | | | | | | | |") print("/ | |___| |___| |___| ___| | |___|") print(" ...
6ec5cd07fb3d8c533ff128eb0dd95232a9417bb7
ArturLange/project-euler
/problem5.py
230
3.6875
4
#!/usr/bin/env python3 from utils import lcm from functools import reduce def largest_multiple(numbers): return reduce(lambda a, b: lcm(a, b), numbers) if __name__ == '__main__': print(largest_multiple(range(1, 21)))
ef6330dd02632a58900100c55d94aae6e4b5462c
loimisu/Metric_Function_Dependencies
/centroid_polygon.py
3,069
3.53125
4
import math def area_for_polygon(polygon): result = 0 imax = len(polygon) - 1 for i in range(0,imax): result += (polygon[i]['x'] * polygon[i+1]['y']) - (polygon[i+1]['x'] * polygon[i]['y']) result += (polygon[imax]['x'] * polygon[0]['y']) - (polygon[0]['x'] * polygon[imax]['y']) return resu...
c4ad987d6f896b2cc28b1ba47f617e885e7b58b6
Aza1250/Spaceship-Game
/SpaceshipGame/rm_level1.py
938
3.671875
4
# This is our first room, or you can also think of it as our first level! # With these lines of code, we create a new Player, based on our object # script 'obj_player'. You can think of an 'obj_player' as a blueprint. # In it we define all the features of our player. Here we only 'build' # that object from the bluepri...
29a4dd3d59e9d89d87a8995c9f01e526177d18c3
Aza1250/Spaceship-Game
/SpaceshipGame/obj_enemy_loop.py
1,604
3.78125
4
# With this line of code we say that each enemy will be moving down, # towards the player at a specific speed (currently: 1). self.y = self.y - 1 # In order to continuously increase our timer by 1, we place it inside # of the loop tab. timer = timer + 1 # Once the timer has reached 120, we build a new enemy projectile...
106d2700989be91bee5e1d5add0aadf4b5e9b522
aryamsharma/secret_cipher
/cipher.py
2,620
3.5625
4
import time import random import string class CF: def __init__(self): self.chars = [i for i in string.printable[:-5]] self.key = self.chars[:] self.seed = time.strftime("%Y%m%d") random.seed(self.seed) random.shuffle(self.key) def encrypt(self, text): self.encr...
1ac25592ce61eff4bd138e8f1d587f6326219c09
ianroses/HackerRank
/Practice/Mathematics/Fundamentals/LeonardosPrimeFactors.py
907
3.921875
4
#!/bin/python3 import math import os import sys # # Complete the primeCount function below. # def primeCount(n): if n == 2: return 1 #print ("Primos de: "+str(n)) count = 0 y = int(math.sqrt( n )) b = 1 prime = True for num in range(2,n): # prime numbers are greater than 1 ...
fb937ff8d6f44b757dc868e8b1b592fff2b53b9c
ianroses/HackerRank
/Practice/Security/Functions/SecurityBijectiveFunction.py
169
3.609375
4
#!/bin/python3 n = int(input()) numbers = list(map(int, input().rstrip().split())) s = set(numbers) if len(numbers) == len(s): print("YES") else: print("NO")
14edfffc06e7e46d3bab06f773b5f7a4e5109338
elikschultz/coursera_algorithms
/course_4/floyd_warshall.py
1,729
3.703125
4
# -*- coding: utf-8 -*- def floyd_warshall(file_name): with open(file_name, 'r') as f: n_vertices = int(f.readline().split()[0]) edges = [[int(j) for j in i.split()] for i in f.read().split('\n')[:-1]] graph_dict = {} for edge in edges: graph_dict[edge[0]] = graph_dict.get(edge...
76d09daccfd56dd055f8e8c50a1da99ed65c2662
elikschultz/coursera_algorithms
/course_3/kruskal_clustering.py
2,875
3.609375
4
# -*- coding: utf-8 -*- with open('clustering1.txt', 'r') as f: file_contents = f.read().split('\n') n_vertices = int(file_contents[0]) edges = [(int(i.split()[0]), int(i.split()[1]), int(i.split()[2])) for i in file_contents[1:-1]] # Adopt merge sort algorithm for sorting edges def merge_sort(x): ...
0843a36ba69abe0a4214368d3f41403df1ca6323
TheBlackCat1/gameQuest
/finalQuest/main.py
6,140
3.609375
4
#This file was created by: Carter Hively #Sources: #Mr. Cozort and his Intro to Computer Programming class #some tutorials for quick reference: https://pythonprogramming.net/pygame-python-3-part-1-intro/ #pygame: https://www.pygame.org #pygame docs: https://www.pygame.org/docs/ #impoting pygame as pg and random and al...
82453bdfd009d7b576d7b4a53b552a385190b2e1
Ziem0/various
/hello.py
614
4
4
#!/usr/bin/env python3 import sys def main(): if len(sys.argv) == 2: name = sys.argv[1] elif len(sys.argv) == 3: name = sys.argv[len(sys.argv)-2] + " " + sys.argv[len(sys.argv)-1] elif len(sys.argv) == 4: name = name = sys.argv[len(sys.argv)-3] + " " + sys.argv[len(sys.argv)-2] + " " + ...
c51045a64cbeb3dc45b80e2c27d32a5de967b612
RiccardoCereghino/ids_ex_1
/indicator/functional.py
8,285
3.671875
4
""" This module generates plots on statistic extracted from the csv file which can be found at: https://www.kaggle.com/martj42/international-football-results-from-1872-to-2017 """ __license__ = "Riccardo-C" __docformat__ = 'reStructuredText' import operator import os from datetime import date from itertools i...
d41589e411649d69a0ba1e58b682a6fd369a1fb3
lewischa/Tree
/tree.py
720
3.796875
4
from node import Node class Tree(object): def __init__(self, root=None): self._root = root def _found(self, value, root): if root is None: return False if root.data() == value: return True if root.value() > value: return _found(value, root.le...
5fe6ff3ac260f15d3ed1edfebb98e96e46da181f
tClark93/pythonSmall
/python_fun/for_loop_basic_1.py
494
3.71875
4
for count in range(0,150): print(count) for count in range(5,1000000,5): print(count) for i in range(1,100): if i % 5 == 0 and i % 10 == 0: print('Dojo') elif i % 5 == 0: print('Coding') else: print(i) count = 0 for i in range(1,500000,2): count += i print(count) for i in range(2018,0,-4...
7c242b82245938b7453f9ebb926eeed79e0c7c92
lxgzhw520/LiKeyao
/day002/hw_005_判断一个人是否可以结婚.py
942
3.84375
4
# _*_ coding:UTF-8 _*_ # 开发人员: 理想国真恵玩-张大鹏 # 开发团队: 理想国真恵玩 # 开发时间: 2019-04-11 09:40 # 文件名称: hw_005_判断一个人是否可以结婚.py # 开发工具: PyCharm # 需求:判断一个人是否可以领取结婚证 # 1:获取该用户的国籍,性别,年龄 country = input("国籍:") gender = input("性别:") age = input("年龄:") # 2 判断该国该性别的法定结婚年龄 if country == "中国": # 中国男人法定结婚年龄22 女20 if gender == '男': ...
71996d70122c834b3c59d54d36b001eb21e6a0ae
ameenhashir/my_python_codes
/Python OOP/Project-OOPs/operator_overloading.py
739
4
4
import math class Circle: def __init__(self,radius): self.__radius = radius def get_radius(self): return self.__radius def area(self): return math.pi * self.__radius ** 2 def __add__(self, other): return Circle(self.get_radius() + other.get_radius()) def __lt__(...
878664bcefd67de9024460c763e16a2a44ccbf47
ameenhashir/my_python_codes
/Python OOP/Project-OOPs/constructor.py
376
3.640625
4
class Person: def __init__(self,*args,**kwargs): self.name = args[0] self.age = args[1] self.height = args[2] self.weight = kwargs['weight'] self.color = kwargs['color'] pakaran = Person('pakaran',32,170,weight=80,color='red') print(pakaran.name) print(pakaran.age) print(pa...
da9f3d99286cd283bcdeb6f0635f05486549b7c8
kbagnato/5-Crowns---Python
/Card.py
3,052
3.796875
4
import copy ############################################# # Card, represents a playing card # @author Kevin Bagnato # @since 3/11/2020 ############################################# class Card: # initializer def __init__(self, inFace, inSuit, inWild = False): """ Parameters ---------- inFace : i...
7b5e97e97327ed410712b2bb16a33b5e5f27b54d
Leomk1998/AyudantiasFP-ESPOL
/FP2020-2/Clase02/Ayudantia2.py
2,747
3.90625
4
# 30/10/2020 # Ayudante: Leonardo Mendoza #Ejercicio 1 """ print("***Validador de cedulas***") cedula = input("Ingrese su numero de cedula: ") val1 = cedula.isdigit() val2 = len(cedula)==10 print(len(cedula)) val3 = cedula.startswith("09") #val3 = cedula[0:2]=="09" valfinal = val1 and val2 and val3 print("Su cedula %...
a345955cc7dabc0e6551f6f0e47e88b36c43ad26
Leomk1998/AyudantiasFP-ESPOL
/FP2020-2/Clase01/Ayudantia1.py
2,158
4.1875
4
# 23/10/2020 # Ayudante: Leonardo Mendoza #Ejercicio 1 """ f = int(input("Escriba un temperatura en grados Farhenheit: ")) c = ((f-32)*5)/9 print("%d grados Farhenheit son %f grados centigrados"%(f,c)) # %d numeros enteros %s strings %f numeros decimales """ #Ejercicio 2 """ numero = int(input("Ingrese un numero:...
ba14cc0ad47d6673bb3a21d1bcf645d0ca288b19
Leomk1998/AyudantiasFP-ESPOL
/FP2020-1/Clase01/Ayudantia1.py
5,793
3.921875
4
''' #taller # Validar una cedula # Las condiciones son: #1. La cédula debe contener solo números, no puede tener letras #2. La cédula debe tener 10 dígitos exactos #3. La cédula debe ser de Gye (09), empezar con estos dígitos #4. Solicite la cédula y presente un mensaje personalizado. #Ejm: La cédula 092821928a es cor...
8cc87cd29b940c3c02f895fb09a09aff6d4aed2e
TyPetrochko/cs323
/bsh/contextfree.py
852
4.09375
4
#! /usr/bin/python import random def generate_list(grammar, axiom): """Generate a list of tokens from grammar, starting with axiom. The grammar should take the form of a dictionary, mapping rules (strings) to lists of expansions for those rules. Expansions will be split on whitespace. Any token in the expansion...
6e416ab2ab96221bc56ae26707974e9252132e4c
Flostin1/Eulers-Method
/main.py
850
3.765625
4
import math import numpy as np import matplotlib.pyplot as plt def f(n): return math.e**-n**2 # b MUST be greater than a a = -5 b = 5 dx = 0.001 x = np.arange(a, b, dx) y = np.array([f(i) for i in x]) plt.plot(x, y) # Euler's Method def euler_method(): initial_condition = 0 slope = 0 y_values = [] ...
b8e8ad706255a94d692e57426dc6baa9ec6a0e40
joverlee521/Blackjack
/blackjack.py
7,273
3.9375
4
# Imports from classes import Deck, Hand, Chips # Global variables playing = True def take_bets(chips): ''' Asks player for bet amount. Verifies player input is an int and does not exceed the amount the player currently has. INPUT: chips(Chips class): the player's Chip object OUTPUT: new_b...
c152acaad1d49adbb7f5ae36c7b8481266ce185e
jugomo/python_review
/basics/rangetype.py
165
3.9375
4
r1 = range(5) r2 = range(1,5) r3 = range(1,15,3) for i in r1: print(i) print("\n") for i in r2: print(i) print("\n") for i in r3: print(i)
f4f1250b51d82c599eb7df384de03048834bb620
jugomo/python_review
/basics/listtype.py
410
3.75
4
#import sys #print(sys.version) lst = [10, 20, 'HELLO', -20, 30.5] print(lst) print(lst[2]) print(lst[3:5]) print(lst*4) print(len(lst)) lst.append(40) print(lst) lst.remove("HELLO") # delete by value print(lst) del(lst[4]) # delete by index print(lst) print(max(lst)) print(min(lst)) lst.insert(3, 99) print(ls...
a8eb0746db8ba765cf4594020dc34b4c9e25256d
BrunoIvan/how-many-sqares
/src/models/Vertex.py
365
3.859375
4
""" Main model to represent sqares in a coordinate plane """ class Vertex: def __init__(self, x, y): """ Represents the horizontal coordinate of the vertex """ self.x = x """ Represents the vertical coordinate of the vertex """ self.y = y def __str__(self) -> str:...
7d9ef171a14163aae31942b75a20063fd40f5e9e
zhuxiaodong2019/VIP9Base2
/objecttest/testobject5.py
1,758
4.09375
4
# -*- coding: utf-8 -*- ''' @Time    : 2021/1/23 17:00 @Author  : zxd ''' #多继承 #师傅类 class Master(): def __init__(self): self.kongfu = '[五香煎饼果子]' def make_cake(self): print(f'运用{self.kongfu}制作五香#####') class School(): def __init__(self): self.kongfu = '[香辣煎饼果子]' def make_cake(self...
8a93636bd5b7b955f431bc4f351583b742fe14cf
senavarro/function_scripts
/functions.py
947
4.40625
4
#Create a function that doubles the number given: def double_value(num): return num*2 n=10 n=double_value(n) print(n) -------------------------------------- #Create a recursive function that gets the factorial of an undetermined number: def factorial(num): print ("Initial value =", num) if num > 1: num = n...
f6791e92bf6f230183bd993e973ddd1dc01fba3a
odindva/GB_AI_Q1_PyBase
/less5/HomeWork/hw_05_06.py
1,815
3.796875
4
# 6) Необходимо создать (не программно) текстовый файл, # где каждая строка описывает учебный предмет и наличие лекционных, # практических и лабораторных занятий по этому предмету и их количество. # Важно, чтобы для каждого предмета не обязательно были все типы занятий. # Сформировать словарь, содержащий название предм...
27a9719821797620ad38aba8c21568ecd6c528a0
odindva/GB_AI_Q1_PyBase
/less3/HomeWork/hw_03_01.py
1,149
4.0625
4
# 1) Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def division_a_by_b(dividend, divider): """Вернет частное от деления a на b Если b = 0 вернет None """ return dividen...
4bcb543d4700959f480a76845b3a8cc14c040697
odindva/GB_AI_Q1_PyBase
/less3/HomeWork/hw_03_05.py
2,055
3.53125
4
# 5) Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводитс...
165dc311329adf40ff83955c606bd0ca0f885362
robertlawrencejorge/turtles
/robert-turtles.py
167
3.5625
4
import turtle size=1 while (True): for s in range(4): turtle.forward(size) turtle.right(90) size=size + 1 turtle.right(20)
aceb7a750bc60bd4d105f6874eb31e3ad78afdda
jshin49/cnn-cats-vs-dogs
/config.py
851
3.53125
4
class Config(object): """ Holds model hyperparams and data information. The config class is used to store various hyperparameters and dataset information parameters. Model objects are passed a Config() object at instantiation. """ # Hyperparameters lr = 0.001 # Learning Rate drop...
5aac90ac386cd5d3fd4315a09b6619e5441c6135
ENSIIE-2022/IA
/Python/2.py
215
3.578125
4
code = {'e':'a', 'l':'m', 'o':'e'} s = 'Hello world!' # s_code = 'Hamme wermd!' s = list(s) counter = 0 for letter in s: if letter in code: s[counter] = code[letter] counter += 1 print(''.join(s))
cdc04e08985e5241fe96acd5d1e1fbc1aae4a83a
caleb-madgwick/pythonCalculatlor
/main.py
13,424
4.21875
4
from tkinter import * from tkinter import messagebox # This is for the messageboxs that are used for the Info button and the error messages class Application(Frame): def __init__(self, master, *args, **kwargs): Frame.__init__(self, master, *args, **kwargs) # This function clears the display and ...
d48b8e88545ebcf87820f63294285c9b0d370331
kingdunadd/PythonStdioGames
/src/towersOfHanoi.py
2,977
4.34375
4
# Towers of Hanoi puzzle, by Al Sweigart al@inventwithpython.com # A puzzle where you must move the disks of one tower to another tower. # More info at https://en.wikipedia.org/wiki/Tower_of_Hanoi import sys # Set up towers A, B, and C. The end of the list is the top of the tower. TOTAL_DISKS = 6 HEIGHT = TOTAL_DISK...
c8d94e4a311f96fa0b1593f2c8f1bf582a876e5b
mrtsnElizabeth/exercise
/1.py
210
3.828125
4
def str_to_dict(some_str): """ :param some_str: str :return: dict """ return {str:some_str.count(str) for str in set(some_str)} print('Str to dict:', str_to_dict('university'))
0b0329ee3244562c8c7aa7abb3068f2c06737bde
codesheff/DS_EnvTools
/scripts/standard_functions.py
706
4.21875
4
#!/usr/bin/env python3 def genpassword(forbidden_chars:set={'!* '} , password_length:int=8) -> str: """ This function will generate a random password Password will be generated at random from all printable characters. Parameters: forbidden_chars: Characters that are not allowed in the pass...
5789a381fa0c64607926104a9713f374f8d28145
aporto/python
/augmented_reality_platformer_game/game.py
17,525
3.9375
4
""" Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ From: http://programarcadegames.com/python_examples/f.php?file=platform_jumper.py Explanation video: http://youtu.be/BCxWJgN4Nnc Part of a series: http://programarcadegam...
97defbcbd96034d5ac170250340d05d18732da78
willpxxr/python
/src/trivial/sorting/quicksort.py
2,527
4.25
4
from math import floor from typing import List def _medianOf3(arr: List, begin: int, end: int) -> (int, int): """ Brief: Help method to provide median of three functionality to quick sort An initial pivot is selected - then adjusted be rotating the first index, center index and end index...
7b5d4d2f9b5658000559949876cbb195d15e5006
willpxxr/python
/src/trivial/data_structures/dllist/dllist.py
777
3.609375
4
from src.trivial.data_structures.dllist.dlllist_node import DlListNode class DllList(): def __init__(self): self.head = None def insert(self, value: int) -> None: tail = self.head while tail is not None: tail = tail.next new_head = DlListNode(value) new_he...
e842f36a010f5272e7d310f9d95f354fe5a70fb5
CrazyMan80052/Learning-PythonS
/org/talon/learning/Practice0/Print10-1.py
85
3.90625
4
for i in range(10,0,-1): print(i, end= " ") x=10 while x>0: print(x) x-1
8b366d877bd0fb3438771b089325878c739ab15d
kick-ass-coders/more-birds
/google image scraper/consolidate_images.py
436
3.625
4
#consolidate images in all directories within a parent directory to live in a new directory def relocate_imgs(parent_directory, new_directory): import os # create list of images dir_list = os.listdir(parent_directory) for dir in dir_list[1:]: img_list = os.listdir(parent_directory+"/"+dir) ...
4d97da5b7a57a64742ef4bd277638fa20a7346ef
SmruthiSuresh/Smruthi-Suresh
/Assignment 3/Question 2/Ques 2 Part 2/Ques2Part2Fin1.py
1,273
3.59375
4
# coding: utf-8 # # Question 2 Part 2 # In[1]: import csv import pandas as pd from pandas import DataFrame import numpy as np import calendar # In[2]: # Reading the csv File dfa=pd.read_csv('employee_compensation.csv') dfa.head() # In[8]: # Filtering by the year type Calendar dfb=dfa[dfa['Year Type']=='Calend...
00ab2d943cb03190ef2e74da69d37fdbddd8a447
howlettjames/Python-CIC-Ambito-CIentifico
/4_Class/test_rational.py
670
3.625
4
from rational import Rational def testRational(): r1 = Rational(3, 2) r2 = Rational(1, 2) print("NUMBERS") print(f"r1 = {r1} and r2 = {r2}\n") print("ARITHMETIC OPS") print(f"Sum: {r1 + r2}") print(f"Sub: {r1 - r2}") print(f"Mult: {r1 * r2}") print(f"Div: {r1 / r2}") print(f"Po...
2578a4f2fe6b527ecd1f594890381141f9939a69
howlettjames/Python-CIC-Ambito-CIentifico
/1_Tarea/grupos.py
254
3.96875
4
nombre = input("Ingrese su nombre: ") genero = input("Ingrese su genero (F o H): ") grupo = "" if(genero == 'F' and nombre.lower() < "m") or (genero == 'H' and nombre.lower() > 'n'): grupo = "G1" else: grupo = "G2" print(f'Tu grupo es {grupo}')
36977d92e591be776ff6ebdfb465a847aa1d1b92
sahil27301/bootcamp
/tests/number_tests/binary.py
612
4
4
def evaluate(expr): ans=input(f"{expr} = ").strip() if ans==str(eval(expr)): print("Good job! Correct Answer!") print("*"*100) return 1 print("Oops! Incorrect Answer!") print("*"*100) return 0 def testBinary(): score=0 print("Enter the expected values of these expres...
4f4bd8e53289cd38b0e63b49b8cfedbc33f5c7bc
sahil27301/bootcamp
/tests/boolean_tests/bools.py
885
3.953125
4
def evaluate(expr, answer): ans=input(expr).strip() if ans==answer: print("Good job! Correct Answer!") print("*"*100) return 1 print("Oops! Incorrect Answer!") print("*"*100) return 0 def testBools(): score=0 print("Answer True or False for the following questions.")...
0c13e87aef344a777129546026e2eef8822809db
klandhu/hello-world
/pythonxs/RvStr.py
204
3.546875
4
#RvStr.py def rvs(s): if s == "": return s else : return rvs(s[1:])+s[0] n = input("请输入需要反转的字符串:") print("反转之后的字符串为:{}".format(rvs(n)))
eb5a128b7f011898cdfe17d80b1d7c9f7e10a54d
klandhu/hello-world
/pythonxs/FibPrV1.py
622
3.84375
4
#fibV1.py def fib(n): if n ==1 or n == 2: print(1) else: s=fib(n-1) + fib(n-2) print(s) n = eval(input("斐波那契数列计算:")) print("斐波那契数列为:{}".format(fib(n))) '''def f(n): if(n<=2): return 1 else: return f(n-1)+f(n-2) if __name__=="__main__": num=i...
d8cbdb05ad327e3ca3bcae385359de474b873c35
JViii/FEUP-IART
/proj1/data_structures/myqueue.py
636
4
4
class Queue: def __init__(self): self.queue = [] def size(self): return len(self.queue) def isEmpty(self): return len(self.queue) == 0 def push(self, node): self.queue.insert(len(self.queue), node) def pop(self): if len(self.que...
5c655c0bc6bbed1cc98f53f769714ae41390494c
JViii/FEUP-IART
/proj1/data_structures/priority_queue.py
1,040
4.0625
4
class PriorityQueue: def __init__(self,heuristic= "none"): self.queue = [] self.heuristic=heuristic def size(self): return len(self.queue) def isEmpty(self): return len(self.queue) == 0 def push(self, node): self.queue.append(node) if se...
5d499785e209954478050d9208212122d8a51634
Coder-Chandler/L_0
/Classic Questions/Fibonacci.py
2,036
4.03125
4
''' Fibonacci numbers Leonardo of Pisa (aka Fibonacci) modeled the following challenge: Newborn pair of rabbits (one female,one male) are put in a pen. Rabbits mate at age of one month. Rabbits have a one month gestation period. Assume rabbits never die, that female always produces one new pair (one male, one female) e...
f9986bd871e98fe34c84bb310bb82bb973f28829
reanbrenda/Lecture2
/assignment_2_2.py
162
3.921875
4
# a program that print the profit def main(): revenue=int(input("enter the total revenue made:")) profit=revenue*(23/100) return profit print(main())
52d309fa9f4cca8b527da7850fca9256a34c2b6c
hannahbishop/AlgorithmPuzzles
/Arrays and Strings/rotateMatrix.py
1,244
4.25
4
def rotate_matrix(matrix, N): ''' Input: matrix: square, 2D list N: length of the matrix Returns: matrix, rotated counter clockwise by 90 degrees Example: Input: [a, b] [c, d] Returns: [b, d] [a, c] Efficiency:...
6608f87666bc2a6897484d8caf9a90eb1e88edff
Arinerron/covid-19-analysis
/src/covidify/sources/wikipedia.py
1,223
3.703125
4
#!/usr/bin/env python3 from bs4 import BeautifulSoup import wikipedia def fetch_wiki(article): data = wikipedia.page(article).html() soup = BeautifulSoup(data, 'lxml') table = soup.find_all('table')[1] # Wuhan coronavirus situation in mainland China as of 24:00 CST rows = table.find_all('tr') al...
8d127518c069a05bbc481fd933e0fc0a4f62f6b3
rhyang6/mais-bootcamp-w2019
/Assignment2/Assignment 2.py
16,275
4.28125
4
#!/usr/bin/env python # coding: utf-8 # # Assignment 2 # In this assignment, we will start with utilizing Sci-Kit learn to implement a linear regression model similar to what we did in Assignment 1. Afterwards, we will be dropping Sci-Kit learning and implementing these algorithms from scratch without the use of mach...
e72fe631c3633f59c643e7a58de5ab3c9c564eb9
Ziiv-git/HackerRank
/HackerRank23.py
1,987
4.1875
4
''' Objective Today, we’re going further with Binary Search Trees. Check out the Tutorial tab for learning materials and an instructional video! Task A level-order traversal, also known as a breadth-first search, visits each level of a tree’s nodes from left to right, top to bottom. You are given a pointer, , pointing...
bf5d37add2379cde576d1576db63c013a69706d4
jessejhuang/clrs-implementations
/pivot.py
475
3.78125
4
# pylint: disable=print-statement import random newList = [random.randint(-100, 100) for i in range(20)] p = newList[0] print("Pivot:", p) print("List:", newList) def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp def pivot(A, p, l, r): i = l j = r while i < j: while A[i] < p: ...
062f87168faf95ca335cc59b551b4d96e3a531f7
gauravmalaviya143/numpy
/2dto1dto3d.py
191
3.953125
4
from numpy import * arr1 = array([ [1,2,3,6,2,9,1,2], [4,5,6,7,5,3,1,2] ]) arr2 = arr1.flatten() arr3 = arr2.reshape(2,2,4) print(arr2) print(arr3)
3e06131167a666dddfe7b71a6d996c18c2b0799e
pnd-tech-club/Practice-code
/Python/mathz.py
1,203
4.03125
4
from math import sqrt, cos, tan p1 = '#1 ' p2 = '#2 ' n1 = '' n2 = '' funcs = ['add', 'sub', 'mul', 'div', 'exp', 'sqrt'] help = "Current operations are: \n -Add(add) \n -Subtract(sub) \n -Multiply(mul) \n -Divide(div) \n -Exponent(exp) \n -Square root(sqrt) \n -Tangent(tan) \n -Cosine(cos)" stop = 0 print "What oper...
6e35ae30c190e93409e9f872a7ed4f69296b1277
kevin-goetz/Python-Specialization
/04_Using Databases with Python/Assignments/PY4E_ALL EXERCISES.py
9,351
3.9375
4
# %% ''' Exercise 15.1: This application will read the mailbox data (mbox.txt) count up the number email messages per organization (i.e. domain name of the email address) using a database with the following schema to maintain the counts: CREATE TABLE Counts (org TEXT, count INTEGER) When you have run th...
a2aa54b07bf17054ab0cd8ab13ed711d6636c997
kevin-goetz/Python-Specialization
/02_Python Data Structures/Assignments/PY4E_Exercise 10.2.py
1,085
4.0625
4
# %% ''' Exercise 10.2: 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct....
3bc2877fd38279591d54aa2f3249187797f1e889
kevin-goetz/Python-Specialization
/01_Programming for Everybody (Getting Started with Python)/PY4E_Exercise 5.1.py
861
3.78125
4
# %% ''' Exercise 5.1: Write a program which repeatedly reads numbers until theuser enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than anumber, detect their mistake using try and except and print an error message and skip to the ...
3206c133dc927242160e32b8a34cd90702c4e2f6
kevin-goetz/Python-Specialization
/03_Using Python to Access Web Data/Assignments/PY4E_Exercise 13.2.py
696
3.875
4
# %% ''' Exercise 13.2: The program will prompt for a URL, read the json data from that URL and then parse and extract the comment counts from the json data, compute the sum of the numbers in the file and print the sum. ''' # import relevant libraries import requests # noqa import json # noqa # get the...
c068e8f8281644f33b51a7a20038b8aae8d72d4f
blainegarrett/merkabah
/core/auth/services/local_password/__init__.py
948
3.78125
4
""" Merkabah Local Password Auth Service Passwords are encrypted using PBKDF2 using SHA1 hashing algorithm """ import os from Crypto.Protocol.KDF import PBKDF2 PBKDF2_ITERATIONS = 5000 KEY_LENGTH = 32 def set_password(password, login): """ Given a plain text password Note: This does not save the login s...
d82be3f23c818b887def5928b6473131e833a325
sveinbjornt/cityloc
/create_db.py
2,768
3.75
4
# -*- encoding: utf-8 -*- """ Create city database from from cities CSV file provided by ??????????? """ from __future__ import print_function from __future__ import unicode_literals from builtins import input import sys import os import sqlite3 import unicodecsv import humanize from pathlib import Pa...
b17cd6531f493f8e5009d6531bde05ca0e659655
TudorMaiereanu/leetcode
/remove_nth.py
1,059
3.78125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): link1 = head c1 = 0 while(link1 != None): link1 = link1...
57a3067579fec4e7b43d1b2b41f9dd18cb1336ec
dcorvi/flask_api_build
/app/routes.py
5,524
3.90625
4
from app import app # jsonify works the same way that JSON.stringify does # request is what allows us to take in parameters in the api call from flask import render_template, jsonify, request # don't confuse with request method above, requests is a library for calling api's, it is specific to python, where request a...
0823d9008a89384cbbe83c0a8fc22dac831ec6e9
hcp4715/NeuroKit
/neurokit2/misc/intervals_to_peaks.py
1,039
3.875
4
import numpy as np def intervals_to_peaks(intervals): """Convenience function to convert intervals to peaks, such as from R-R intervals to R-peaks of an ECG signal. This can be useful if you do not have raw peak indices and have only interval data such as breath-to-breath (BBI) or rpeak-to-rpeak (RRI...
d0083945b817ded546eff9b1554e659be2eef8b5
shenriet/autoptim
/tutorials/rosenbrock.py
345
3.5625
4
# Author: Pierre Ablin <pierreablin@gmail.com> # License: MIT # This is the simplest example of autoptim use. from autoptim import minimize, numpy as np # Specify the loss function : def rosenbrock(x): return (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2 # Choose the starting point: x0 = np.zeros(2) x_mi...
53cecd207777cb4b81667a0869fc3318f8673f47
mciaccio/pythonCode
/udacityPythonCode/classes/inheritance.py
2,075
4.34375
4
# class name first letter uppercase "P" class Parent(): # constructor def __init__(self, last_name, eye_color): print("Parent Constructor called\n") self.last_name = last_name self.eye_color = eye_color # super class instance method def show_info(self): prin...
5c2eb5d57096f1766bdfb345a72d629ce657e4fc
dsevernyuk/mocks
/src/calculations/calc2.py
122
3.5
4
from math import pi APPROX_PI = round(pi, 2) def calculate_approx_area(radius): return APPROX_PI * radius * radius
05bc7ce1dc5e7e94fd495aba3986e99243d48df5
amantaymagzum/magzumcs
/2.py
187
3.578125
4
number=5 digit = -4.54356876 word="Результат" boolean=True str_num='5' print(word+str(number+int(str_num))) del number number=7 print('Результат:',number)
b452e031126d3ca3fb47cd070f317635bbd37688
SI206-UMich/wn2021-project2-madgau12
/Project2.py
11,825
3.65625
4
from bs4 import BeautifulSoup import requests import re import os import csv import unittest def get_titles_from_search_results(filename): """ Write a function that creates a BeautifulSoup object on "search_results.htm". Parse through the object and return a list of tuples containing book titles (as prin...
4c7e937fb60562b687b98be26a98e9e7a0350732
spiritdjy/MixLeetCode
/mixleet/leecode/l33_retota_array.py
1,857
3.625
4
class Solution: def search(self, nums: list, target: int) -> int: return self._search(nums, target, 0) def _search(self, nums, target, base): # print(nums, target, base) if len(nums) == 0: return -1 middle = len(nums)//2 middle_value = nums[middle] i...
05a275030923c66f92a9988275ca97cd239db3a5
christianvluu/snake_ws
/src/snake_control/scripts/data_processing.py
2,678
3.984375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd # Learned the majority of sklearn, etc. from https://www.udemy.com/course/machinelearning/ np.random.seed(12345) data = pd.read_csv("/home/christianluu/snake_ws/data/final_calib.csv") x = data.iloc[:,-2:-1].values # x is the currents y = data.ilo...
14b2f14f302163914b425d67b902dccd10263932
Bishuu1/TareaEdd
/ListaDoble.py
2,474
3.890625
4
class Node: def __init__(self, nombre, apellido, telefono, mail): self.apellido = apellido self.nombre = nombre self.mail = mail self.telefono = telefono self.next = None self.prev = None class LDE: def __init__(self): self.head = None self.tail =...
8ad0f485fbad4f5edc9df95ba3a4b21257add7bc
ashwin-magalu/Python-OOPS-notes-with-code
/access.py
713
4.28125
4
class Employee: name = "Ashwin" # public member _age = 27 # protected member __salary = 10_000 # private member --> converted to _Employee__salary def showEmpData(self): print(f"Salary: {self.__salary}") class Test(Employee): def showData(self): print(f"Age: {self._age}") #...
ab8f17f2d6c604e8642c3363558e75b6f33d3d68
ashwin-magalu/Python-OOPS-notes-with-code
/overloading.py
935
3.59375
4
class Account: def createAccount(self, name, email, password, mobileno): self.name = name self.email = email self.password = password self.mobileno = mobileno def createAccount(self, name, email, password): self.name = name self.email = email self.passwor...
5b0cf645206c20b4e86dc26d07135e5fdfe79315
sxxa-qlp/LPY
/liao_text/property.py
338
3.640625
4
class Student(object): @property def score(self): return self._score @score.setter def score(self,value): if not isinstance(value, int): raise ValueError('score must be integer!') if value > 100 or value < 0: raise ValueError('score must between 0-100') self._score = value s = Student() s.score = 2...
8ea290285850d4b073ba375f4b13e4898b402869
sxxa-qlp/LPY
/Py2/powN.py
118
3.953125
4
N = float(input()) #先算前5个 for i in range(5): #注意end为空格 print(pow(N, i),end = ' ') print(pow(N, 5))
b3edfa76f3d604c9068c1283b088d3b6f6bdec32
sxxa-qlp/LPY
/liao_text/trim.py
486
3.578125
4
class Student(object): def __init__(self,name,gender): self.name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self,gender): if gender in ('male','female','x'): self.__gender = gender else: raise ValueError('bad value') def get_inf(self): print('%s:%s'...
140a50b4d69e20bf0cb70cba843f374f9ab6c518
sxxa-qlp/LPY
/Py2/100yineijishu.py
651
3.828125
4
""" Author: Xinyu OU Function: 计算100以内的奇数和 """ # 定义一个全局变量用于保存最终的结果 sum1 = 0 # 使用for循环对加数进行遍历, # for循环中需要考虑起始值、终止值和步长 for i in range(1,100,2): # 给奇数计数 注意取整函数 a = int(i/2) # 打印出计算了哪些奇数,str()用于将整数类型转换为字符串,并显示在屏幕中 #注意取整后加一 print("第" + str(a+1) + "个奇数为:" + str(i)) #计算循环的当前轮次中,求和的结果 sum1 ...
dbd58965bb0b8e6fc281f3d04329a2af51f858fe
sxxa-qlp/LPY
/Py2/jisuanjiecheng.py
76
3.5
4
temp = eval(input()) a = 1 for i in range (temp): a = a*(i+1) print(a)
c07554966800e4fd6da53e118a00e0652f22a074
pr0d33p/PythonIWBootcamp
/Data Types/26.py
129
3.875
4
list = [1, 2, 3, 4] string = "emp" newList = [] for item in list: newList.append(string+"{}".format(item)) print(newList)