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
6ac042747b53fd8ce535eccb0d89588568c7d1be
anhbkpro/common-sense-dsa
/sorting/practice.py
1,487
4.03125
4
array = [0, 5, 2, 1, 6, 3] def greatest_three_product(array): array = sorted(array) return array[-1] * array[-2] * array[-3] print(greatest_three_product(array)) array = [9, 3, 2, 5, 6, 7, 1, 0, 4] def find_missing_number(array): array = sorted(array) for index, item in enumerate(array): ...
9cba1d39e4dd85865781be033e4b5e282c9dd040
anhbkpro/common-sense-dsa
/binary-search-tree/find_inorder_successor.py
1,166
3.890625
4
class Node: def __init__(self, value): self.left = None self.right = None self.parent = None self.value = value root = Node(20) node9 = Node(9) node25 = Node(25) root.left = node9 root.right = node25 node5 = Node(5) node12 = Node(12) node11 = Node(11) node14 = Node(14) node9.parent = root node9.left = node...
01cec51411415da104d9069e845c3ae8e7da8635
ishvinder9528/python
/CoustomerManagenetSystem.py
2,466
3.921875
4
#BLL start class Customer: listCus=[] def init(self): self.Id=0 self.Name="" self.Address="" self.Mobile="" def addcustomer(self): Customer.listCus.append(self) def searchcustomer(self,Id): for e in Customer.listCus: if(e.Id==Id): ...
f5e8db4c8456afe1ff9b58e1e1ce54deeabbf15b
priyanka36/NeuralNetworksFromScratch
/ImplementingNumpy.py
376
3.59375
4
#Using numpy to represent only one neuron import numpy as np inputs=[1,2,3,3.5] weights=[0.5,0.8,0.9,0.3] bias=2 output=np.dot(weights,inputs)+bias print(output) #Using numpy to represent only multiple neurons inputs=[1,2,3,2.5] weights=[[0.2,0.8,-0.5,1] ,[0.5,-0.91,-0.26,-0.5], [-0.26,-0.27,0.17,0.87]] biases=[2,3,0...
cc23534d846968701551e75268b93ff9df41bf76
qiuosier/Aries
/helpers/file_signatures.py
3,187
3.5
4
"""Contains helper functions to create file signature dictionary from online resources. Run the build_json() to create and save the signature dictionary. File signature info are obtained from https://gist.github.com/qti3e/6341245314bf3513abb080677cd1c93b The "signatures" variable in this module is a signature dicti...
e7c187fd38320a219cfce3be7da1808881c26694
AdamGualberta/super-duper-palm-tree
/connect4game.py
2,362
3.75
4
#connect4 python implementation #play stuff here #Author = Adam Gendron, November 2016 import string from dank import * class game(object): def __init__(self): #initialize new gameboard self.currentBoard = gameboard() self.winState = True #setting players hardcoded, future may...
655da078140a70573ca21a8da67a3449d2b6f9e1
NSO2008/Python-Projects
/Working with files/Using functions/Functions.py
1,063
4.03125
4
filepath = "Functions_data.txt" READ = "r" WRITE = "w" APPEND = "a" listOfWords = [] def printWords(): print(names) return def main(): numOfNames = input("Enter the number of words/text/phrases/sentences you wish to remember: ") for questions in range(int(numOfNames)): words = inp...
7ccc459d2ab9e420b47bfefd00e04dddff87fa8a
NSO2008/Python-Projects
/Printing to the terminal/HelloWorld.py
584
4.21875
4
#This is a comment, it will not print... #This says Hello World... print('Hello World') #This is another example... print("This uses double quotes") #Quotes are characters while quotation is the use quotes... print("""This uses triple quotation... it will be displayed however I type it""") #This is an exampe of...
b7d8297cbd2b98b8cf1f57f738ceb27e0cfa5b68
ronnyohawa/python-codes
/loops.py
394
3.828125
4
a,b=0,1 num=int(input("enter your maximum value :")) while a<num: print(a) a,b=b,a+b x=int(input("enter a number")) if x<0: x=0 print("negative changed to zero") elif x==1: print("single") else: print("more") words=['cat','dog','chicken','horse'] for a in words: print(a,len(a)) for a in ...
2a4199fbdbbd5a99ee60be5124e8f9e45d0c8794
IoC-Sunderland/Properties-Vs-Getters-and-Setters
/main.py
2,379
4.03125
4
class JavaStyle: ''' A class that utilises "private" attributes and Getters and Setters''' def __init__(self,x): self._x = x # _x is Protected def get_x(self): return self._x def set_x(self, x): self._x = x JavaStyle_1 = JavaStyle(42) JavaStyle_2 = JavaStyle(4711) p...
0b8f08d1f44d32eac328848be344c8d5e7cca3ad
cbolles/auto_typing
/auto_type/main.py
2,162
4.125
4
""" A tool that simulates keypresses based on a given input file. The program works by accepting a source file containing the text and an optional delimeter for how to split up the text. The program then creates an array of string based on the delimeter. Once the user presses the ESCAPE key, each value in the array wil...
a15100eeac7db4076b4e9bae09e966b1f4ab590e
diko316/python-sample
/sample/oop/declaration.py
666
3.953125
4
""" Class declaration """ class Base(object): """ Example Base Class """ def __init__(self): print "initialized Base Class" @classmethod def log(cls): """ Log you know hihihii """ print "log Base Class" class SubClass(Base): """ Example Sub Class """ def __init__(s...
e92de533344382046a41e4d0b18d1d2d5c301db0
Lotame/DataStream_Cookbook
/Recipes/Convert_Files_Into_JSON_And_CSV/Mapping_JsonToCsvConverter.py
2,771
3.640625
4
#!/usr/bin/python # # Write in Python3.6 # Filename: # # Mapping_JsonToCsvExtractor.py # # # Basic Usage: # # python Mapping_JsonToCsvExtractor.py /directory/containing/datastream/mapping/json/files # # Utilities import sys import os import json import argparse def writeCsvHeader(delimiter, csv_file, *args):...
4375838f17b8de6ac3136fe114869d19dd16ad02
leoffx/fizz
/fizz/fizz.py
5,379
3.765625
4
def buzz(max_number = 100): if max_number < 0 or max_number > 100: raise NotImplementedError("Maximum number must be between 1 and 100.") number_list = get_number_list(max_number) for number in number_list: if number == 1: print("1") if number == 2: print("2...
fd16d103233463200b3ef88f0878947e69d366a4
CSBUnlimited/Machine-Learning
/ML in Python & R/Part 2 - Regression/Section 6 - Polynomial Regression/MyWork/polynomial_regression.py
4,117
3.71875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 21:07:22 2020 @author: chath """ ## Data Preprocessing # Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd ## Import dataset dataset = pd.read_csv('Position_Salaries.csv') x = dataset.iloc[:, 1:2].values # Just to make x as mat...
3aa1d42dbbe55beadaeafe334950694fa9ece8f2
mickeyla/gwc
/Test A/test.py
596
4.125
4
#Comments are not for the code #Comments are for you #Or whoever answer1 = input ("What is your name?") print ("My name is", answer1) answer2 = input ("How old are you?") print ("I am", answer2, "years old!") answer3 = input ("Where are you from?") print ("I am from", answer3) answer4 = input ("Do you like coding?"...
cc8bf4379d575d1d414c7fd61e236c3d4d904b12
hauqxngo/PythonSyntax
/words.py
1,385
4.75
5
# 1. For a list of words, print out each word on a separate line, but in all uppercase. How can you change a word to uppercase? Ask Python for help on what you can do with strings! # 2. Turn that into a function, print_upper_words. Test it out. (Don’t forget to add a docstring to your function!) def print_upper_w...
2cc5586fc796d6e1d49e9ad5e0eeff648dd8bd51
shirisha24/loop
/54321.py
242
3.75
4
# m=1 # i=5 # while i<=25: # j=i # while j>=m: # print(j,end=" ") # j=j-1 # print() # i=i+5 # m=m+5 i=5 m=1 while i>=1: j=i while j>=m: print(j,end=" ") j=j-1 print() i=i-1
2fd2d17158507bddd069441f14eae98b170ebfe7
shirisha24/loop
/prime.py
148
3.921875
4
n=int(input("enter num")) i=1 c=0 while i<=n: if n%i==0: c=c+1 i=i+1 if c==2: print("prime number") else: print("not prime")
ff71069e6bdaaa10b60154e7d55ce314e027dc99
matsumotokoki/python_tutrial
/q_6.py
95
3.921875
4
def power(x): ans = int(x)*int(x) return ans x = input("number? >>") print(power(x))
4dab68750ec5551efb4c29efa7edb446e7ab385e
jpak1996/interview
/exp.py
355
3.75
4
def exp(a,b): if b==0: return float(1) elif b>0: initial = float(a) for x in range(1,b): a = a*initial else: initial = float(a) a = 1/float(a) b = -b for x in range(1,b): a = a/initial return a print(exp(2,0)) print(exp(2,4)) print(exp(-2,3)) print(exp(-2,4)) print(exp(2,-1)) print(exp(2,-3)) ...
da3f83d2e5be006670c78a1c583e8f81a28b7339
JoySnow/Algorithm
/leetcode/441_arranging-coins.py
840
3.640625
4
""" https://leetcode.com/problems/arranging-coins/description/ AC. """ class Solution(object): def arrangeCoins(self, n): """ :type n: int :rtype: int x * (x+1) / 2 <= n """ l, r = 1, n while l < r: # [1, 3] => 2 # [1, 4] => 3 ...
b29f5057632f76a6e12681431fd4fdbf0b91e8e2
JoySnow/Algorithm
/leetcode/majority-element.py
1,602
3.59375
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ """ Make sure candidate1 is diff with candidate2. Case5 means another diff value occurs, this make a new pair together with candidate1 and candidat...
61bd249ca9c05a88c6a8c8c541120336db36a81a
JoySnow/Algorithm
/tree/B-Tree.py
9,683
3.734375
4
""" B-tree Follow Chap18 of <Intro to Algo> Simple functions: insert, delete, search Author: Xiaoxue Wang Time: 2018-02-07 """ import logging FORMAT = '%(asctime)s - %(levelname)s: %(funcName)s():%(lineno)d:\t%(message)s' logging.basicConfig(filename="bt.log", level=logging.DEBUG, ...
a009d1c350414d7ff2a0d0407fee28ac43896a2b
JoySnow/Algorithm
/leetcode/excel-sheet-column-title.py
675
3.734375
4
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ # num = '' # while n: # num += chr(n % 26 + 64) # print "n % 26: ", n % 26 # print "n/26: ", n/26 # n /= 26 # print num # #num...
9fe09a75083d05a172e61ce01faf3ab5d0e3e638
JoySnow/Algorithm
/tree/basic.py
1,253
4.3125
4
import Queue # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def make_a_basic_n_level_tree(n): """ :type n: int :rtype: TreeNode """ if n <= 0: return None root = TreeNode...
61370e3901a768726e5d98bde3941efe540e80f3
trabalhos-da-faculdade/T3_ORGARQ
/cache1.py
1,750
3.546875
4
# -------------------------------- # TESTE DE HIT OU MISS DA CACHE 1 # -------------------------------- # Exercicio 1 # Mapeamento Direto # 10 Bits para tag # 3 Bits para linha # 2 Bits para palavra # 1 Bit para selecao do byte em uma palavra # Cache com 8 Linhas # 4 Palavra...
a12cd30988bc452c174685df5a9aff0eb2042157
jtoutee/Openclassrooms_Git_jtoutee
/class_Compteur.py
557
3.609375
4
# -*-coding:Latin-1 -* class Compteur: """Cette classe possde un attribut de classe qui s'incrmente chaque fois que l'on cre un objet de ce type" C'est assez puissant si on y pense bien! """ objets_crees = 0 def __init__(self): """ chaque fois qu'on cre un objet on incrmente le compteur""" Compteur.obj...
b5cd050ffb5ea44b8ae0381c794c4f5f3eaf7567
frclasso/python_examples_three
/files-working.py
299
3.78125
4
#!/usr/bin/env python3 def main(): infile = open('lines.txt', 'r') #segundo argumento define a ação, r = read, w = write, a = append outfile = open('new.txt', 'w') for line in infile: print (line, file = outfile, end=' ') print('Done!!') if __name__=='__main__':main()
3254e17af9dbe588a64229334f4a06b9a78042c2
frclasso/python_examples_three
/function-working2.py
232
3.53125
4
#!/usr/bin/env python3 def main(): testfunc(1,2,3,4,42, 43, 44) def testfunc(this, that, other, *args): print(this,'/', that,'/', other) for n in args: print (n, end=' / ') if __name__ == "__main__":main()
d2eae8b6cdbbb4fc442c21ef5930a1a8b082d508
frclasso/python_examples_three
/exception-working2.py
455
3.796875
4
#!/usr/bin/env python3 def main(): try: for line in readfile('lines.doc'): print(line.strip()) except IOError as e: print ("Cannot read file:", e) except ValueError as e: print ('Bad filename', e) def readfile(filename): if filename.endswith('.txt'): fh = open(filena...
89e9d15c4385acc04034acb4406bf4468967785a
dongxiaohe/Algorithm-DataStructure
/leetcode/896-Monotonic-Array.py
314
3.671875
4
class Solution(object): def isMonotonic(self, A): increasing = decreasing = True for i in range(1, len(A)): if A[i - 1] < A[i]: decreasing = False if A[i - 1] > A[i]: increasing = False if not decreasing and not increasing: return False return True
3be7956ff4d6cf1f72d695cab2a6daa32d8e5fbb
dongxiaohe/Algorithm-DataStructure
/leetcode/965-Univalued-Binary-Tree.py
374
3.59375
4
class Solution: def isUnivalTree(self, root): uniValue, queue = None, [root] while queue: node = queue.pop(0) if uniValue == None: uniValue = node.val elif uniValue != node.val: return False if node.left: queue.append(node.left) if nod...
bacda7959f55fca6af4519b4ffeb6a480481415d
dongxiaohe/Algorithm-DataStructure
/leetcode/241-Different-Ways-to-Add-Parentheses.py
589
3.546875
4
class Solution: def diffWaysToCompute(self, input): if input.isdigit(): return [int(input)] result = [] for i in range(len(input)): if input[i] in "+-*": part1 = self.diffWaysToCompute(input[0:i]) part2 = self.diffWaysToCompute(input[i + 1:]) ...
a46be1b8f16be2fa42e59826df7a013907c467d4
dongxiaohe/Algorithm-DataStructure
/leetcode/538-Convert-BST-to-Greater-Tree.py
621
3.5625
4
class Solution: def convertBST(self, root): def _convert(node, sum, state): if not node: return if node.right: _convert(node.right, sum, state) node.val += state["sum"] sum = node.val state["sum"] = node.val if node.left: _convert(node....
d0d14c9c2c02f1ef663f4fa0e2915bc30df1df6f
dongxiaohe/Algorithm-DataStructure
/leetcode/79-Word-Search.py
850
3.578125
4
class Solution: def exist(self, board, word): def _dfs(board, word, i, j, m, n, wordPosition): if len(word) == wordPosition: return True if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[wordPosition]: return False tmp = board[i][j] board[i][j] = "*...
ca8eb8f50540236ef2f08b11b4fa73c5c97934f3
dongxiaohe/Algorithm-DataStructure
/leetcode/131-Palindrome-Partitioning.py
1,124
3.96875
4
class Solution: def _isPal(self, s): return s == s[::-1] def partition(self, s): if not s: return [] result = [] """ This logic is to check s itself is a palindrome """ if self._isPal(s): result.append([s]) """ This is a super cool way ...
31d2c6e6ea48290e1f45ac6fe008530b91999fe5
dongxiaohe/Algorithm-DataStructure
/leetcode/367-Valid-Perfect-Square.py
371
3.515625
4
class Solution(object): def isPerfectSquare(self, num): if num <= 1: return True start, end = 1, num >> 1 while start <= end: mid = start + ((end - start) >> 1) power = mid ** 2 if power == num: return True elif power < num: start = mid + 1 ...
f5b20f256f3c3c06339b127fd62fc66f99107ba8
dongxiaohe/Algorithm-DataStructure
/leetcode/648-Replace-Words.py
1,025
3.8125
4
import collections class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.word = None class Trie: def __init__(self): self.root = TrieNode() def insert(self, strList): for str in strList: current = self.root for t i...
b6895dc01b38e861294dc7d7aedfb7a2de837f7d
dongxiaohe/Algorithm-DataStructure
/leetcode/211-Add-and-Search-Word-Data-structure-design.py
901
3.765625
4
class TrieNode: def __init__(self): self.isWord = False self.children = {} class WordDictionary: def __init__(self): self.parent = TrieNode() def addWord(self, word): curr = self.parent for char in word: if char not in curr.children: curr...
0632cab4a3cba2292c0c1ce3f0e3b2a9f3186434
ungeschneuer/similiar_text_checker
/app/start.py
1,981
3.53125
4
import shelve import calculate import storage import compare import window def start(): while True: # Oeffnet Tkinter Operation um Textdatei zu bekommen filename = window.getfilename() # Wenn gecancelt wird gefragt, ob das Programm beendet werden soll. if filename == '': ...
af3403868c1020d8d0d3b6a3284f5be4ed982843
Momentum-Team-8/python-word-frequency-roanblanchard
/word_frequency.py
1,270
3.75
4
STOP_WORDS = [ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he', 'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were', 'will', 'with', '\n', '' ] words = {} punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~-''' def print_word_freq(file): file = open(file, "r") ...
fa3c37b752cda9de86760c05221f42233be99bdc
MaxwellCoriell/Bangazon-Basic-Orientation-Exercises
/cars.py
1,089
4.03125
4
showroom = set() showroom.add("Supra") showroom.add("Diablo") showroom.add("NSX") showroom.add("911") print(showroom) # show the items in the set print("--------") print(len(showroom)) # show the length of the set print("--------") showroom.add("NSX") # tried to add an item to the set that already existed. print(s...
7528e211bc0f3ed4c6320c110f5406c93cf6faf9
TheIdanLapid/PythonTA.all
/FullPuzzle.py
16,013
4.03125
4
############ # QUESTION 1 ############ class Polynomial(): def __init__(self, coeffs_lst): self.coeffs = coeffs_lst def __repr__(self): terms = [" + ("+str(self.coeffs[k])+"*x^" + \ str(k)+")" \ for k in range(len(self.coeffs)) \ if se...
9771217829208b8d3218b84b8f144c9cd5857e72
TheIdanLapid/PythonTA.all
/add_hex.py
927
3.71875
4
def add_hex(A,B): key = "0123456789abcdef" #legit chars in hex base result = "" carry = "" while A != "" or B != "": if A == "": A = "0" elif B == "": B = "0" digit_a = str.index(key, A[-1]) #last char of A's index digit...
be8fc7374858e1eb60bf2c3d3f82e7d351eb67eb
rorschachwhy/mystuff
/learn-python-the-hard-way/ex11_提问.py
502
4.1875
4
#ϰ11 print "How old are you?" age = raw_input() #עʾ䣬printһšԲỻ #6'2"鿴you're '6\'2"'tall print "How tall are you?", #һֵ䣬ѡšҲֵheightIJе˼ height = raw_input(), print "How much do you weight?" weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)
f318ba10d7384cec391620866cf1dbaa4d533e1e
rorschachwhy/mystuff
/learn-python-the-hard-way/ex7_10.py
2,062
4.40625
4
#ϰ7ӡ print "Mary had a little lamb." print "Its fleece was white as %s." % 'snow' print "And everywhere that Mary went." #ӡ10 print "." * 10 end1 = 'C' end2 = 'h' end3 = 'e' end4 = 'e' end5 = 's' end6 = 'e' end7 = 'B' end8 = 'u' end9 = 'r' end10 = 'g' end11 = 'e' end12 = 'r' #עⶺţcomma÷űʾո print end1 + end2 + end3 ...
bd55c06a453d71196818f0931424535c6b1b47c2
Xerrex/cli-blog
/app/models.py
959
3.609375
4
from datetime import datetime class User (object): def __init__(self, username, password): self.username = username self.password = password self.role = "normal" def __repr__(self): return '<User {}'.format(self.username) class Admin(User): def __init__(self, username...
b9aca14147a83020a98c423326da53267a25e8f2
Alexandra0102/python_basic_11_05_20
/env/les1_hw_6.py
1,244
4.25
4
"""6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b км. Программа должна принимать значения параметров...
72e1661a12e1bff0c2914b1327a0e31bbc2a62e3
NikPeg/SmallWorldSynchronization
/watts-strogatz-master/SmallWorldGraph.py
2,869
3.53125
4
import random from Graph import Vertex, Edge, Graph from RandomGraph import RandomGraph # Fifo based on Raymond Hettinger's recipe @http://code.active.state.com/recipes/68436 class Fifo(object): def __init__(self): self.nextin = 0 self.nextout = 0 self.data = {} def append(self, valu...
1f52ebb74b762dcce6213360939086acb0b59f46
getconnected2010/testing123
/adventure story.py
1,194
4.1875
4
name = input('What is your name?:') print(f'Hello {name.capitalize()}, you are about to go on an adventure. You enter a room and see two doors. One is red and the other blue.') door_input = input('which door do you choose?: ') if door_input == 'red': print('Red door leads you to the future. You have to help a s...
ad0f0a5db0b0ed49f0424fc474b802fa0d374581
josemariasosa/jomtools
/python/classes/exercises/person-list.py
368
4.15625
4
#!/usr/bin/env python # coding=utf-8 """ EN: ES: """ # ------------------------------------------------------------------------------ class A(object): """Definiendo la clases A""" def __init__(self, cantidad): self.cantidad = cantidad a = A(10) print(a.cantidad) # -------------------------------...
b761bcfa4e38075ff0eeb5fdf774a2d841d694bb
yogeswaran79/mindsdb
/mindsdb/libs/helpers/general_helpers.py
2,059
3.71875
4
""" ******************************************************* * Copyright (C) 2017 MindsDB Inc. <copyright@mindsdb.com> * * This file is part of MindsDB Server. * * MindsDB Server can not be copied and/or distributed without the express * permission of MindsDB Inc **************************************************...
d80510661f7ca63b64ce29c6593cb895c44ac845
Zenterio/opensourcelib
/k2/k2/utils/timestring.py
665
3.53125
4
from zaf.config import ConfigException def parse_time(timestring): """Parse time strings in the [[hh:]mm:]ss format into seconds.""" invalid_time_error = "Invalid time specified: '{time}'. Format is '[[hh:]mm:]ss'".format( time=timestring) if not timestring: return None times = times...
d26c990b62b872581a838d61f2a35643315ec26d
aadiupadhyay/CodeForces
/codeforces/224/A.py
216
3.75
4
def Sides(): inputs = raw_input().split() a = int(inputs[0]) b = int(inputs[1]) c = int(inputs[2]) x = (a*c/b)**0.5 y = (b*c/a)**0.5 z = (a*b/c)**0.5 print int(4*(x+y+z)) Sides()
6886258203cddcfa428b626abc93be234a7d3b55
aadiupadhyay/CodeForces
/codeforces/1326/A.py
219
3.8125
4
def solve(): n=int(input()) if n==1: print("-1") else: if (n-1)%3: print("2"*(n-1)+"3") else: print("2"*(n-2)+"33") for i in range(int(input())): solve()
3309b2ed6b38d6c153b58680e0b766a5104a34f5
aadiupadhyay/CodeForces
/codeforces/1367/A.py
152
3.65625
4
def solve(): s=input() x="" x+=s[0] for i in range(1,len(s),2): x+=s[i] print(x) for _ in range(int(input())): solve()
9f88939e5d490cce624b71f4da6097fa3ecf2e17
Ammar-Ali1993/text-encryption
/transpose.py
453
3.546875
4
class Transpose: def __init__(self): self.map = [5, 10, 6, 8, 1, 3, 9, 4, 7, 2] def encrypt(self,text): returnString='' for i in self.map: returnString += text[i-1] return returnString def decrypt(self,text): returnString = '' counter=0 ...
cd7793038854eab3c67e631d3c158f2f00e9ad70
gauravraul/Competitive-Coding
/lcm.py
485
4.15625
4
# Program to get the lcm of two numbers def lcm(x,y) : #take the greater number if x>y: greater = x else: greater = y #if greater is divisible by any of the inputs , greater is the lcm #else increment greater by one until it is divisible by both the inputs while(True)...
111497f1b16aaf63fbe66df46dfc1eb12b0e705e
migantoju/design-patterns
/structural/facade.py
1,225
4.3125
4
""" *Facade Pattern* Proporciona una interfaz unificada más simple a un sistema complejo. Proporciona una forma más sencilla de acceder a los métodos de los sistemas subyacentes al proporcionar un único punto de entrada. Oculta la complejidad de los sitemas y provee una interfaz al cliente con la cual puede acced...
df5331645a4052f0fe6c5273e8deac783eb0a699
nikolisan/Diploma-Thesis
/Coriolis/calculate_traj.py
3,883
3.609375
4
import numpy as np import matplotlib.ticker as ticker import matplotlib.pyplot as plt import matplotlib.animation as animation def plot_circle(center, radius): """ Plots a circle using the parametric equations :param center: A list of the circle's center: [x,y] :param radius: The radius of t...
40635a3486cccba9f793a9ea70fada458a39b539
Prazhant/ISYE6501
/Assignment7/Assignment7.py
5,187
3.59375
4
from pulp import *; import pandas as pa; import xlrd as xlrd; #1.read the excel raw data foodDataRaw = pa.read_excel("diet.xls") #2.converting raw data to list foodData = foodDataRaw[0:64].values.tolist() #3. Extracting each column of the data and adding to datadictionary foods = {x[0] for x in foodData} cost = {x...
b1d24eb915b5bd6176254399ffb6b75bedbde366
BlagaCristi/PacmanSolvingAgents
/Pacman 2 - Multiagent/multiagent/multiAgents.py
25,529
3.71875
4
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.e...
573f616ea030b4f8794098c9bbb537bd884a3d98
concpetosfundamentalesprogramacionaa19/practica220419-mrnarvaez3
/demo3.py
359
3.65625
4
""" archivo: demo.py Ejemplo de lenguaje Pyhton autor: @rober """ # lectura de datos dato1 = input("Ingrese el vaor 1: ") dato2 = input("Ingrese el valor 2: ") suma = int(dato1) + int(dato2) multiplicacion = int(dato1) * int(dato2) # salida de datos print ("El valor de la suma es: %s\n El valor de la multiplica...
080490316a8413721b8d03d5b6fdae892e97bbd2
d-easton/text_tools
/funcs.py
1,847
4.03125
4
# Support functions for basic text analysis # Created by David Easton @ d-easton, 28.03.2020 from .support.values import stop_words def tokenize(raw, lower=True): """ Tokenize breaks a string of raw text into a list of string tokens raw -- input string lower -- Flag to cast variables...
c19881141a287260b4ea61e14b8adc6c7ac1f779
znn1414/branch_test
/20180816/test_20180820.py
977
3.6875
4
#coding:utf-8 #导入 import random for i in range(5): print(random.randint(1, 10)) import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed ' + response + '.') import random def getAnswer(answerNumber): if answerNumber =...
a566b259ea6203f8a3e78359aff19cd7f86f8a09
as-chapa/respource_sort
/resource_sort_sample2.py
1,209
3.953125
4
import csv class Resource: """ list型として受け取りアンパックして代入する 受け取るlistの順序が正しい前提となるクラス resource_list[0]: date resource_list[1]: idle resource_list[2]: sys resource_list[3]: user resource_list[4]: cpu ※date, cpu以外のgetterは検証では不要だったので割愛 """ _date: str _idle: str _sys: str ...
acc1598c9cc5ad11ebf51e83cb7bce767efc75a2
zzhang115/python01
/function.py
415
3.5
4
def sayHello(): print "hello world" def saySth(name): print "hello baby %s" %name sayHello() saySth("zzc") def name_info(name, age, job, nationnality="Chinese"): global gl, gl1 gl = 123 gl1 = 100 print "your name: %s age %d your nationnality:%s" %(name, age, nationnality) return name resul...
a8ea8f0cd0bb9185f7c56ccc8c476d153fb8a3fb
jzgombic/IS211_Assignment4
/sort_compare.py
4,052
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import random def insertion_sort(a_list): """ An algorithm which sorts a list and returns the sorted list as well as the amount of time the sort had taken. Args: a_list (list): A list of any data type. Returns: (tup...
7411b82055cf80b9f25079fbc88631711157f126
thiagovictoria/Coursera
/(01)_PYTHON USP/SEMANA_02/(04)_Exercícios de Programação/05_Praticar_tarefa_de_programação_(Lista_01)_03.py
114
3.96875
4
num = int(input("Digite um número inteiro:")) dezena = (num//10)%10 print ("O dígito das dezenas é", dezena)
0cfa69023bed80add3dac9c5055a9f1672502721
thiagovictoria/Coursera
/(01)_PYTHON USP/SEMANA_04/(04)_Exercícios de Programação/02_Tarefa_de_programação_(Lista_03)_03.py
92
3.984375
4
n = int(input("Digite um numero:")) x=0 while n>0: i=n%10 x+=i n=n//10 print(x)
9cf19d840ee0135add90ab70f25291947d3b9ca3
thiagovictoria/Coursera
/(01)_PYTHON USP/SEMANA_07/(01)_Repetições Encaixadas ou Laços Aninhados/Teste.py
1,927
4
4
#Exerc_01 ''' Quantas vezes o programa executará a linha 6 (# Iteração)? x = 1 cont = 0 while x < 3: y = 0 while y <= 4: # Iteração y = y + 1 x = x + 1 10 ''' #Exerc_02 ''' Quantas vezes será impressa a palavra "oi" ao ser executado o código abaixo? fora = 5 while fora > 0: dentro...
0a4b63e376e300b3acb0213f666a676f01d1e756
AleksandraSandor/codeabbey
/jednostki.py
185
3.671875
4
print("jednostki") jednostka = float(input("podaj ilość centymetrów, żeby zamienić na metry")) print("Cześć {} cm to {:.4f} m" .format(jednostka, (jednostka/100)))
2d7167ec369dc03293978c129264f37c3921ef63
AleksandraSandor/codeabbey
/lokata.py
397
3.75
4
print("lokata") poczatkowy = float(input("podaj swój początkowy stan konta ")) stopa = float(input("podaj roczną stopę oprocentowania w % ")) wiek = float(input("podaj liczbę lat na lokacie ")) print("stan Twojego konta, czyli {:.2f} po {:.0f} lat przy oprocentowaniu {:.2f} % będzie wynosił {:.2f}".format(p...
0585d799a05094fc2ca9f3fd30c17048e58c52d8
PassionateLooker/LCO
/day18.py
206
3.984375
4
''' find max of these elements 1,0,5,4,2,7,465,4 without using conditional statements and loops ''' array=[0,45,2,6,1,8] def largest(n): n.sort() l=n[-1] return l print(largest(array))
4c46c22021f995ce8bf7ca55255ba70704cce7a4
PassionateLooker/LCO
/day10.py
295
3.84375
4
''' salesperson rita drives 2052 miles in 6 days, stopping at 2 towns each day.How many kms does she avg between stops? ''' miles=2052 days=6 stops=2 kmPerMiles=1.60934 avgmile=(miles/days)/stops kmConvToMiles=avgmile*kmPerMiles print('She drives avg of',kmConvToMiles,'kms')
7b659ed44a06ac7ba56c56d210f6f441dfa2d7e7
the07/Python
/mp3_downloader/program.py
3,765
3.59375
4
import urllib.request import urllib.parse import re import urllib import wget import os #clear the screen os.system('clear') os.system('cls') # Intro print(''' MP3 FUCKING DOWNLOADER ===================== DOWNLOAD MP3 MOTHERFUCKER ===================== ''') #user prompt to ask mode print ('''\t\t\t Select a mode...
f3415bce34f14cd2febbc32dd09eb22b8db3776e
the07/Python
/freshstart/CookBook/calculate_e.py
625
3.828125
4
from decimal import Decimal, getcontext def factorial(number): """ Returns the factorial of a number""" if number == 0: return 1 elif number == 1: return 1 else: return number * factorial(number -1) def calculate_e(precision): """Calculates the value of e to the given prec...
4d8e97b7749d85b15f5e1f20e332332ddf8e2513
the07/Python
/Algorithms/vowel_reduce.py
425
4.21875
4
#take a word and remove all the vowels and capitalise the first word state_names = ['Alabama', 'California', 'Oklahoma', 'Florida'] vowels = ['a','e','i','o','u'] for state in state_names: state_list = list(state) for letter in state_list: if letter.lower() in vowels: state_list.remove(let...
6d789e3a0c1b16b9792eac754da9509e63001c8d
the07/Python
/Data Structures/code_fragment_2_1.py
3,315
4.1875
4
class CreditCard: """A consumer credit card""" def __init__(self, customer, bank, acnt, limit, balance=0): """ Create a new credit card instance The initial balance is zero. customer the name of the customer bank the name of the bank acnt the account i...
2d2eefce01166d116552665e3c0405113d45cc5a
the07/Python
/Algorithms/append.py
132
3.59375
4
text = "This is the appended text\n New line again! " saveFile = open('exampleFile.txt','a') saveFile.write(text) saveFile.close()
93a903f47ad6ff6743553e37de5bfbd1fb459f86
the07/Python
/Algorithms/max_gcd.py
923
3.671875
4
#!/bin/python3 import sys def gcd(x,y): """ Function to calculate the gcd""" result = x % y if result == 0: return y return gcd(y, result) def maximumGcdAndSum(A, B): # Complete this function A.sort() B.sort() i, j = n, n max_gcd = 0 pair_sum = 0 while i: i...
d762353e375b06d91cf4f56326db2dcd05798f85
the07/Python
/Algorithms/time_conversion.py
241
3.5
4
T = str(input()) suffix = T[-2:] arg = T[:-2].split(':') if suffix == 'AM': arg[0] = int(arg[0]) % 12 arg[0] = str(arg[0]).zfill(2) else: arg[0] = 12 + (int(arg[0]) % 12) arg[0] = str(arg[0]).zfill(2) print (':'.join(arg))
0792d8a39fb1f7fe8f76be78a1d178d3866e88ce
TotBrigi/Python
/Lottery.py
693
3.90625
4
import random def generate_lottery_numbers(how_many_numbers): lottery = [] while True: if len(lottery) == how_many_numbers: break lottery_numbers = random.randint(1, 100) if lottery_numbers not in lottery: lottery.append(lottery_numbers) return lottery de...
87e8544f99518db9e52bb69912f4d18ab6a769c8
BlaineBeltran/Python-Course
/Programming for Everybody Files/payRate.py
180
4.03125
4
# This program will calculate your Payment amount hrs = input("How many hours do you have? ") rate = input("What is your hourly rate? ") pay = float(hrs) * float(rate) print(pay)
aa82f7586a2a6206ad0ed5426dbc4faa5bce4f43
Muenmac/data_science_basics
/operators.py
785
3.84375
4
# operators.py x = 5 y = 7 # arithemtic operators z = x + y print(z, type(z)) z = x - y print(z) z = x * y print(z) z = x / y print(z) # % modulo operator for the rest of 2 variables, NOT the actual result z = x % y print(z) # exponential, 5^7 z = x ** y print(z) # NOR division, Doppelteilen, Ergebnis ist nach...
a2f79b776ce1265619a10c08fb1339a42811005c
Muenmac/data_science_basics
/casting.py
254
4.03125
4
#casting.py # integer casting x = int(8) y = int(2.8) z= int("42") print(x, y, z, type(y)) print("y is" , type(y)) # float casting a = float(8) b = float("33.5") print(a, b, type(b)) # string casting f = str(33) g = str(42.7) print(f, g, type(f))
f8f6579b78fdc39b466e3cce1f7955338cdc0bfb
HungOm/py4e
/Course 2/Week 5/9.4 Assignment.py
1,007
3.9375
4
# def readFile(): name = input("Enter file :") if len(name) <1 : name = 'mbox-short.txt' handle = open(name) #text =str(handle.read(name)) #newText = str(text) #def makeList(): #readFile() words = list() # fh = handle.split() for line in handle: line = line.rstrip() #default split "blankspace" if not line.star...
d0a296404efb91afee470dce545f57c4413541b1
HungOm/py4e
/Course 2/Week 4/8.4 python2.py
214
3.9375
4
fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: words=line.split() for word in words:continue else: newwords=words.append(word) print(line.rstrip())
ecf0d4117ad8aab226e9808899b922d720cb0294
2018JTM2248/assignment-8
/ps2.py
1,919
4.65625
5
#!/usr/bin/python3 ###### this is the second .py file ########### ####### write your code here ########## #function definition to rotate a string d elemets to right def rotate_right(array,d): r1=array[0:len(array)-d] # taking first n-d letters r2=array[len(array)-d:] # last d letters rotate = r2+r1 # r...
9ac5b6b93c71e31fe15df1a830b5caed548e9cb4
ambervancamp/InformaticaPP
/PycharmProjects/ProefPracticum/MasterMindAsked.py
4,746
4.1875
4
# The definition of ALL_COLORS is repeated here. That repitition can # be avoided, but it would lead us to far at this point. ALL_COLORS = ("red", "green", "blue", "yellow", "orange", "white") def get_nb_black_white_matches(given, guess): """ Return the number of black and white matches of the guessed combina...
c51da958190e374bf9ab81632b7cca0f12a3d704
vikashvishnu1508/algo
/oldCodes/reverseOnlyAlpha.py
754
3.703125
4
def reverse_only_alpha(s): # fill in new_s = [i for i in s if i.isalpha()] new_s = reverse_array(new_s) s = list(s) j = 0 for i in range(len(s)): if s[i].isalpha(): s[i] = new_s[j] j += 1 return ''.join(s) def reverse_only_alpha2(s): new_s = list(s) ...
620f08c42f7787718afa05210bef6c49e5422dff
vikashvishnu1508/algo
/oldCodes/threeNumSort.py
588
4.21875
4
array = [1, 0, 0, -1, -1, 0, 1, 1] order = [0, 1, -1] result= [0, 0, 0, 1, 1, 1, -1, -1] def threeNumSort(array, order): first = 0 second = 0 third = len(array) - 1 for i in range(len(array)): if array[i] == order[0]: second += 1 elif array[i] == order[2]: third...
b71a8ef228748fe80c9696c057b4f6c459c13f49
vikashvishnu1508/algo
/Revision/Sorting/ThreeNumSort.py
521
4.15625
4
def threeNumSort(array, order): first = 0 second = 0 third = len(array) - 1 while second <= third: if array[second] == order[0]: array[first], array[second] = array[second], array[first] first += 1 second += 1 elif array[second] == order[2]: ...
44bb6d4663112ca951642534ce20ad2fa81a8c27
vikashvishnu1508/algo
/Revision/Stack/ShortenPath.py
642
3.609375
4
def shortenPath(path): # Write your code here. startWithSlash = path[0] == '/' pathArr = list(filter(isUseful, path.split('/'))) stack = [] for folder in pathArr: if folder == '..': if startWithSlash and len(stack) > 0: stack.pop() if not startWithSlash: if len(stack) > 0 and stack[-1] != '..': ...
91264526b0894bd07968ebdfd0fbfe7047576983
vikashvishnu1508/algo
/oldCodes/binarySearch.py
390
4.0625
4
def binarySearch(array, target): # Write your code here. left = 0 right = len(array) - 1 while left < right: middle = (left + right) // 2 if array[middle] == target: return middle if array[middle] > target: right = middle - 1 else: left...
4b56de005259fa36f89377a8f315b029ea6a0ef4
vikashvishnu1508/algo
/oldCodes/threeNumberSum.py
704
4.15625
4
def threeNumberSum(array, targetSum): # Write your code here. array.sort() result = [] for i in range(len(array) - 2): left = i + 1 right = len(array) - 1 while left < right: newSum = array[i] + array[left] + array[right] if newSum == targetSum: ...
4ddce658928e7cfe29afaa4f838145daf2c1329d
vikashvishnu1508/algo
/oldCodes/Dijkstras Algorithm.py
1,150
3.578125
4
def dijkstrasAlgorithm(start, edges): # Write your code here. visitedNodes = {} nodeByVal = [float('inf') if i != start else 0 for i in range(len(edges))] updateNodeValues(start, edges, visitedNodes, nodeByVal) for i in range(len(nodeByVal)): if nodeByVal[i] == float('inf'): nodeByVal[i] = -1 return nodeByVa...
451ac8a21f5eea77d61df92f99cf3b68cf1c411d
vikashvishnu1508/algo
/oldCodes/DFS.py
841
3.859375
4
# Do not edit the class below except # for the depthFirstSearch method. # Feel free to add new properties # and methods to the class. class Node: def __init__(self, name): self.children = [] self.name = name def addChild(self, name): self.children.append(Node(name)) return self ...
8fdc059728bf11a0a45e80ea46aadfa0c97a8e8e
vikashvishnu1508/algo
/Revision/DynamicProgramming/maxProfit.py
344
3.6875
4
def maxProfit(prices): min_price = prices[0] max_profit = -float('inf') for i in range(1, len(prices)): if prices[i] < min_price: min_price = prices[i] else: max_profit = max(max_profit, (prices[i] - min_price)) return max_profit prices = [10, 7, 5, 8, 11, 9] ...