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
88ae5b90c736580fe0a6d9f195198859643165fb
jecht1014/book
/AlgorithmPictureBook/main.py
843
3.578125
4
import sort import time import random #再帰条件の変更 import sys sys.setrecursionlimit(100000) l = list(range(3000)) random.shuffle(l) start_time = time.time() sorted_list = sort.bubble_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.selection_sort(l) print('time:{0...
367c5957b54fa406d70a501e853213a6c31b3df7
joelamajors/TreehouseCourses
/Python/Learn Python/1 Basics/Stage 3/containment.py
568
3.796875
4
# in if "java" in "javascript": print(True) else: print(False) if 5 in [1,2,3]: print(True) else: print(False) if "cheese" in "cheeseshop": print(True) else: print(False) cheeseshop = [] if "cheese" in cheeseshop: print(True) else: print(False) days_open = ['Monday', 'Tuesday', 'Wedn...
2e8d1f5ff5523cd0707efe331b47fd235fe00220
joelamajors/TreehouseCourses
/Python/Learn Python/1 Basics/Stage 2/index.py
268
3.71875
4
# indexes begin at 0 # can index from the end using negative nos >>> alpha = 'abcde' >>> alpha.index('a') 0 >>> 'abcabc'.index('a') 0 alpha_list = list(alpha) alpha_list.index('b') 1 alpha_list.index('cd') 2 alpha_list.index('ce') error alpha[0] a alpha_list[2] 'c'
a9067a7adee78d3a72e2cd379d743dd360ed2795
joelamajors/TreehouseCourses
/Python/Learn Python/2 Collections/4 Tuples/intro_to_tuples.py
578
4.5625
5
my_tuple = (1, 2, 3) # tuple created my_second_tuple = 1, 2, 3 # this is a tuple too # the commas are necesary! my_third_tuple = (5) # not a tuple my_third_tuple = (5,) # parenthesis are not necessary, but helpful. dir(my_tuple) # will give you all the stuff you can do. Not much! # you can edit _stuff_ within a ...
8824bf993e2383393d16357e6a318fd27e8e0525
joelamajors/TreehouseCourses
/Python/Learn Python/2 Collections/5 Sets/set_math_challenge.py
2,248
4.4375
4
# Challenge Task 1 of 2 # Let's write some functions to explore set math a bit more. # We're going to be using this # COURSES # dict in all of the examples. # _Don't change it, though!_ # So, first, write a function named # covers # that accepts a single parameter, a set of topics. # Have the function return a list of...
b169b9c1989b06af6287ce0a14575612b13e7600
joelamajors/TreehouseCourses
/Python/Learn Python/2 Collections/3 Dictionaries/teachers.py
3,186
4.125
4
# This challenge has several steps so take your time, read the instructions # carefully, and feel free to experiment in Workspaces or on your own computer. # For this first task, create a function named num_teachers that takes a single # argument, which will be a dictionary of Treehouse teachers and their courses. #...
ec730dce1940f4c4cb07b131c219c288a8c43b78
joelamajors/TreehouseCourses
/Python/Learn Python/3 Object-Oriented Python/1 Instant Objects/instant_objects_init_challenge.py
993
4.0625
4
# Challenge 1 # Our Student class is coming along nicely! # I'd like to be able to set the name attribute at the same time that # I create an instance. Can you add the code for doing that? # Remember, you'll need to override the __init__ method. class Student: name = "Your Name" def __init__(self, name, **k...
135b08e8fbbf31e611e7c8e0e3f0abb4c83f1c71
Nick-Nch/gb_1lesson_task
/task-1.py
245
4.125
4
a = 'Hello!' first_name = input('Введите ваше имя:') last_name = input('Введи вашу фамилию: ') age = input('Введите ваш возраст: ') print(a + ' ' + first_name + ' ' + last_name + ' ' + str(age))
6bda2d2e367999193ba547a9e2ddc6a179c71e7d
Alba126/Laba21
/zad4.py
1,509
3.5625
4
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * from tkinter import filedialog as fd from tkinter import messagebox as mb def insert_text(): file_name = fd.askopenfilename() try: f = open(file_name) s = f.read() text.insert(1.0, s) f.close() except(Fil...
53af822d0be8545dc514de1187943879caf85a07
Emilio-MC/portafolio1
/Reversa Numero.py
1,290
4
4
""" Entrada: Un numero entero mayor o igual a 0 Salida: La cantidad de digitos del numero Restricciones: Tiene que ser un numero entero positivo mayor o igual a 0 """ def CantidadDigitos(num): if (isinstance (num,int) and num >=0): if (num<10): return 1 else: ...
083dc11e75ae612a60edd5b6e311ae4d4b7ada26
brian-sherman/Python
/C859 Intro to Python/Challenges/11 Modules/11_9 Extra Practice/Task6.py
842
4.0625
4
""" Complete the function to return the number of leap years in the list import calendar # Complete the function to return the number of leap years in the list def countLeapYears(yearList): # Student code goes here # expected output: 2 print(countLeapYears([2001, 2018, 2020, 2090, 2233, 2176, 2200, 2982])) # expe...
e0dc49212a72b8f58ba69c192bf48e41718d93c5
brian-sherman/Python
/C859 Intro to Python/Challenges/11 Modules/11_9 Extra Practice/Task1.py
434
4.21875
4
""" Complete the function that takes an integer as input and returns the factorial of that integer from math import factorial def calculate(x): # Student code goes here print(calculate(3)) #expected outcome: 6 print(calculate(9)) #expected outcome: 362880 """ from math import factorial def calculate(x): f = ...
4b775221b8af334d4b2f8b9af0c64ecd2d3c9724
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_5_1_Multiplication_Table.py
548
4.25
4
""" Print the two-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output for the given program: 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9 """ mult_table = [ [1, 2, 3], [2, 4, 6], [3, 6, 9] ] for row in mult_table: for element in row: list_len = len(row) current_id...
fd3d0f0a14900b339535fc94ef21b59619ba66e1
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_8_2_Histogram.py
797
4.96875
5
""" Here is a nested loop example that graphically depicts an integer's magnitude by using asterisks, creating what is commonly called a histogram: Run the program below and observe the output. Modify the program to print one asterisk per 5 units. So if the user enters 40, print 8 asterisks. num = 0 while num >= 0...
6da6609432fd57bc89e4097da96dcd60e80cb94c
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_15_1_Nested_Dictionaries.py
2,843
4.96875
5
""" The following example demonstrates a program that uses 3 levels of nested dictionaries to create a simple music library. The following program uses nested dictionaries to store a small music library. Extend the program such that a user can add artists, albums, and songs to the library. First, add a command that ...
ffd50de6b5a8965a8b34db611bd115d2939df135
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_3_1_Iteration.py
1,068
4.4375
4
""" Here is another example computing the sum of a list of integers. Note that the code is somewhat different than the code computing the max even value. For computing the sum, the program initializes a variable sum to 0, then simply adds the current iteration's list element value to that sum. Run the program below...
f1b2c6a2815b2621cab190582196521ec04da9e2
brian-sherman/Python
/C859 Intro to Python/Challenges/07 Functions/7_17_1_Gas_Volume.py
678
4.375
4
""" Define a function compute_gas_volume that returns the volume of a gas given parameters pressure, temperature, and moles. Use the gas equation PV = nRT, where P is pressure in Pascals, V is volume in cubic meters, n is number of moles, R is the gas constant 8.3144621 ( J / (mol*K)), and T is temperature in Ke...
f16de52263a33b9000c36699550698abdbee0c3a
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_5_1_Printing_List.py
251
4
4
""" Write an expression to print each price in stock_prices. Sample output for the given program: $ 34.62 $ 76.30 $ 85.05 """ # Apple (APPL) stock prices 2005-2007 stock_prices = [34.62, 76.30, 85.05] for price in stock_prices: print('$', price)
0c123a95902de5efa3ecb815f22a3d242e376623
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_4_2_Print_Output_Using_Counter.py
330
4.46875
4
""" Retype and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks. while num_printed != num_stars: print('*') Sample output for the correct program when num_stars is 3: * * * """ num_stars = 3 num_printed = 0 while num_printed != num_stars: print('*') num_pri...
de8809d34f4bd91b00fb0b56d2835b3464c6ce3a
brian-sherman/Python
/C859 Intro to Python/Challenges/08 Strings/8_4_5_Area_Code.py
256
4.21875
4
""" Assign number_segments with phone_number split by the hyphens. Sample output from given program: Area code: 977 """ phone_number = '977-555-3221' number_segments = phone_number.split('-') area_code = number_segments[0] print('Area code:', area_code)
2f13722b0bd4d477768080b375bdd904af9da065
brian-sherman/Python
/C859 Intro to Python/Challenges/08 Strings/8_6 Additional Practice/Task_2_Reverse.py
294
4.21875
4
# Complete the function to return the last X number of characters # in the given string def getLast(mystring, x): str_x = mystring[-x:] return str_x # expected output: IT print(getLast('WGU College of IT', 2)) # expected output: College of IT print(getLast('WGU College of IT', 13))
0416f7bd9af4ef2845a77eb966ab0a21afd7fd64
brian-sherman/Python
/C859 Intro to Python/Boot Camp/Week 1/2_Calculator.py
1,871
4.4375
4
""" 2. Basic Arithmetic Example: Write a simple calculator program that prints the following menu: 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Quit The user selects the number of the desired operation from the menu. Prompt the user to enter two numbers and return the calculation result. Exa...
444195237db2c8f053a44b172038335f9d02567e
brian-sherman/Python
/C859 Intro to Python/Challenges/06 Loops/6_8_1_Print_Rectangle.py
256
4.5
4
""" Write nested loops to print a rectangle. Sample output for given program: * * * * * * """ num_rows = 2 num_cols = 3 for row in range(num_rows): print('*', end=' ') for column in range(num_cols - 1): print('*', end=' ') print('')
3cf756ebdd38a6a5ff233af1ba998c12f7ed1fa3
brian-sherman/Python
/C859 Intro to Python/Boot Camp/Week 1/8_Tuple_Example.py
534
4.625
5
""" 8. Tuple Example: Read a tuple from user as input and print another tuple with the first and last item, and your name in the middle. For example, if the input tuple is ("this", "is", "input", "tuple"), the return value should be ("this", "Rabor", "tuple") Example One: Enter your name to append into the tuple: ...
0435c9456e5a0497f827d003c40499b34879f048
TatyanaVysotskaya21/common
/python_functionality/homework.py
3,334
3.859375
4
from typing import List, Dict, Union, Generator # We will work with such dicts ST = Dict[str, Union[str, int]] # And we will put this dicts in list DT = List[ST] def task_1_fix_names_start_letter(data_list) -> DT: """ Make all `names` field in list of students to start from upper letter Examples: ...
7f50a6f44b280bc60fcde9509f4b66456fdf1cbc
vahid242/python_WorkBook
/1. operation/operation.py
434
3.8125
4
# dir(list) temp=[5,8,6] print(temp) temp.append(7) print(temp) temp.clear() print(temp) temp=[5,8,6] print(temp) print(temp.index(8)) temp=[5,8,6,4,3,8] print(temp.index(8,2)) temp.remove(4) print(temp.__getitem__(1)) print(temp[1]) print(temp[1:4]) print(temp[:4]) print(temp[2:]) print(temp[-1]) print(temp[-5]) name=...
46fb132e794de103f5aecaaaf1db42c25a91bcfe
jmbjones/python
/alter.py
12,332
3.578125
4
''' Alter A program that will assign a level of uniqueness to a Search_Term class instance and then alter by broadening or narrowing the term as determined by the level of uniqueness Morgan Jones Last Updated: 7/28/2011 by Morgan Jones ''' import string, cPickle from sanitize import * from itertools impor...
81d7b794c5337ccd8c684ae1331a5849c0256b60
AlphaAlpacaa/Project-Euler-s-Solutions
/Project Euler's Solutions/Circular_primes.py
675
3.671875
4
import sympy def all_numbers(x): numbers = [] number = str(x)*2 for i in range(len(str(x))): numbers.append(int(number[i:i + len(str(x))])) return numbers primes = sympy.sieve.primerange(2,1000000) circular_primes = [] for prime in primes: if prime in circular_primes: continue ...
8d60911b7cabdd4ff2fc92d67beb6feb2a99ff02
AlphaAlpacaa/Project-Euler-s-Solutions
/Project Euler's Solutions/Lattice_paths.py
154
3.640625
4
def fact(x): factorial = 1 for i in range(1,x+1): factorial *= i return factorial steps = fact(40) / (fact(20)*fact(20)) print(steps)
263fcf3812654b97c32d708a65fdebd8778c3fb5
AlphaAlpacaa/Project-Euler-s-Solutions
/Project Euler's Solutions/Goldbach's_other_conjecture.py
699
3.90625
4
"""It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as ...
ca65106d680f9386f6c963404c4945c30509eeda
djallel/DM-ALGO-Python
/Exo1/Exo1.py
466
3.6875
4
print("Exo 1 Ecrire une fonction qui a en paramètre un tableau non vide et qui renvoie le" "plus petit élément d’un tableau non vide") tableau=[1,2,4,5]; def plusPetitElementDunTableau(tableau): # if tableau non vide renvoyer le min mini = tableau[0] for i in tableau: if i <= mini: ...
cd81e784543ed2bb0e70a2108efdc9ebeb4ae952
RyanLongRoad/Iteration
/n! development exercise.py
219
3.578125
4
#Ryan Cox #16/10/14 (fixed on 19/20/10) #Development exercis - factorial program n = int(input("input value of n: ")) if n>=0: f = 1 while (n > 0): f = f * n n = n - 1 print(f)
dbcc90b655b3a457698bca15caac0a8f9fdfa49c
mida-hub/hobby
/practice/design_pattern/21_strategy.py
3,927
3.5625
4
# Strategy from abc import ABC, abstractmethod from enum import Enum from random import randint class HandType(Enum): GUU = 0 CHOKI = 1 PAA = 2 @classmethod def show_all(cls) -> [int]: return list(map(lambda c: c.value, cls)) class Hand: def __init__(self, hand_index): if not...
1f6874ea0ea210791ce57f954beee8d16755bee6
mida-hub/hobby
/atcoder/python/beginner/abc247/C/main.py
645
3.546875
4
#!/usr/bin/env python3 import sys def solve(N: int): s = [] s.append('0') s.append('1') for n in range(2, N+1): s.append(f'{s[n-1]}+{n}+{s[n-1]}') print(s[N].replace('+', ' ')) return # Generated by 2.12.0 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default ...
d0fc518cc4c53fea46a2b45ac08c2110a3e693b2
mida-hub/hobby
/atcoder/python/templates/binary_search.py
533
3.8125
4
def is_ok(arg): # 条件を満たすかどうか?問題ごとに定義 pass def meguru_bisect(ng, ok): ''' 初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す まずis_okを定義すべし ng ok は とり得る最小の値-1 とり得る最大の値+1 最大最小が逆の場合はよしなにひっくり返す ''' while (abs(ok - ng) > 1): mid = (ok + ng) // 2 if is_ok(mid): ok = mid ...
2427d252d4fc0235870e745cb7814e0b9e4c2ac6
mida-hub/hobby
/practice/design_pattern/11_flyweight_01.py
964
3.53125
4
# Flyweight class User: def __init__(self, name='', age=''): self.__name = name self.__age = age @property def name(self): return self.__name @name.setter def name(self, name): self.__name = name @property def age(self): return self.__age ...
227ed7f2d235d4eec29fdfc74cdaaf5e9c6b625e
mida-hub/hobby
/practice/python/basic/061_070/067_dfs.py
1,743
3.5625
4
def deep_first_search(H, W, S): """ H: 高さ W: 幅 S: 文字列のリスト """ def search(x, y): # 迷路の外か壁 if x < 0 or H <= x or y < 0 or W <= y or S[x][y] == '#': return False # 以前に到達している場合 if reached[x][y]: return False # 探索済みフラグ reached[x][y] = True ...
e8e8832fc68a24da1877221e6ba996eeacf9358e
mida-hub/hobby
/practice/design_pattern/09_decorator.py
1,303
3.734375
4
# Decorator from abc import ABC, abstractmethod class Component(ABC): @abstractmethod def operation(self): pass class ShowCharComponent(Component): def __init__(self, char): self.__char = char def operation(self): print(self.__char * 20) class ShowDecorator(Component): ...
0510324c9d427978b0738b55c1a813e440eb84c4
mida-hub/hobby
/practice/python/basic/121_130/121_pandas.py
312
3.671875
4
import pandas as pd dtype = {'name': 'object', 'number': 'int8'} df = pd.read_csv('in_sample.csv', dtype=dtype) print(df.head()) # print(df.dtypes) # print(df.memory_usage(index=False)) df['number'] = df['number'] + 3 print(df.head()) numbers = df.number numbers += 3 df['number'] = numbers print(df.head())
75b708bfa0b493375cd0a4c4100d2ea26623f7f5
mida-hub/hobby
/atcoder/python/beginner/abc250/B/main.py
907
3.828125
4
#!/usr/bin/env python3 import sys def solve(N: int, A: int, B: int): for i in range(N * A): for j in range(N * B): flag = f"{(i//A) % 2}{(j//B) % 2}" # print(f"{(i//A) % 2}{(j//B) % 2} ", end="") if flag == "00" or flag == "11": print('.', end="") ...
1123f76b1322d2dbc0c01abcdc843ea1784b424d
mida-hub/hobby
/atcoder/python/beginner/abc243/A/main.py
895
3.796875
4
#!/usr/bin/env python3 import sys def solve(V: int, A: int, B: int, C: int): while True: V -= A if V < 0: print('F') return V -= B if V < 0: print('M') return V -= C if V < 0: print('T') ...
8a00632b46ee735a0c84b42d69044a4adbeef9ac
mida-hub/hobby
/practice/design_pattern/05_prototype.py
2,286
3.84375
4
# Prototype from abc import ABC, abstractmethod from copy import deepcopy class Prototype(ABC): @abstractmethod def use(self, msg): pass @abstractmethod def _clone(self): pass class MessageBox(Prototype): def __init__(self, decoration_char): self.__decoration_char = decor...
6f16863f16868e645188545e5c85ace7a32258e7
mida-hub/hobby
/practice/python/basic/051_060/058_inner_func_nonlocal_var.py
358
3.765625
4
# inner関数 / ノンローカル関数 def outer(): outer_var = '外側の変数' def inner(): nonlocal outer_var outer_var = '内側の変数' print('inner') print(f'outer_var = {outer_var}, id = {id(outer_var)}') inner() print('outer') print(f'outer_var = {outer_var}, id = {id(outer_var)}') outer()
e309e3a641c69e2ac6b149a1d6cba385a77ae34e
gbmhunter/AdventOfCode2018
/day04/main.py
2,242
3.546875
4
def get_minute(line): colon_pos = line.find(':') minute_str = line[colon_pos + 1: colon_pos + 3] return int(minute_str) input = [] with open('input.txt', 'r') as file: for line in file: input.append(line.strip()) input.sort() guard_sleep_times = {} total_guard_sleep_time = {} curr_min = 0 f...
d77aa08a423e57c4868dcaed67c1fe83855edd1a
Kadam-Rutuja/Class_and_Object_in_Python
/pass_statement.py
70
3.5625
4
i = 'A' #print the ASCLL print("The ASCII value of" +i+ "is",ord(i))
d4a8c471e20e1d9955251f1643b72e4417363138
bliiben/pythonOS
/CPU.py
1,575
3.53125
4
import OSException def execute(program, memory, state=0,numberOfOperation=1): print (program,state,memory) maxOp = state + numberOfOperation while state < len(program) and state < maxOp: #type of operation if(program[state][0]=='r'): print("operation "+str(state)+" is assign") doAssign(program[state],me...
94a8e38b9007c8c833d63256960fab13cd34e430
ACS6132-Anasazi-Model/Anasazi-Model
/fileEditor.py
1,961
3.703125
4
import csv #def readData1(): # file = open("target_data.csv","r") # data = file.read() # print(data) def readData(): data = [] file = open("target_data.csv","r") csv_read = csv.reader(file, delimiter=',') for row in csv_read: data.append(row) return data #print(...
17645e44fd305be416337c7e7f90ad3faa48dbfd
kevm192/KDD_Meetup_Presentation
/NeuralNets/sampleNeuralNetwork.py
1,020
3.609375
4
import os import random from neuralnetwork import * inputs = [[0,0],[0,1],[1,0],[1,1]] targets = [[0],[1],[1],[0]] random.seed(0) # to get repeatable results input_size = 2 # each input is a vector of length 2 num_hidden = 2 # we'll have 2 neurons in hidden layer output_size = 1 #we need 10 outputs for each input...
f4f6c625ca359e0b95b5ab9ab0853bb95bf048d0
MadSounds6/Zadanie_rekrutacyjne
/are_anagram.py
823
3.734375
4
def are_anagrams(s1, s2, s3): """ Funkcja sprawdza czy łańcuchy znaków są swoimi wzajemnymi anagramami :param s1: pierwszy łańcuch znaków :param s2: drugi łańcuch znaków :param s3: trzeci łańcuch znaków :return: True jeśli łańcuchy znaków są anagramami, False jeżeli nie są """ # Funkcja...
c0b651bfa55c1571da9146356c34e6198f872d5d
ilooner/stock-analysis-tools
/plot_aggregates.py
394
3.546875
4
import click import pandas as pd import plotly.express as px @click.command() @click.argument('source') def main(source): df = pd.read_csv(source) df['timestamp'] = df['timestamp'].transform(lambda ts: pd.to_datetime(ts, unit='ms', origin='unix')) fig = px.line(df, x='timestamp', y=["lowestPrice", "average...
f4a2eba123ada1276a4bbae8f7dff350ea206d70
ahwang16/W4111-f18
/Projects/HW1-Templates/Python/CSVTable.py
5,129
3.921875
4
import csv # Python package for reading and writing CSV files. import copy # Copy data structures. import sys,os,json # You can change to wherever you want to place your CSV files. rel_path = os.path.realpath('./Data') class CSVTable(): # Change to wherever you want to save the CSV files. ...
b5032ca6f75c856e059ccf974a9429d063cd5cf8
ahwang16/W4111-f18
/HW_Solutions/HW1/CSVDataTable.py
23,289
3.6875
4
import csv # Python package for reading and writing CSV files. import copy # Copy data structures. import os # Use for some directory functions # Some custom exceptions that convert technology specific exceptions to # more problem specific and intuitive exceptions. import DataTableExceptions...
c06f5adda64ce907690da5632e137e9c19d1f2a9
imharrisonlin/Runestone-Data-Structures-and-Algorithms
/Algorithms/ParseTree.py
1,748
3.78125
4
# Parse tree for mathamatical expression: # 1. How to build a parse tree from a fully parenthesized mathematical expression. # 2. How to evaluate the expression stored in a parse tree. # 3. How to recover the original mathematical expression from a parse tree. # Part 1 build a parse tree from BasicDS import Stac...
68150df94d2940bb980649e15c56a07194cb59fb
imharrisonlin/Runestone-Data-Structures-and-Algorithms
/Algorithms/Sorting/Quick_Sort.py
2,138
4.21875
4
# Quick sort # Uses devide and conquer similar to merge sort # while not using additional storage compared to merge sort (creating left and right half of the list) # It is possible that the list may not be divided in half # Recursive call on quicksortHelper # Base case: first < last (if len(list) <= 1 list is sorted) #...
60c6f8b69764f33105014f67dd3187f80a4134da
mhope-2/python_unit_tests
/test_employee.py
2,129
3.609375
4
import unittest from employee import Employee from unittest.mock import patch class TestEmployee(unittest.TestCase): @classmethod def setUpClass(cls): """ Runs once at the very beginning before the test""" print("setUpClass") @classmethod def tearDownClass(cls): """ Runs once...
4ca185b8b5ef579873526f2093bbf3a05cd84f82
alu-rwa-dsa/implementations-paularah
/week2/question_one.py
325
4.0625
4
""" A simple function that replaces all the whitespaces in a string with a single whitespace using regular expressions """ import re def white_space(text): if type(text) != str: raise ValueError # Whitespace pattern we're searching for pattern = re.compile(r'\s+') return re.sub(pattern, ' ', t...
25eed7cce916e7cdc176aaa75205983f652a84a9
souvikban16/codechef
/ATM.py
161
3.96875
4
print("Enter the money and the account balance") while(True) tran=int(input()) balance=float(input()) if tran<=2000 and balance<=2000 break
f531522aa5c55574eaf0faef881abfc0337d7f4a
byteh/learn-python3
/leetcode/460_lfu_cache.py
2,641
3.515625
4
#https://leetcode.com/problems/lfu-cache/description/ import time class LFUCache(object): def __init__(self, capacity): """ :type capacity: int """ curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print "%s --- capacity[%d] --- "%(curTime, capacity) sel...
4b9ee452522521a39495d7e059c76b4393cbc331
byteh/learn-python3
/chapter-1/lambda_1-16-19.py
651
3.96875
4
#!/usr/bin/python #coding:utf-8 #1.16.2 #使用 lambda 创造匿名函数 a = [10,20,30] def do_list(a_list, func): total = 0 for element in a_list: total += func(element) return total print do_list(a, lambda x:x**2) print do_list(a, lambda x:x+5) # b = [lambda x: x%3 ==0 for x in a] # print b #1.17 使用map映射函数...
b18baf986c1bf8ce1c6bc90cfb555f130d014003
abriggs914/CS2613
/Labs/lab20/test_expr.py
920
3.65625
4
from expr import Expr from copy import deepcopy six_plus_nine = Expr('+', 6, 9) six_times_nine = Expr('*', 6, 9) compound1 = Expr('+', six_times_nine, six_plus_nine) compound2 = Expr('*', six_times_nine, compound1) compound3 = Expr('+', compound2, 3) def test_equality(): assert six_plus_nine == deepcopy(six_pl...
e851369810638bbb327a4433b34f5ae40adabae7
abriggs914/CS2613
/Labs/lab14/divisive.py
232
3.5625
4
#no exception handling def fraction(a,b): if(b == 0): return 'NaN' else: return a/b #with exception handling def fraction2(a,b): try: return a/b except ZeroDivisionError: return 'NaN'
d48c43ebc0e0476addae92a7e0cf9d8efd200563
abriggs914/CS2613
/ExamPrep/Fizzbuzz.py
617
3.671875
4
#!/usr/bin/python3 class FizzBuzz: def __init__(self, max): self.n=1; self.max=max self.__iter__() def __next__(self): a = self.n self.n = a + 1 if a <= self.max: if a % 3 == 0 and a % 5 == 0: return 'FizzBuzz' elif a % 3 == 0: ...
634f49accc2aeecc58d76e14fb7070b74878f5b7
ctuck99/matplotlib
/x-axis_log_scale.py
211
3.671875
4
import matplotlib.pyplot as plt # exponential function x = 10^y datax = [ 10**i for i in range(5)] datay = [ i for i in range(5)] # convert x-axis to Logarithmic scale plt.xscale("log") plt.plot(datax, datay)
00a8e4b2db4d6acda89eab67ac236b992593ef90
jccf12/python-minerva
/Fall 2017 to Fall 2018/heapq.py
1,715
3.640625
4
#heappush, heappop, and heapify def max_heapify(A, i): n = len(A) l = 2*i+1 r = l+1 if l <= n-1: if A[l] > A[i]: largest = l else: largest = i else: largest = i if r <= n-1: if A[r] > A[largest]: largest = r if largest != i...
42bcf12fd806610449df7c2609414e7d02e46a96
jccf12/python-minerva
/Fall 2017 to Fall 2018/pre-class7.1.py
1,293
3.65625
4
import heapq def add_to_median_heap(minh, maxh, elem): heapq.heappush(minh,elem) heappush(maxh,elem) def median(minh,maxh): pass def max_heapify(A, i): n = len(A) l = 2*i+1 r = l+1 if l <= n-1: if A[l] > A[i]: largest = l else: largest = i else:...
15456a0158d90a90cf531cbfb1e63c9f8fd07ab9
chapmanjamesg/coinsToCash
/coinsToCash.py
1,074
3.75
4
import math def calc_dollar(): piggyBank = { "pennies": 342, "nickels": 9, "dimes": 32, "quarters": 40 } dollarAmount = 0 for coins in piggyBank: if coins == "pennies": coins * .01 += dollarAmount # elif coins == "nickles": # coins * .05 += dollar...
e09cb075d298ad5df82ff20177c21ada11b1b7fa
KalinaMichal/4sem
/Python/Lista4/z4.py
994
3.546875
4
#!/usr/bin/python3 import math from inspect import getfullargspec def overload(function): MyFunc.functions[(function.__name__, len(getfullargspec(function).args))] = function def overrider(*args, **kwargs): return MyFunc(function.__name__)(*args, **kwargs) return overrider class MyFunc: fu...
a0f1b01f87f886f530aea9d2aba31bcced4e67e6
KalinaMichal/4sem
/Python/Lista3/z4.py
498
3.765625
4
#zakomentowane jest inna metoda def quick(lista): if lista == []: return [] else: pivot = lista[0] smaller = quick(list(filter(lambda x: x < pivot, lista[1:]))) #smaller = qsort1([x for x in list[1:] if x < pivot]) bigger = quick(list(filter(lambda y: y >= pivot, lista[1...
7875b1b97522bc8f42901d184aa5320073ead22f
gakhromov/SelfStudy
/Grocking algorithms/my own stuff/Sieve of Eratosthenes.py
749
3.671875
4
def clear_lst(lst): n = len(lst) i = 0 while i < n: if lst[i] is None: del lst[i] n -= 1 else: i += 1 return lst def eratosthenes(n): if n < 2: return nums = list(range(n+1)) curnum = 2 todel = 1 while curnum is not None: ...
68ac0a40d9fbd9020e7b83a8f94d1754e8f45b4f
gakhromov/SelfStudy
/Grocking algorithms/4.1.py
142
3.640625
4
def sumlist(l:list)->int: if(l==[]): return 0 else: return l[0] + sumlist(l[1:]) l = [1,2,3,4] print(sumlist(l))
47a4339979a4787b4e44cb5e6ff519033bbfe2e3
avkramarov/gb_python
/lesson 5/Задание 1.py
600
4.25
4
# Создать программно файл в текстовом формате, записать в него построчно данные, # вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка. lines = [] new_item = input("Введите значение >>>") while new_item != "": lines.append(new_item) new_item = input("Введите значение >>>") ...
0eec248e00713cf6ac52bdad5b9012cca2882f98
avkramarov/gb_python
/lesson 8/Задание 1.py
1,699
3.625
4
# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки # формата «день-месяц-год». В рамках класса реализовать два метода. # Первый, с декоратором @classmethod, должен извлекать число, месяц, год и преобразовывать # их тип к типу «Число». Второй, с декоратором @staticmethod, дол...
ff920ddb5e615cc591f8daef82f41fc8782d28c9
avkramarov/gb_python
/lesson 3/Задание 2.py
1,029
3.671875
4
# Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, # город проживания, email, телефон. Функция должна принимать # параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def new_func(*users_data): user...
b18daeacb7de198085e4064b05755f63a49bb040
avkramarov/gb_python
/lesson 4/Задание 7.py
866
4.25
4
# Реализовать генератор с помощью функции с ключевым словом yield, # создающим очередное значение. # При вызове функции должен создаваться объект-генератор. # Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, # а в цикле необходимо выводить только пер...
ad278895dc6fa22915d4ffaea08e3a4ecd0cef4d
avkramarov/gb_python
/lesson 5/Задание 4.py
681
3.703125
4
# Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. with open("Задание 4.txt", "w+", encoding="UTF-8") as my_file: line = input("Введите цифры через пробел >>> ") my_file.writeline...
5f415e92bf5a802eeb48d8945659721d8a5d0a6d
cvijayarenu/programming
/euler/strfunc.py
699
3.890625
4
def longest_repetatinve_substring(str): matrix = [[0 for i in range(len(str))] for i in range(len(str))] for i, x in enumerate(str): for j, y in enumerate(str): if i == 0 or j == 0: matrix[i][j] = 1 if x == y else 0 elif x == y: matrix[i][j] = matr...
2478e39c4a4a7cbf21cc9f614aae6f500d4d9e1e
cvijayarenu/programming
/euler/15.py
399
3.609375
4
def recPath(rows, coloum): result = [[0 for x in range(coloum + 1)] for y in range(rows + 1)] for r in range( rows + 1): for c in range( coloum + 1): if r == 0 or r == 0: result[r][c] = 1 else: result[r][c] = result[r-1][c] + result[r][c-1] re...
67f62c0043d1b2bc66d146f0cdd137b0f3dbc30b
system-error/random_mean_mode_range_list
/list.py
1,006
3.734375
4
import random def randomList(): randomlist = random.sample(range(1,100),50) randomlist.sort() return randomlist def meanOfList(randomlist): return sum(randomlist) / float(len(randomlist)) def medianOfList(randomlist): median = int((len(randomlist)+1) / 2) print (median) re...
f6e9c673bc283396ea8aa33cd2cb2c9ab18f9399
Ra1nyHouse/PACE2017
/utils.py
247
3.828125
4
from math import sqrt def distance(a, b): ''' Parameter: a, b are two tuples in form of (x, y) that contains the coordinate of two locations Return: The distance between a and b ''' return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
ce1e57eb3168263137047a967c2223b65017ec89
kzmorales92/Level-2
/M3P2a.py
250
4.3125
4
#Karen Morales # 04/22/19 #Mod 3.2b #Write a recursive function to reverse a list. fruitList = ["apples", "bananas", "oranges", "pears"] def reverse (lst) : return [ lst[-1]]+ reverse (lst[:-1]) if lst else [] print (reverse(fruitList))
9b2945fae4ecc911007b7dbdb0a78d4d847eed15
vitay/ANNarchy_future
/ANNarchy_future/parser/RandomDistributions.py
482
3.578125
4
class Uniform(object): def __init__(self, name, min, max): self.name = name self.min = min self.max = max def human_readable(self): return "Uniform(" + str(self.min) + ", " + str(self.max) + ")" class Normal(object): def __init__(self, name, mu, sigma): self....
d2d5cf22e250582a66760d0a5d9dfb8e2c5839e7
claudiogar/learningPython
/problems/ctci/e3_4_queueWithStacks.py
691
3.90625
4
# CTCI e3.4: Implement a MyQueue class which implements a queue using two stacks. class MyQueue: def __init__(self) -> None: self.s1 = [] self.s2 = [] self.phase = 0 def push(self, e:int): if self.phase == 1: while len(self.s2) > 0: o = self.s2.p...
0dd146fe487c1796295f1e46429906f23854656b
claudiogar/learningPython
/algos/quicksort.py
847
3.890625
4
import random ################### # Complexity: # Time: # Worst case (pivot is consistently the greatest element): O(Nˆ2) # Average case: we halve the array with each call of quicksort O(N*logN) ################## def quicksort(array): quicksort_inplace(array, 0, len(array)-1) def quicksort_inplace(array, ...
85d986e6a42307635cd237b666f0724a27537b16
claudiogar/learningPython
/problems/ctci/e3_5_sortStack.py
1,024
4.15625
4
# CTCI 3.5: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure. The stack supports the following operations: push, pop, peek, and isEmpty. class SortedStack: def __init__(self): ...
09c1d5fea3e80de3a84978b8b601d93aafbd5a8f
claudiogar/learningPython
/problems/ctci/e1_1_isUnique.py
911
4.09375
4
# Excercise 1.1 from Cracking the coding interview # Problem: Implement an algorithm to determine if a string has all unique characters. # What if you cannot use additional data structures? def isUnique(s:str) -> bool: initialLength = len(s) # if there are more chars than the whole ASCII alphabet, there must ...
3582258ed453a1d36f5a757ae75590bb24adefce
haydenedelson/Houses
/import.py
1,364
4.03125
4
from sys import argv, exit from cs50 import SQL import csv # Check for proper arguments if len(argv) != 2: print("Error: Usage: python import.py [filename].csv") exit(1) # Open SQL database db = SQL("sqlite:///students.db") def main(): # Open CSV file # Create reader object with open(argv[1], ne...
105101794bccdcd53e0d06ce65d92436403491f2
cvaldez83/Useful-Python-Commands
/elapsedTime.py
168
3.921875
4
import time #initial time t0 = time.time() #enter code here that you want to know how long it takes t1 = time.time() print("Time required: ", t1-t0) #it's in seconds
792474f418b33b9085c17ff00c5c5ead514b5343
cvaldez83/Useful-Python-Commands
/AutomateTheBoringStuff/Lec41_SCRAPING_Selenium.py
606
3.5
4
from selenium import webdriver from selenium import webdriver browser = webdriver.Chrome('G:\Software\Python\Lib\site-packages\selenium\chromedriver') # path to chromedriver.exe browser.get("https://automatetheboringstuff.com") elem = browser.find_element_by_css_selector('body > div.main > div:nth-child(1) > ul:nth-c...
d49527adb9f12415bb1407dd78919ffa96a13a74
jakab922/linked_list
/linked_list/dll.py
1,417
3.5
4
from base import LLBase class DLL(LLBase): """Node class for the doubly linked list. The class has 3 members which are the following: - *data*: This is the the data that is stored in the current node. By default it's `None`. - *prev*: Points to the previous node in the ...
79cef484c08be448f2ee12d9418d0151215e98ed
UmaMoiseenko/IS211_Assignment4
/sort_compare.py
2,245
3.671875
4
import time import random def insertion_sort(a_list): t_start = time.time() for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position - 1] > current_value: a_list[position] = a_list[position - 1] po...
0f8758a9edc24ebdce3b4aea927c67975156bb82
shaypal5/comath
/comath/segment/segment.py
2,109
3.8125
4
"""Defines a one-dimensional line segment.""" from math import ( inf, ) class LineSegment(object): """Defines a one-dimensional line segment.""" @staticmethod def _parse_edge(edge): if isinstance(edge, (int, float)): return edge if isinstance(edge, str): if ed...
e84c6f0d0b8bf6e05e41c5058de7d96f7d0fff4b
Deepak0709/Deep-Learning
/Car_Predicitons_Final/run_me.py
2,532
3.515625
4
from model_function import * # model_funtion.py is the main program that calls model.py program. import pandas as pd import numpy as np #input var. work_dir = 'C:/Users/DK/OneDrive/Desktop/Coursera/Projects/Car_Predicitons_Final' # current working directory test_data_percentage = 10 ...
e67dabcf7939fed74a3d1e4eef6561bd93571116
huntersfuntime/python_code_challenges
/aLevel_one/extremes.py
234
3.6875
4
""" Take in a iterables, and return a tuple containing min and max values. Hint. Use min/max function """ def extreme(chars): extremes([1,3,4,5,6]) #(1, 6) extremes((99,25,30,-2)) #(-7, 99) extremes("antartica") #('a', 'z')
16650aafcc1b6255da3b3b0bfe6b70d595e29b85
huntersfuntime/python_code_challenges
/aLevel_one/pemdas.py
255
3.953125
4
""" Take in two numbers, add them together. If the two numbers are the same, return the sum, and double it. sum_double(1, 2) -> 3 sum_double(3, 2) -> 5 sum_double(2, 2) -> 8 """ def sum_double(a, b): sum_double(1, 2) sum_double(3, 2) sum_double(2, 2)
21e5b51560428d36ecfdc2f12dd413e023d4eb0f
rickyjreyes/Python_Tutorial
/5Conditionals.py
407
4.09375
4
print(3==4) if True: print("True") else: print("False") if 100 == (2 * 50): print("True") else: print("False") if 19 <= 19: print("True") else: print("False") if -50 >= 15: print("True") else: print("False") if 12 != 12: print("True") else: print("Fa...
86fccf5df89eb49af7ab1b269cc9696fe2254291
nanareyes/CicloUno-Python
/Condicionales/ejercicio6-otraversion_condicional.py
1,045
4.1875
4
''' Elabora un algoritmo que permita ingresar el monto de la venta alcanzada por un vendedor durante un mes, se debe calcular la bonificación (%) que tiene derecho de acuerdo a la siguiente tabla: 0 - 1000.000 Bonificación 0 1.000.100 - 2.500.000 Bonificacion 0.04 2.500.100 o más Bonificación 0.08...
3c110c3201336c827c7f7d5809ab36e98696d2b9
nanareyes/CicloUno-Python
/FuncionesParaColeccionesDatos/ejercicioClase.py
674
4.15625
4
""" 1. Crear una función que determine el equipo de futbol, cuyo nombre inicie con la letra “T”, utilizar la función map para iterar en la lista equipos. equipos = ["América", "Millonarios", "Tolima", "Cali", "Junior"] Generar una lista de resultado que indique con true los nombres que inicien con la letra “T” y ...
332eed32569e32afefc62070d4d385cc3c9de63e
nanareyes/CicloUno-Python
/Nivelacion_3/programacionFuncionalEjercicios.py
923
4.03125
4
# Programación funcional # Minimizar el número de asignaciones # Funciones de primera clase (variables), funciones de orden superior (reciben o retornan funciones) def operacion(signo): if signo == "+": def suma(a=0, b=0): return a + b return suma elif signo == "-": def...
bbbd46db4543d771796c2ac5bbb2362f7d4a7f12
nanareyes/CicloUno-Python
/Ejercicios_Variables_firts_Class/temperatura_fahr.py
510
3.8125
4
''' #Para explicar Try y Except utilizaremos de ejemplo una función que convierte la temperatura en grados Fahrenheit a una temperatura en grados Celsius: temperatura_fahr = input('Ingrese la temperatura en grados Fahrenheit: ') fahr = float(temperatura_fahr) cel = (fahr - 32.0) * 5.0 / 9.0 print(cel) ''' temperat...
4e5f9cf4bbb9b4022988076028ea5f77e171cd0f
nanareyes/CicloUno-Python
/Ejercicios_Variables_firts_Class/eje3_confuncion.py
502
3.921875
4
''' Elaborar un algoritmo que permita averiguar si una persona debe sacar cédula de ciudadanía, si la persona es mayor de 17 años debe imprimir "Debe sacar cédula de ciudadanía" en caso contratrio imprimir "No debe solicitar cédula" ''' def cedula_edad(e): if e <= 17: print("No debe solicitar cédula") ...