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
3fce3216f1aed44b946d4cb7cef15bbabe369563
xiewenwenxie/168206
/168206107/斐波那契.py
143
3.6875
4
alist =[] for i in range(): if i ==0 or i ==1: alist.append(1) else: alist.append(alist[i-2]+alist[i-1]) print(alist)
e20b42a56a58997eaf812786471fe85a690f6299
xiewenwenxie/168206
/168302232/合并排序.py
534
3.9375
4
def merge_sort(arr): if len(arr) == 1: return arr mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] ll = merge_sort(left) rl = merge_sort(right) return merge(ll, rl) def merge(left, right): result = [] while len(left) > 0 and len(right) > 0: if left[0] <= righ...
a8cca64d33e7013d9f3a2dc5544a9f0f56491969
sheputis/Machine_learning_project_1
/part_a_OLS_of_fifth_order_with_ND_bootstrap_variance_bias.py
545
3.5
4
from ... import ML_classes bias=[] variance=[] for deg in range(9): print("running bootstrap of degree %s " % (deg+1)) A = OLS_main(deg+1) B = run_the_bootstraps(A.x_,A.y_,A.z_,deg+1) C = var_and_bias(A.X_,A.z_,B.beta_list) print('bias') print(C.bias) print('variance') print(C.var) ...
ea437ba87abe0b2c12c8b215d468a4a116acbdb4
Guwudao/CJG-crawl
/file_collection.py
1,002
3.796875
4
import os import shutil def file_rename(file_list, dir): for file in file_list: global n n += 1 old_name = path + "/" + dir + "/" + file print(old_name) new_name = path + "/" + dir + "/" + str(n) + ".jpg" print(new_name) print("-" * 50) os.rename(ol...
1ece98edbc86c7c6af2f11327b1fd2c0adc8a320
anudeepsamaiya/coursera-py4e
/ch_13/json_webdata.py
363
3.625
4
import json import urllib.request url = input("Enter Location: ") print("Retrieving url %s" %url) data = urllib.request.urlopen(url).read().decode() data = json.loads(data) length = len(data) print("Retrieved %s characters" %length) items = [item['count'] for item in data['comments']] print("Count: %s" %len(items)) ...
4a753f05fa70c21d32047b799d1e5f8f7b82866b
bakossandor/DataStructures
/Trees/level-order-traversal.py
1,318
3.890625
4
from collections import deque class Node: def __init__(self, data): self.data = data self.right = None self.left = None def inorder(self): if self.left is not None: self.left.inorder() print(self.data) if self.right is not None: self.righ...
45eb0065c98e74c6502b973fc234b6a19ffed92a
bakossandor/DataStructures
/Stacks and Queues/single_array_to_implement_3_stacks.py
910
4.28125
4
# describe how would you implement 3 stack in a single array # I would divide the array into 3 spaces and use pointer to mark the end of each stack # [stack1, stack1, stack2, stack2, stack3, stack3] # [None, None, "1", None, "one", "two"] class threeStack: def __init__(self): self.one = 0 self.two...
b86d42a1ed8bd87ddae179fda23d234096459e0c
bakossandor/DataStructures
/LinkedLists/linked_list.py
2,278
4.28125
4
# Implementing a Linked List data structure class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add(self, val): new_node = Node(val) if self.head is not None: new_node.next...
70b34361cd29f6ee7a71ce060143dc1582e86dc4
bakossandor/DataStructures
/LinkedLists/find_a_middle_of_a_linked_list.py
989
4.03125
4
# a -> b -> c -> d -> e -> f # Find the middle of the linked list, if the linked list is has even number of elements the middle is count / 2 + 1, (the second element in the middle) class Node: def __init__(self, data): self.data = data self.next = None a = Node("a") b = Node("b") c = Node("c") d ...
a5519710c3fe32c21ac6f82d8b73d81408fb5783
jeremymatt/CCEA-DNFEA
/testing/feature_selection_test.py
1,844
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 23 22:56:48 2019 @author: jmatt """ import pandas as pd import matplotlib.pyplot as plt def sel_input_feature(cand_match_counts): """ Selects an input feature as the 'template'. The probability of a feature being selected is inversely proportional to th...
fde065d489829790dc79713b2f4f7168b818cdf2
lucaslb767/alfredo
/main.py
1,021
4.03125
4
import Alfredo import inspect def inicio(): '''Apresenta programa''' Alfredo.linguinha() print('Olá esse aqui é o Alfredo. \n ') def menu(): resposta = input('Escolha entre, feliz, assustado, triste, linguinha, dormindo, sexy, dinheiro ou apaixonado. \n Escreva "sair" para terminar \n') return...
ac0a06956c805cfcaa673eb5f310a16a77adac70
Epiann1/TerminalLoginSystem
/main.py
2,963
3.90625
4
from database.login import * from getpass import * if __name__ == '__main__': login = input('Do you want to test this login script?').lower().strip() if login == 'yes': sign = input('Do you have an account?').lower().strip() if sign == 'yes': username = input("What's your username?"...
3270976350426d14e79908d04a1c41716ae78da8
SEETHAMRAJU/Competitive_Programming
/Codeforces/Problems/122B.py
211
3.515625
4
x = raw_input() f = 0 s = 0 for i in x: if(i == "7"): s+=1 elif(i == "4"): f+=1 if(s>f): print "7" elif(f>s): print "4" elif(s== f and f == 0): print "-1" else: print "4"
302b25ed3291b55a498b5396a98631d1c231c8c0
SEETHAMRAJU/Competitive_Programming
/Hackerrank/clac.py
804
3.796875
4
import math def clr(): print('\n'*50) print("\t\t\t Calculator ") print("1 : + \t2 : - \t3 : x \t4 : / \t5 : ^ \t6: Continue\t7: Exit ") while(1): x=[0,0,0] y = input("Please enter number corresponding to the operation : ") x[0]=input("Please enter a number : ") x[1]=input("Please enter another num...
13b57f2134150fe3e7c404979ffd7a8f802c9b86
SEETHAMRAJU/Competitive_Programming
/Hackerrank/pangram.py
332
4.0625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT x = raw_input() y = x.lower() y = y.replace(" ","") print y s = [] if(len(y) < 26): print "not pangram" exit() for j in y: if(j not in s): s.append(j) if(len(s) == 26): print "pangram" print s else: print "not pangram"...
92e9f57b38452b18d19289495efc5afe10ef1d9e
SEETHAMRAJU/Competitive_Programming
/Codeforces/Problems/Lever.py
361
3.828125
4
x = raw_input() left = 0 right = 0 i = 0 for i in range(0,len(x)): if(x[i] == "^"): break; for j in range(0,i): if(x[j] != "="): left += (i-j)*(int(x[j])) for j in range(i+1,len(x)): if(x[j] != "="): right += (j-i)*(int(x[j])) if(left > right): print "left" elif(right>left): ...
0578c44f2473824f40d21139c27241366873de41
AnnaLupica/Election-Analysis
/xArchive/Python-practice.py
1,591
4.34375
4
#Creating list counties=["Arapahoe", "Denver", "Jefferson"] print(counties[2]) for county in counties print(county) #Insert new item in list counties.append("El Paso") counties.insert(2,"El Paso") #Remove item from list counties.remove("El Paso") counties.pop(3) print(counties) #Change item in list counties[2]...
56b5cce9dbf3835c0801276d0b8096a683d56c04
kartikmadhira1/DSAlgorithms
/python/hackerrank_misc/graph_traversal.py
5,843
3.875
4
import numpy as np class Node(): def __init__(self, value): self.value=value #node has a list of edges self.edges=[] self.visit=False self.next_node=None class Stack(): def __init__(self,head): self.queue_list=[head] def enqueue(self,value): sel...
78be3187f80c40955430c6aa33689d0992c5dd80
pythongitproject/python-project
/basics/returnfunc.py
1,144
3.6875
4
#coding=utf-8 #返回函数 def calc_sum(*args): def sum(): ax = 0 for i in args: ax = ax + i return ax return sum f = calc_sum(1,2,3,5,7,9) #当lazy_sum返回函数sum时, # 相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)” print(f) #返回的是求和函数,而不是求和结果 print(f()) #调用函数f时,才真正计算求和的结果 #闭...
7941fb430d41aef13e1600bc831195c1a575b7b9
pythongitproject/python-project
/ioprogramme/StringIO_BytesIO.py
736
3.5
4
#!/usr/bin/env python3 #coding=utf-8 #StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO from io import StringIO f = StringIO() f.write('hello') f.write(' ') f.write('world!') print(f.getvalue()) #getvalue()方法用于获得写入后的str #要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取 ff = StringIO('hello!\nhi!\ngoodbye!') while ...
0a781bf3cece688691e4e0992bf163ab0a87c73a
MaximPolak/Python
/2020-08-07/Palindrom.py
300
3.75
4
def je_palindrom(slovo): if slovo == slovo[::-1]: return True else: return False assert je_palindrom("radar") assert je_palindrom("míč") == False slovo = input("Zadejte slovo: ") if je_palindrom(slovo): print("JE to palindrom") else: print("NENÍ to palindrom")
7a91d73fa746c6492d245a592530f810e1ab9f6d
MaximPolak/Python
/2021-04-15/Zasobnik.py
716
3.71875
4
import sys class StackUnderflowError(Exception): pass class Stack: def __init__(self): self._posloupnost = [] def push(self, hodnota): self._posloupnost.append(hodnota) def pop(self): if self.is_empty(): raise StackUnderflowError return self._posloupnost.pop...
518c3dcc0357e713aeb11b42443c5a517ce460f5
WesleyNeuman/WesleysPythonToolkit
/WesleysPythonToolkit/PandasWrappers.py
4,249
3.75
4
import pandas as pd import numpy as np def df_stringsplit(df: pd.DataFrame, colname: str, splitchar: str) -> pd.DataFrame: """Performs stringsplit on a dataframe column and automatically adds new columns to the dataframe containing the splits""" # Split on character and rename resulting dataframe columns ...
8011677ced248deace659e4281228bffd54bc45f
SeanWangYS/Deep-Learning-in-Python
/facial-expression-recognition-master/logistic.py
2,344
3.828125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from util import getData, softmax, cost, y2indicator, error_rate from sklearn.utils import shuffle ''' Classification model 這篇運用 numpy ,寫了一個 Logistic Regression 用上的技術有: L2 regularization ''' '''use logistic regression + softmax (...
0f712314df43606bb6bccb1504bbe0d1b1bd0175
SeanWangYS/Deep-Learning-in-Python
/ann_class/tf_example.py
2,488
3.578125
4
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # create the data Nclass = 500 D = 2 # dimensionality of input M = 3 # hidden layer size K = 3 # number of classes X1 = np.random.randn(Nclass, D) + np.ar...
281ba489b004e19ae5bcc92da8a4464bae8d09ce
shubhamOO73414/GitDemo
/p2.py
191
3.96875
4
#Simple Calculator a=input("Enter first number : ") b=input("Enter second number : ") print "Summation=",(a+b) print "Subtraction=",(a-b) print "Multiplication=",(a*b) print "Division=",(a/b)
e51f1635c531d4b315a8fe93eab543bbda91f103
raj-rox/Coding-Challenges
/sortedinsert.py
552
3.75
4
#Couldnt debug :/. Try again on weekend? #https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem def sortedInsert(llist, data): # Write your code here if llist is None: x=DoublyLinkedListNode(data) return x current=llist while current: ...
afedf2f99d4bc5935ac2a06956ff1ed3cab51999
raj-rox/Coding-Challenges
/reducedstring.py
493
3.609375
4
#Stack question :() Needed Bagde help. Redo. #https://www.hackerrank.com/challenges/reduced-string/submissions/code/212065928 if s is None or "": return "Empty String" stack=[] for i in s: if stack: if stack[-1]==i: stack.pop() else: ...
28c8ea5014e85fe01689cc4847eaa2ff6264f652
raj-rox/Coding-Challenges
/webscraper.py
1,988
3.640625
4
import json import requests from bs4 import BeautifulSoup url="https://en.wikipedia.org/wiki/Manchester_United_F.C." r=requests.get(url) #print(r) #Responses: 100 information, 200, accept: 300, redirect, 400: Mistake from my pc, 500: Mistake from the server's side. soup=BeautifulSoup(r.content,'html.parser')#Wha...
97d430a520e681cd8a0db52c1610436583bf9889
raj-rox/Coding-Challenges
/hurdle.py
946
4.125
4
#1st attempt. DONE. bakwaas #https://www.hackerrank.com/challenges/the-hurdle-race/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'hurdleRace' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters:...
9732a41224543a8e8e26892be05fd0924c8b65cb
raj-rox/Coding-Challenges
/dynamicarray_v2.py
2,331
4.0625
4
#https://www.hackerrank.com/challenges/dynamic-array/problem # def dynamicArray(n, queries): # # initialize a variable no of arrays..done # rows = n # arr = [] # ans=[] # for i in range(0,n): # arr.append([]) # lastAnswer=0 # for i in range(0,len(queries)): # if queries[i][0]==1: # idx=(...
02819047458c3cd2dea5a9810384e4af79ef31f5
raj-rox/Coding-Challenges
/CTCI/Q1.2/q1.2.py
400
3.65625
4
def Reversor(str): rev="" word=list(str) word.pop() n=len(word) while(n>0): rev = rev + word.pop() n=n-1 return rev ans=repr(Reversor("Hell\0")+"\0") print(ans) #In python strings are immutable. So can't do it "in place". That extra place will have to be used unfortunately. #It...
7747bd640f7c430c4453cb555a1c0f737ff9aa75
BHushanRathod/csv_file_reader
/readcsv/readfile.py
1,136
3.5
4
import csv from collections import defaultdict import urllib.request import os columns = defaultdict(list) # each value in each column is appended to a list import ssl ssl._create_default_https_context = ssl._create_unverified_context emp_name = '' with open('input_excel.csv') as f: reader = csv.DictReader(f) ...
0e1bdae20f986a6814b9c88c683f2ca970bf8c77
b-anubhav/tkinter-applications
/time.py
1,322
3.859375
4
import time from tkinter import messagebox from tkinter import * root = Tk() root.geometry("300x200") root.title("Time Counter") hour = StringVar() minute = StringVar() second = StringVar() hour.set("00") minute.set("00") second.set("00") hourEntry = Entry(root, width = 3, font = ("Arail",15,""),textvariable=hour...
8d13f16e031bc71d3456e97ec3f98ce81ffe168f
tanbir6666/test-01
/python inside/python list comps 3h 3m.py
1,336
4.15625
4
names=["tanbir","taohid","tayeb","Robin","Amir"] empty_list=[] def loop(loopItem): for x in loopItem: print(x) for person in names: empty_list.append(person) print(empty_list) empty_list.clear() print(empty_list) print([person for person in names]) empty_list.clear() for person in na...
6f134495fa15c220c501a82206a33839d0083079
tanbir6666/test-01
/starting codes/python after 1 hour.py
808
4.21875
4
newString="hello Tanbir"; print(type(newString)); newstring_value= newString[5:] print(newstring_value); print(newstring_value.upper()); print(newstring_value.lower()); print(newstring_value.replace("Tanbir", "Taohid")) print(newstring_value); #replace string whatTosay=newString.replace("hello","how are you"); pri...
44378c7c1aca7e8fa2f28699d5e7236541281b95
tanbir6666/test-01
/tic tac toe app/return.py
170
3.5
4
e=10 def res(): global e while e<=100: e += 1 print(res(), "by") return "hello" print(res()) res()
ae6db08c0397bcbfd82b577946f687caf803b436
Adelaide95/laba7
/2.py
1,036
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == '__main__': a = tuple(map(float, input().split())) C = float(input()) count = 0 for elem in a: if elem > C: count += 1 print("Количество чисел больших С:", count) max_elem = 0 for i, item in enumerate(a): ...
115ee3be9afae8166678d670a94c8fd1487365e4
jtorrez/major_recommender
/src/modeling/interest_quiz/interests_cleaning.py
7,909
3.8125
4
from __future__ import division from collections import Counter import numpy as np import copy import operator def majors_string_to_list(qa_lst): """ Converts the string containing the majors associated with each question to a list. Returns the modified list. Parameters ---------- q_a_lst: li...
2ae0fb72d08062a9e4fa1627f95919a4fbbf74ac
jtorrez/major_recommender
/src/modeling/outcomes_quiz/outcome_model.py
3,922
3.703125
4
from __future__ import division import pandas as pd import numpy as np import outcome_cleaning as cl def normalize_ratings(df, ratings_col): """ Returns a normalized column by forcing all values between 0 and 1, then add 1 to protect against ratings of zero. Parameters ---------- df: pandas d...
c69b0687caa7ae51d04b4377e86963b40e51b1dc
williamfu24/CS141-CSI-
/Comp Sci 141/Python Programs/Connect The Dots/dots_Fu_William.py
1,957
3.921875
4
# Name: William Fu # Project: Connect The Dots # Pledge: I have neither given nor received unauthorized aid on this program. # Description: This program asks a user for a file, drawing a picture using # code from the file the user called, and then closing after a click on canvas # Input: User is asked for a fil...
9c6627692d958ddf64b87aaa495ce7e315dc8e8f
simon-fj-russell/ds_python
/linear_regression.py
2,509
4.1875
4
# Linear Regression model using stats models # First import the modules import pandas as pd import statsmodels.api as sm import seaborn as sns import matplotlib.pyplot as plt sns.set() # User made functions # Use Stats models to train a linear model # Using OLS -> ordinary least squares def train_lr_model(x, y): #...
1d384f6089c14be5d8feb8f9244d3e2ad9dedc19
navpreet-ml/Python-Projects
/mile_to_km.py
1,032
3.796875
4
from tkinter import * def button_clicked(): new_text = input.get() km = int(new_text) * 1.6 my_new_label1.config(text=km) km = 1 window = Tk() window.title("Mile to Km Converter") window.minsize(width=200, height=150) window.config(padx=5, pady=5) #Label my_label = Label(text="Miles", f...
fb89a4cbf5b6d9e34dc50254a1ecf53cd36c689b
OnlyHeStandsHere/Weather
/weather.py
862
3.53125
4
import json class Weather: def __init__(self, filename): self.fileName = filename self.file = open(self.fileName) with open(self.fileName) as file: self.weather = json.loads(file.read()) def get_json(self): return self.weather def get_city_id(s...
8daa7cccc3dea88db8b87984614c1504ee023c42
liusida/geoffrey-hinton-course-demos
/demos/demo-lecture-3-1.py
4,451
4.625
5
""" This demo is based on Lecture 3 "A toy example to illustrate the iterative method" Story: Each day you get lunch at the cafeteria. Your diet consists of fish, chips, and ketchup. You get several portions of each. The cashier only tells you the total price of the meal. After several days, you should be able to figu...
2a385a8f936f13d2bf8c9715afb427d0f1949daf
drjonesy/youtube-to-mp3
/flask/Timer.py
204
3.53125
4
import time a = time.time() b = a count = 0 while count <= 10: b = time.time() if int(b) - int(a) == 1: print(count) count += 1 a = time.time() b = a
1534038dc5e3b89ae413d76b0fd55032be15bfdd
heynoparking/code
/www.py
634
3.734375
4
def Queens (Q): x = [] for i in Q: x +=i print (x) new_x = [] for i in range(0,len(x),2): new_x.append(x[i]) new_x2 = [] for i in range (1,len(x),2): new_x2.append(x[i]) add = [a+b for a,b in zip(new_x,new_x2)] less = [a+b for a,b in zip(new_...
e37c490d9cf6c0e3e7eb51b1430fa0e7e9e51434
heynoparking/code
/lesson2.py
577
3.6875
4
a = 1 while a < 20: print a, a += 2 print("end") n = 100 iterate = 0 total = 0 while iterate != n: iterate += 1 total += iterate print(total) a=5 while a<7: if(a%2==0): print(a,"is even") else: print(a,"is odd") a+=1 n = 0 ans = [] while n <= 1000: if (n % 11 == 0):...
868b1e41c1c54c73e00b23df9969beed9038eb63
heynoparking/code
/lesson7.py
466
3.6875
4
class Car: def s (self,speed,color): self.s__peed = 0 self.color = color print (self.__speed,self.color) def boost (self): self.__speed += 10 print (self.__speed) def stop (self): self.__speed -=1 print (self.__speed) def set_speed(self,speed...
01cfaddf50fa28ae5b7ac24e0d36aaebf2a32983
heynoparking/code
/lesson6a.py
158
3.515625
4
class Human: def __init__ (self,name_org,age_org): self.name = name_org self.age = age_org n = Human("amber",20) print(n.name,n.age)
71fa0a90054ab54f0a0e67c7f9ae42c1858f73ef
krthornton/WorKeeper
/main.py
5,085
3.875
4
""" To Do: 1. Add ability to edit assignments """ from assignment import * import os import json def main(): # Print welcome screen welcome() # Load the save file and load previously saved assignments save_file = open("assignments.json", "r+") assignment_dic = [] load_assignments(assignment...
843f815ae79d759460e1bc0d7831fda4df163da7
Amarang/braille
/braille.py
7,693
3.78125
4
#!/usr/bin/env python from __future__ import print_function import sys import time import random import math import os import numpy as np import argparse """ values are a 4x2 (row x col) grid of dots for Braille key (i,j) specifies a character representing i filled dots starting from the bottom of column 1, and j f...
c7e723b7e7b07c466ba9aaa314cb293539583432
malufreitas/s6-desafio-api-rest
/main.py
1,040
4.09375
4
''' Exemplo: POST data = {"question": [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12, 5]} Response = {"solution":[3 ,3, 3, 3, 2, 2, 2, 5, 5, 12, 12, 4]} Função = solution([2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12, 5]) == [3, 3, 3, 3, 2, 2, 2, 5, 5, 12, 12, 4]] ''' def main(): data = {"question": [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12,...
b8ab326b4770a8f38ff12ffbe0cc275f90a43d36
AlbertUlysses/leetcode-problems
/algorithms/python/remove_element.py
343
3.625
4
class Solution: def removeElement(self, nums: List[int], val: int) -> int: while val in nums: nums.remove(val) return len(nums) """ Runtime: 40 ms, faster than 70.75% of Python3 online submissions for Remove Element. Memory Usage: 13.8 MB, less than 6.06% of Python3 online submissions f...
2e8a17d29fd352af98d0cc4b2b53d9d543601f6a
trenton1199/Python-mon-K
/Reminder.py
2,157
4.34375
4
from datetime import date import os def pdf(): pdf = input(f"would you like to turn {file_name} into a pdf file? [y/n] ").lower() if pdf == 'y': pdf_name = input("what would you like the pdf file to be named ") + ".pdf" font_size = int(input("what would you like your font size to be?")) ...
467afed5a60fd8a79678f6e74c5198a5b1c33cfd
psicho/GeekBrainsPython
/HomeWork2/hw02_easy.py
1,879
4.0625
4
# Задача-1: # Дан список фруктов. Напишите программу, выводящую фрукты в виде нумерованного списка, выровненного по правой стороне # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз print('Задача-1:') p = list() p = "яблоко", "банан", "киви", "арбуз", "грейпф...
2dfad5d7fcf6789c93002064f621691677899758
kraftpunk97-zz/Fundamentals-ML-Algos
/k_means.py
2,338
4.1875
4
#! /usr/local/bin/python3 '''Implementing the k-Means Clustering Algorithm from scratch''' import numpy as np import matplotlib.pyplot as plt import pandas as pd def kmeans(dataset, num_clusters=3, max_iter=10): ''' The k-means implemention ''' m, n = dataset.shape cluster_arr = np.zeros(dtype=in...
1068a00c1d0b11c81b04c8accf08ec3220554d89
rprustagi/EL-Programming-with-Python
/Sample-Programs/nooverload.py
144
3.734375
4
def product(a, b): res = a * b return res def product(a, b, c): res = a * b *c return res print(product(2,3,4)) print(product(3,4))
ccba99c95415350d7150972f9659de3cb747f59b
rprustagi/EL-Programming-with-Python
/Sample-Programs/AddStack.py
551
3.828125
4
# original code taken from # https://education.pythoninstitute.org/course_datas/display/97/837# #------------------------ from CStack import * class AddingStack(Stack): def __init__(self): Stack.__init__(self) self.__sum = 0 def getSum(self): return self.__sum def push(self, val): self.__sum +=...
6d8062bf06c135d240274cd05a268052340fe692
rprustagi/EL-Programming-with-Python
/Sample-Programs/twosquares.py
176
3.515625
4
from turtle import * x=100 n=4 angle=360/n for i in range(n): forward(x) left(angle) penup() forward(x) pendown() for i in range(n): forward(x) left(angle) input()
6dfa8d911118cd86a61c7c3c7abe1747a20899b4
rprustagi/EL-Programming-with-Python
/Sample-Programs/box.py
191
3.734375
4
n=20 for i in range(n): for j in range(n): if (i==0) or (j==0) or (i==n-1) or (j==n-1) or (i==j) or (i==n-1-j): print("*", end="") else: print(" ", end="") print("")
ab87e9277d7605bb7353c381f192949b40abcc49
rprustagi/EL-Programming-with-Python
/MT-Python-Programming/MT-Programs/hanoi.py
2,368
4.5
4
#!/usr/bin/env python3 """ turtle-example-suite: tdemo_minimal_hanoi.py A minimal 'Towers of Hanoi' animation: A tower of N discs is transferred from the left to the right peg. The value of N is specified by command line argument An imho quite elegant and concise implementation using a tower class, wh...
9cd28cb21882d7d156fc0cfea9f543a522544990
rprustagi/EL-Programming-with-Python
/MT-Python-Programming/MT-Programs/L10-power.py
572
4.0625
4
#-------------------------------------------------------------------- import sys # i/p: argv[1]: N; argv[2] = K def power(n, k): if k==1: return n else: if k % 2 == 0: #even power x = power(n, k//2) return x*x else: # odd power x = power(n, (k-1)//2) return n*x*x if len(sys.ar...
19d8b87a4a8c0f527c1f2db36d0541f05668ab9f
rprustagi/EL-Programming-with-Python
/MT-Python-Programming/MT-Programs/L03-epowerx.py
524
3.859375
4
#computing e till first n terms. #-------------------------------- import sys # sys.argv = ["compute", 5] #uncomment for Idle3. n = int(sys.argv[1]) x = float(sys.argv[2]) sum = 1.0 term = 1.0 for i in range(1,n+1): term = term*x/i sum = sum + term print("Value of e for first", n, "terms =", sum) #using epsi...
14314f66e7cfb00d073d8be9c79f9f2da15a22ef
mjdawson89/AgileUnoModule3
/assignment3.py
313
4.09375
4
#Module 3 Assignment #Matthew Dawson #100720 #read text file (a question) f = open("question.txt","r+") question = f.read() #print(question) #use text question as the prompt for input function answer = input(question + "\n") #print(answer) #write the user's answer back to the text file f.write("\n" + answer) f.close()...
bf0a4da0a61a5f243baaed1860166156b476dd96
PrakulDashing/Hacktoberfest2020
/Python/rev_pyramid_pattern.py
438
4.09375
4
def r_pyramid(n): k = n - 2 for i in range(n,-1,-1): for j in range(k,0,-1): print(end = " ") k = k + 1 for j in range(0,i + 1): print("* ",end = "") print("\r") while True : try: a = int(input("Enter a positive Integer : ")) print("\n") if a <= 2: print("It's not a...
e57876f8bf960cb658529c1eff664e4ea445e5ab
seohyoj55/Baekjoon
/python/2442.py
164
3.703125
4
n = int(input()) for i in range(1, n+1): for j in range(0, n-i): print(" ",end='') for k in range (0, i*2-1): print('*',end='') print()
2aad1d6d758beffdad976fbd29673d9df33f5ea5
rowan-walshe/advent-of-code-2020
/day_6/day6_1.py
903
3.59375
4
from typing import List, Set def split_into_groups(raw_input: List[str]) -> List[List[Set[str]]]: groups = [] group = [] for line in raw_input: if line == "": groups.append(group) group = [] else: person = set() for c in line: ...
4d09df9184c4321ce18e1236bb6b8b1501cbf639
ashishpatel26/codelibrary
/WebSearchDataMiningExamples/P05/solutions/task3.py
5,677
3.734375
4
# Implementing Hierarchical Agglomerative Clustering # ================================================== # Task # ---- # - Cluster the "Italian cities" dataset (from Lecture 5) using Hierarchical Agglomerative Clustering # - Implement the Single link (MIN), Complete link (MAX), and Group average methods for compa...
2a2a1766f405f0dbf05196987b2b48741ff8ea9e
ashishpatel26/codelibrary
/WebSearchDataMiningExamples/P06/solutions/task2.py
4,196
3.921875
4
# Text preprocessing and document similarity # ========================================== # Task # ---- # - Write a function that creates (and prints out) the document-term matrix from an input set of documents # - Apply the following preprocessing steps: # * Tokenization # * Lowercasing # * Stopword r...
94fd0458b2282379e6e720d07581fd15467d0581
Anirban2404/HackerRank_Stat
/CLT.py
2,013
4.125
4
#!/bin/python import sys ''' A large elevator can transport a maximum of 9800 pounds. Suppose a load of cargo containing 49 boxes must be transported via the elevator. The box weight of this type of cargo follows a distribution with a mean of 205 pounds and a standard deviation of 15 pounds. Based on this in...
157d3c824a34224542d6fa2aa5a63180de43e268
Anirban2404/HackerRank_Stat
/Poisson_Dist.py
570
4.09375
4
#!/bin/python import sys ''' A random variable, X, follows Poisson distribution with mean of 2.5. Find the probability with which the random variable X is equal to 5. ''' def factorial(x): fact = 1 if x == 0: return 1 else: for i in range(1, x + 1): fact = fact...
75dfccf2dc4c732b9007bb3e48a8b45d8c4a5221
l0veKry/ASL-Recognition
/hmm_submission.py
14,924
3.859375
4
import numpy as np import operator def gaussian_prob(x, para_tuple): """Compute the probability of a given x value Args: x (float): observation value para_tuple (tuple): contains two elements, (mean, standard deviation) Return: Probability of seeing a value "x" in a Gaussian dist...
d1664bd1faeaa166f13424424f79995e20824ed8
m-j-hacker/Intro-Python-I
/src/bignum.py
176
3.5
4
# Print out 2 to the 65536 power # (try doing the same thing in the JS console and see what it outputs) # YOUR CODE HERE import math #num = math.pow(2, 65536) print(2**65536)
9d4d40a5b0a7cace14bf5202c204f48dfe6f99fc
jeancitojdx/Final_de_Datux
/Modulo3/src/funciones_generales/validaciones.py
262
3.890625
4
def validar_ingreso_numero(n='a'): while True: try: n = int(input("Introduce un número: ")) return n except: print("Ha ocurrido un error, introduce bien el número") #print(validar_ingreso_numero())
3f9c80a5c549c1ea85026f25165269c170905cc1
Deepthi004/PFSD-programms
/PFSD/p26.py
218
4.03125
4
n= int(input("Enter a number: ")) sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if n == sum: print("Armstrong number") else: print("Not Armstrong number")
007f7990988f6a39faf3f1f9673c13a17b04bd1a
Deepthi004/PFSD-programms
/PFSD/problem6.py
72
3.765625
4
n=int(input("Enter Value")) if n<0: n=-n print("Result=",n)
7432cf565054627bed07145d8c1f99c0d4fc3949
MinJae-Gwon/Algo
/Day17/link_list.py
1,149
3.78125
4
class Node: def __init__(self, data, link = None): self.data = data self.link = link head = None def enqueue(n): global head if head == None: head = Node(n) else: parent = None p = head while True: if p.data > n: print("와꾸") ...
0624bc696c1cf16ceeafbe70aea612673bde0d0a
MinJae-Gwon/Algo
/Day34/회전.py
541
3.78125
4
my_map=[] my_map.append([1,2,3,4,5]) my_map.append([6,7,8,9,10]) my_map.append([11,12,13,14,15]) my_map.append([16,17,18,19,20]) my_map.append([21,22,23,24,25]) N=5 def rotate(): global N my_map_second = [] for i in range(0, 5): line = [0] * 5 my_map_second.append(line) for y in ...
c643a69b909e9f54c54b9da12db639aa05ad3b0f
MinJae-Gwon/Algo
/practice/etc/rhombus.py
371
3.703125
4
N = 7 for y in range(N): for x in range(N): if y <= N//2: if x < N//2-y or x > N//2+y: print(' ',end='') else: print('*',end='') else: if x < N//2-(N-y-1) or x > N//2+(N-y-1): print(' ',end='') else: ...
fa608fd5af3cee8fbdb9e997d8fc11cd0633df87
MinJae-Gwon/Algo
/codeforce/징검다리.py
800
3.5
4
def can_go(i): global stone, jump gap = 0 while True: if stone[i] == 0: gap += 1 i += 1 else: break if i == len(stone): break if gap > jump: return -1 else: return gap def go(): global stone, jump fla...
d86fce5a32b9eb3e9270311067733ec61408046c
matthieudelaro/convertor
/main.py
707
3.8125
4
# This file describes the convertor classes and provides some tests. # It has been designed for Python 3.5.1 Please upgrade if you # are using Python 2.X version. import sys from Convertor import Convertor def convert(): if len(sys.argv) != 2: print("Please provide as unique argument the path of the" + ...
c2db391ec0e8175b58ba57a3ee8b20068ae155ff
AlapanGhosh/tbag
/game.py
6,637
4
4
import time import os c1=0 def s1(): os.system('cls') print('Your ship wrecked and you washed ashore on a remote island. You wake up and find yourself alone,with nothing.\n You have survive.You sure you up to this task?') print('You find a bottle and some paper and a pen along the shore, some logs and...
8d8268c3535462fd1425503be62d356d9aab9994
EvieNelson/program-arcade-games
/Lab 04 - Camel/main_program.py
2,654
3.9375
4
# Completed Lab 4 import random print("Welcome to Camel!") print("You have stolen a camel to make your way across the great Mobi desert.") print("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.") print("Hint: all capitals.") print() A = "A. Drink from your ...
893af752512eebff4a4a534b485bcd1f9a8f9dd3
AshwinHebbar314/pjelr
/014.py
655
3.5
4
#%% def collatz(x): counter = 0 while(x!=1): counter += 1 if(x%2 == 0): x = x/2 else: x = (3*x + 1) return counter+1 #collatz(27) #%% import time def determinelen(l): longlen = 0 longind = 0 for i in range(l, 0, -1): #if(...
f7405b64e1e4895be76061d0ce3a87e65f5cd7c7
AndreaDex/python-rimario
/_funzioni.py
2,353
3.875
4
import os def trova_rima(verso, caratteri_rima): """Data una frase trova l'ultima parola da questa seleziona un n di caratteri finali trova tutte le parole che finiscono con quei caratteri """ parole_del_verso = verso.split(' ') rima = parole_del_verso[-1] lettere_per_rima = rima[-...
b904c0981ca7e7534312dd889dec92862fb695d7
rahulgyawali/AI
/nqueen_dfs.py
707
3.703125
4
board = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] n = 4 def safe (row,col) : for i in range(0,col) : if(board[row][i]) : return False for i,j in zip(range(row,-1,-1),range(col,-1,-1)) : if(board[i][j]) : return False for i,j in zip(range(row,n,1),range(col,-1,-1)) : if(board[i][j]) : return F...
4aa692633576198ea6580dfd97e2b068d5dbe920
AbhijeetDixit/MyAdventuresWithPython
/OOPython/ClassesExample2.py
1,927
4.34375
4
''' This example shows the use of multiple classes in a single program''' class City: def __init__(self, name): self.name = name self.instituteCount = 0 self.instituteList = [] pass def addInstitute(self, instObj): self.instituteList.append(instObj) self.instituteCount += 1 def displayInstitute(self)...
e47ed9df59f4cc50e80f26ffd4a2040e1e49fbb4
ninjadq/pygorithm
/stack.py
328
3.640625
4
from collections import deque class Stack(object): def __init__(self): self._dq = deque() def push(self, item): self._dq.append(item) def pop(self): return self._dq.pop() def is_empty(self): return len(self._dq) == 0 def size(self): return len(self._dq) ...
906794349cda988e7677b5f05c6454c1556bc95f
ajith3530/web_automation_script
/SRM_Automation.py
870
3.71875
4
#Pranav Code import xlrd #to access xl file related commands, use xlrd library workbook=xlrd.open_workbook("Dataset.xlsx") #creating an object to access the workbook worksheet=workbook.sheet_by_name("Data") #creating an object to access the worksheet rows=w...
feab8a8d49184c878b9504a20ce7856de76b2343
Rositsazz/Playground
/week01/test_elevator.py
1,128
3.5
4
import unittest from elevator import elevator_steps class TestElevator(unittest.TestCase): def test_empty_elevator(self): self.assertEqual(0, elevator_steps([], [], 5, 2, 200)) self.assertEqual(0, elevator_steps([40, 50], [], 5, 2, 200)) self.assertEqual(0, elevator_steps([], [3, 4], 5, 2...
957f18f7ef13a92229a7014300a859319eebae1b
SharukhEqbal/Python
/fibonacci_with_generators.py
483
4.34375
4
# Fibonacci series 1,1,2,3,5,8,... using generators def get_fibonacci(): a = 1 b = 1 for num in range(5): yield a # this will remember the value of a for next iteration a,b = b, a + b [i for i in get_fibonacci()] """ o/p: [1, 1, 2, 3, 5] def get_fibonacci_without_generator(): a = ...
241601c162bc121857880488aef422de86ded5f1
anuragrana/Python-Scripts
/Convert-Ebook-To-Kindle-Format.py
1,657
3.5625
4
# # Author - Anurag Rana # Go to this article for more help. http://thepythondjango.com/python-script-1-convert-ebooks-from-epub-to-mobi-format/ # from os import listdir, rename from os.path import isfile, join import subprocess # return name of file to be kept after conversion. # we are just changing the extension. ...
84d155c35fbf03583ac91358be2e4891b53dda96
Sudoka/PA6
/derp.py
221
3.59375
4
from vector import * a=Vector([1,3,5]) b=Vector([5,1,3]) c=Vector([4,5,4]) d = Vector([1,8,5]) print str(a < b) print str(b > a) print str(a >= b) print str(a <= b) print str(a != [1,3,5]) print str([1, 3, 4] < a)
c8a58c16cfd519cd069a6b53b471dd0ec94061db
dalejung/earthdragon
/earthdragon/feature/anchor.py
4,756
3.5
4
""" An anchor's behavior is a cascading list of Attrs where the hooks/pipelines/etc are carried from each class to its subclasses. Implicit in discussing anchors is class hierarchy. We use the terms parent/child where child is always the current context. Which means that we don't touch the child when processing the pa...
8720d528fb634c4a61eeb5b33a3405ee87883ada
Siddhant-Sr/Turtle_race
/main.py
1,006
4.21875
4
from turtle import Turtle, Screen import random race = False screen = Screen() screen.setup(width= 500, height= 400) color = ["red", "yellow", "purple", "pink", "brown", "blue"] y = [-70, -40, -10, 20, 50, 80] bet = screen.textinput(title="make your bet", prompt="Which turtle will win the race? Enter a color") all_tur...
898378a30acdd20bd8674ba56ce32c61d21e4198
HerBon/8-Puzzle-A-Star
/cp468_a1/src/generate_puzzle.py
2,239
3.5625
4
# Created on 2020 M10 14 # @author: Danni import random class puzzle: def __init__(self): self.goalState = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] self.moves = 0 self.empty = [0, 0] self.currState = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] def generateRand(self): ...
b564ea712865a0cda05b8350f1f4985bc1fd9b48
gurram1223/PythonExamples
/PythonEx/Examples/listEx.py
1,129
4.03125
4
from macpath import split s="show how to index into sequences".split() print(s) print(s[4]) print(s[-1]) #s=s[x:]+s[:x] print(s[3:]) print(s[:3]) print(s[:]) u=s.copy() print(u) a=[[1,2],[3,4]] b=a[:] print(a is b) print(a==b) c=[21,32] print(c*4) w="the quick brown fox jumps over the lazy do...
3c7665bbadb5ae2903b9b5edfda93d3a78ada475
dgupta3102/python_L1
/PythonL1_Q6.py
916
4.25
4
# Write a program to read string and print each character separately. # a) Slice the string using slice operator [:] slice the portion the strings to create a sub strings. # b) Repeat the string 100 times using repeat operator * # c) Read string 2 and concatenate with other string using + operator. Wo...
347ac39407381d1d852124102d38e8e9f746277f
dgupta3102/python_L1
/PythonL1_Q19.py
969
4.21875
4
# Using loop structures print even numbers between 1 to 100. # a) By using For loop, use continue/ break/ pass statement to skip odd numbers. # i) Break the loop if the value is 50 print("part 1a --------------") for j in range(1, 101): if j % 2 != 0: # checks the number is Odd and Pass pass ...