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
9e2f2ccb0e7c1f8103abb86d1581e24ca4d03f3d
aengel22/Homework_Stuff
/module12_high_low.py
2,532
4.21875
4
# The get_price function accepts a string that is assumed to be # in the format MM-DD-YYYY:Price. It returns the Price component # as a float. def get_price(str): # Split the string at the colon. items = str.split(':') # Return the price, as a float. return float(items[1]) # The get_year funct...
55ebfed116af1e9389e2a81d432a237b90e7262e
RecklessDunker/Codewars
/Get the Middle Character.py
789
4.25
4
# -------------------------------------------------------- # Author: James Griffiths # Date Created: Wednesday, 3rd July 2019 # Version: 1.0 # -------------------------------------------------------- # # You are going to be given a word. Your job is to return the middle character of the # word. If the word's length is ...
deec653fc1bbe1f2ff5d32d2970265a89e68b7b0
cthompson7/MIS3640
/Session01/hello.py
2,277
4.59375
5
print("Hello, Christian!") # Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell print wrong? print(Hello, world!") # When I leave out o...
e2ae0826393ebf746222d47506a538662f0c4016
cthompson7/MIS3640
/Session11/binary_search.py
1,069
4.28125
4
def binary_search(my_list, x): ''' this function adopts bisection/binary search to find the index of a given number in an ordered list my_list: an ordered list of numbers from smallest to largest x: a number returns the index of x if x is in my_list, None if not. ''' left = 0 right =...
bd44ae5876737c0c879d3dc5d37458f1fe1fd9d4
cthompson7/MIS3640
/Session14/practice.py
765
3.71875
4
t = ('a', 'b', 'c', 'd', 'e') # t1 = 'a', # print(type(t1)) # # t = tuple('Babson') # # print(t) print(t[0]) print(t[1:3]) t = ('A',) + t[1:] # makes a new tuple and then makes t refer to it print(t) email = 'zli@babson.edu' id, domain = email.split('@') print(id) print(domain) t = divmod(7, 3) print(t) def print...
3095b87c82652db37f143f04901243d058cf98d2
Suhas294/Simple-Python
/2.1.py
190
4.09375
4
# Reversing the digits of the number n = int(input("Enter number: ")) rev = 0 while(n>0): dig = n%10 rev = rev*10+dig n = n//10 print("Reverse of the number: ",rev)
71befd615b280437f1726051875471f2cc5381f5
Suhas294/Simple-Python
/2.1.1.py
179
4.46875
4
# Square root of a number using sqrt() predefined function TEST CASE #1 n = float(input("Enter the number: ")) sqrt = math.sqrt(n) print ("Square root of the number: ", sqrt)
e85a37909ae8720285f433b5e29101e4859c50d1
sebastianochiari/LUS-midterm-project
/data-analysis/corpus.py
3,155
3.890625
4
import os.path def loadCorpus(file): """ create the corpus as list of lists from a given file :param file: input file to read :return: list of lists with the single words from the given file """ # read the file if not os.path.isfile(file): print('File does not exist.') else: ...
9d74b2283e95a5d13580aaa55f2bf03a8808443e
RodericDay/advent
/2015_original/challenge_11.py
1,315
3.78125
4
import itertools as it def solve(password): ''' Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. Passwords may not contain the letters i, o, or l, as these letters can be ...
04333d64aa785de69f913521f336bdaf985a6589
RodericDay/advent
/2015_original/challenge_08.py
944
3.96875
4
''' "" is 2 characters of code (the two double quotes), but the string contains zero characters. "abc" is 5 characters of code, but 3 characters in the string data. "aaa\"aaa" is 10 characters of code, but the string itself contains six "a" characters and a single, escaped quote character, for a total of 7 characters ...
11483724cd608043cda5f3ab66d3941a6a1c93ba
RodericDay/advent
/2015/08.py
751
3.640625
4
import re def down(string): ''' >>> down('""') (2, 0) >>> down('"abc"') (5, 3) >>> down('"aaa\\\\"aaa"') (10, 7) >>> down('"\\\\x27"') (6, 1) ''' return len(string), len(eval(string)) def up(string): ''' >>> up('""') (2, 6) >>> up('"abc"') (5, 9) >>>...
7e2aa99b94e6cf7530f48aff7ca665a8e16d84d1
RodericDay/advent
/2015_original/challenge_02.py
1,264
3.765625
4
''' The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. Fortunately, every present is a box (a perfect right rectangular prism), which makes ...
93ce0d8f8f75672fefd50a4db63ebd4926637bb9
mmukhame/qbb2015-homework
/day2/types.py
561
3.859375
4
#!/usr/bin/env python # Integer i = 10000 # Float point / real number f = 0.333 i_as_f = float(i) f_as_i = int (f) # String s = "A string" #Boolean truthy = True falsy = False #Lists -- convention contains only one type (all integers) l=[1,2,3,4,5] l.append(7) #Tuple -- elements can have different types t=(1,...
0175218aa4cec9b6f32b954c0f66e4ee7bcc785e
yongwww/kaggle_Microsoft_Malware
/tools/filter_feature.py
2,912
3.53125
4
import numpy as np import pandas as pd data_df = pd.read_csv('../data/feature_set.csv') Y = data_df['Class'] feature_names = data_df.columns.values[2:] #print feature_names def entropy(target): # Get the number of users n = len(target) # print np.bincount(np.array([0, 1, 1, 1, 0, 0,1])) outputs [3,4] ...
380c75a685552bf42203197326cd6bbc5dfeeb2c
flackbash/PlaylistSorter
/PlaylistSorter.py
1,392
3.5625
4
import re import operator import os def sortPlaylist(playlist): """Sorts playlist entries by artist Arguments: playlist - a string: name of the m3u playlist """ # open playlist file source = open(playlist, encoding="latin-1") lines = source.readlines() source.close() newList = []...
131d90af5b5ac42912b70580033bf127c0998a0f
ErenBtrk/PythonClassExercises
/Section2-Exercise7.py
364
4.09375
4
''' 7. Write a Python class to implement pow(x, n). ''' class Power: def pow(self,num,p): if(pow == 1): return 1 else: return num* pow(num,p-1) print(Power().pow(5,2)) print(Power().pow(1,10)) print(Power().pow(3,3)) print(Power().pow(10,2)) print(Power().pow(2,-3)) print...
582339ed5aab54bad6404827ba551024ada4c576
ErenBtrk/PythonClassExercises
/Exercise5.py
227
4.03125
4
''' 5. Define a Python function student(). Using function attributes display the names of all arguments. ''' def student(firstName,lastName,age): return f"{firstName},{lastName},{age}" print(student("Ali","Veli","25"))
b5e37bcec8cc0e841d2fb3d204c7f98f8f5976fc
kiran90429/Project_3
/com/highradius/Metrics/ConfusionMatrixColSumMetric.py
1,074
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 29 17:06:32 2017 @author: BharatChandra.T """ from sklearn.metrics import confusion_matrix class ConfusionMatrixColSumMetric: """ * This is a metric class which will return the column sum of each class in confusion * This class have one variable contains nam...
0cef45e2a99c268531312f140f4f98ab8453da96
pseudobrilliant/youtube_analyzer
/src/scraper/youtube_scraper.py
2,652
3.59375
4
import argparse from selenium import webdriver import time import os def scrape(url): """Scrape youtube url for comments""" content = get_content(url) return content def get_content(url, headless=True, pause=4): """Use selenium browser automation to open a youtube url, scroll to bottom and return ...
852efc4839a66e33192a38feba2fb419eb26acf2
JeffOnABike/sunday_puzzles
/puz100916.py
2,343
3.90625
4
''' Next week's challenge, from listener Darrell Myers of Somerville, Mass.: Name a famous actress of the past — first and last names, 10 letters altogether. Change one letter in the first name and one letter in the last. The result is a two-word phrase naming a food item often found in a kitchen cabinet or refrigerato...
418c7070a8683046745e56626db4020067a98601
helloworldsundar/onlinecodetest
/2darraydemo.py
1,332
3.609375
4
#!bin/python3 import sys minsize = -99999 def findHourGlassSumAtI (arr,i,j): sum = 0 length = len(arr[0]) #validate the input arrange possible # fail fast method if (i+2) not in range(length): return minsize if (j+2) not in range(length): ...
054d1821dc578120bb3e73ebea97912b9f5e9467
Quentin18/fsmdot
/examples/example6_nfa.py
908
3.921875
4
""" Example 6: NFA -------------- An example of a nondeterministic finite automaton which has epsilon-moves. We calculate the epsilon closure of each state. The NFA is converted into a DFA using the powerset construction. Graphs: - graph6_nfa.dot - graph6_dfa.dot Source: https://en.wikipedia.org/wiki/Powerset_constr...
ca729696bef1d1b21e91ac28920145c2248b7299
baboosh/RumOnTheRocks
/stopWatch.py
2,393
4
4
import tkinter as tk import time class StopWatch(tk.Frame): """ Implements a stop watch frame widget. """ def __init__(self, parent=None, **kw): tk.Frame.__init__(self, parent, kw) self.start = 0.0 self.endtime = ...
d2c3f792c5b41ff79f7d6f7fa76c75317c6687be
aleperno/blog
/fibo.py
1,313
4.25
4
#!/usr/bin/python import time def recursiveFibo(number): """Recursive implementation of the fibonacci function""" if (number < 2): return number else: return recursiveFibo(number-1)+recursiveFibo(number-2) def iterativeFibo(number): list = [0,1] for i in range(2,number+1): list.append(list[i-1]+list[i-2])...
36667874b3641086694c255b0571c2c1fbe861a0
guntursandjaya/Assignment-1-Driving-Simulation
/Driving Simulator.py
503
3.9375
4
u = 0 t = int(input("Time spend on the road: ")) a = int(input("Acceleration: ")) s = int(input("Distance: ")) speed_limit = 60 v = int(u + a*t) d = (a*(t**2)/2) for i in range (t+1): print("Duration",i,"Distance","*"*int((a*(i**2)/2)/10)) if v > 60: print("The person went over the speed limit","reached",v,"m...
1efd13cf20f386b40174e6728f1fe0ca372399b5
cx84/pythonwork
/Notes_cx.py
21,202
3.953125
4
""" Day_01 快捷键: 移动到本行开头:home 键 移动到本行末尾:end 键 注释代码:ctrl + / 复制行:ctrl + d 选择列:鼠标左键 + alt 移动行:shift + alt + 上下箭头 智能提示:ctrl + space 整理格式(如空格等)ctrl + alt + L 多行同时缩进: 选择多行之后按tab 多行同时取消缩进: 选择多行之后按shift + tab 重命名多个相同变量: shift + F6 注释: 1.单行注释:以#号开头 2.多行注释:三引号开头,三引号结尾。 函数 表示一个功能,函数定义者是提供功能的人,函数调用者是使用功能的人 print(数据)作用:蒋括号中的内容显示在...
fadb32ab13e1085a286c6ef66ab8c5e3506a05cc
chantera/coordparser
/data/extract.py
740
3.53125
4
import argparse from teras.io.reader import read_tree def extract_words(tree): def _traverse(node, buf): assert len(node) > 0 if len(node) == 2 and isinstance(node[1], str): # Leaf buf.append(node[1]) else: # Node for child in node[1:]: _traverse(...
5da637dc89ff1d54d87b436c98e99dddb0ae32da
anassNasserallah/band-reduction-in-multispectral-images
/PCA_hyperspectral_images.py
1,725
3.640625
4
# import the librairies for the task import scipy.io as io import numpy as np from matplotlib import pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.decomposition import PCA #Constants for the application FILENAME = "./PaviaU.mat" # Filename of the image we want to transform RAW_IMAGE_DI...
7850a710550a6bba787f81b5945d70098c60ba14
jradd/small_data
/emergency_map_method.py
518
4.46875
4
#!/usr/bin/env python ''' the following is an example of map method in python: class Set: def __init__(self, values=None): s1 = [] # s2 = Set([1,2,2,3]) self.dict = {} if values is not None: for value in values: self.add(value) def __repr__(self): return "Set: " + str(self.dic...
7f187b84e91ee65d5334d9c10ebd2bc47699eb3f
amit-s19/My-Python
/Python_WebScraping/first.py
874
3.828125
4
# First implementation of BeautifulSoup and Requests module. import requests from bs4 import BeautifulSoup # get method used to get the content of the requested webpage. result = requests.get('https://www.google.co.in') # stats_code gives the connection code, 200 if successfull and the page exists, 404 otherew...
01660b6944184aaadd0617a540c9bafbad0d76a7
saatvi-rajgopal/Python-challenge
/PyPoll/Analysis/Pypoll.py
1,560
4
4
# Import import os import csv # FIGURE OUT THE FILEPATH ON YOUR COMPUTER csvpath = "02-Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv" # read in the CSV data into memory - a list of lists with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvr...
82072161ea0a78224818d060a8e4db02f95cd65a
xxpasswd/algorithms-and-data-structure
/other/build_parse_tree.py
1,588
3.84375
4
""" 将带括号的数学表达式表示为一个树结构 过程: 遇见数字,将当前的节点设置为数字,返回父节点 遇见符号,将当前的节点设置为符号,右边插入节点,返回右边节点 遇见括号,左边插入一个树,开始括号里面表达式的树建立 """ from node_tree import BinaryTree def bulid_parse_tree(alist): # 先构建一个空树 stack = [] t = BinaryTree(None) stack.append(t) cur_t = t for i in alist: if i == '(': cur...
9fcdb9f0c15c1860418fce220561361069acdc18
xxpasswd/algorithms-and-data-structure
/data_structure/stack/array_stack.py
711
3.765625
4
""" 数组实现栈 操作: push():O(1) pop():O(1) """ class ArrayStack: def __init__(self, capacity): self.capacity = capacity self.items = [None] * self.capacity self.top = 0 def push(self, item): if self.top + 1 == self.capacity: return False self.items[self.top] = i...
44bd5a02ab1a41eafcc74588deb545c885741ea6
xxpasswd/algorithms-and-data-structure
/data_structure/linked_list/singly_linked_list.py
9,274
4.125
4
""" 单链表: insert_to_head():O(1) insert_to_tail():O(n) delete_head():O(1) delete_tail():O(n) find_by_value():O(n) find_by_index():O(n) insert_after():O(1) insert_before():O(n) delete_by_node():O(n) delete_by_value():O(n) delete_last_N_node():O(n) delete_last_Nth_node():O(n) reverse():O(n) find_mid_node():O(n) has_ring():...
bbf82081f0321698be667ffdfc0a9b5d197080e3
xxpasswd/algorithms-and-data-structure
/other/binary_tree.py
1,708
3.890625
4
class BinaryTree: def __init__(self): self.heaplist = [0] self.size = 0 def insert(self, value): self.heaplist.append(value) self.size += 1 self.percolate_up() def delete_min(self): self.size -= 1 temp = self.heaplist[1] self.heaplist[1] = se...
e9cd26ca245ab26e290e9878a4fc11af73bb56fb
xxpasswd/algorithms-and-data-structure
/algorithem/summary_ranges.py
862
4.09375
4
''' 给定一个排过序的数组,给出它的范围总结 example:[1,2,3,6,7,8,10] ----> ["1->3","6->8","10"] ''' def summary_ranges(nums): # 开始的左端点 start = nums[0] # 范围结束右端点,初始化为数组第一个数 last = nums[0] # 输出结果 out_list = [] for i in nums[1:]: # 当数字连续时,更新右端点 if i == last + 1: last = i # 当连续...
28aa9e66286818d5ee939a6016df3dbe5490a265
xxpasswd/algorithms-and-data-structure
/other/queue.py
1,334
4.21875
4
''' python 队列实现 is_empty():O(1) enqueue(item):O(n) dequeue(item):O(1) size():O(1) ''' class Queue: def __init__(self): self._queue = [] def is_empty(self): return self._queue == [] def enqueue(self, item): self._queue.insert(0, item) def dequeue(self): return self._...
77c81d09b6d8224e8a16f75a10ba9597f37f73c1
thebertster/aoc_2017
/aoc_2017/day_01.py
978
3.8125
4
from lib.aoclib import AOCLib def solve_puzzle(circular_list, offset): """Solves the puzzle based on a particular offset. Args: circular_list (list): The circular list to work with. offset (int): The offset into the list to use. Returns: The solution. """ circle_size = len...
95a3aa9fbc89837526c1f3e4dd44e85783176f20
bhaumik1991/Python-Basic-Programs
/prime_number.py
481
4.1875
4
#Python program to print all Prime numbers in an interval n = int(input("Enter the number of terms:")) for num in range(2,n+1): for i in range(2,num): if num%i == 0: break else: print(num) #Python Program to check Prime Number n = int(input("Enter a number:")) if n>1: for i in r...
ce2d85c84e99da46f039a6d9c6099b2648ebbaf2
TemurKhabibullaev/TestingMyCode
/names.py
932
4.0625
4
def get_formatted_name(first, middle, last): """Generate a neatly formatted name""" full_name = first + ' ' + middle + ' ' + last return full_name.title() def city_country(city, country): full_name = city + ' ' + country return full_name class AnonymousSurvey(): """Collect anonymous answers ...
308844a54148b1f34b3498fa8dca80bf11e1733f
rec/EnergyEngineersCodes
/SummerStudents2016/Adventure.py
381
3.984375
4
print 'You find yourself inside a small house.' print 'In front of you is a small box. What do you do?' print '1: Open the box ' print '2: Leave the house' s = raw_input('-->') if s == '1': print 'Inside the box you find a magic cookie.' print 'You win the game!' elif s == '2': print 'You walk away and n...
a3f88296ada2c3c3dbc8e53a08bdec8545ca2879
divyamagwl/IASmachine
/IAS.py
9,348
3.640625
4
from bitstring import BitStream from MainMemory import MainMemory from Registers import Registers from colors import Colors """ IAS machine consists of Registers and Main memory """ class IAS: def __init__(self): self.memory = MainMemory() self.registers = Registers() """ Defines the Instruct...
b3f14dfd81fefc6bf96ce36b50577b200e712034
LABSN/expyfun
/examples/experiments/formatted_text.py
2,011
3.984375
4
""" ============================================== Display text with different formatting methods ============================================== This example demonstrates differences between the Text and AttrText classes. """ # Author: Dan McCloy <drmccloy@uw.edu> # # License: BSD (3-clause) from expyfun import Exper...
db68d24f4ed3286a8b2b24bf113a23f3df74d8aa
Oiselenjakhian/Drawing-Adinkra-Symbols-using-Python
/damedame.py
3,671
3.859375
4
""" Project Name: Drawing Adinkra Symbols using Python Symbol Name: Dame Dame Developer Name: Truston Ailende Email Address: trustonailende@gmail.com """ import turtle import math # Square def drawSquare(length): turtle.penup() turtle.setposition(-length/2.0, length/2.0) turtle.pendown() ...
925ffcfcff7df4ee4db086783374321ee32f092a
Andreabrian/python-programming-examples-on-lists
/assign1.py
295
4.21875
4
#find the largest number in the list. a=[] n=int(input("Enter the number of elements:")) for i in range(n): a.append(int(input("enter new element:"))) print(a) s=a[0] for i in range(1,len(a)): if a[i]>s: s=a[i] y=("the largest number is: ") print(y,s)
5f498fc6d83701963d4800d121630523e805568b
chriskok/PythonLearningWorkspace
/tutorial11-tryelsefinally.py
1,333
4.4375
4
# ---------- FINALLY & ELSE ---------- # finally is used when you always want certain code to # execute whether an exception is raised or not num1, num2 = input("Enter to values to divide : ").split() try: quotient = int(num1) / int(num2) print("{} / {} = {}".format(num1, num2, quotient)) except ZeroDivision...
524f34a1965d2ceaf92b1616d468114ca15dad36
chriskok/PythonLearningWorkspace
/tutorial9-objects.py
657
4.03125
4
# Real world objects: Attributes & Capabilities # Example: Attributes(fields/ variables) Dog has weight, height, fav food. # Capabilities (Methods/ functions) Dog can run walk, eat class Dog: def __init__(self, name="", height=0, weight=0): self.name = name self.height = height self.weigh...
64a4cf637aa3236b91b95bcc0c8d551497d65910
chriskok/PythonLearningWorkspace
/acronymgenerator.py
195
4.09375
4
# Random Access Memory : RAM # Enter string user_input = input("Enter string: ") input_list = user_input.split() # Convert into an acronym for i in input_list: print(i[0].upper(), end="")
1d1b0213e352a561d37417353719711b31bd3de4
chriskok/PythonLearningWorkspace
/primenumber.py
696
4.34375
4
# Note, prime can only be divided by 1 and itself # 5 is prime because only divided by 1 and 5 - positive factor # 6 is not a prime, divide by 1,2,3,6 # use a for loop and check if modulus == 0 True def is_prime(num): for i in range(2, num): if (num % i) == 0: return False return True d...
8d598dc40e8428a74f5668cc6b6a29a86214e9bd
chriskok/PythonLearningWorkspace
/pinetree.py
1,026
4.3125
4
# How tall is the tree: 5 # 1 while loop and 3 for loops # ### ##### ####### ######### # # 4 spaces: 1 hash # 3 spaces: 3 hashes # 2 spaces: 5 hashes # ... # 0 spaces: 9 hashes # Need to do # 1. Decrement spaces by 1 each time through the loop # 2. Increment the hashes by 2 each time through the loop #...
8baa7982908922b69f895d33eaba0c92cb712215
claireyegian/preCalc
/loopDemo.py
275
3.8125
4
#Claire Yegian #1/18/18 #loopDemo.py - how to use a loop """for i in range(1,101): if '7' in str(i) or i%7==0: print('Buzz') else: print(i)""" i = 1 while i <= 100: if '7' in str(i) or i%7==0: print('Buzz') else: print(i) i += 1
cd6759aa55356291bb5b1f277fd8f0a88f950be1
TapasDash/Python-Coding-Practice
/oddEvenList.py
519
4.1875
4
''' This is a simple programme which takes in input from the user as a series of numbers then, filter out the even and odd ones and append them in two different lists naming them oddList and evenList Input : 1,2,3,4,5,6 Output : oddList = [1,3,5] evenList = [2,4,6] ''' myList = [eval(x) for x in input("Enter ser...
749875a8643c2954bcfa4707000bfeb3a04bf333
namtp-ai/ML-Source-
/Deeplearning/perceptron.py
906
3.609375
4
''' Perceptron for classification . ''' import numpy as np import matplotlib.pyplot as plt class Perceptron : def __init__(self,eta,n_inter): self.eta = eta self.n_inter = n_inter def net_input (self , X): return np.dot(X, self.weight[1:])+self.weight[0] de...
1c603b0e0b1745ed98914dc57219a5fbcb1533a3
namtp-ai/ML-Source-
/TensorFlow/Traffic_Sign/learn tensorflow/base_operation.py
1,126
3.90625
4
# Base Operation example using Tensorflow Library import tensorflow as tf # Base constant operations a = tf.constant(2) b = tf.constant(3) # Launch the default graph with tf.Session() as Sess: print('a =2 , a=3') print('Addition with constants ', Sess.run(a+b)) print('Mutiplication with constant...
e2b0611961cd47c9d0a07cdfb93526d30790c786
lincrampton/runestonePy
/CCCwk5.py
7,539
4.25
4
#!/usr/bin/env python # coding: utf-8 # ## Homework Week 5 # # Lin Crampton, CCC CIS157, Stefan Bund # In[1]: ''' Problem 11.1 The following sample file called studentdata.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scor...
24967da58485e075c1e5876418d1c41ffcbd5dc3
h27han/BomberMan
/MAINPROGRAM.py
61,411
3.578125
4
''' From: Hongjun Han For: Ms. Wun Date: May 23, 2014 Program Purpose: Displaying a multiplayer game to entertain the user ''' #Import & initialize the pygame module import pygame from pygame.locals import * #This is not necessary for most games, but can simplify some things pygame.init() class map(): mapchoic...
68e416fb4457c9bf408201923220b98e57706848
Swetha-Selvaraj/Optimization_Algorithms
/quick_sort.py
398
3.875
4
def quick_sort(arr): l = len(arr) if l <= 1: return arr else: pivot = arr.pop() items_greater = [] items_lower = [] for item in arr: if item > pivot: items_greater.append(item) else: items_lower.append(item) return quick_sort(items_lowe...
a1e6915dc11c38eb2316a4c463357fb530cf2e88
jacksonmarkey/nand2tetris
/06/hackParser.py
3,659
3.515625
4
"""Parser Contains methods useful for parsing Hack assebly code into binary. Used in assembler.py """ from typing import List import translator class HackParser(): nextFree: int = 16 # starting address for storing variables def parse(self, assLine: str) -> str: if (assLine[0] == "@"): return self.aInstru...
4d411df7fca76cf645bf01100fd30743aec68e88
ayushnagar123/Automate-the-Boring-Stuff-with-Python
/5 Web Scraping/5 Downloading PDF Document.py
665
3.6875
4
import requests # downloading a pdf file file=requests.get('http://www.souravsengupta.com/cds2015/python/LPTHW.pdf') try: # raise_for_status() method makes the program to halt if a bad download occurs, something like : the download link is invalid. file.raise_for_status() # making a file object saveFile=open('...
64425a7eb67ddb3758d3782502e682932879e802
ayushnagar123/Automate-the-Boring-Stuff-with-Python
/truthfalsy.py
182
4.03125
4
name='' while not name: print('enter your name') name=input() numOfGuests=int(input()) if numOfGuests: print('make sure to have enough seats for your guests') print('done')
42791911361b9d6f526c4e80e6074eb36cafaa61
inkky/ML
/multithread/pool.py
828
3.59375
4
# -*- coding: utf-8 -*- # @Time : 2018/4/26 14:30 # @Author : Inkky # @Email : yingyang_chen@163.com ''' 进程池就是我们将所要运行的东西,放到池子里,Python会自行解决多进程的问题 ''' import multiprocessing as mp def job(x): return x * x # 接下来用map()获取结果, # 在map()中需要放入函数和需要迭代运算的值, # 然后它会自动分配给CPU核 def multicore(): # pool = mp.Pool() ...
04edbaa127a19c39abb58fc4ab009161ddd40aee
rexarabe/Python_Projects
/class_01.py
1,414
4.53125
5
"""Creating and using class """ #The car class class Car(): """ A simple attemt to model a car. """ def __init__(self, make, model, year): """Initialize car attributes.""" self.make = make self.model = model self.year = year #Fuel capacity and level in gallons. ...
52da4305c357ff6c2fd0e82c88a4bc44fd668d81
Valitseja/Postcard
/postcard/mailer.py
2,024
3.65625
4
#!/usr/bin/python """.""" import smtplib class MailmanAuthError(Exception): """Authentication error""" class MailmanSendError(Exception): """The SMTP server didn't accept the data.""" class Mailman: """This class manages email sending.""" def __init__(self, host, port, username=None, password=None...
a000e1d11e9d1815a4441d0763112c2613b67754
dafengge/git
/idcheck.py
723
3.765625
4
#6-2 import string import keyword alphas = string.letters + '_' nums = string.digits alphanumeric = alphas + nums keywordhad = keyword.kwlist print 'Welcome to the Identifier Check v1.0' myInput = raw_input('Identifier to test?') if len(myInput) > 0: if myInput[0] not in alphas: print '''invalid:first...
1663672d8845901bdafd3a7953a8eb3492df6c86
kburt990/sudoku_solver
/sudoku_logic.py
4,331
3.953125
4
class sudoku: #represents standard 9x9 sudoku board def __init__(self): self.board=self.create_board() def create_board(self): #set up 9x9 board for standard game board=[] for i in range(9): board.append([0,0,0,0,0,0,0,0,0]) #fill board with default values return boa...
b71c815fa1f8167c8594774745dfccef3931add9
mustafaAlp/StockMarketGame
/Bond.py
1,075
4.3125
4
#!/usr/bin/env python """ This module includes Bond class which is a subclass of the Item class. Purpose of the module to learn how to use inheritance and polymorphizm in the python. Its free to use and change. writen by Mustafa ALP. 16.06.2015 """ import random as ra from Item import Item # ...
7b75b84bc987b2675df35082f3d30cb1ae6a3c1e
Ed-Mwaura/annuity_calculator-CLI-VERSION---hs
/calculator_cli.py
4,427
3.625
4
import math import argparse import sys class Calculator: parser = argparse.ArgumentParser() parser.add_argument("--type", help="type of calculation", choices=["diff", "annuity"]) parser.add_argument("--principal", help="credit principal", type=int) parser.add_argument("--payment", help="monthly paym...
b161bc26e29dc7e190d3db8a0155f7e83d9d1b0b
Aysinm/python-hometasks
/task4 stacks&queues/stack.py
611
3.90625
4
class Stack: def __init__(self): self.items = [] def push(self, item): # положить элемент в стек self.items.append(item) def pop(self): # удалить элемент из стека и вернуть его значение return self.items.pop() def peek(self): # вернуть значение последнего элемента стека (не...
70371539232e80409d7555c1d350ebcd3e525eea
TCromack/Python
/Function_Compound_Interest/Function_Compound_Interest/Function_Compound_Interest.py
2,686
4.0625
4
# Tyler Cromack # 10/17/19 # CIT-4205-DE1 # Homework #6 Compound Interest with Functions # This program takes a user's Principle, Interest Rate, Times Compunded and # Years in order to give their Future Value for their investment. import math fDeposit = fRATE = nTIMESCOMPOUNDED = iYEARS = 0 #Initialize the variables ...
850934889ae2797e134414a5565af9064a700883
heldemfilipe/Armazenador-de-Senha
/main.py
1,870
4.0625
4
from string import digits, ascii_lowercase, ascii_uppercase def VerificaCaracter(tipo, senha): v = 0 n = 0 while v == 0: for s in tipo: if s in senha: v += 1 n += 1 else: v += 1 numero = False if n > 0: numero =...
f9da34e9fb355bd36fe4ef6a7bcdfdbd7748e09d
fukupage/python_learning
/samplepackage/user.py
473
3.953125
4
# モジュール化---------------------------------------------------- class User: def __init__(self, name): self.name = name def say_hi(self): print("ハーイ {0}".format(self.name)) class AdminUser(User): def __init__(self, name, age): super(AdminUser, self).__init__(name) self.age = age def say_hello(self...
184bae5f5f0168e9fa7af1100c78ebc0a0e288c1
prathamesh07/Bank_sms_analysis_1.1
/function_definitions/bank_sms_preperation_function_definitions/balance_sms_adjustment_script.py
3,588
3.59375
4
from datetime import datetime, timedelta import pandas as pd """ This script adjusts first balance sms of each day as first sms of that day by truncating time part to 00-00-00. So that this sms can be used to compute opening balance. Also, there is entry of same sms but with prev day date and time 23-59-59. So that w...
b7a4af38ff7887b69eba8eccf7bae611bf1d9647
athiraivan/python
/for.py
99
3.671875
4
for i in range(0,10): print("hey i am %d"%(i)) for i in "hello,world": print("hey i am %s"%(i))
84584843fcf38702c391d83341492a753021b866
camel910116/Interfaceframework_http
/util/bubbleSort.py
350
3.90625
4
def bubbleSort(listx): lrange= len(listx) for i in range(lrange-1): #外循环控制一共要比较多少次元素 for j in range(lrange-1-i): #内循环控制每一次元素的比对 if listx[j]<listx[j+1]: listx[j+1],listx[j] = listx[j],listx[j+1] return listx print(bubbleSort([1,28,6,39,2]))
26c3e650eddb2c736279bccc1f8c99c5c6f794aa
rlopezb115/CursoPython
/4. HerramientasControlFlujo/b_FuncionRANGE.py
1,099
4.125
4
print('Inicio...') print('\nSecuencia de números, básico') # único parámetro, indica el final y no es parte de la secuencia. for num in range(10): print('Número: ', num) print('\nSecuencia de número, empieza con otro rango.') # Primer parámetro indica el comienzo del rango. # Segundo parámetro indica el final y n...
9a4f1299272641c37741e91a527908422e6b81f5
saurabhkumar8112/Audio-Generation
/codechef.py
128
3.921875
4
t=input() for i in range(int(t)): s=input() if " not " not in s: print("regularly fancy") else: print("Real Fancy")
3391af853761c080256c594278d0925b25b7ac14
sota1235/AOJ-Answers
/answers/0027.py
300
3.78125
4
#!/usr/bin/python # AOJ # 0027 import datetime days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] while True: m, d = map(int, input().split(' ')) if m == 0: break print(days[datetime.date(2004, m, d).weekday()])
195b7b422e3cef48d7a66ea7b0ef0071c7309127
cornerkick87/repl.it-prework
/2.8numbers.py
274
3.96875
4
#2.8 numbers: century #Statement #Given a year (as a positive integer), find the respective number of the century. Note that, for example, 20th century began with the year 1901. # Read an integer: #random yr input a = int(input()) b = (a // 100) # Print a value: print(b)
7b6569527b31d9f8b48c70bd033438bf26ff4676
cornerkick87/repl.it-prework
/2.5numbers.py
198
4.0625
4
# 2.5 numbers: sum of digits #Statement #Given a three-digit number. Find the sum of its digits. #answer # Read an integer: a = int(input()) b = (a % 10) c = (b % 10) # Print a value: print(b + c)
75ecbaf707af30540d26b03034f02979dd48856d
jpharo91/John-Ay190
/ws7/pi.py
1,002
3.859375
4
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as pl import numpy.random as random # sample starting values radius = 5.0 N = 1000000 # Function to calculate pi via Monte Carlo def pi(radius, N): rad = radius * radius x = 2.0 * radius #Calculate sides of box in which circle in inscribed ...
6be4e0a7a106a0d6aff63090864cd6721db25bb1
Juliadaphiny/Lista_05
/Questão_01.py
501
3.828125
4
# Disciplina: Probabilidade e Estatística # Aluno: JÚLIA DAPHINY LINS BRANSÃO # Lista_4 ld = int(input('Digite o número de lados do Polígono: ')) #Le a quantidade de lados pedidos M = float(input('Digite a medida do lado do Polígono: ')) #Le as medidas dos lados if Ld == 3: area = M ** 2 * 3 ** (1/2) / 4 #Cal...
24fe39f439ac0c77a1f2b403de52b3e72a2a8f84
sheldore/ShowMeTheCode
/0006/0006.py
617
3.703125
4
# -*-coding:utf8 -*- # author: yushan # date: 2017-01-22 # summary: 找到文档中重要的词语 import os import os.path import re from collections import Counter def word_count(content): word_pattern = r'[a-zA-Z-]+' words = re.findall(word_pattern, content) return Counter(words).most_common(1) root_dir = "text" lst_dir...
e53fdf17d5dd1071fb9c11a48b45d3eab61b7120
sheldore/ShowMeTheCode
/0011/0011.py
482
4
4
# -*-coding:utf8 -*- # author: yushan # date: 2017-03-02 def filtered_words(word,file): words_lst = [] with open(file,'r') as f: for line in f.readlines(): words_lst.append(line.strip().decode("gb2312").encode('utf-8')) return words_lst.__contains__(word) if __name__ == "__main__": ...
271e0768387a0c14936b1f9dd34c9d6a561d76f1
sanujkul/Artificial-Intelligence
/01_basicTicTakToe.py
2,110
4.03125
4
#!/usr/bin/python3 import time import random board = ["", "", "", "", "", "", "", "", ""] players = ["X" , "0"]; available = [0,1,2,3,4,5,6,7,8]; #All board positions available in the beginning def displayBoard(): print("__________________________________________________") for i in range(3): print(...
153dad602ba402070b59f75658d2bf05ac6542ec
COSC310-Team7/OmarMourad_310_Project
/Assignment3/NeuralNet_Agent/GUI.py
7,707
3.515625
4
# Import tkinter and agent.py from tkinter import * from agent import * from places import * from directions import * # botname specified bot_name = "Steven" BG_GRAY = "#ABB2B9" BG_COLOR = "#17202A" TEXT_COLOR = "#EAECEE" FONT = "Helvetica 14" FONT_BOLD = "Helvetica 13 bold" class ChatApplication: def __init_...
7519b24c6fa69630553ae83e2550e9e73da8dc2e
hwshim0810/solved-algorithm-problems
/src/codejam/2018_kickstart/A/A_2018_QA.py
817
3.609375
4
def is_complete(number, plus=True): total = 0 while True: cnt = 0 for c in number: if int(c) % 2 != 0: cnt += 1 if cnt == 0: break else: if plus: number = str(int(number) + 1) else: ...
9e218b6c6ae48954db91143c887bc2757f57d16d
mfornet/tictactoe-ai
/game.py
1,874
3.734375
4
EMPTY = '.' PLAYER0 = 'O' PLAYER1 = 'X' class TicTacToe: FINAL = [ [(0,0),(0,1),(0,2)], [(1,0),(1,1),(1,2)], [(2,0),(2,1),(2,2)], [(0,0),(1,0),(2,0)], [(0,1),(1,1),(2,1)], [(0,2),(1,2),(2,2)], [(0,0),(1,1),(2,2)], [(0,2),(1,1),(2,0)] ] def _...
3aca086a79c8778264e3ebedcac0db8c2cce5fb7
Jasmine424/EC602-DesignBySoftware
/Homework4/modeling.py
1,616
3.546875
4
#Copyright 2017 Simin Zhai siminz@bu.edu class Polynomial(): def __init__(self, seq=None): self.poly = dict() if seq != None : inc = 0 for c in reversed(seq): self[inc] = c inc = inc + 1 def __getitem__(self,x): if x in...
7b63e21fe63a1076606b9287be93e4981c013c4a
joshdoyle/taskw_gcal_sync
/taskw_gcal_sync/helpers.py
1,324
3.796875
4
""" Various helper methods. """ import re def get_object_unique_name(obj): """Return a unique string associated with the given object. That string is constructed as follows: <object class name>_<object_hex_id> """ return "{}_{}".format(type(obj).__name__, hex(id(obj))) def xor(*args): """Tru...
967f120b4882b93e25fbf9f17b7f584dbf4b19e4
harisankar14/python-oops-concet
/class variable &multi object.py
723
4
4
''' fields belongs to class and fields have two things 1) instance variable 2)class variable 1)instance variable- the variable belongs to instance/object 2)class variable-the variable belongs to the class ''' class student: clg="vitam" #class variable (this value is same for all the objects i.e. created...
51bfe17dc6234952f6ca214dcd548b9eee5a8a31
fernandezfran/python_UNSAM
/ejercicios/Clase07/random_walk.py
1,708
3.578125
4
# random_walk.py # # E 7.10: Caminatas al azar # import numpy as np import matplotlib.pyplot as plt def randomwalk(largo): pasos=np.random.randint(-1,2,largo) return pasos.cumsum() N = 100000 walks = [] for i in range(12): walks.append(randomwalk(N)) # considero como maximo la que en total (sumatoria) se...
4aa65e5ce29cd4fae61a8e321842cf2b11af1eee
fernandezfran/python_UNSAM
/ejercicios/Clase12/burbujeo.py
1,362
4.53125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def ord_burbujeo(lista): """ Ordenamiento por burbujeo. O(N^2) Pre: los elementos de la lista deben ser comparables Post: la lista está ordenada Devuelve la cantidad de comparaciones realizadas """ #comparaciones = 0 n = len(lista) -...
9dc1ef1a9a6348c9cec7e1a40683f349b5dc9137
fernandezfran/python_UNSAM
/ejercicios/Clase01/1.21.py
369
3.8125
4
### E 1.12: Expresiones regulares texto = 'Hoy es 6/8/2020. Mañana será 7/8/2020.' # Encontrar las apariciones de una fecha en el texto import re print(re.findall(r'\d+/\d+/\d+', texto)) # ['6/8/2020', '7/8/2020'] # Reemplazá esas apariciones, cambiando el formato print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\2-\1', texto))...
1e5317034aa1e7a1ba1d6c691b54398c096ac3bc
VeinFu/python_notes
/io_async/coroutine.py
384
3.59375
4
#!/usr/bin/env python # *-* coding: utf-8 *-* def consumer(): r = '' while True: n = yield r if not n: return print '[Consumer]: consuming %s ...' % n r = '200 OK' def producer(c): c.send(None) m = 0 while m < 5: m += 1 print '[Producer]: producing %s ...' % m s = c.send(m) print '[Producer]:...
289cd31f86b7ce070fc72f5b3dbe7fae6bd6c2a6
ekim1707/pythonexercises
/rpg.py
5,223
4.1875
4
# In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee # def main(): # hero_health = 10 # hero_power = 5 # goblin_health = 6 # goblin_power = 2 # while goblin_health > 0 and hero_he...
097d55fecea26fa221f7d662649f9772f667e2e0
ekim1707/pythonexercises
/stringpractice.py
3,145
4.34375
4
# 1. Uppercase a String # Given a string, print the string uppercased. string = input('Enter a word: ') sstring = str(string).upper() print(sstring) # 2. Capitalize a String # Given a string, print the string capitalized. string2 = input('Enter a word: ') sstring2 = str(string2).capitalize() print(sstring2) # 3. Re...
7b41c93fec032207e5c7de81aa72563c5fc85861
ekim1707/pythonexercises
/hello2.py
145
4.21875
4
name = input("What's your name? ") strname = str(name.upper()) print('Hey, ' + strname + '! Your name has ' + str(len(name)) + ' letters in it!')
76512e65fadd9589b50889cbf42b99f68686983e
andrewlehmann/hackerrank-challenges
/Python Data Structures/Compare two linked lists/compare_linked_lists.py
956
4.1875
4
#Body """ Compare two linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def equalityCheck(first, ot...
b9f3e75af6869d8c24d68e31087be17042005f4f
lwiz851/uip-prog3
/laboratorio/quiz 2.py
440
3.953125
4
#luis Martinez #clase#3 quiz 2 compra=float(input("Ingrese monto compra:")) if compra >=500: descuento=0.30 descuento=compra*0.30 total=compra-descuento print(total) elif compra>=200 and compra<500: descuento=0.20 descuento=compra*0.20 total=compra-descuento print(total) elif compra>=100...
d0d6a3daf905fe7d9b534c04398618f21be875f6
kjhurley/workspace-for-learnign
/newmystuff/src/display/single_channel_listing.py
2,708
3.53125
4
from kivy.app import App from kivy.uix.button import Button import kivy.uix.label import kivy.uix.gridlayout """ top line - channel icon in top left, current time in top right under that a box containing date and time of current program hard left against the margin. time since start/time left hard agaist...