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
35c0f0888ad01a93a6cc9f49868d6098a0fd021d
JonBebi/nyc-mhtn-ds-071519-lectures
/week-1/OOP/Calc.py
1,832
3.734375
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import math class Calc: def __init__(self, data): self.data = data self.length = len(data) self.__create_stats() def __create_stats(self): self.mean = self.__calc_mean() self.median...
8f2e160ece51be5a75a8b992c900dacbbbcf8236
bitsandrewsbits/Y0UR_ENglish_vocabulary
/Y0UR_EnglishV0CABULARY_1_v3_.py
793
3.8125
4
#Y0UR_EnglishV0CABULARY - version 1_3 #this program should be use for writting and repeating your english word in this vocabulary import functions_Y0UR_EN_Voc_1_3__ as f_yev #Main part of programm words_file = open('Y0UR_ENglish_W0RD5.txt', 'at') words_file.close() words_read = open('Y0UR_ENglish_W0RD5.t...
21deb0602e1083ae7983c2b9e5a2a5ea332d4cbd
LunarLite/Proteasen
/Application/Algorithms/depth_algorithm.py
5,139
3.71875
4
# depth_algorithm.py # # Heuristics - Protein Pow(d)er # http://heuristieken.nl/wiki/index.php?title=Protein_Pow(d)er # # Students: Mick Tozer, Eline Rietdijk and Vanessa Botha # # this file contains the Depth-first algorithm, # that uses the priority-queue principle based on an amino_acid_chain's score. # # # > Able t...
273b56a48a8bcb4eccfd6020852347a27407649c
Napster56/Sandbox
/function_scpoe_demo.py
666
4.21875
4
def main(): """Demo function for scope of an immutable object.""" x = 3 # int is immutable print("in main, id is {}".format(id(x))) function(x) print("in func, id is {}".format(id(x))) def function(y: int): print("in func, id is {}".format(id(y))) y += 1 # assignment creates a...
87f0528ad87ca333109df2a21864358aff4f4a8e
Napster56/Sandbox
/reverse_text_recursively.py
284
4.28125
4
""" Function to reverse a string recursively. """ def reverse(text): if len(text) < 2: # base case return text else: # recursive step = reverse(rest of text) + first char of text return reverse(text[1:]) + text[0] print(reverse("photon"))
cfaa99685d9aeb0b2822f22f84a7f582876215d8
Napster56/Sandbox
/exam_question.py
1,610
4.09375
4
""" Program to compute highest, lowest, average """ rainfall = [15, 10, 23, 43, 10, 78, 90] highest = rainfall[0] lowest = rainfall[0] for value in rainfall: if value > highest: highest = value if value < lowest: lowest = value average = sum(rainfall) / len(rainfall) print("lowest {}, highest {...
1abc35b03c60414bb9261d3ffa35ebfb9c9faefa
Napster56/Sandbox
/Classes demo/person.py
1,260
4.15625
4
""" Program to create a person class """ from datetime import datetime class Person(): def __init__(self, first_name="", last_name="", dob="01/01/1900", gender="female"): self.first_name = first_name self.last_name = last_name self.dob = dob self.gender = gender def calculate...
165bd77cb033c6535f0ebf67d16986a24f83dd7f
Napster56/Sandbox
/CreditCard_class.py
2,471
4.15625
4
""" Create a class for a consumer credit card """ class CreditCard: def __init__(self, customer, bank, account, limit): """Make a new credit card instance The initial balance is zero. """ self.customer = customer self.bank = bank self.account = account sel...
3f94d844b6920c24a5b0043848440c6582a0e5cf
Napster56/Sandbox
/print_dictionary.py
927
4
4
""" Program to print all words in a dictionary file; file has one word per line """ # open file named "dictionary.txt" for reading('r') data = open("dictionary.txt", 'r') # iterate thru the file one line at a time # for line in data: # print(line) def main(): # main program print("Find words containing v...
689b0af2411c98e7bd92590ceb0b24d8ac68b254
Napster56/Sandbox
/user_name.py
547
4.3125
4
""" Ask user for their name Tell them how many vowels are in their name Tell them how many capitals are in their name """ count_vowels = 0 name = "Bobby McAardvark" # name = input("Name: ") for letter in name: if letter.lower() in 'aeiou': count_vowels += 1 print("Out of {} letters, {} has {} vowels".form...
5f522189d56fe7cd74fcdd8153ada80032a89cee
Napster56/Sandbox
/Classes demo/circle_class.py
498
4.46875
4
""" Program to create a Circle class which inherits from the Shape class. The subclass Circle extends the superclass Shape; Circle 'is-a' Shape. """ from shape import Shape class Circle(Shape): def __init__(self, x=0, y=0, radius=1): super().__init__(x, y) # used to access the instance of the Shape cl...
f4ca8f55ec31d63d82b33b20a76085bcb6a258ea
Napster56/Sandbox
/file_methods.py
813
4.15625
4
""" # readline method temp = open("temp.txt", "r") # open file for reading first_line = temp.readline() # reads exactly one line print(first_line) for line in temp: # read remaining lines print(line) temp.readline() # read file, return empty string print(temp) temp.close() # read m...
71f742d2403fbb039db24ac14f7c944f286b18ec
tfilipov01/Basic-Python-Lab
/lab_9.py
363
4.03125
4
#!/usr/bin/env python #Task 1 # ask user for a number #convert it and use try except to handle wrong input ''' try: action except: what to happend if the action is not successful and return error ''' #Taks 2 #Using While create menu #Using try/except convert the choice to integer #if input is q exit menu #if ...
56ee0a57ef3ad81066b13f757ecc050b95a68f8c
miro1501/playground
/leetcode/defanging_an_IP_address.py
1,226
3.9375
4
""" Runtime: 16 ms, faster than 71.48% of Python online submissions for Defanging an IP Address. Memory Usage: 13.4 MB, less than 87.28% of Python online submissions for Defanging an IP Address. """ class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str ...
677b9d3b5a6b4c827e16c0433dce769b84bcc166
albertchan58/Quiz
/round2.py
9,795
4.09375
4
''' Programmed by: Albert Chan Programmed on: January 31, 2019 Programmed for: ICS3U1-04 Purpose: Create a function which prompts the user to enter the roots of a randomly generated quadratic equation for Round 2 of the Math Quiz. All randomly generated quadratic equations in th...
9b5e405f76e13cec2b74a39e497772b616cedff8
ku-nlp/jumanpp
/script/string2charlit.py
303
3.6875
4
# this script transforms strings from input line # "asdf" to 'a', 's', 'd', 'f' # which are useful for pegtl library while True: line = raw_input("string to charize: ") if len(line) == 0: exit(0) res = [] for c in line: res.append("'%s'" % c) print(", ".join(res))
45dab0917e66f54d76737a871782fe9779b01707
devjmitchell/decision-maker
/decisions.py
808
4.03125
4
from random import randint # Welcome messages print ("\nUnsure what to do? Enter your choices and I'll help you decide what you should do.") print ("Hint: Type DONE when you've entered all of your choices.") # Start your_input blank, since it needs DONE to finish asking your_input = "" # Creates a blank list for dec...
21e2137de426204958da44ce3ab80c96f2fc3467
my-temporary-name/Machine-Learning
/Assignment 2/tree/base.py
8,175
3.78125
4
""" The current code given is for the Assignment 1. You will be expected to use this to make trees for: > discrete input, discrete output > real input, real output > real input, discrete output > discrete input, real output """ ##### References Used Are ######## # https://machinelearningmastery.com/implement...
031a54e3140a67e1cab487c73f55893cd693b62a
my-temporary-name/Machine-Learning
/Assignment 1/metrics.py
3,686
3.875
4
import pandas as pd import numpy as np import math def accuracy(y_hat, y): """ Function to calculate the accuracy Inputs: > y_hat: pd.Series of predictions > y: pd.Series of ground truth Output: > Returns the accuracy as float """ if isinstance(y_hat,pd.Series): ...
641773b48d5dcf702ce6871f3060a944d48df226
m223xu/My-Data-Structures-and-Algorithms
/Searching-and-Sorting/QuickSort.py
1,656
3.59375
4
## if all the elements are the same, running time becomes O(n^2) ## T(n) = T(k) + T(n-k-1) + O(n) ## average running time O(nlogn), best case O(nlogn) ## in-place algorithm, but not stable import random def quickSort(A, low, high): ## if we always pick the last element as pivot, ## the running time will be O(...
614132f4f52052101c3e6d3ca55dcb74f2095916
TeamChironda/LinkedInProjects
/Essential Training/StatementsAndExpressions.py
367
3.875
4
words = ['zac', 'vas', 'chi'] count = 0 while (count < 3): print(" print words with while loop" , words[count]) count += 1 a, b = 0, 1 while (b < 1000): print(b, end=' ', flush=True) a, b = b, a + b print() for i in words: # for each elements of words the value i will be assigned to those elements ...
2adc6c29a7b0ec47d183da09235c1e6b6ec996c9
iluvjava/DataStructure
/python/algorithms/dynamic_programming.py
3,134
3.890625
4
""" This is a collection of good/classic/insteresting Dynamic Programming problems and their corresponding solutions. """ def edit_distance(w1, w2): """ Given 2 string, what is the minimum number of operations that transform one string to the other. Set of operations: 1. Deletion. ...
b70a80f967536d6f553c683ad87d39733c809c63
dpopov22/Non-Photorealistic-Rendering
/tree.py
1,453
3.734375
4
#Domnika Popov #Tree file #10/10/19 import lsystem as ls import shapes as s import turtle_interpreter as t import random class Tree(s.Shape): '''creates a new type of object, allowing new instances of that type to be made, a tree in this case, using the parent function of shapes''' def __init__(self, distance=5,...
f21fd82c63350616b46bacae6926d5da47d909c3
rahulsharma0628/lit_leets
/344_reverse_string.py
332
3.796875
4
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ for i in range(int(len(s)/2)): s[i], s[len(s)-i-1] = s[len(s)-i-1], s[i] # 1. Swapped the index value with the corresponding index from the right...
30289b848066776c8b15a2a5e28c7f7d65a1aee5
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex053a.py
235
4.03125
4
frase = str(input('Digite uma frase: ')).upper().strip() palavras = frase.split() junto = ''.join(palavras) if frase == junto[::-1]: print('A frase é um palíndromo') else: print('A frase não é um palíndromo') print(junto)
5e1390f2bdc9044de2dd6049ef3a5e0632cbf2c6
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex060.py
330
4.1875
4
from math import factorial num = int(input('Digite um número para calcular seu fatorial: ')) fact = factorial(num) print('Calculando {}! = '.format(num), end='') while num != 0: if num == 1: print('{}'.format(num), end=' = ') else: print('{}'.format(num), end=' x ') num -= 1 print('{}'.forma...
c8d1a82acd49fb48ac8d5186f82a6f3667527e90
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex095.py
1,173
3.640625
4
jogador = dict() jogadores = list() while True: gols = [] jogador['nome'] = str(input('Nome do Jogador: ')).strip() partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for c in range(0, partidas): gols.append(int(input(f'Quantos gols na partida {c}? '))) jogador['gols'] = ...
cc750cd6674b3910de4b22f6cc992d030b2a5295
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex63.py
338
4.03125
4
print('-'*23) print('Sequência de fibonacci') print('-'*23) termos = int(input('Quantos termos você quer mostrar? ')) x = 3 t1 = 0 t2 = 1 print('~'*30) print('{} → {}'.format(t1, t2), end='') while x <= termos: t3 = t1 + t2 print(' → {}'.format(t3), end='') t1 = t2 t2 = t3 x += 1 print('→ FIM') prin...
390d6490f129576a11ede9b944044523a259ec00
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex080b.py
480
3.9375
4
lista = [] for c in range(0, 5): num = int(input('Digite um valor: ')) if c == 0 or num > lista[-1]: lista.append(num) print('Adicionado no final da lista') else: x = 0 while x < len(lista): if num <= lista[x]: lista.insert(x, num) ...
10a46978bcd48ade035b71693f868b4c8641dff2
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex003.py
185
3.9375
4
#Faça um programa que some dois números. n1 = int(input('Primeiro número: ')) n2 = int(input ('Segundo número: ')) s = n2 + n2 print('A soma entre {} e {} é {}'.format(n1, n2, s))
8b804d6b1dc808da418589563b1409c8a1dc655b
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex054.py
355
3.953125
4
maior = 0 menor = 0 from datetime import date for x in range(1, 8): pessoa = int(input('Em que ano a {}ª pessoa nasceu? '.format(x))) res = date.today().year - pessoa if res >= 18: maior += 1 else: menor += 1 print('Ao todo tivemos {} pessoas maiores de idade\nE também tivemos {} menores...
ec5c3fb81b7a89390c274cf850374bb29cbe91ea
Djheffeson/Python3-Curso-em-Video
/Projetos/Tiny Write.py
512
3.734375
4
alfabeto = {'a':'ᵃ', 'b':'ᵇ', 'c':'ᶜ', 'd':'ᵈ', 'e':'ᵉ', 'f':'ᶠ', 'g':'ᵍ', 'h':'ʰ', 'i':'ᶤ', 'j':'ʲ', 'k':'ᵏ', 'l':'ˡ', 'm':'ᵐ', 'n':'ⁿ', 'o':'ᵒ', 'p':'ᵖ', 'q':'۹', 'r':'ʳ', 's':'ˢ', 't':'ᵗ', 'u':'ᵘ', 'v':'ᵛ', 'w':'ʷ', 'x':'ˣ', 'y':'ʸ', 'z':'ᶻ'} frase = str(input('Digite sua frase: ')).strip().l...
7c7c7d0a88d5ec01981c740e6e2b69ca3a88c93e
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex080.py
672
4.0625
4
lista = [] num = 0 for c in range(0, 5): num = int(input('Digite um valor: ')) if c == 0: lista.append(num) print(f'Valor {num} adicionado no final da lista') else: if num <= min(lista): lista.insert(0, num) print('Adicionado na posição 0 da lista') el...
cada36f973bb4168bce08868f8a1e5699401fc02
Djheffeson/Python3-Curso-em-Video
/Exercícios/ex104.py
345
4
4
def leiaint(num): print('-'*30) num = input('Digite um número: ') while not num.isnumeric(): print('\033[0;31mERRO! Digite um número inteiro válido.\033[m') num = input('Digite um número: ') return num # Programa Principal n = leiaint('Digite um número: ') print(f'Você acabou de digit...
a5bd3b82f87f107822b104a009e93261b78008e8
teeradon43/Data_Structure
/Lab/newRange.py
393
3.90625
4
print(' *** New Range ***') def findRange(strt=0,sTop=0,stP=1): #Start , Stop , Step if strt > sTop: strt , sTop = sTop , strt while strt < sTop: print(strt, end=' ') strt += stP pass x = [float(i) for i in input('Enter Range : ').split()] if len(x) < 3: for e in range(3): ...
d9d5bca64263b592ac66cc580cf3d8aff5315a62
teeradon43/Data_Structure
/Lab/LinkedList/lab43.py
2,422
4.125
4
""" Chapter : 6 - item : 3 - MergeOrderList จงเขียนฟังก์ชั่นสำหรับการ Merge LinkList 2 ตัวเข้าด้วยกันโดยห้ามสร้าง Class LinkList จะมีแต่ Class Node ซึ่งเก็บค่า value ของตัวเองและ Node ถัดไป โดยมีฟังก์ชั่นดังนี้ createList() สำหรับการสร้าง LinkList ที่รับ List เข้ามาโดยจะ return Head ของ Linklist printList() สำหรับกา...
9e0bc6ad810e7276974e3bcba786b66ba06383e0
teeradon43/Data_Structure
/Lab/Queue/lab31.py
1,607
3.859375
4
""" Chapter : 4 - item : 1 - Basic Queue เขียนโปรแกรมโดยรับ input 2 แบบ โดยใช้ QUEUE ในการแก้ปัญหา E <value> ให้นำ value ไปใส่ใน QUEUE และทำการแสดงผลค่าที่ทำการ enqueue และ index ของตัวที่ทำการเพิ่มเข้าไป D ให้ทำการ dequeue ตัวที่อยู่หน้าสุดของ Queue ออกและแสดงตัวเลขที่เอาออกและแสดงขนาดของ Queueหลังจากทำการ dequeue...
ba83fcff3f4995dcd46454f67ca5ce5c78a7d557
teeradon43/Data_Structure
/Lab/Basic Python/lab03.py
452
3.71875
4
print('*** New Range ***') rng = [item for item in input('Enter Input : ').split()] tu = [] i = 0 if len(rng) == 3: i = float(rng[0]) while i < float(rng[1]): tu.append(round(float(i), 3)) i = i + float(rng[2]) elif len(rng) == 2: i = float(rng[0]) while i < float(rng[1]): tu.ap...
4a50ac2346aee77dfd6080be2541d3c810b04cea
alexisdavalos/DailyBytes
/BinaryTreeVisibleValues/binaryTreeVisibleValues.py
921
4.21875
4
# Given a binary tree return all the values you’d be able to see if you were standing on the left side of it with values ordered from top to bottom. # This is the class of the input binary tree. Do not Edit! class Tree: def __init__(self, value): self.val = value self.left = None self.right...
0e1edb19f7d0c384a374545ba1d28d726fbd453e
alexisdavalos/DailyBytes
/MoveElementToEnd/moveToEnd.py
506
4.03125
4
# Given an array of integers and an integer. # Write a function that moves all instances of that integer in the array # to the end of the array and returns the array. # The function should perform this in place (mutate the array) # Maintaining the order of other integers is not required. def moveElementToEnd(array, ...
6681a57d55dbe2ea18d6f6d5c65776935455dde9
alexisdavalos/DailyBytes
/MakePalindrome/makePalindrome.py
524
4.1875
4
# Write a function that takes in a string with any set of characters # Determine if that string can become a palindrome # Returns a Boolean after processing the input string def makePalindrome(string): # Your Code Here return # Test Cases Setup print(makePalindrome("aabb")) # => true (abba) print(makePalind...
454add08e2dfab1113a5997026e9edbe56889259
simonstanley/tools
/Utils/iris_functions.py
26,606
3.8125
4
import iris import iris.analysis import numpy import datetime import re def cube_time_converter(time, time_unit): """ Convert time between datetime object and number value (standard format in an iris cube). Args: * time: datetime, or float, int Which ever type is given, it is converted to...
ff5fe5603ad45442f52a5802f24e65ef6614156e
rahuladream/PyGame
/Day2/day2_keypress_event.py
1,049
4
4
import pygame """ KEYDOWN detects the key press and, KEYUP detects the key release. Both events have two attributes - key: an integer id which represents every key on keyboard. - mod: bitmast of all the modifier keys that were in the pressed state """ pygame.init() # Set screen title pygame.display.set_caption(u'Ke...
2e266395a9c25f1807bdc98ac81db6bd8ee53352
LawrenceHlapa/Analyse
/AnalysePredict/stop_words_remover.py
922
4
4
def stop_words_remover(df): """ Usage: Should split string in a list in rows Should remove stop_words in the dictionary from the dataframe Should create a new column labeled "without_stop_words" Args: DataFrame Returns: a column labeled "Without_Stop_words" with stop words removed. "...
042842be4d2dfe4533fd3f4ad37019474f96866f
AlbertFranquet/shared
/routines/frequency_ordering.py
439
3.65625
4
def frequency_each_letter(text): new_freq = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0} for c in te...
a81fbd97048a26cb87b7b1462eeb3252b3202c0c
KeenanJones1/python-intro
/conditionals.py
448
3.78125
4
# conditonals / statements age = 20 # Remember those indentations if age == 60: print('Damn, why do you want to come in?') elif age >= 18: print("Come on in") else: print("Hey you are too young!") my_age = 24 your_age = 18 # and & or if my_age > 20 and your_age > 15: print('Both are you are old enoug...
63894f340229457ad18e67673496bbd954178278
razorblack/python_programming
/PythonPractice/FileOperations.py
398
3.8125
4
with open("file.txt", 'r+', encoding='utf-8') as f: print("Printing the content of the file \n") f.seek(0) print(f.read()) print("") print("Appending content \n") f.write("This is added to this file \n") f.write("Through file operations \n") f.write("in python. \n") print("Printing...
dc4b771cc52cb1a5d19e2a5e07858472fcb9254d
razorblack/python_programming
/PythonPractice/PrimeOrComposite.py
307
4.28125
4
userInput = int(input("Enter a number to check for prime \n")) count = 0 # To count no. of factors of user input number for i in range(2, userInput): if userInput % i == 0: count += 1 if count > 0: print(f"{userInput} is composite number") else: print(f"{userInput} is a prime number")
e5e647601be99ae9e20aa7c3f0f37f4867a18802
razorblack/python_programming
/PythonLab/Program6.1.py
673
4.125
4
# Method to perform Linear Search def linear_search(list_of_number, no_to_search): size = len(list_of_number) for i in range(0, size): if list_of_number[i] == no_to_search: print(f"Search Successful: Element found at index {i}") return print("Search Unsuccessful: Element Not...
45d4769e5bed7d734f3ef5648a1fae66c8c61fb4
razorblack/python_programming
/PythonPractice/SetOperations.py
742
4.09375
4
primeSet = set() oddSet = set() def isPrime(i): count = 0 for n in range(2, i): if i % n == 0: count += 1 if count > 0: return 0 else: return 1 def prime(num): count = 0 i = 1 while count <= num: if isPrime(i) == 1: primeSet.add(i)...
8386ac0809da57b560b1c321209e0e422a565169
razorblack/python_programming
/PythonPractice/QuadraticRoots.py
423
3.984375
4
print("Enter quadratic coefficients \n") a, b, c = input() D = (b * b) - (4 * a * c) root1 = (-b + pow(D, 1 / 2)) / (2 * a) root2 = (-b + pow(D, 1 / 2)) / (2 * a) if D == 0: print("Equal roots \n") print(f"Roots are {root1} and {root2}") elif D > 0: print("Roots are distinct \n") print(f"Roots are {root...
8a3d944d0380a91fb26c3f4beab9124bdd0af50a
mega-mac-slice/learn-python
/src/2018_10_01_1538450506/main.py
864
3.5625
4
#!/usr/bin/env python3 import unittest import math def solve(value: int) -> int: freq = [0 for _ in range(10)] while value > 0: digit = int(math.floor(value % 10)) freq[digit] += 1 value = int(value / 10) result = 0 multiplier = 0 for value in range(1, 10)[::-1]: ...
a9ad614c6832d79fef8f69b984b6d32458122158
Farrukh1998/Webtasks
/tasks/reverseQueue.py
1,499
3.9375
4
class Node: def __init__(self, data): self.data = data self.next = None class QueueLinkedList(): def __init__(self): self.head = None self.size = 0 self.tail = None def enqueue(self, element): self.size += 1 if self.head == None: ...
16662472039070320a992cfde1998c974190b484
RahulWangawar/python_pycharm_code
/proj2/Exercise/6)Healthy programmer.py
1,650
3.59375
4
# Healthy Programmer # 9am - 5pm # Water - water.mp3 (3.5 litres) - Drank - log # Eyes - eyes.mp3 - every 30 min - EyDone - log # Physical activity - physical.mp3 every - 45 min - ExDone - log # # Rules # Pygame module to play audio from pygame import mixer from datetime import datetime from time import time def music...
93f2a7223c3d02166f9ab441f9fbd73ba52c7e7d
minaeid90/pycourse
/advanced/example6.py
991
3.71875
4
#-*- coding: utf-8 -*- u''' DESCRIPTORS EXAMPLE 6: Let's really use the __set__ ''' class TypedAttrib(object): def __init__(self, name, typ): self.name = name # Avoid using 'type' as attribute name self.typ = typ def __set__(self, inst, val): if isinstance(val, self.typ): ...
b8f6125de3b647d2b8c3c6a8fee82d258c6b8731
minaeid90/pycourse
/advanced/example0.py
2,923
4.53125
5
#-*- coding: utf-8 -*- u''' DESCRIPTORS EXAMPLE 0: How attributes look up works ''' # Let's define a class with 'class' and 'instance' attributes class MyClass(object): class_attr = "Value of class attrib" def __init__(self): self.instance_attr = "Value of instance of {0} attrib".format(self.__class__....
85b2bc739e5dfd89b584c3f9b4b59f3a38964399
ppwicho/pooPython
/ordenamientopormezcla.py
1,241
3.6875
4
import random def sort_mezcla(lista): if len(lista) > 1: medio = len(lista) // 2 izquierda = lista[:medio] derecha=lista[medio:] print(izquierda, '*' * 5, derecha) #llamada recursiva en cada mitad sort_mezcla(izquierda) sort_mezcla(derecha) #iterad...
6bcb240042ac7a1f44dbfc8b0363fba812456c12
jkeller51/CS448_MP1
/include.py
5,810
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 29 16:35:11 2018 @author: jkell, HaokunLi1994 """ import os # Indicating ON/OFF of debugging mode debug = 0 class Node(object): """ Using coordinates (x, y) to mark the position of this node. Args: x(int):x-th line of the maze y(int):y-th...
db61f84edcc3fdb5fb25549d7378265412e4f1a6
leanstartpad/PythonPlayground
/algorithms/recursion.py
185
4.09375
4
#recursion will be in here def fact(x): if x == 1: return 1 else: return x * fact(x-1) print("Enter a number") y = input() result = fact(int(y)) print(result)
82c1ac873ca0adb6cbe39d4c9972547f8e353a27
otienonick/Password-Locker
/test_details.py
1,100
3.859375
4
import unittest from user import User class TestUser(unittest.TestCase): def setUp(self): ''' a method that runs before any test ''' self.new_user = User('nick','1982') #create a dummy user def test_init(self): ''' testcase to check if object or cla...
ac1e4c2187ed1bd5328890211a5c90663011f804
pierroz127/family-balance
/utilities/date_helper.py
1,386
3.953125
4
from datetime import datetime, date def get_month_label(month): if month == 1: return 'Jan' elif month == 2: return 'Feb' elif month == 3: return 'Mar' elif month == 4: return 'Apr' elif month == 5: return 'May' elif month == 6: return 'Jun' e...
24bc311c6dbaf65ec464054ecb6a8c46ccdb9836
vijayaramanp/InfyTQ-OOP
/day2_assgn_11_flower_shop.py
1,735
3.796875
4
#OOPR-Assgn-11 #Start writing your code here class Flower: def __init__(self): self.__flower_name=None self.__price_per_kg=None self.__stock_available=None def set_flower_name(self, flower_name): self.__flower_name=flower_name.lower() def get_flower_name(self): ...
2efaa4205861585f895b5026b9e39936ec9da359
vijayaramanp/InfyTQ-OOP
/day3_assgn_20_job_application.py
1,163
3.609375
4
#OOPR-Assgn-20 #Start writing your code here class Applicant: __application_dict={"A":4,"B":3,"C":5} __applicant_id_count=1000 def __init__(self,applicant_name): self.__applicant_id=None self.__applicant_name=applicant_name self.__job_band=None @staticmethod def get_appl...
ce581feaab267161332c7a07481e18b38b6053ba
hydrophyl/Python-1.0
/PythonOOP/clstaticmethod.py
1,214
3.578125
4
import datetime my_date = datetime.date(1996, 10, 6) class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of...
5ec97e800f1991815379482c8efab963a585abe8
hydrophyl/Python-1.0
/LPTHW/exc12.py
298
4.03125
4
print("How old are you? ", end='') age = input() print("How tall are you? ", end='') height = float(input()) print("How much do you weigh? ", end='') weigh = float(input()) BMI_Wert = height / weigh print(f"So, youre {age} old, {height} tall and {weigh} heavy.") print(f"Your BMI ist: {BMI_Wert} ")
6692a0b469278f6c6d13eabadab36a6e426b2936
hydrophyl/Python-1.0
/TricksnTips/loop2.py
333
4.21875
4
names = ['Cory','Chris', 'Dave', 'Trad'] heroes = ['Peru','Christie', 'David', 'Tradition'] """ for index, name in enumerate(names): hero = heroes[index] print(f"{name} is actually {hero}") """ for name, hero in zip(names,heroes): print(f'{name} is actually {hero}') for value in zip(names, heroes): ...
a478340918ffc16d833b90d814683a2008e2ac8d
hydrophyl/Python-1.0
/CS50/characterinput.py
313
4.09375
4
import datetime now = datetime.datetime.now() name = input("Hey what's your name: ") age = int(input("Ok {}, What's your age: ".format(name.title()))) yrs = (now.year + 100) - age msg = ("Ok {}, so you're {} years old and the year {} hat your 100th birthday!\n".format( name.title(), age, yrs)) print(msg)
eef8ed2377548b0026b6fc747734799aa5007fdc
hydrophyl/Python-1.0
/prime.py
622
3.984375
4
import time import math def is_prime(n): #Return true if n is a prime number, false otherwise if n == 1: return False #1 is not prime max_divisor = math.floor(math.sqrt(n)) for divisior in range(2,1 + max_divisor): if n % divisior == 0: return False # n is not prime retu...
65a9835d5dab23733b354afba020c41625651ba7
hydrophyl/Python-1.0
/CS50/int.py
189
3.59375
4
from cs50 import get_int x = get_int("x: ") y = get_int("y: ") print(f"+ = {x+y}") print(f"- = {x-y}") print(f"* = {x*y}") print(f"/ = {x/y}") print(f"// = {x//y}") print(f"mod = {x%y}")
ec7dd4bdd83a7a85593ca3e2098f84670455ba89
ChernenkoSergey/Supervised-and-Unsupervised-Learning-with-Python
/Раздел 2 Классификация и регрессия с использованием контролируемого обучения/regressor_multivar.py
3,155
3.671875
4
import numpy as np from sklearn import linear_model import sklearn.metrics as sm from sklearn.preprocessing import PolynomialFeatures # Файл содержащий данные, с разделителями-запятыми, чтобы легко загрузить его с помощью вызова одной строки input_file = 'data_multivar_regr.txt' # Загружаем данные из файла data = np....
06b528df392c95d4a1be682f7034b223dbc6c113
soroushj/python-opencv-numpy-example
/ygrayscale.py
469
3.53125
4
import numpy as np def y_grayscale(rgb_image): """Return a grayscale version of the RGB image, using the Y channel of the YCbCr color space.""" # For details on the YCbCr color space, see: # https://en.wikipedia.org/wiki/YCbCr # https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.601-7-201103-I!!PDF-E...
b52c8e82c03defefe1c7a3f4c77937d657e98eb5
swp0107/leetcode
/longestPalindrome.py
753
3.5625
4
class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) output = '' # Make a table to store information whether [Si,...Sj] is a palindrome table = [[0 for x in range(n)] for y in range(n)] # All substring of length 1 are palindromes if n >= 1: for i in range(n): table[i][i] = True ...
b513818ffb35ae4103ac24aca60e9437d64160f0
Ivy-Murage/ashanti_project
/ashanti1.py
2,211
3.859375
4
# year_code def year_code(year): yy = year % 100 return (yy + (yy // 4)) % 7 dict_month = {'January': 0, 'February': 3, 'March': 3, 'April': 6, 'May': 1, 'June': 4, 'July': 6, 'August': 2, 'Septembe...
996a2ad7bffc4fd521cf70575fc302e0b52db1b3
mandarborkar/hello-world
/bubblesort.py
342
4.03125
4
inputarray = [8, 7, 4, 3, 9, 6] print ("My input array = ") print (inputarray) for i in range(len(inputarray)): for j in range(len(inputarray)): if inputarray[i]<inputarray[j]: larger=inputarray[i] inputarray[i]=inputarray[j] inputarray[j]=larger print ("My output array =...
cedd2feeb64448f5a595313ede197222b011fbb4
ruarcs/PyTicTacToe
/GameRunner.py
1,465
3.53125
4
from Game import * class GameRunner: 'This class contains main and runs the game' def main(): limit_depth = True from_file = True filename = raw_input("Enter the name of your game file of choice:") file = open(filename, 'r') num_games ...
e4598a7212964d5dc6440bb57d16342e46b1fd95
usfrank02/pythonProjects
/project3.py
288
4.34375
4
#! python import sys name = input("Enter your name:") print (name) #Request user to input the year he was born year_of_born = int(input("What's the year you were born?")) #Calculate the age of the user age = 2020 - year_of_born print("You will be {} years old this year!".format(age))
5c92f1f2d736947f43ed3b7ce5e5a52dc043903d
JuanCarlos-A01376511/Mision-03
/Cálculo del Pago de un Trabajador.py
1,727
3.984375
4
# Autor: Juan Carlos Flores García, A01376511 # Descripción: Programa que imprime los datos de un trabajador y calcula su pago semanal. # La siguiente función calcula el pago normal del trabajador. def calcularPagoNormal(horasNormales, pagoPorHora): pagoNormal = pagoPorHora * horasNormales return pag...
09b48b173a645ceea91885eb2c974bee12b894b4
RITUait/NLP-Projects
/stop_words.py
565
3.90625
4
#Stop words from nltk.tokenize import word_tokenize from nltk.corpus import stopwords example_sentence = "This is an example sentence to show you, how it is working." stop_words = set(stopwords.words("English")) filtered_sentence = [] example_tokenize = word_tokenize(example_sentence) print(example_token...
33d07a4a352d0885cb319f90cf87a39df440ebf0
Regato/exersise12
/Romanov_Yehor_Exercise21.py
1,476
3.796875
4
# 1st Exercise: input_data = input('** 1st input, Please enter any string sentence: ') split_data = input_data.split() output_data = [len(i) for i in split_data] print('1st output, Your result list is: ', output_data, '\n') # 2nd Exercise: input_data = input('** 2nd input, Enter any float numbers and separate them ...
d10ac24f32faecb7d6621605482825db923614ab
Regato/exersise12
/Romanov_Yehor_Exersise_9.py
781
4.0625
4
# Importing simplejson library to use loads function import simplejson # **Variables with input data (string type)** str_input_list = input() # Making from string to list with simplejson loads function json_loads_list1 = simplejson.loads(str_input_list) # This variable will contain the result of program output_list = l...
2e046c0d4fc1e243a8ae9e85b56d10f9195e473b
Regato/exersise12
/Romanov_Yehor_Exercise14.py
582
4.15625
4
# Entering input and making from string all UPPER case: input_string = input('[!] INPUT: Please enter your value (only string type): ') upper_string = input_string.upper() # Function that count letters in string: def letter_counter(x): return upper_string.count(x) # For cycle that check every letter for duplica...
2b605e60701e1fbda9d682afe5857b7202dfe6c2
calwoo/python-exercism
/difference-of-squares/difference_of_squares.py
284
3.859375
4
def square_of_sum(count): sum_of_count = count * (count + 1) / 2 return sum_of_count**2 def sum_of_squares(count): sum = 0 for n in range(count): sum += (n+1)**2 return sum def difference(count): return square_of_sum(count) - sum_of_squares(count)
38582bca142960e852de0445e04d76afb018a1fb
Jattwood90/DataStructures-Algorithms
/1. Arrays/4.continuous_sum.py
435
4.25
4
# find the largest continuous sum in an array. If all numbers are positive, then simply return the sum. def largest_sum(arr): if len(arr) == 0: return 0 max_sum = current = arr[0] # sets two variables as the first element of the list for num in arr[1:]: current = max(current+num, n...
5b2f85d9e26b3dcd0c3c8e7724d5091867d64dd1
Jattwood90/DataStructures-Algorithms
/4. Recursion/4. recursion_int_2.py
1,056
3.828125
4
# python has a itertools library that does this for you def permut(s, out=None): if out is None: out = [] if s in out: return out else: out.append(s) return permut((s[-1] + s[:-1]), out) # my attempt didn't solve all possible versions """ 1. iterate through...
13dab8fca1389c7d8c0598468d5ef12e6cb9f6a1
Jattwood90/DataStructures-Algorithms
/2. Stacks, Queues, Deques/4. Parenthesis_balance.py
869
3.96875
4
# Parentheis stack problem - you may be asked to create a stack using class, however it is doable using lists and its methods as a function. def balance(s): if len(s) %2 !=0: return False # edgecase check opening = set('[{(') matches = set( [('(',')'),('[',']'),('{','}')] ) st...
dbce4d3ef5dd9f1538f2b593784643e5f967f87f
nt3rp/computer-science
/trees.py
2,812
3.828125
4
class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def children(self): if self.value is None: return None count = 0 if self.left: count += 1 if se...
69493bf74b28704c11a941aa1b4f8e596b929b97
Zymbol/NotCarGurus
/Relations/insertgenerator.py
1,065
3.5
4
import csv tableName = "Customer" with open('Customer.csv', 'r') as csvinput: reader = csv.reader(csvinput) firstLine = False with open('create_{0}.sql'.format(tableName), 'w') as sqloutput: createCommand = """ DROP TABLE IF EXISTS {0}; CREATE TABLE {0} ( Account_ID INT UNSIGNED NOT NULL AUTO_...
0e7c9e5b71fde2ec0e7e3a17ff13530c3a432dc8
jvillamarino/python
/Platforms_courses/DataCamp/Learn_python_list/chapter_3_manipulation_list.py
5,101
4.15625
4
# INFORMATION ====================================================================== ''' You should copy list with reference or without reference ''' print("*" * 10, " With Reference ", "*" * 10) person_names = ["Jesús", "Humberto", "Sara", "Ronald"] students = person_names del person_names[3] # If you print per...
d5d78fb7c0300182a31418cadf08e3ef255997f3
jvillamarino/python
/Platforms_courses/Platzi/hanged_game.py
2,718
3.875
4
import random IMAGES = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O |...
9b9b07556cc95ec055af0e3ae93af5d7ace7a120
jvillamarino/python
/Platforms_courses/Platzi/factorial.py
339
4.3125
4
def calculate_factorial(number): if number == 1: return 1; return number * calculate_factorial(number-1) if __name__ == '__main__': number = int(input("Escribe un número a multiplicar: ")) result = calculate_factorial(number) print(f'El resultado del factorial para el número {numbe...
66f7d62439d660d0e4fe4ba44ead4de2fc85fb62
krasewallet/pytools
/zipFolder.py
941
3.75
4
#coding:utf-8 import zipfile import argparse import os def zipFolder(baseDir,zip_name): z = zipfile.ZipFile(zip_name,'w',zipfile.ZIP_DEFLATED) #参数一:文件夹名 for dirpath, dirnames, filenames in os.walk(baseDir): fpath = dirpath.replace(baseDir,'') #这一句很重要,不replace的话,就从根目录开始复制 for filename in filenames: z....
008ac86ed3421933d293ba65cb71f2fbf4843d66
HtutLynn/AsyncCV
/reader_writer_queue_np.py
6,131
3.84375
4
""" https://stackoverflow.com/questions/11515944/how-to-use-multiprocessing-queue-in-python 1. Classic Producer - Consumer problem (https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem) 2. Python multiprocessing 3. Pytorch multiprocessing 4. Bounded Buffer problem """ import os import sys import time from ...
1875db9c4ccb20388e20cd0983523bdc74e196d6
cbrandt83/Election_Analysis
/3.2.11_SkillDrill.py
723
3.859375
4
#the list of dicts voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county": "Denver", "registered_voters":463353}, {"county":"Jefferson", "registered_voters":432438}] #iterate through list of dictionaries # for dicts in voting_data: # print(f"{dicts['county']} county has {dicts['registered_vot...
45c2ea8e0cc264921ad6b6fae79a02bd4033b6f5
yycnetlab/ankidecks
/tools/yycnl-ankiaddcards-default.py
18,127
3.953125
4
# YYC Net Labs - Anki Script # Written by: Kelvin Tran - May 30th, 2020 (Prefix 933) # DISCLAIMER: This script is being provided as-is with no guarantee of functionality, availability, or support of any kind. # NOTE: For debugging, you can disable the bare exceptions (except: ...) - identified in the error message (For...
107eafaa7913959bc79cd7980beb87da3ebe29af
yashmittal21/Algorithms
/Find Max/16123004.py
158
3.875
4
l = [ 2,3,4,5,6,8] n = len(l) curr_max = 0 for i in n: # TODO Fill Code here if l[i] > curr_max: curr_max = l[i] print("Max element is ", curr_max)
888545a047ed7320d00c16825a84812df0fde621
gorefbitim/learn_python
/1_advanced.py
1,132
3.5625
4
import numpy as np import pandas as pd url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv" crime = pd.read_csv(url) crime.head() crime.info() # pd.to_datetime(crime) crime.Year = pd.to_datetime(crime.Year, format='%Y') crime.info() crime = cr...
05f4b33ea30c0562e66ee744f8ae4cde3a163b30
adafruit/Adafruit_CircuitPython_VL53L0X
/examples/vl53l0x_simplecontinuous.py
1,589
3.59375
4
# SPDX-FileCopyrightText: 2021 Smankusors for Adafruit Industries # SPDX-License-Identifier: MIT # Simple demo of the VL53L0X distance sensor with continuous mode. # Will print the sensed range/distance as fast as possible. import time import board import busio import adafruit_vl53l0x # Initialize I2C bus and senso...
4a1f4998286fa36eb64a2fc66841759d049e41d6
MarcoFaretra93/ggpl
/2016-10-28/workshop_03.py
3,224
3.625
4
from pyplasm import * import math def generate_steps(stepNumber, tread, riser, stepWidth): """ generate_steps is a function that, given a stepNumber represent the number of the step, tread represent the depth of the step, riser represent the height of the step and at the end stepWidth that represent the width of t...
306ac2e072b8d0748bbaba2b08b65efd1a4bd837
apiphidayatal/segitigapython
/input>.py
265
3.890625
4
print("masukan nilai"); baris = input("") baris = int (baris) for i in range (0, baris): for j in range(0, i + 1): print("*", end=' ') print("") for i in range (baris, 0, -1): for j in range(0, i -1): print("*", end=' ') print("")
5142c17653f8694c190642b5dee21e92449fa384
DavidNP96/Heuristieken
/code/algorithms/kmeans.py
1,038
3.640625
4
from copy import deepcopy import numpy as np import random from matplotlib import pyplot as plt def kmeans(neighborhood, iterations): """K-means algorithm. Finds the location for the batteries where the total distance of the neighborhood are the lowest. """ current_distance = 0 for house in...