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
7096287a54a9d089fc4b3627cb62ac4b380fd082
ras9841/practice
/arrays_and_strings/rotate_matrix/rotate.py
628
3.703125
4
def rotate90(matrix, n): """ Rotates a NxN matrix 90 degrees about the center. """ for layer in range(int(n/2)): start = layer end = n - 1 - layer for i in range(start, end): offset = i - start top = matrix[start][i] # top <- left ...
b6f03023ab52a12b262e46960de3ff0b3c1986d9
ras9841/practice
/sorting/sortMethods.py
2,150
4.25
4
def bubbleSort(lst): """ Time complexity: O(n^2) Space complexity: O(1) """ size = len(lst) for _ in range(size): swapping = True while swapping: for i in range(size-1): if lst[i] < lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i]...
98fb385c1785e70928cd87f39641a07b80c8ac10
jjd9/CSE_397_Team
/Problem1/prior.py
2,076
3.84375
4
#!/usr/bin/env python # import numpy as np from math import log, pi def Gaussian(x,sig,mu): """ Calculate normal distribution given parameters """ nom = np.exp((-(x-mu)**2)/(2*sig**2)) den = sig*np.sqrt(2*np.pi) output_G = float(nom)/den return output_G def prior_U(q): """ This rou...
fe7ec0cb6c9b425a85c49d48fed6b6da832b231e
tanxvyang/Python-
/src/day01/other/slicing.py
164
4.03125
4
#分片示例 # 对http://www.something.com形式的URL进行分割 url = input('Please enter the URL:') domain =url[11:-4] print( "Domain name is :" + domain)
ff81753ee82445671d025a9abfe191d6dd75a079
tanxvyang/Python-
/src/day03/变量.py
292
3.734375
4
''' counter = 100 #整形变量 miles = 1000.0 #浮点型变量 name = "runoob" #字符串 print(counter,miles,name) ''' ''' #python允许同时为多个变量赋值 a=b=c=1 print(a,b,c) print("======================================================") a,b,c=1,2,"runoob" print(a,b,c) '''
5c7943ead4a9fabee7697ed75bd644b9978d7926
tincher/adventofcode
/2.py
1,232
3.703125
4
dummy = {'min': 1, 'max': 3, 'char': 'f', 'password': 'afsadf'} with open('./input2.txt') as input_file: # part 1 lines = input_file.read().split('\n') elements = [] for line in lines: if line == '': break policy, password = line.split(':') ...
a4571cc812a230b63563f9e6054689b217fd2d24
rashi174/Data-Structures
/Graphs/Graph-BFS-adjacencyList.py
726
3.921875
4
from collections import defaultdict class Graph: def __init__(self): self.graph=defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) #adding edges bw the nodes def bfs(self,s): # s is the starting node from where bfs will beginnnnn :) visited=[False] * (max(self.graph)+1) queu...
3bab822ac9d8d46b54787f6f15984adc60885206
rashi174/Data-Structures
/Trees/HeightOfBinaryTree.py
558
3.984375
4
#Height of a Binary Tree # 10 Level1 # / \ # 20 30 Level2 # / \ / \ # 40 50 N 60 Level3 # \ # 80 Level 4 #Height = Total Levels = 4 root=TreeNode(10) root.left=TreeNode(20) root.left.left=TreeNode(40) root.right=TreeNode(30) roo...
b7551990f09cafa0776cbcbff57bcf50602348a0
rashi174/Data-Structures
/Trees/Find-Bottom-Left-Tree-Value.py
1,076
4.03125
4
''' 513. Find Bottom Left Tree Value Given the root of a binary tree, return the leftmost value in the last row of the tree. Example 1: Input: root = [2,1,3] Output: 1 Example 2: Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7 Constraints: The number of nodes in the tree is in the range [1, 104]. -...
2e23bc89d20ba5ef74c3938d50a48ea8df8995b2
jyheo/python365_hansung
/tkinter/Tkinter06_events.py
544
3.5625
4
from Tkinter import * def main(): app = Tk() def key(event): print "pressed", repr(event.char) def callback(event): frame.focus_set() print "clicked at", event.x, event.y def enter_callback(event): print "dragged at", event.x, event.y frame = Frame(app, width=20...
c6335dbad96197cc3c17b27f230a90aab5e4976e
andela-sjames/jelly_dance
/andela_camp_prj1.py
1,313
3.953125
4
def n_sur_bestscore(total): whole_number = total / 3# divide by 3 because total is a summation of 3 digits if total % 3 > 0: return whole_number + 1 #adding one because numbers in triplet score differ by 1 return whole_number# return whole number for uniform triplet score def sur_bestscore...
e5600d8b229aa7642bc92a267f07ebc4af49a260
EsslamAshour/project-1
/YuushaNoTsurugi/game.py
5,193
3.578125
4
""" File name: game.py Author: Esslam Ashour Date created: 26/9/2021 Python Version: 3.9.6 """ import random import time import os import sys import db level_data = db.level_data def start(): """ Print info about the game, get the player name and insert it into the database. """ pr...
b8ba0f7e41dea4b26753cf931b2ad1fb67240a4f
Miguel-Caringal/CHCIProgrammingClub
/Challenge of the Week/week 1/easy/Miguel Caringal.py
277
4.21875
4
month= int(input()) day= int(input()) if month > 2: print ('After') else: if month == 2: if day == 18: print ('Special') elif day <18: print ('Before') else: print ('After') else: print ('Before')
34cf7d1fc1697c2003903673fe642e304e9c0b0b
LucestDail/python.DataAnalysis
/test0208/test1.py
405
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 7 17:28:09 2021 @author: myung test1.py : 다음 결과를 예측하시오 """ a = "Life is too short, you need python" if "wife" in a: # false print("wife") elif "python" in a and "you" not in a: # true and false => false print("python") elif "shirt" not in a: # true print(...
227e1d4607d29d7e6a14eabef1bde0dd8f71d93b
LucestDail/python.DataAnalysis
/20210216before/NewFileReader.py
255
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from operator import itemgetter import sys input_file = sys.argv[1] print("output : ") with open(input_file, 'r', newline='') as filereader: for row in filereader: print("{}".format(row.strip()))
99a96d6358fb2eba004c460834619155983adfe7
LucestDail/python.DataAnalysis
/20210216before/2021020810.py
769
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 13:34:08 2021 @author: dhtmd """ class Car: color = "" speed = 0 def upSpeed(self, value): self.speed += value def downSpeed(self, value): self.speed =+ value myCar1 = Car() myCar1.color = "빨강" myCar1.speed = 0 myCar2 = Car() myCar2.co...
54c700de10720d06b53604289defef06c19b57bf
LucestDail/python.DataAnalysis
/20210216before/2021020512.py
563
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 14:54:20 2021 @author: dhtmd """ def getSum(target): return sum(target) def getMean(target): if(len(target) == 0): return 0 else: return sum(target) / len(target) list = [2,3,3,4,4,5,5,6,6,8] print(f"getSum(list) : {getSum(list)}") print...
c83d97f15f3bfcea035590892a9b5f90fd7f6268
LucestDail/python.DataAnalysis
/20210216before/2021020404.py
310
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 4 12:03:22 2021 @author: dhtmd """ money = int(input("값 입력 : ")) print(f"500 : {money//500}") money = money%500 print(f"100 : {money//100}") money = money%100 print(f"50 : {money//50}") money = money%50 print(f"10 : {money//10}") print(f"1 : {money%10}")
54c1c5f6b8621cd70458e28d21c3c98dcfd8bc96
LucestDail/python.DataAnalysis
/20210216before/test.py
220
3.796875
4
def sum_digit(num): total = 0 str_num = str(num) for digit in str_num: total += int(digit) return total digit_total = 0 for i in range(1,1001): digit_total += sum_digit(i) print(digit_total)
09e70709f5df9179523da8bb8c9cb2718ef6aa72
LucestDail/python.DataAnalysis
/20210216before/2021020909.py
656
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 9 14:05:52 2021 @author: dhtmd """ import sqlite3 con, cur = None, None row = None con = sqlite3.connect("iddb") cur = con.cursor() cur.execute("select * from usertable") item_list = cur.fetchall() for it in item_list: print(it) print() cur.execute("select * fro...
a19c56dad0d3854a8ff24b1480d0e85023073805
LucestDail/python.DataAnalysis
/20210216before/2021020403.py
351
3.671875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 4 11:53:32 2021 @author: dhtmd """ a = int(input("값1 입력 : ")) b = int(input("값2 입력 : ")) print(f"{a} + {b} = {a+b}") print(f"{a} - {b} = {a-b}") print(f"{a} * {b} = {a*b}") print(f"{a} / {b} = {a/b}") print(f"{a} // {b} = {a//b}") print(f"{a} % {b} = {a%b}") print(f"{a}...
2d1155830d23d6a9b27470952acc868a3fe8a3c1
LucestDail/python.DataAnalysis
/20210216before/2021020522.py
445
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 17:10:55 2021 @author: dhtmd """ input_value = input("주민등록번호를 입력하세요(111111-1111111) => ") try: checker = input_value.split("-")[1][0] if(checker == "1" or checker == "3"): print("남자입니다.") elif(checker == "2" or checker == "4"): print("여자입니다...
73d859a88124a4e7f698dc215c270057e4ea1da8
ArthurJiang/playground
/leet_code/2.py
1,641
3.65625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: res = ListNode() cur_node = res tmp_sum = 0 r...
b7573ea7b46439650857a1553e9efb33e575fc69
BrandonLMorris/ml-examples
/linear_regression/linear_regression.py
5,643
4
4
#!/usr/local/env python3 """ Simple linear regression with gradient descent. No optimization attempts have been made, this is purely for example and educational purposes. Data is randomly generated and saved to a file in the current directory for reproduceability. To regenerate the data, simply delete the 'linear_regr...
d11a38ad5ca8e04815972194b871bec579cb580f
hseling/hseling-web-nauchpop
/docker/deps/search_wheels.py
1,729
3.578125
4
import zipfile import re import os import argparse def main(dir, name_to_search): # Check all files in the directory and print the name of the package for root, dirs, files in os.walk(dir): wheels = (fname for fname in files if fname.endswith('whl')) for fname in wheels: filename =...
c8fb428bf5ca8843fa2aa00c6ecd387506955324
jessicazeng/CSE-310-Project
/src/server.py
35,971
3.53125
4
__author__ = 'Jessica' # http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python from socket import * from string import rstrip # os library used to determine if a file exists # datetime library used for date requests # re library used to match for find strings that have a pattern import os, datet...
d5539aa1fe5855c796342923bec7465245be64a4
IvanGalvagno/PythonOO
/main.py
1,198
3.59375
4
# from pythonOOexample.math.calc import calc_sum # from pythonOOexample.string.str import hello # calc_sum(2,2) # hello() # from car import Car # carro1 = Car() # print(carro1.name) # print(carro1.color) # carro2 = Car() # carro2.name = 'A200' # carro2.color = 'Gray' # print(carro2.name) # print(carro2.color) # prin...
e32f0c68a8315fbe24a092d49eee455ff6ccfb91
elephant-is-elepahnt/Algorithm
/chapter5/Selection_Algorithm.py
955
3.625
4
def partition(A, p, r): standard = A[r] part_1 = p for part_3 in range(p, r): if A[part_3] <= standard: temp = A[part_1] A[part_1] = A[part_3] A[part_3] = temp part_1 += 1 temp = A[r] A[r] = A[part_1] A[part_1] = temp ret...
854f0a4d8d5330990a605f2884387affd9d7e1d1
elephant-is-elepahnt/Algorithm
/chapter6/BinarySearchTree.py
3,317
4.0625
4
class BinarySearchTree: def __init__(self): self.root = None def search(self, x): #t is root of the Tree t = self.root while True: if t is None: return None elif t.key == x: return t elif t.key > x: ...
4f2153ab0e35bf75c4f1ff56519ab2b6eaa1c7de
rpaswan/TestPY
/list_comprehension.py
473
4
4
# num=[1,2,3,4,5,6,7] # even=[] # for i in num: # if i%2==0: # even.append(i) # print(even) # num=[1,2,3,4,5,6,7] # even=[i for i in num if i%2==0] # print(even) # x=input("enter any number") # x=int(x) # if x in num: # print(x, "is found in list") # cities=["mumbai","new your", "paris"] # countar...
bf493c73614fb96f2563ebf2ebdaaa3625936716
swathiacharya/Python-workingSpace
/DataStructure/Graph/sourceLongestPath_DAG.py
1,982
3.640625
4
class Graph: def __init__(self, nodes): self.nodes = nodes self.allEdges = dict() self.parent = dict() self.distance = dict() for node in self.nodes: self.allEdges[node] = {} self.parent[node] = None self.distance[node] = ...
eb19db7eadce8f3f336391f4c4d74fdbbf89e7bf
swathiacharya/Python-workingSpace
/DAA/Sort/mergeSort.py
738
4
4
""" """ def merge(arr1,arr2,arr): i = 0 j =0 k = 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: arr.append(arr1[i]) k = k + 1 else: arr.append(arr2[j]) k = k + 1 if i == len(arr1): arr.append(arr1[i]) ...
266ff360770391e3432a44416de828da7f358178
swathiacharya/Python-workingSpace
/DataStructure/Graph/CycleDetectionUndirectedGraph_DFS.py
2,016
3.609375
4
class Graph: def __init__(self, node): self.nodes = node self.allEdge = dict() self.parent = dict() self.visited = dict() self.count = 0 for node in self.nodes: self.allEdge[node] = [] self.parent[node] = -1 self.visited[no...
33b403ac4126da95837a90983afea9ce0273b79c
vitovincentdo/admin-karir
/python/Component/paths.py
981
3.796875
4
""" This class is only used for declaring path to file or to folder Example: ```python from paths import Path retrievePath = Path() #declare Path read_file = open(retrievePath.pathArticleData, 'r') #open a file data.json inside article folder """ class Path(): def __init__(self): self.pathArticleTag = '../p...
631d3cccbe7eaae2b92e52f4c9664baf28338b75
SimplyKyra/100daysofcode-with-python-course
/days/01-03-datetimes/code/Day 3 Pomodoro Timer.py
816
3.53125
4
# Pomodoro Timer from time import sleep import os longDuration = 25 #1500 shortDuration = 5 #300 #input("Choose a break time (3-5 minutes).") iterations = 0 longBreak = 30 #1800 firstTime = True def longDurationFunc(): sleep(longDuration) os.system('say "Take a break"') def breakFunc(longBreak): if lo...
82aee3c209836fbf58ab5c26cb5914765b89f011
lancelafontaine/coding-challenges
/daily-programmer/daily-programmer-easy-026/python3/daily-programmer-easy-26.py
358
3.765625
4
def removeConsecutiveChars(initStr): previousChar = '' newStr = '' extraChars = '' for char in initStr: if previousChar == char: extraChars = extraChars + char else: newStr = newStr + char previousChar = char return [newStr, extraChars] print(remove...
7c4a5f301b66f206d4eaab2bbfb85dc4266167a8
lancelafontaine/coding-challenges
/daily-programmer/daily-programmer-easy-022/python3/daily-programmer-easy-22.py
165
3.8125
4
def appendUniqToList(origList, appendList): return origList + [elem for elem in appendList if elem not in origList] print(appendUniqToList([1,2,3], [2,3,4,5]))
d14dec960b610a9e2d036a4f06c52927df000740
lancelafontaine/coding-challenges
/hackerrank/algorithms/02-implementation/between-two-sets/python3/between-two-sets.py
696
3.71875
4
#!/bin/python3 def between_two_sets(a, b): counter = 0 for i in range(max(a), min(b)+1): should_increment = True for num in a: if not (float(i)/num).is_integer(): should_increment = False for num in b: if not (float(num)/i).is_integer(): ...
d66f7a89f4d4c28a13ad94131d7281f1f0323907
williamgl/CS-161
/Day 6-Module 4 practice.py
1,449
4.09375
4
# Author: Gan Li # Date: 8/2/21 8:49 上午 # Description: Chapter 6 and Module 4 practice """ def compare(a, b): if a > b: return 1 elif a == b: return 0 else: return -1 x = float(input('Please type in x:')) y = float(input('Please type in y:')) print(compare(x, y)) """ """ Ackermann...
fe409c7c9203755b4a2f9eaf005f39e757201aa4
williamgl/CS-161
/Day 4-Koch curve.py
518
3.5625
4
# Author: Gan Li # Date: 7/31/21 1:31 下午 # Description: Chap 5 exercise 5 from __future__ import print_function, division import turtle t = turtle.Turtle() t.pu() t.pd() angle = 60 def koch(t, n): if n < 3: t.forward(n) return x = n / 3 koch(t, x) t.left(angle) koch(t, x) t.r...
6edc146aeb107de0d61fe5727ac26644c16156e2
gauravgadhvi/main
/assignments/assignment0/boolean_search.py
2,797
4.03125
4
""" Assignment 0 You will implement a simple in-memory boolean search engine over the jokes from http://web.hawkesnest.net/~jthens/laffytaffy/. The documents are read from documents.txt. The queries to be processed are read from queries.txt. Your search engine will only need to support AND queries. A multi-word quer...
d90ca1b98ee7193be0e975c65da448dbf3cbbaa3
JesusSePe/Python
/Examen1v2/Concessionari/validació/comprovarPreu.py
386
3.828125
4
def comprovar_preu(): cool = False while not cool: try: preu = float(input('Introdueix un preu: ')) if 10000 < preu < 40000: return preu else: print("El preu ha de ser entre 10000€ i 40000€") except ValueError: print...
282bc7d2373e1da0d013122ceaa7e3eb95c98305
JesusSePe/Python
/functions/Modules_Practice/Exercise4.py
1,196
4.0625
4
# Create a module to verify passwords. # Conditions: # Length: minimum 8 characters. # Uppercase, lowercase, numbers and at least, 1 non-alphanumeric character. # Password can not contain spaces. # Return 'The password is not secure' when the password is correct. # If everything is correct, return True. def password_c...
4909483db899206839815604d10e358b5e48f3a0
JesusSePe/Python
/functions/Exam Practice/Exercise10.py
1,039
4
4
def ordenar_lista(lista, orden): # First, we check that all conditions are correct. # Orden must be asc or des if orden == 'asc' or orden == 'des': # The lista variable must be a list. if type(lista) == list: # The lista variable must have at least, 1 item if len(list...
717ae3da091a599a064163bd1e472606448a9b96
JesusSePe/Python
/recursivity/Extras/print_n_to_0.py
148
3.625
4
def downgrade(num): if num == 0: print(num) return else: print(num) return downgrade(num-1) downgrade(15)
2aa9219f38ace10bf1c4f63af44db6a685fa3a12
JesusSePe/Python
/functions/firstExercises.py
4,852
4.375
4
# This program has several functions, that are really simple programs. ######################### # FUNCTIONS DECLARATION # ######################### # Function to calculate the final price when a discount is applied. def discounted_price(original, percent): return original - (original * percent / 100) # Functio...
a5a62e8a5f03096ad0ad03eb27d9da6e1864a6b5
JesusSePe/Python
/recursivity/Exercises3.py
1,503
4.28125
4
"""Exercise 1. Rus multiplication method.""" from math import trunc from random import randint def rus(num1, num2): if num1 == 1: print(num1, "\t\t", num2, "\t\t", num2) return num2 elif num1 % 2 == 0: print(num1, "\t\t", num2) return rus(trunc(num1 / 2), num2 * 2) else: ...
e861cf7c26e034494c255c199e7037e8d684c6fa
KodairaTomonori/PRML
/Chapter1/equation.py
949
3.703125
4
import numpy ''' PRML: Chapter1: Equations all function should require numpy object ''' def polinomial(w): ''' p5, 1.1, polinomial function numpy.array: w = w0, w1, w2...wn this function return function, not float or integer. returned function return float or integer. ...
237d9f3039570ac80821bfde409e8acdf2344c47
lesenpai/project-euler
/task4.py
738
4.1875
4
""" Число-палиндром с обеих сторон (справа налево и слева направо) читается одинаково. Самое большое число-палиндром, полученное умножением двух двузначных чисел – 9009 = 91 × 99. Найдите самый большой палиндром, полученный умножением двух трехзначных чисел. """ def is_palindrome(n): s = str(n) return s == s...
0b4ce92856869feb7546294cc92f53ed1ed0a622
gutiantian123Abc/Leetcode_python
/easy/Squares_of_a_Sorted_Array.py
1,022
3.953125
4
''' 977. Squares of a Sorted Array https://leetcode.com/problems/squares-of-a-sorted-array/ Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: ...
94980b813d69c176aed8fc68d373244fdcae4dbc
dalerxli/bpnn-ngsim-congestion
/bpnn.py
5,364
3.53125
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset ngsim_us101 = pd.read_csv("NGSIM_US101.csv") ngsim_us101 = ngsim_us101.drop('Unnamed: 0', axis=1) X = ngsim_us101.iloc[:, 0:18].values y = ngsim_us101.iloc[:, 18].values # Splitting the dataset in...
44c7e22be5ded83f72dd7716ae2ec434b8ea599f
xiaoheiwowo/Mixed
/Leetcode/data_structure.py
674
3.796875
4
class Node(object): def __init__(self, left, data, right): self.left = left self.data = data self.right = right def order(self, tree): if tree is not None: print(tree.data) # return tree.data self.order(tree.left) self.order(tree....
91e9fdbd5b792e34faab35dd1c05f2a2e7f12618
jeromeslash83/My-First-Projects
/basic_games/Tic_Tac_Toe.py
2,908
3.953125
4
start_game = True def tic_board(board): print(f"| {board['1']} | {board['2']} | {board['3']} |") print(f"----+---+----") print(f"| {board['4']} | {board['5']} | {board['6']} |") print(f"----+---+----") print(f"| {board['7']} | {board['8']} | {board['9']} |") def check_winner(count, board): ...
352a06c853b95af900c04a573e600f417cd7e51f
jeromeslash83/My-First-Projects
/basic_games/Higher_Lower_game/Higher_Lower.py
1,989
4.03125
4
#HIGHER LOWER GAME #Import the files needed in the program. import random from game_data import data import art #Set the first two choices of A and B and the current score which is 0. high_score = 0 game = True A = random.choice(data) B = random.choice(data) if A == B: B = random.choice(data) def ch...
502b41273a57a4d1ca29215e005d5763eb41e163
jeromeslash83/My-First-Projects
/random_stuff/BMI_Calculator.py
661
4.28125
4
#BMI CALCULATOR print("Welcome to Jerome's BMI Calculator!") while True: Name = input("What is your name? ") Weight = input("What is your weight (in kgs)? ") Height = input("What is your height(in m)?") BMI = float(Weight) / (float(Height) * float(Height)) print("Your BMI is", BMI) i...
94a32ee621e62308dafe7d92b0de9b05f356a10d
simuchand/Python-Basic-Programs
/X or O.py
3,461
3.953125
4
from random import randrange import time def DisplayBoard(board): print( """ +-------+-------+-------+ | | | | | """,lst[0][0], """ | """,lst[0][1], """ | """,lst[0][2], """ | | | | | +-------+-------+-------+ | | | ...
52bd91b8e40bf46a6d78ba5347fcbc53e5046379
karelrenaldi/simple-ann
/src/ann.py
5,125
4.15625
4
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler import copy class ANNClassifier: """ Simple implementation ANN with 2 layer (1 hidden layer, 1 output layer). This implementation works for binary classification problem. """ def __init__(self, layers=...
7292af58cb685a2147e6801455e3d88dd03d7620
Jeanselme/Kaggle
/utils/save.py
346
3.578125
4
""" Saver by Vincent Jeanselme vincent.jeanselme@gmail.com """ import pickle def save(structure, name): """ Saves the given structure in the file """ with open(name, 'wb') as output: pickle.dump(structure, output, pickle.HIGHEST_PROTOCOL) def load(name): """ Loads a structure from the given file """ wit...
8397a514306cecdcf4f530923fb0f2613bb423f7
pablocorbalann/Taur
/bot/groups/chat/nl.py
1,416
3.875
4
# In this file natural language tool kit (nltk) utils are stored in different # functions. # imports import numpy as np import nltk from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer() def tokenize(sentence): """ Using the bag words algorithm, every sentence has to be deconstructed to a list of re...
72c80694158b8fb38fdf4a365bbb73e493a40d5e
tobyshooters/etudes
/languages/python/arithmetic.py
1,645
3.625
4
# parser etude: evaluating arithmetic expressions def typify(s): try: return int(s) except: return s def find(a, e): try: return a.index(e) except: return None def ast(a): for op in ["+", "*"]: index = find(a, op) if index != None: return [op, ast(a[:index]), ast(a[ind...
01dfc11678b81a19780e0a47f2b962301c155df5
Markos9/Mi-primer-programa
/comer_helado.py
972
4.25
4
apetece_helado_input = input("Te apetece un helado? (SI/NO): ").upper() if apetece_helado_input == "SI": apetece_helado = True elif apetece_helado_input == "NO": apetece_helado = False print("Pues nada") else: print("Te he dicho que me digas si o no, no se que has dicho pero cuento como que no") a...
6a1e8e32571c94da455083f9e023374bb7d898a8
mjrish96/The-ATM-Machine
/ATM.py
2,076
4
4
def account(): print ("Welcome to the bokuwabank ATM terminal v1.0") print ("Please enter your pin number") account = raw_input("Pin number is 1337: ") account = (1337) account() def balance(): print "View your balance?" see = raw_input("Enter Y or N: ") if (see == "y") or (see...
ac6ee679bb4f1a3d26cb79be7fec6691b0f70334
emerald2-0/100DaysofCode
/Day001/query_wikipedia.py
661
3.921875
4
import wikipedia def print_wiki_results(user_content): """ Searching for pages that match the specified word """ results = wikipedia.search(user_content) for result in results: try: page = wikipedia.page(results) except wikipedia.exceptions.DisambiguationError: ...
3b561251b8326284eb949e63d393f9529ea1be9f
dksingh04/algorithms
/postfixevaluation.py
752
3.859375
4
from pythond.basic.stack.Stack import Stack def postFixEvaluation(postfixExpression): opStack = Stack() tokenList = postfixExpression.split() for token in tokenList: if token not in "*+-/==": opStack.push(int(token)) else: operand2 = opStack.pop() operand1 = opStack.pop() result = doMath(token, opera...
9d3afaed074e58fa14f8cf35c98b6695e5db4556
DmitryIT/MITx6.00.1x
/week3/fibonacci.py
565
3.734375
4
import time num_of_calls = 0 def fibonacci(x): global num_of_calls num_of_calls+=1 if x == 1: return 1 if x == 2: return 2 else: return fibonacci(x-1) + fibonacci(x-2) def fibonacci_efficient(x,d): global num_of_calls num_of_calls+= 1 if x in d: return ...
cff22167208dba83f5702bd41a85d63e3baf32ae
winston1214/baekjoon
/1000-2000/1284.py
190
3.59375
4
# @Author YoungMinKim # baekjoon while True: num=input() if num=="0": break print((len(num)+1)+sum([2 if element=="1" else 4 if element=="0" else 3 for element in num]))
8c9228269af53c7983fff3a273c96238bef95aba
winston1214/baekjoon
/10001-11000/10870.py
202
3.84375
4
# @Author YoungMinKim # baekjoon def fibonacci(N): if N==0: return 0 elif N==1: return 1 else: return fibonacci(N-2)+fibonacci(N-1) N=int(input()) print(fibonacci(N))
db72fc450b4bb2d5177fb11271bf7bd2a2fa27e3
Mynotesoracledba/Shell-scripts-Assignments
/web_scrapper.py
1,213
3.703125
4
import requests #specify the url we want to scrape from request_url='https://en.wikipedia.org/wiki/The_World%27s_Billionaires' #convert the link into text site_repsonse=requests.get(request_url).text # print(site_repsonse) #import BautifulSoup library to pull data out of HTML and XML files from bs4 import BeautifulS...
cd1ddf662b245efe3c17b0aa388bcb61f81c8277
mskl/fit-bi-zns-homeworks
/ulohy/04/Fuzzy/Term/term_aggregate.py
1,627
4
4
class TermAggregate: """ Used to store combinations of Terms """ def __init__(self, term1, term2, kind): """ Note that func2 might be None in case of inverse """ self.func1 = term1 self.func2 = term2 self.kind = kind def __and__(self, other): """ movie['Good'] & equ...
2bc3f9ced3b80faebeeb4a4472317fe886c02eb4
amchigello/python_repository
/scripts/matrices.py
430
3.609375
4
a = [ [1,2,3], [4,5,6], [7,8,9] ] b = [ [1,2,3], [4,5,6], [7,8,9] ] c = [ [0,0,0], [0,0,0], [0,0,0] ] print("Sum of matrices") for i in range(len(a)): for j in range(len(b)): c[i][j] = a[i][j] + b[i][j] print(c) print("Transpose matric...
80f3531a10014de7beb5c64527dc1e3a0a5cdedb
amchigello/python_repository
/sorting_algorithms/bubble_sort.py
236
3.96875
4
def bubble_sort(l): n = len(l) for i in range(n): for j in range(0, n - i - 1): if l[j] > l[j + 1]: l[j], l[j + 1] = l[j + 1], l[j] print(l) arr = [8, 3, 9, 2, 1, 5] bubble_sort(arr)
457b16c4b8626a4fc186492b81ddecd71e4e159a
Jinholy/dl_study
/deep_test/3.py
572
3.59375
4
import tensorflow as tf X = [1, 2, 3] Y = [1, 2, 3] W = tf.Variable(5.0) hypothesis = X * W cost = tf.reduce_mean(tf.square(hypothesis - Y)) #optimizer가 미분하는거 대신해줌 (밑에 #으로 주석한부분) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train = optimizer.minimize(cost) #gradient = tf.reduce_mean((W * X - Y...
d1a261382f708fb604370b8fe0bcc97337504d2d
YogeshKapila/sierpinski-fractal
/ToolA_v1.py
755
3.9375
4
import turtle def draw_sierpinski(length, depth=2, n=2.0): if depth == 0: for i in range(0, 3): t.fd(length) t.left(120) else: draw_sierpinski(length/n, depth-1, n) t.fd(length/n) draw_sierpinski(length/n, depth-1, n) t.bk(length/n) ...
404a8b5acc870d77913eb0d85d249808d65205a2
milesdavis71/okj_vizsga_jupyter
/src/felfedezesek.py
645
3.71875
4
import pandas as pd header_names = ['ev', 'elem', 'vegyjel', 'rendszam', 'felfedezo'] df = pd.read_csv('src/felfedezesek.csv', sep=';', encoding='windows-1250', header=0, names=header_names) print(f'Elemek szama: {len(df)}') felfedezesek_okorban = df[df['ev'].str.contains('kor')] print(f'Felfedezeek szama az okorban: ...
d02faf79c21f33ace38aabe121dcffc7a213e457
vivekmuralee/my_netops_repo
/learninglists.py
1,069
4.34375
4
my_list = [1,2,3] print (my_list) print (my_list[0]) print (my_list[1]) print (my_list[2]) ######################################################### print ('Appending to the lists') my_list.append("four") print(my_list) ###################################################### print ('Deleting List Elements') del my_...
efa90afa01ad57923c25ca3d27859752f39ba002
wbetterton/python-challenge
/PyPoll/main.py
1,276
3.609375
4
import os import csv import pandas as pd csvpath = os.path.join("..","3 - Python","election_data.csv") csv_pandas_path = "election_data.csv" poll_df = pd.read_csv(csv_pandas_path, encoding="utf-8") #poll_df.head() with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') ...
5c57dbc8b193a0dbd5cb3c0be2ee062461229d14
RyanIsCoding2021/RyanIsCoding2021
/turtle1.py
1,136
3.9375
4
from tkinter import Tk, simpledialog, messagebox def read_from_file(): with open('capital_data.txt') as file: for line in file: line = line.rstrip('\n') country, city = line.split('/') the_world[country] = city def write_to_file(country_name, city_name): ...
f572297af8404665a78f43a65cdf281178eddd90
RyanIsCoding2021/RyanIsCoding2021
/23.py
2,035
3.859375
4
import pygame import sys # Window dimensions WIDTH = 500 HEIGHT = 500 # Colors RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) pygame.init() # Set up the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Button demo') clock = pygame.time.Clock() class Button: def __init...
a5d50fade90116a81c4a1258f4ae25842533db91
RyanIsCoding2021/RyanIsCoding2021
/exercises/5.py
171
3.625
4
list1 = [10, 20, 30, 40, 10, 60, 20, 70, 10] last_index = len(list1) - 1 if list1[0] == list1[last_index]: print("result is true") else: print("result is false")
8613db5a6191c97a2368b84cb4a274843902a0d6
RyanIsCoding2021/RyanIsCoding2021
/mase game.py
7,797
3.921875
4
# Python Maze Game import turtle import math import random w = turtle.Screen() w.bgcolor("black") w.title("Maze Game") w.setup(700, 700) w.tracer(0) class Pen(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("square") self.color("grey") self.penup() ...
92379a4874c8af8cc39ba72f79aeae7e0edb741c
RyanIsCoding2021/RyanIsCoding2021
/getting_started2.py
270
4.15625
4
if 3 + 3 == 6: print ("3 + 3 = 6") print("Hello!") name = input('what is your name?') print('Hello,', name) x = 10 y = x * 73 print(y) age = input("how old are you?") if age > 6: print("you can ride the rolercoaster!") else: print("you are too small!")
f070a232fd7cee4769a397a69bd23c62de2bd821
campadrenalin/ConcurrenTree
/ConcurrenTree/validation/cmdline.py
440
3.875
4
def consider(queue): ''' Takes an iterable, produces a simple approval loop. ''' for request in queue: print request response = raw_input("Approve, Reject, Defer, or Quit? [a|r|d|q] ") if response == 'a': request.approve() elif response == 'r': request.reject() elif response == 'q': print "Exitin...
bb3a3d7c736c3acc6221ad770c7576da4038b140
campadrenalin/ConcurrenTree
/ConcurrenTree/node/__init__.py
1,381
3.609375
4
from node import Node from random import SystemRandom # Core types from string import StringNode from map import MapNode from list import ListNode from number import NumberNode from single import SingleNode from trinary import TrinaryNode randy = SystemRandom() def bigrandom(): return int(randy.random()*1000000) ...
717da695f05c9efe2ad3f338f54233a950aac62e
campadrenalin/ConcurrenTree
/ConcurrenTree/auth.py
690
3.53125
4
import user class Auth(object): ''' Key-value store for storage spaces keyed on username. ''' def __init__(self): self.contents = {} def make(self, username, password): if username in self: return self[username] else: self[username] = user.UserStorage(usern...
6198f28e9e7820407d9e0eee8bd4d84b001ed2da
richiTachi/videoCourse
/video_course/meijuyeshiyigelei/new.py
372
3.59375
4
from enum import Enum,unique # @unique class WEEKDAY(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 Say = 6 print(WEEKDAY.Sun) print(WEEKDAY["Sun"]) print(WEEKDAY.Sun.name) print(WEEKDAY.Sun.value) print(WEEKDAY(3)) for w in WEEKDAY: print(w) # for name,value in ...
a1c859da79fd15a4da752db1736a6fda7aafd46c
richiTachi/videoCourse
/venv/nine9_1.py
1,140
3.78125
4
class Dog(): """一次模拟小狗的简单测试""" def __init__(self,name,age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.t...
f954e3328f4efc64e66bec6741ffc71e4ef96860
richiTachi/videoCourse
/video_course/zhengzebiaodashi/z8.py
254
3.8125
4
import re arr = "A8C3732D86" def convert(value): matched = value.group() # print(matched) if int(matched) >= 6: # print("9") return "9" else: # print("0") return "0" r = re.sub("\d",convert,arr) print(r)
3c48c7b6c7efa64c77256169aeba59097f43f316
richiTachi/videoCourse
/venv/nine9_3_1Car.py
1,560
3.953125
4
class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def describe_car(self): a_car = self.make + " " + self.model + " " + str(self.year) return a_car.title() def read_odometer(self...
b4d374321123c9db85ecb7134751b25d86c9b361
richiTachi/videoCourse
/venv/nine9_2_1Car.py
2,307
3.875
4
# class Car(): # def __init__(self,make,model,year): # self.make = make # self.model = model # self.year = year # # def get_descripive_name(self): # a_car = str(self.year) + " " + self.make + " " + self.model # return a_car.title() # # my_car = Car("lamborghini","lp700","...
ca19ffedc841a6b35f87ffd008bc6bffa06507e7
richiTachi/videoCourse
/video_course/zhengzebiaodashi/z3.py
78
3.5
4
import re s = "python1111java678php" r = re.findall("[a-z]{3,6}",s) print(r)
90a16fe005b091cb666ab6e1ca3c60be327ba41d
chrischendev/ref-samples
/Python/python-proctice-demo/src/alg/proc_0002.py
765
3.609375
4
# 排序算法 # 冒泡排序 使用中间变量交换值 def fun01(): arr = [34, 20, 76, 84, 46, 11, 98, 39, 5, 10] l = len(arr) for i in range(l - 1): for j in range(l - i - 1): if arr[j + 1] < arr[j]: tmp = arr[j + 1] arr[j + 1] = arr[j] arr[j] = tmp print(arr) ...
3e00cb605c9fd4537591c64c6efe47236821e131
gukir/coursera_python
/phib.py
129
3.5625
4
def phib(n): if n < 3: return 1 else: return phib(n - 1) + phib(n - 2) i = int(input()) print(phib(i))
269dad5bbf0d5557bc0a428da63ea2af5f308bbb
doraecode/practice-python
/00017-Ctrl-F/00017-Ctrl-F.py
386
3.59375
4
test = input(" n,m :") number = test.split() n = input("enter word n: ") m = input("enter word m: ") num_n= int(number[0]) num_m= int(number[1]) word_n = n.lower()[:num_n] word_m = m.lower()[:int(num_m)] count=0 for i in range(num_n): if i+1<=num_n: nextPt=i+num_m if(word_n[i:nextPt]==word_m): ...
d2bc0779954c792e5cca77278b2871c90f17a43a
doraecode/practice-python
/00052-Disaster-Star/00052-Disaster-Star.py
284
3.53125
4
n = int(input("")) for i in range(n): for j in range(n): if i+j>=(n/2)-0.5 and i-j>=-((n/2)-0.5) and i<=(n/2)-0.5 or i>(n/2)-0.5 and (i-((n/2)-0.5))-j<=0 and (i-((n/2)-0.5))+j<=n-1: print("*",end=" ") else : print("-",end=" ") print("")
382a8805c05e9d127133d9f16238063432b0e9eb
doraecode/practice-python
/00115-ACM-Judge/00115-ACM-Judge.py
964
3.734375
4
def wordCase(case,result): switcher = { 1:'Case #'+str(case)+': Yes', 2:'Case #'+str(case)+': No - Wrong answer', 3:'Case #'+str(case)+': No - Time limit exceeded', 4:'Case #'+str(case)+': No - Runtime error' } return switcher.get(result,"Invalid Case") def checkCase(): ...
de167b900a5edb09e4d6f8cad0150da0800c0825
extraname/sometask
/task.py
6,589
3.546875
4
from math import factorial """ Task 1. Если мы из корректно записанного арифметического выражения, содержащего числа, знаки операций и открывающие и закрывающие круглые скобки выбросим числа и знаки операций, а затем запишем оставшиеся в выражении скобки без пробелов между ними, то полученный результат назовем правиль...
ce11c9afca397cac439a25ceda238ca38f674572
kunmukh/Interesting-Projects
/Fashion Classification/Fashion wear Classification.py
1,725
3.625
4
import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt # DATA LOADING AND PROCESSING # load the data set data = keras.datasets.fashion_mnist # separate the data into training and testing data set (train_images, train_labels), (test_images, test_labels) = data.load_data...
5c859170bc9a8df7cb85d3123872b5849b1a507e
Elisayiqin/Machine-Learning-Sec.2
/Q_12.py
1,382
3.546875
4
def Q_12(self, X_train_scaled, X_test_scaled, y_train, y_test, learning_rate=0.001, nIteration=7000): # Task 12: Given the (X_train, y_train) pairs denoting input matrix and output vector respectively, # Fit a linear regression model using the stochastic gradient descent algorithm you learned in class to obtain...
0b024a0d6b60933f494014706ecead4da7b755df
aravs16/python-exec
/bank_class.py
418
3.765625
4
class Bank: account_num = "" balance = 0 min_bal = 0 pan_num = "" def __init__(self, act_num, bal, min, pan): self.min_bal = min self.account_num = act_num self.balance = bal self.min_bal = min self.pan_num = pan def deposit(self,amount): self.b...
6b8160b7e2c1abdc15c57315de09363c0bca6357
BjornChrisnach/Edx_IBM_Python_Basics_Data_Science
/nmpy_02.py
6,459
3.5
4
# Import the libraries import time import sys import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # Plotting functions def Plotvec1(u, z, v): ax = plt.axes() ax.arrow(0, 0, *u, head_width=0.05, color='r', head_length=0.1) plt.text(*(u + 0.1), 'u') ax.arrow(0, 0, *v, h...