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
16f80f759ad12bd5f731ad6b942f9205297e20bf
CharmingTree/PythonLearning
/solution/sums.py
133
3.71875
4
def solution(a, b): answer = 0 if a == b : return 0 return sum(range(a,b+1)) or sum(range(b, a+1)) print(solution(5,3))
9587e4baa193397f050e6df52703cd045932d958
CharmingTree/PythonLearning
/grammar/generatorEx.py
583
3.578125
4
gt = (x for x in range(100)) for i in gt: print(i) print(type(gt)) import time def fibon(n): a = b = 1 result = [] for i in range(n): result.append(a) a, b = b, a + b return result # start_t = time.time() # for x in fibon(100000): # pass # end_t = time.time() # print('tota...
c1e827c5e89512076143c54002cf140e945c4069
m-bansal/ML
/polynomial regression vs linear regression.py
1,874
3.5625
4
#Importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #For calculating mean_squared error from sklearn.metrics import mean_squared_error #Creating a dataset x= 10*np.random.normal(0, 1, 70) y= 10*(-x**2)+np.random.normal(-100, 100, 70) #Plotting dataset plt.figure(f...
5d2f255ddf4a4bcc74935e5e0ab07b6f7b0c5a6e
jrainlau/python-learning
/4.dict和set/demo-1.py
95
3.6875
4
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key in d: print key, ':', d[key]
da9298c875c51275148edeefe3b4ea061c19ecca
jrainlau/python-learning
/5.函数/demo-2.py
189
3.890625
4
def average(*args): sum = 0.0 if len(args) == 0: return sum else: for item in args: sum += item return sum/len(args) print average(1, 2, 3)
2ffd82690c4b4df05e9d72138fd836d9fa98e35e
jrainlau/python-learning
/4.dict和set/demo-2.py
253
3.734375
4
s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul']) print s s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print x[0] + ':', x[1] s = set(['Adam', 'Lisa', 'Paul']) if 'Adam' in s: s.remove('Adam') else: s.add('Adam') print s
27b0635ca93e026b7a9fc0dade8956649f9a0f04
katharinameislitzer/smartninjacourse
/Class6_Python3/Review_1.py
224
3.59375
4
# functions def hello(): print("hello") def beautiful_day(text): return "Hello "+text+". It is a beautiful day!" # "print" is not "return" ! hello() #beautiful_day("Goodbye") x = beautiful_day("Franek") print(x)
aedb27dbf1f3a5f8b2f6ad82db177b2c99a9d66b
katharinameislitzer/smartninjacourse
/Class1_Python3/example_00100_hello_world_exercise.py
92
3.71875
4
# print a string with the words Hello and your name print("Hello", end=" ") print("Kathi")
0bd2d83a82395c518a0860e6d490dfad023e8b3d
katharinameislitzer/smartninjacourse
/Class3_Python3/example_01210_read_analyse_exercise_solution.py
422
4.15625
4
# open the file "height.txt" # it contains the height of each person in the class # separated by a come "," # write a program which reads the file # saves the different heights in a list # and calculates the average height with open("height.txt") as file: a = file.read().split(",") height_avg=0 number_of_people=...
ae9edbb910fb5f988a866c525e61860c8f7e29e4
katharinameislitzer/smartninjacourse
/Class2_Python3/example_00630_secret_number_exercise_1.py
462
4.09375
4
# Modify the secret number game code below such # that it shows the number of attempts # after each failed attempt secret = "7" guess = 0 counter = 0 while True: counter += 1 guess = input("Guess the secret number") if guess == secret: print("Oh, so great!, you won!") break elif coun...
2dc8aaf7d72fe4a7ce57d819c393d27fb551e559
katharinameislitzer/smartninjacourse
/Class1_Python3/homework/hw_1_5_multiply_checker_absolute_numbers.py
589
4
4
def multiplication(number_1: float, number_2: float) -> float: result = number_1 * number_2 return result def difference(number_1, number_2): result = number_1 * number_2 return result if result >=0: return result else: return -result assert multiplication(5, 2)==10, multipl...
daae20709890ef1120fbb77a983136aa9869e1cc
katharinameislitzer/smartninjacourse
/Class6_Python3/example_01610_classes_instances.py
309
3.859375
4
class Human(object): def __init__(self, age, name): self.age = age self.name = name if __name__ == '__main__': x = Human(19, "alfred") print(x.age) # access attributes with "." print(x.name) beatrix = Human(22, "beatrix") print(beatrix.age) print(beatrix.name)
f0af0f69fb46ff4c28abc52c96ac2590ec6ed770
katharinameislitzer/smartninjacourse
/Class6_Python3/example_01622_classes_methods_exercise_2.py
664
3.890625
4
# create a class bank account # it has 2 fields: name and balance # it has methods to withdraw and deposit and print statement class BankAccount(object): def __init__(self, name, balance): self.name = name self.balance = balance def print_statement(self): print(str(self.name) + ",your...
7765f80af736da20a16dcd7ec7aae67d12e313ef
katharinameislitzer/smartninjacourse
/Class6_Python3/example_01670_classes_exercise_social_account.py
1,462
3.921875
4
# create classes for social account # they have a field for: name, friends # they have methods to: count_friends, befriend, unfriend class SocialAccount: # Graph (object) muss man bei python 3 nicht mehr dazuschreiben def __init__(self, name): # freunde noch nicht, weil wissen wir noch nicht self.name = ...
7ead56c5eff91f2c77a07160363211d7c124d579
katharinameislitzer/smartninjacourse
/Class1_Python3/example_0500_calculator_excercise_2.py
899
4.375
4
# print welcome to user name = input("Please enter your name: ") print(f"Welcome {name}") # read user input for operation operation = input("Please enter a mathematical sign (+, -, *, /): ") print(f"You entered {operation}") # read user input for first value first_value = int(input("Please enter number one: ")) print(f...
88d3b8c1db8dad814feb2f49427cd9130580fff9
katharinameislitzer/smartninjacourse
/Class1_Python3/example_00210_operations_integers_with_variables_exercise.py
680
3.96875
4
# Task 1 # define 2 variable and give them the values 2 and 10, then calculate the result of the division 2/10. # print the result # write your code here x = 2 y = 10 result = x / y print(result) # Task 2 # save your first name and last name as string, and concat them to 1 variable, # and print the result x = "K...
e727bd1ad1586c1368d3996350a0c6f65cde6a00
oh1001/Python-class-2
/dasgal7.py
128
3.609375
4
# hunii ner ugugdsun bol ehnii usgiig tom bolgo name = input() a = name[0].upper() urt = len(name) print(a + name[1:urt])
a8ad2f52a50cc7be3a9fc3f86c6a206bc1369e11
HaoxuZhang/python-learning
/some-tests/iter.py
245
4.25
4
list=[1,2,3,4] it=iter(list) print(next(it)) print(next(it)) for x in it: print(x,end=" ") #该函数输出为 ''' 1 2 3 4 ''' #iter返回的是一个迭代器,第一次使用next函数会让迭代器指向第一个元素并且保存位置
cdaae938a7cd387c13b1d16f226bfaaf75cf7ce4
HaoxuZhang/python-learning
/some-tests/forTest3.py
312
3.96875
4
#该循环用来说明test都干了什么事,每次循环,test代表的是列表中的值,最后发现 #列表中没有test的值,就进入了else。但是每次循环输出的test不是10,是数组中的值 tests=[1,2,3,4,5,6] test=10 for test in tests: print(test) else: print("没有循环数据")
6597c3441e0ed4ac8f96a73ef1374b50e08d2fdc
HaoxuZhang/python-learning
/python100questions/13.py
152
3.71875
4
def cube(n): return n*n*n for i in range(100,1000): tmp=i total=0 for j in range(0,3): total+=cube(tmp%10) tmp=tmp//10 if total==i: print(i)
f65ad32c1fba0d5fca6948f1a6ae2cecc447cd54
HaoxuZhang/python-learning
/some-tests/forTest2.py
231
3.703125
4
sites=["Baidu","Google","Runoob","Taobao"] site="string" for site in sites: if site=="Runoob": print("菜鸟教程") break print("循环数据 "+site) else: print("没有循环数据!") print("完成循环")
eb2bb97fc97487f5d1d46605bd9ec76bbbb62f3b
wayneyeye/py-scraping-learning
/ch2/bs_more.py
776
3.59375
4
from urllib.request import urlopen from urllib.error import HTTPError,URLError from bs4 import BeautifulSoup import sys # html=urlopen("http://www.pythonscraping.com/pages/warandpeace.html") # bsObj=BeautifulSoup(html,'lxml') # print(bsObj.h1) def getGreens(url): try: html = urlopen(url) except (HTTP...
550dd8ab9ba9d4ad3527ed8461efa4623fc6497a
pransil/skLearnMnistViz
/plot_mnist_filters.py
2,337
4.28125
4
""" ===================================== Visualization of MLP weights on MNIST ===================================== Sometimes looking at the learned coefficients of a neural network can provide insight into the learning behavior. For example if weights look unstructured, maybe some were not used at all, or if very l...
382a6f59d07f783a24c41c4d13a020d9ff2febf3
fzyang1227/ds2000proj
/api_v5.py
8,880
3.609375
4
''' api_v5.py This file takes data from api and multiple csv files to create a culmulative csv file of nba player stats and salaries with our player win contribution stat (Cont) at the end. Also, it runs a function to create a separate csv for modifying teams' season stats necessary for creati...
5c928ec55693b87ceb2f807f3e246c17824231b7
gatfieldlab/disome_codebase
/venv/lib/python3.4/site-packages/accessories/random_utils.py
1,445
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Utilities for random processes""" import sys import random NumberTypes = (int, float) class RandUtilException(Exception): """A simple custom Exception class for random_utils.py""" def __init__(self, m): message = "[random_utils] {}".format(m) ...
0a6b853ad18f8de841ecee96b45ec17860984cc2
gatfieldlab/disome_codebase
/venv/lib/python3.4/site-packages/accessories/collections_utils.py
746
3.71875
4
# -*- coding: utf-8 -*- """ Utilities for collections items @author: barpat """ import collections def fix_depth_recursive_defaultdict(depth=3, t=int): """Generates a recursive defaultdict object with a given depth. The innermost values of the object will the of type 't'""" if depth==1: return col...
a4ac93e13af0e537ea1837f556ca5abd61a5637d
fireJera/python
/exercise/exercise5.py
173
3.859375
4
#!/usr/bin/python # -*- coding:UTF-8 -*- l = [] for i in xrange(0,3): x = int(raw_input('integer:\n')) l.append(x) l.sort() print l l.sort(reverse = True) #逆序 print l
966092e7570c1d7ffac8095acaad89e9a7d210e3
fireJera/python
/exercise/exercise4.py
466
4
4
#!/usr/bin/python # -*- coding:UTF-8 -*- year = int(raw_input('year:\n')) month = int(raw_input('month:\n')) day = int(raw_input('day:\n')) months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] sum = 0 leap = 0 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)) : leap += 1 if 0 < month < 12...
410b186b7c0a4c6d3bbd7b1b265478c2768f4791
jbirondo/Python-The-Basics
/script3.py
1,192
3.890625
4
from tkinter import * window=Tk() def kg_conversions(): # Get user value from input box and multiply by 1000 to get kilograms gram = float(e1_value.get())*1000 # Get user value from input box and multiply by 2.20462 to get pounds pound = float(e1_value.get())*2.20462 # Get user value from input ...
a6f8056b3ca552c08541b6a98b9608bfc3c4f504
DeepakPal18/Python-
/prime factor(continue).py
222
3.96875
4
num=int(input('enter any number...')) print('the prime factors of {} are: ' .format (num)) d=2 while( num>1): if( num%d==0): print(d) num=num/d continue d=d+1 print('***********')
035e2fe2712444fae7ebb18f22831476256876fe
DeepakPal18/Python-
/fact-while.py
147
4.15625
4
num=int(input('enter a number..')) fact=1 i=1 while (i<=num): fact=fact*i i=i+1 print(' factorial of {} is: {}' .format( num,fact))
b3a0de2ec6e9b016216d0a60bdf418b0f41b8394
ulisesgaribay/programacionpython
/prob2-1.py
303
3.90625
4
#!/usr/bin/python # -*- coding:utf-8 -*- import math print "ingresa el cateto adyacente: " a = float(raw_input()) print "ingresa el cateto opuesto: " b = float(raw_input()) def hipotenusa(a,b): hipotenusa = math.sqrt(a)+math.sqrt(b) return hipotenusa print "tu hipotenusa es: " print hipotenusa(a,b)
bcd5959486e3e713dee1523fb2cff275f5d27d1c
ulisesgaribay/programacionpython
/prob3-6.py
360
4.03125
4
#!/usr/bin/python # -*- coding:utf-8 -*- print "ingresa numero de años humanos" x = float(raw_input()) def convierte(x): if 0 <= x <= 2: x = x*10.5 return x if x > 2: x = (x-2)*4+2*10.5 return x x = convierte(x) if x >= 0: print "el numero de años perro equivalente es: ",x,"años perro" elif x < 0: print "ER...
13144f83a1d56f907910cc5a29aae4b94555ee37
ThinkingJoules/Pi-learning
/Python_Learning/create_table.py
1,465
3.875
4
import sqlite3 from sqlite3 import Error import os def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: conn = sqlite3.connect(db_file) return c...
ff081eac686bb45161af87aae837c76702e57f56
jacob-02/OpenCV_Studies
/thresholding_binary.py
1,176
3.5
4
import cv2 as cv image = cv.imread('/home/jacob3006/PycharmProjects/OpenCV_Studies/Images/img.png') cv.imshow('image', image) grey = cv.cvtColor(image, cv.COLOR_BGR2GRAY) cv.imshow('GREY', grey) # Simple Thresholding threshold, thresh = cv.threshold(grey, 225, 225, cv.THRESH_BINARY) # Makes the values of the pixels...
ba952e218294b7258b1c6c3dd47464e2671b7b09
jacob-02/OpenCV_Studies
/basic_functions.py
1,145
3.640625
4
import cv2 as cv image = cv.imread('/home/jacob3006/Pictures/Screenshot from 2021-03-28 23-13-03.png') cv.imshow('Anime', image) # Converting an image into a greyscale grey = cv.cvtColor(image, cv.COLOR_BGR2GRAY) cv.imshow('Anime Grey', grey) # Blurring an image blur = cv.GaussianBlur(image, (9, 9), cv.BORDER_DEFA...
86994d0215f304e295e55852704affd5c608dd28
Mpreyzner/python_algorithms
/selection_sort.py
481
4.09375
4
def find_smallest(array): # selection search smallest = array[0] index = 0 for i in range(1, len(array)): if array[i] < smallest: smallest = array[i] index = i return index def selection_sort(array): sorted = [] for i in range(len(array)): smallest...
3bc4c4a6489d517288488c4bc1c33802177a65cc
Mpreyzner/python_algorithms
/n_queens.py
2,564
4.3125
4
# The N Queen is the problem of placing N chess queens on an N×N chessboard # so that no two queens attack each other. # 1) Start in the leftmost column # 2) If all queens are placed # return true # 3) Try all rows in the current column. Do following for every tried row. # a) If the queen can be placed safel...
8355192756b3603ed6df390ab08b8405be66938b
josemrp/test-python
/hackerrank/easy/ifElse.py
162
3.921875
4
N = int(input()) if N % 2: print ('Weird') else: if N > 1 and N < 6: print('Not Weird') elif N > 5 and N < 21: print('Weird') else: print('Not Weird')
d074f86327f31d29e0164083abfd115ff8bd0a3a
Feng2012/LeetCode
/algorithms/python/SingleNumber.py
430
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://oj.leetcode.com/problems/single-number/ """ import functools class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): return functools.reduce(lambda x, y: x ^ y, A) if __name__ == '__main__': s =...
fee9e80001a9976f10071fa34c0962e04f6ff6b4
Feng2012/LeetCode
/algorithms/python/RemoveDuplicatesfromSortedList.py
1,047
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/ """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a List...
087cba7d5b10bd591ecdff530a8e0df0d5bdcf6b
Feng2012/LeetCode
/algorithms/python/MinStack.py
1,029
3.953125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://oj.leetcode.com/problems/min-stack/ """ class MinStack: def __init__(self): self._stack = [] self._min_index = [] # @param x, an integer # @return an integer def push(self, x): try: if x < self.getMin(): ...
3235cf5a894c4ac9c116a7fcbf1fadf0dfbbd50b
ericxlima/ILoveCoffee
/scrips/jogo_da_forca.py
3,719
3.515625
4
from random import choice import json class JodoDaForca: def __init__(self, nick): self.categorias = {'animais': ['coelho', 'cavalo', 'coruja', 'gaivota', 'porco', 'galinha', 'macaco', 'baleia', 'golfinho', 'morcego', 'girafa', 'elefante', ...
8b6e412c9ded323bf6ce854b82fc683caec22fd0
markfickett/LED-Controller
/examples/frompy/lowlevel.py
2,577
3.828125
4
""" Demonstrate generating colors in Python and using data_sender to transfer them over Serial to the Arduino. (Optionally simulate entirely in Python.) Low-level version, using fewer layers of abstraction (and convenience). """ # Set how many times to update the pattern (insert one Color) and redisplay # on the LED ...
7f26895236745c1dddcfa80cce123627fc7e03b7
Milooooo1/schoolExercises
/HICT-PROG/Les 8/Verplichte Opdrachten8_5.py
442
3.71875
4
#Opdracht8_5 def namen(): namen = {} namenLijst = [] running = True while running: naam = input("Voer een naam in: ") if naam != " ": if naam != namenLijst: namenLijst.append(naam) else: running = False for naam in namenLi...
f791edba14217fdd27a5ccfc24da491c6e600c61
rudydevolder/RealPython
/SQL 2a. INSERT.py
584
3.546875
4
from ibus import exception __author__ = 'rudy' import sqlite3 employees = [ ('De Volder', 'Rudy'), ('De Volder', 'Ilse'), ('Baeyens', 'Tom'), ('Op de Locht', 'Rik'), ('De Volder', 'Anja') ] with sqlite3.connect("new.db") as connection: c = connection.cursor() try...
ea629047b8aad7804304031a284078a8eba6fcd7
Krishna9331/python
/chapter13/ex13.py
680
4.09375
4
# “ This is how we add modules to your script from the Python feature set.” # argv variable holds the arguments we pass to our Python script when you run it. from sys import argv # “unpacks” argv so that, rather than holding all the arguments, it gets assigned to four variables we can work script, first, second, third ...
a4061d17e097fc2a7753ce54998eac01619272b1
simransidhu8/C98---Functions
/countWordsFromFile.py
299
4.28125
4
def countWordsFromFile() : fileName = input("Enter file name: ") numberOfWords = 0 f = open(fileName) for line in f : words = line.split() numberOfWords = numberOfWords + len(words) print("Number of words: ") print(numberOfWords) countWordsFromFile()
c9d51020d0c19b569694d017ec8d9cd4e9df787c
cathyp11/SI206-HW
/HW5/hw5.py
182
3.578125
4
import re f = open('regex_sum_37803.txt') total = 0 for line in f: numbers = re.findall('([0-9]+)', line) if len(numbers) != 0: for a in numbers: total += int(a) print(total)
55690b9a76cd08f7be698c9424821bdd1a595158
hanyslmm/celebrity
/head.py
1,193
3.984375
4
import datetime class User: """A member of FriendFace. For now we are only storing their name and birthdayself. But soon we will store an uncomfortable amount of user information.""" def __init__(self, full_name, birthday, poster, quote): self.name = full_name self.birthday = birt...
fdb120c3bca04124748aac5550b861efe0fecbd4
exitquote/pythonchallenge
/level1.py
202
3.65625
4
import string str = "map" outstring = '' str1 = string.lowercase str2 = str1.replace(str1[:2], '')+str1[:2] table = string.maketrans(str1, str2) outstring = string.translate(str, table) print outstring
a9e322397f6d9846e71285df491dc96b4cafda0c
aitorcastel/CrackingCodes
/reverse.py
278
3.796875
4
# reverse cipher print('Write a message: ') message = input() rev='' i = len(message) - 1 while i >= 0: rev = rev + message[i] i -=1 print('[>] Reverse: \t'+rev) message='' i = len(rev) -1 while i>=0: message+=rev[i] i-=1 print('[>] Original: \t'+message)
42eb87653598d17644e7075d0e6fb0cd4851ddeb
afterthepen/demos_fizzbuzz
/fizzbuzz.py
399
3.875
4
#https://www.afterthepen.com for number in range(1 , 100): if (number % 3 == 0 and number % 5 != 0): print("Fizz " + str(number)) if (number % 3 != 0 and number % 5 == 0): print("Buzz " + str(number)) if (number % 3 == 0 and number % 5 == 0): print("FizzBuzz " + str(number...
6cbdac0fd720215156635b9fc6d9492280bde556
Timoteus99/Kattis
/candy_distribution.py
1,737
3.5
4
def isPrime(n): #vrne ce je prastevilo ali ne if (n <= 1) : return False if (n <= 3) : return True i = 1 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i += 1 return True def modInversePrime(a, m): #vrne "power" od a...
dd3fb33cb48e483072565f6e3d077f273633c24c
Timoteus99/Kattis
/proofs.py
1,182
3.796875
4
def pravilno_sklepanje(stevilo_primerov): '''Funkcija vrne ''correct'', če je sklep pravilen, v nasprotnem pa vrstico v kateri se prvič pojavi napaka''' mnozica_sklepov = set() for i in range(stevilo_primerov): #preverimo po vseh vrsticah vrstica = input() if vr...
fbb35d42c8ea92d11bcf48b23c451a2fd6566919
Nucelles/BSP1-Neural-Network
/Neuron.py
4,194
4.25
4
from random import uniform import numpy as np class Neuron: """ This is the base class of the network layers, it is used to perform the mathematical operations on the data. :param debug: Bool used to check whether or not to run neuron on debug mode. :type debug: bool :param partialDerivat...
0da0ed62861394a7c4f59eb442dc4a77e1f810fc
Pycone/Python-for-Beginners
/src/ch4/ch4.py
1,350
4.28125
4
''' List example ''' numbers = [1, 2] numbers.append(3) numbers.remove(3) len(numbers) numbers.pop() numbers = [5, 7, 1, 2, 3] numbers.sort() numbers[0] numbers[1] numbers[2] = 'hello python' print (numbers) numbers = [[1,2,3],[4,5,6]] students = [] students.append(['David', 123, True]) students.append(['Hubert', 321...
30b7f276c094ec8fe225eac3914a28f634472480
Pycone/Python-for-Beginners
/src/ch8/pokemon_better.py
1,852
3.859375
4
''' Inheritance example We can do better # Eevee(Normal), Vaporeon(Water), Jolteon(Eletric), Flareon(Fire) ''' class Pokemon: def __init__(self, poke_name, poke_type, poke_weight, poke_height, poke_cp, poke_hp): self.name = poke_name self.__type = poke_type self.__weight = poke_weight ...
74eded6ce7b77a3307c71ee0bb3d3b3f4828632d
pzq7025/sort
/quick_sort.py
1,635
3.984375
4
import random """ 快速排序 20230519::已修改,结合了快排的思想。 参考的讲解:https://www.bilibili.com/video/BV1at411T75o/?spm_id_from=333.337.search-card.all.click&vd_source=1f83a43974d81c3e83a94712b9af0cf5 """ # def quick_sort(data): # 这里存在问题 # if len(data) >= 2: # mid = data[len(data) // 2] # left, right ...
bef5fd5878d0c7bfbb9c25fb743d927e8be7adab
nabssss/PASSWORDGENERATOR
/main.py
278
3.640625
4
import string import random def generatePassword(num): password = '' for n in range(num): x = random.randint(0, 94) password += string.printable[x] return password # generate and print a 16 character random password print(generatePassword(16))
895294d0ce5b58e0dd3a7ee80e7596eacaf84a19
ShrublandsAssociates/scratch
/basics/volitlity.py
711
3.75
4
import math import numpy as np import pandas as pd # just set the seed for the random number generator np.random.seed(107) # Generate the daily returns returns = np.random.normal(0, 0.1, 100) # sum them and shift all the prices up into a reasonable range X = pd.Series(np.cumsum(returns) * 6, name='X') X.plot() def ...
aace2fe61eef59d1039d4876036464aa595e9f42
nitikagoel01/fsdse-python-assignment-8
/even_numbers.py
93
3.65625
4
def get_even_numbers(num): lst = [i for i in range(2,num + 1,2) if i > 0] return lst
ed9cb43eb0d53e499724b3dec998f6dd4a209767
lyoness1/cracking
/chapter2.py
7,522
3.9375
4
# LINKED LISTS class LinkedListNode(object): def __init__(self, value, next=None): self.value = value self.next = next def __str__(self): return str(self.value) class LinkedList(object): def __init__(self, head=None, tail=None): self.head = head self.tail = tail ...
54bf86af0d776aa8ab5fc23fb4ca9baa424f2eb5
ChoiHongYong/Hong
/NumberRun.py
1,908
3.5625
4
#----------------------------------------------- # 이 파일은 수정하면 안되며, 제공된 Number.py 파일의 # 함수를 수정해서 프로그램을 완성해야 합니다. #----------------------------------------------- from number.Number import * def main(): # 제공 데이터 세트2를 실행하려면 loadData에서 제공 데이터 세트1을 주석 처리하고제공 데이터 세트2를 주석 해제하여 실행 inputData = loadData() ...
fd5c7ed83140a150d194162aa737c831e67b8b3c
HunterLaugh/codewars_kata_python
/kata_6_Cat_and_Mouse_-_Harder_Version.py
1,334
3.859375
4
''' Cat and Mouse - Harder Version You will be given a string (x) featuring a cat 'C', a dog 'D' and a mouse 'm'. The rest of the string will be made up of '.'. You need to find out if the cat can catch the mouse from it's current position. The cat can jump (j) characters. Also, the cat cannot jump over the dog. S...
862fbb1580e0dd290a61dae003c552128fe97c64
HunterLaugh/codewars_kata_python
/kata_4_Validate_Sudoku_with_size_N_N.py
2,053
4.125
4
''' 4 kyu Validate Sudoku with size `NxN` Given a Sudoku data structure with size NxN, N > 0 and √N == integer, write a method to validate if it has been filled out correctly. The data structure is a multi-dimensional Array(in Rust: Vec<Vec<u32>>) , ie: [ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1...
d720678c5d305947059da4ea89fa966aeecd0b51
HunterLaugh/codewars_kata_python
/kata_6_Format_words_into_a_sentence.py
1,028
4.21875
4
''' Format words into a sentence Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arr...
b42a39a0b4ffb5c0ddf1998e4fe5a0feda77572b
HunterLaugh/codewars_kata_python
/kata_5_Common_Denominators.py
1,452
3.625
4
''' Common Denominators Common denominators You will have a list of rationals in the form { {numer_1, denom_1} , ... {numer_n, denom_n} } or [ [numer_1, denom_1] , ... [numer_n, denom_n] ] or [ (numer_1, denom_1) , ... (numer_n, denom_n) ] where all numbers are positive ints. You have to pr...
e782a8a494d70e5f2d4b0000b1f1d2658513b2ee
HunterLaugh/codewars_kata_python
/kata_5_Regex_for_Gregorian_date_validation.py
1,115
4.15625
4
''' Regex for Gregorian date validation Your task is to write regular expression that validates gregorian date in format "DD.MM.YYYY" Correct date examples: "23.12.2008" "01.08.1994" Incorrect examples: "12.23.2008" "01-Aug-1994" " 01.08.1994" Notes: maximum length of validator is 400 charac...
91477e21aa28a96d9a1b4a5a2cea98680470b855
HunterLaugh/codewars_kata_python
/kata_4_Path_Finder_#1_can_you_reach_the_exit.py
1,737
3.671875
4
''' Path Finder #1 can you reach the exit Task You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise. Empty positions are marked .. Walls are marked W. Start and exi...
9108b8a9d921c105bfc2aa93373b04dd237d4bd2
HunterLaugh/codewars_kata_python
/game/sudoku_v1.1.py
1,975
3.609375
4
# coding:utf-8 # 数独 9*9 二维数组,横行、竖列、3*3矩阵是1-2-3---9填充,不重复 import datetime class solution(object): def __init__(self,board): self.b=board # 数独 9*9 self.t=0 # 运行次数 # 获得下一个未填的位置 def get_next(self,x,y): # x row for col in range(y+1,9): if self.b[x][col]==0: return [x,col] # x+1 ...
fac4798566a105f5713c0657bbc40ddc87e2a9b8
HunterLaugh/codewars_kata_python
/kata_7_Reverse_words.py
448
3.796875
4
def reverse_words(text): res=[] i=0 temp=[] while i<len(text): if text[i]!=' ': temp.append(text[i]) elif text[i]==' ' and temp: p=temp[::-1] l=''.join(p) res.append(l) res.append(' ') temp=[] else: res.append(' ') i+=1 if temp: p=temp[::-1] l=''.join(p) res.ap...
3936d910807507e628b4a0ef156a3a8f9eac24eb
HunterLaugh/codewars_kata_python
/kata_8_Who_ate_the_cookie.py
879
4.5625
5
''' 8 kyu Who ate the cookie For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the stateme...
b44e00b7ae1786a0882c7ee6bf9a9e9d05790fcb
HunterLaugh/codewars_kata_python
/kata_8_Opposite_number.py
234
3.96875
4
''' 8 kyu Opposite number Very simple, given a number, find its opposite. Examples: 1: -1 14: -14 -34: 34 But can you do it in 1 line of code and without any conditionals? ''' def opposite(number): return -number
0927566c044f49a722fbb682799ae65f69064527
HunterLaugh/codewars_kata_python
/kata_4_Square_into_Squares._Protect_trees.py
1,742
3.609375
4
''' My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of ...
b3fef404b2e1ad7b3dee0bd829d04dfb990d4a83
Carlo369/jtc_class_code
/challenges/psuedo_code/planning_challenge.py
4,598
3.65625
4
import numpy as np my_playlist = [{'artist': 'Bilal', 'title': 'Sometimes', 'favorite': False}, {'artist': 'Chaka Khan', 'title': "I'm Every Woman", 'favorite': False}, {'artist': 'Chaka Khan', 'title': "Ain't Nobody", 'favorite': False}, {'artist': 'Parliament', ...
91ce21140d3ef1fc0a0aa0771979746d4fb330b9
Wallkon/Ejercicios-de-The-Python-Workbook
/Exercise_12_Distance_Between_Two_Points_on_Earth.py
1,929
4.5625
5
""" The surface of the Earth is curved, and the distance between degrees of longitude varies with latitude. As a result, finding the distance between two points on the surface of the Earth is more complicated than simply using the Pythagorean theorem. Let (t1, g1) and (t2, g2) be the latitude and longitude of two point...
b6a82fcd735f61bd3e64f7ed31073371e57c6cb3
nareshchari/tasks
/genrandom.py
399
3.71875
4
import random # to get different lists doesnt contain same values in between lists startvalue=1 endvalue=10 for genlist_ in range(10): # getting each time fresh list randomlist_=[] for genval in range(10): # generating random values and appending in list randomlist_.append(random.randint(st...
fad83d25211a8b0087a0de1252cfe14fa6aed2dd
robert-m-proph/Gas-Price-Analysis
/gas_price_analysis.py
117,391
4.21875
4
# Robert Propheter # Gas Price Analysis ''' Note from author: Program runs, but needs to be optimized to clear repeating code. Also need to update the program to use more functions/methods, breaking the program down into code that is better optimized. ''' # ==================== Main function to run program =======...
75aa222bb1bb19864d3cf2ccac5b4e443f64f2e6
cyan478/Celine-Amy
/occupation.py
941
3.578125
4
#Celine Yan and Amy Xu #Period 6 Soft Dev import csv import random hi = open("occupations.csv", "rb") reader = csv.reader(hi) dic = {} L = [] out = "You consult the wizard about which job you should pursue...the answer is: " def listify(L, readin): for occupation in readin: L.append(occupation) retur...
b9820c7bd8d1035661f88fcb2dd543a90dbe3044
sourav-sahaji/LSTM_tsc
/tsc_main_custom.py
9,505
3.546875
4
# The file has been downloaded as .py from the .ipynb with similar name on 22/07/2016 # coding: utf-8 # In[ ]: """LSTM for time series classification Made: 30 march 2016 This model takes in time series and class labels. The LSTM models the time series. A fully-connected layer generates an output to be classified wit...
a2a92bdb40873327349a0b6129f43838a0908103
EDalSanto/ThinkPythonExercises
/b.py
331
3.984375
4
from bisect import bisect_left def b(t,word): """ Checks whether a word is in a list and where Precondition: the words in the list are sorted_t t: list of strings word: strings Returns: True or False """ i = bisect_left(t, word) if i != len(t) and t[i] == word: return True return False print b([1,2,3],...
04097e7c0c6025741652220998b728d4184967a8
EDalSanto/ThinkPythonExercises
/gcd.py
255
3.890625
4
def gcd(a,b): if b == 0: return a else: return gcd(b,a%b) print gcd(100,44) # 4 # based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a.
b196da2d624b0f937d945eaca4f4f15f3dad2616
EDalSanto/ThinkPythonExercises
/anagrams_db.py
651
3.921875
4
from anagram_sets2 import * import shelve def store_anagrams(filename,h): """ Stores anagrams in h in shelf filename: string file name of shelf ad: dictionary that maps strings to list of anagrams """ shelf = shelve.open(filename, 'c') for word,word_list in h.items(): shelf[word]...
b98068b9164c4daa471c65ea6ec25082dd26db0f
EDalSanto/ThinkPythonExercises
/cartalk1_triple_double.py
594
4.375
4
fin = open("ThinkPython/words.txt") def triple_double(word): """Tests if a word contains three consecutive double letters""" i = 0 doubles = 0 while i < len(word)-1: if word[i] == word[i+1]: doubles += 1 if doubles == 3: return True i += 2 ...
d3d32c9a42e29956f2c7e03255e14b46837abe65
robertodessi/openCV
/anagram.py
514
3.515625
4
def aux2(toAnagram, result = "", res = []): if len(toAnagram) == 0: return result else: for x in xrange(len(toAnagram)): temp = toAnagram.replace(toAnagram[x], "", 1) res.append(aux2(temp, result + toAnagram[x])) return res def t(toAnagram, result = ""): if len(toAnagram) == 0: return [result] else:...
99859ffc10741968f6823947a3e90328c43f6dc0
TheNothingMan/Euler
/Euler 31_1.py
838
3.515625
4
import time import pdb e = "y" def count(coin_index, remainder, level): global counter #global level level +=1 while coin_index > 0 : remainder1 = remainder print("c_i:", coin_index, ", r:", remainder, ", l:", level, ", c:", counter) while remainder1 >= coinsr[coin_index] : remainder1 = remainder - coins...
5530f544dcf36717881491465060a5d12392f9fb
MLDMXM2017/ECOC_DES
/DES_new/FeatureSelection/FeatureSelector.py
8,495
3.71875
4
""" Feature Selection. Code by Tycho Zhong, Dec 6, 2017. """ import numpy as np from DataComplexity import datacomplexity class FeatureSelector(object): """ Select k best features. Parameters: k: int or 'all' Number of top features to select. The “all” option bypasses selection, for use i...
18204f87feb62b71a674a7d70e3e812d7350131d
robbyt/elb_tool
/elb_tool/user_input.py
3,273
3.78125
4
#!/usr/bin/env python import sys, argparse, os class UserInput(object): usage = "Please read --help" def __init__(self, args): ''' sets up the user input system. When setting up this class, pass sys.argv[1:] into the class, otherwise for testing pass in a dict of simulated arg...
8fe029fb32ac3abdf45470b503896dd9d61f7d85
Hammad-Ishaque/pydata-practise
/main.py
1,389
4
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ...
16ef347dfe4d1d3c867620055843fe6d861db985
Hammad-Ishaque/pydata-practise
/turing/pramp.com.py
130
3.796875
4
# Smallest substring of all characters def shortest_unique_substring(arr, str): return arr = ['x', 'y', 'z'] str = 'xyyzyzyx'
9bd1d9c2a6a087a028eed2119926ea5bc3f94811
Hammad-Ishaque/pydata-practise
/DesignPatterns/FactoryPattern.py
868
4.125
4
from abc import ABCMeta, abstractmethod # What particular instance to create class IPerson(metaclass=ABCMeta): @abstractmethod def person_method(self): """ :return: """ class Student(IPerson): def __init__(self): self.name = "I am Student" def person_method(self):...
617b1997e430a67fe48a93f038640e65611b0acd
mat2uken/myojin
/auth/tools.py
1,480
3.59375
4
import hashlib md5_constructor = hashlib.md5 md5_hmac = md5_constructor sha_constructor = hashlib.sha1 sha_hmac = sha_constructor UNUSABLE_PASSWORD = '!' # This will never be a valid hash def to_str(x): if isinstance(x, str): return x elif isinstance(x, unicode): return x.decode("utf8") asse...
d9405765b49bb85aef0a081ad585fffa5f571d12
rajjoshi96/Hackerrank
/harddrive.py
647
3.796875
4
#!/bin/python3 import os import sys # # Complete the hardDrive function below. # def hardDrive(k, hdds): print(k) print(hdds) sum=0 for x in range(len(hdds)): for y in range(len(hdds)): sum=hdds[x]+hdds[y] print("sum=",sum) # # Write your code here. # if __...
468d48bc6115d475d469655f01dbfc3c714f5210
Ruanfc/lista3_python_para_engenharia
/10/main.py
748
3.90625
4
#!/usr/bin/env python3 info = dict() while(True): e = input("Insira nome e idade separador por espaço: ") if e == "sair" or e == "quit" or e == "exit": break dados = e.split() if len(dados) > 2: print("Use apenas um espaço para inserir dados") continue try: info.upda...
53fe220d2fcb589571740e9f1998c8977385b350
KazZBodnar/pythoncalc
/main.py
1,793
4.3125
4
import math #help = input("PythonCalc V 1.0; Say 'help' for more info, and 'ready' to start the calculator.") #if help== "help" or "Help": # print("Signs: '+', '-', '*', '/', '^2', 'sqrt', '^3', '!', 'power'.") #else: print("PythonCalc V 1.0 type help for a list of commands") sign = input("What sign should I use?") if...
eb39c96d98e1e0813a65215471616a5fe75c71ad
hermineavagyan/OOP
/userClass.py
2,077
4.125
4
class User: #defining a class attriute bank_name = "First Dational Dojo" #creating the class constructor def __init__(self, name, email_address): self.name = name self.email = email_address self.account_balance = 0 # increases the user's balance by the amount specified def make_depo...
2b9f1803a50c7cb1a267e3d1c583a9b4a5e351d7
ellennugroho/themis-ml
/themis_ml/datasets/german_credit_data_map.py
6,299
3.5625
4
"""Define data normalization map for German Credit Data. See here for more details: https://archive.ics.uci.edu/ml/datasets/Statlog+(German+Credit+Data) """ import pandas as pd from .data_types import VariableType, Variable, VariableMap # A categorical map for variables in the german credit dataset. # This map is a...
c069162616ae7c88cd340cf425e63b90e0770f46
cs-fullstack-2019-spring/python-loops-cw-leejr1983
/PythonLoopsCW.py
1,708
4.34375
4
from _ast import If def main(): # problem1() #problem2() #problem3() problem4() # Exercise 1: # Print -20 to and including 50. # Use any loop you want. def problem1(): for numbers in range(-20,51): print (numbers) # Exercise 2: # Create a loop that prints even numbers from 0 to ...
3fada3a7b38abbb5ca321208a19b4a757f80db95
jcamier/mke_scikit
/ai.py
980
3.71875
4
class ToBe(object): no_function = 0 function = 1 life = function death = no_function human = 'Homo sapiens sapiens' i = '' me = '' cause = '' def ai_exist(self): i = 1 me = 'not God' if i == 1: print (self) print("I am alive!"...