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
b287cb17087999c6af8cd81aeaf5175e44a0d1d3
TeknikhogskolanGothenburg/PGBPYH21_Programmering
/okt 8/namingconvention.py
751
3.578125
4
# Constant values are named using SCREAMING_SNAKE_CASE RED = (255, 0, 0) BLUE_COLOR = (0, 255, 0) # Classes are named using CapWords class BasketballTeam: def method1(self): pass def method2(self): pass def snake_case_name(this_is_also_snake_case): for i in range(10): pass ...
abb9d52157685bddea5221d814e0d85d7bfb0f12
AI-mania/cspath-datastructures-capstone-project
/SoHo Restaurant Project/SoHo_project_presentation.py
5,949
4.625
5
# NO PEEKING AT THE PROJECT CODE BEFORE RUNNING IT # DON'T CHEAT!! # RUN THE CODE TO VIEW THE PRESENTATION ...
3a6c89a859aa5e88fdc95863b45800c7c7603b18
DanAVV/PythonHomework
/Python_Homework_electionresults.py
2,131
3.65625
4
import os import csv from collections import Counter csvpath = os.path.join( "/Users/Danie/Desktop/Python1/", "election_data.csv") votes = 0 uniques = [] ballots = [] ballotsc = [] words3 = [] words4 =[] percentages = [] with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, deli...
5b4d7b4fbee0d15a4787266226e494223d657152
Orlando-MLDS/GettingStartedWithData
/dataloader.py
1,366
3.78125
4
import pandas as pd # Suggestion: functions named after file type and if with Pandas # ie, csv_load and csv_pandas or similar # only making one Excel function, two outputs to demo def Excel(file): # Pandas excel loader is built off of several other excel readers, # such as openXLRD and xlsxwriter # t...
d8d31d1041cfc68d4b072bdae46d417f192d55ae
nurgleth/data_analysis
/less 4/process.py
1,176
3.546875
4
import os import time from multiprocessing import Process, Queue # класс процессор и класс очередь final_fib_number = 40 def worker(task: int, process_index: int): # вычисляем числа Фибоначи process_index - айди процесса def fib(n: int) -> int: return fib(n - 1) + fib(n - 2) if n > 2 else 1 numbe...
e9e2bd2ea3128c517e4b4cb2663288521cbc689c
matthias-gass/rock-paper-scissors
/players.py
1,194
3.5
4
import random import logbook player_log = logbook.Logger('PLAYERS_LOG') computer_names = ['Dozer', 'Petra Leuchter', 'A. Fast'] class Player: def __init__(self, name): self.name = name self.current_roll = None self.current_score = 0 def pick_current_roll(self, rolls): ...
7d834b6c24fbec9ae2eb7ffb4bd3a42f1d0335ee
Bakushin10/programming-practice
/effective-python/class/classMethod2.py
948
3.75
4
class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + '.' + last + "@email.com" self.pay = pay Employee.num_of_emps += 1 def fullname(self): return "{} {}".format...
274eee2343e7ed435fa5dd37ed537203156a5b06
Bakushin10/programming-practice
/medianOfTwoSortedArrays.py
716
3.609375
4
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ # m1 = self.getMedian(nums1) # m2 = self.getMedian(nums2) m = sorted(nums1 + nums2) print(m) ans...
8caaf4793e0f1797a5bbde3c09bc44cf4e91bfd5
Bakushin10/programming-practice
/twoNumber.py
682
3.53125
4
class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 ans = ListNode(0) while l1 or l2: Sum = carry if l1: Sum, l1 = Sum + l1.val, l1.ne...
c98cd32c4782e731575070d3b0c36d0c7b4958fe
Bakushin10/programming-practice
/shoppingOffer_recur.py
1,902
3.578125
4
""" https://leetcode.com/problems/shopping-offers/ """ from operator import add from operator import mul class Solution(object): def shoppingOffers(self, price, special, needs): """ :type price: List[int] :type special: List[List[int]] :type needs: List[int] :rtype: int ...
6b81e0ab8d59adb4ef7928506d4cf4c2c7db6769
Bakushin10/programming-practice
/algo/largestRange.py
1,245
3.671875
4
def largestRange(array): # Write your code here. # sort and remove duplicates # # runtime O(n) # # array = list(sorted(set(array))) start = 0 curr = 0 longestDistance = 0 res = [] if len(array) == 0: return 0 if len(array) == 1: return [array...
b31e9361c8d5e1add361982e68eba7fd5eb8fc3d
Bakushin10/programming-practice
/bitwise/bitwise_operations.py
507
3.65625
4
def is_chosen_color(chosen_colors, color): # 'chosen_colors & color' is binary AND return color == chosen_colors & color red = 1 blue = red << 1 yellow = blue << 1 green = yellow << 1 pink = green << 1 white = pink << 1 black = white << 1 # binary OR to include all chosen colors chosen_colors = red | yellow | w...
1cc24fc037a68690e9e6b70a890b97cb51f7d38b
Bakushin10/programming-practice
/interview.py
2,797
3.65625
4
""" random problems for the interview """ def duplicate(arr): """ [1, 2, 3, 1, 4, 5, 2] 1, 2 """ duplicate = [] for i in range(len(arr)): target = arr[i] ocur = arr.count(target) if ocur > 1 and target not in duplicate: print(target) d...
5aa3b17662546c231c834752fa01836b9d66df0b
Bakushin10/programming-practice
/algo/increasingSubsequence.py
608
3.75
4
""" https://www.algoexpert.io/questions/Max%20Sum%20Increasing%20Subsequence """ def increasingSubsequence(array): maxSum = [array[0]] maxIndex = 0 for i in range(1, len(array)): currentMax = array[i] for j in range(i): if array[j] <= array[i] and currentMax <= maxSum[j] + array[...
6e533089bda7d9f4e7d57c327f50a68d891261b0
JustForkin/Programming
/Python/PythonSimple/src/SpellChecker.py
989
3.828125
4
''' Created on May 11, 2011 @author: Michael ''' class SpellChecker: #Reads in a list of words from Dictionary.txt and "spell-checks" user-inputted words def spellCheck(self): myFile = open("Dictionary", 'r') wordList = myFile.readlines() for i in range(0, len(wordList), 1): ...
74251f502d61ba389be20ed190d0dc380a5ec5de
nclarkson147/cs331-s21-anaaparamesh
/lab08/lab08.py
12,465
3.6875
4
from unittest import TestCase import random import functools ################################################################################ # 1. IMPLEMENT THIS HEAP ################################################################################ class Heap: def __init__(self, key=lambda x: x): self.dat...
e24f37b0b915edddec4fb8f350e199f5bd6810f3
deejaymmm/Python_Next
/re_sub.py
528
3.75
4
import re import sys pattern = r"human" for line in sys.stdin: string = line.rstrip() print(re.sub(pattern, "computer", string)) """ Вам дана последовательность строк. В каждой строке замените все вхождения подстроки "human" на подстроку "computer" и выведите полученные строки. Sample Input: I need to under...
4d9695091b3abd9a3faaf1ce044effd7ab13942a
ValeriKozarev/Valerium
/test/blockchain_test.py
1,568
3.515625
4
import unittest from src.blockchain import Blockchain class TestBlockchainMethods(unittest.TestCase): """ All unit-testing for the blockchain class exists here """ def test_node_registration(self): blockchain = Blockchain() self.assertEqual(len(blockchain.nodes), 0) blockchai...
c54395797d91b3dfe5ce506b3f62c46a40b3a3e4
misty-garcia/python-exercises
/4.7_numpy_exercises.py
6,734
3.84375
4
import numpy as np a = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7]) # How many negative numbers are there? neg_a = a[a<0] neg_a len(neg_a) # How many positive numbers are there? pos_a = a[a>0] pos_a len(pos_a) # How many even positive numbers are there? pos_and_even_a = pos_a[pos_a % 2 == 0] pos_and_even_a...
7652b7429fb21fb7dd762ac2036a874787616d62
misty-garcia/python-exercises
/solutions.py
3,808
3.734375
4
def isnegative(numb): ''' >>> from solutions import isnegative >>> type(isnegative(0)) <class 'bool'> >>> isnegative(4) False >>> isnegative(0) False >>> isnegative(-6) True ''' return numb < 0 def count_evens(numbs): ''' >>> from solutions import count_evens ...
348b06da5feb831184eade63a4a5475e349f5fd9
stllfe/data-structures
/src/trees/binary_tree.py
5,737
3.703125
4
from collections import deque class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __str__(self): return f'<Node: {type(self.value).__name__} = {self.value}>' def __bool__(self): return True ...
70ef82c7ddc5906442e2d0c6d31af224bec43209
josedlujan/python-examples-pycharm
/PrimerProyecto/nuevo.py
610
3.765625
4
import threading import time ''' Es decir, si tienes un archivo llamado mi_modulo.py, si lo ejecutamos como programa principal el atributo __name__ será '__main__', si lo usamos importandolo desde otro modulo (import mi_modulo) el atributo __name__ será igual a 'mi_modulo'. ''' class MiHilo(threading.Thread): ...
944bcfd2a043d24a1ba027350f40181be9df4e12
skafev/Python_fundamentals
/05.Fifth_week_more_exersices/01Messaging.py
474
3.609375
4
numbers = input().split() text = input() secret_word = "" while len(numbers) > 0: i = 0 sum_digits = 0 for num in numbers[0]: sum_digits += int(num) while i < sum_digits: for x in enumerate(list(text)): i += 1 if i == sum_digits + 1: secret_wo...
1ece4dc8dbea4b1ec13a63548011f70c3e5573c1
skafev/Python_fundamentals
/02.Second_week_exersice/03Elevator.py
197
3.703125
4
number_of_people = int(input()) capacity = int(input()) courses = 0 while capacity > 0: number_of_people -= capacity courses += 1 if number_of_people <= 0: break print(courses)
9e2da82d3fd629d472021de2e8cc249a28942c1b
skafev/Python_fundamentals
/06.Six_week/03Emails.py
725
3.65625
4
class Email: def __init__(self, sender, receiver, content): self.sender = sender self.receiver = receiver self.content = content self.is_send = False def send(self): self.is_send = True def get_info(self): return print(f"{self.sender} says to {self.receiver}...
6a473211bdf82c3517d5bdab14c4e776607b9f8a
skafev/Python_fundamentals
/09.Nine_week_exersice/02Find_Variable_Names_in_Sentences.py
211
3.6875
4
import re text = input() pattern = re.compile(r'(\b_)([A-Za-z0-9]+)\b') matches = re.findall(pattern, text) res = [] for match in matches: _, variable = match res.append(variable) print(','.join(res))
a966f488918be020548d8c0cfbebfa4afca4ad5d
skafev/Python_fundamentals
/03.Third_week_more_exersices/01Zeros_to_back.py
141
3.78125
4
numbers = input().split(", ") numbers.sort(key="0".__eq__) my_list = [] for number in numbers: my_list.append(int(number)) print(my_list)
acd9f66acc86cfaafae4b7a1014661e9d1d7f063
skafev/Python_fundamentals
/Final_exam/03-03-03The_Pianist.py
1,502
3.875
4
number_of_pieces = int(input()) pieces = {} for n in range(number_of_pieces): data = input().split("|") piece = data[0] composer = data[1] key = data[2] pieces[piece] = {} pieces[piece]["composer"] = composer pieces[piece]["key"] = key while True: command = input().split("|") if co...
657761041e3920565b92187a140a1c3434c1630b
skafev/Python_fundamentals
/08.Eight_week_exersice/10Wining_ticket_50_100.py
1,145
3.84375
4
tickets = input().replace(", ", " ").split() winning_symbols = "@", "#", "$", "^" symbols = "" left_side = "" right_side = "" symbol = "" for ticket in tickets: if len(ticket) < 20 or len(ticket) > 20: print("invalid ticket") continue if ticket == 20 * "@" or ticket == 20 * "#" or ticket == 20 *...
cfcada2ac7db5861ecde85c1766d9e2739d0d7f1
skafev/Python_fundamentals
/Final_exam/01-01Secret_chat.py
891
3.90625
4
message = input() while True: command = input() instructions = command.split(":|:") if instructions[0] == "Reveal": break elif instructions[0] == "InsertSpace": index = int(instructions[1]) message = message[:index] + " " + message[index:] print(message) elif instr...
360229f6d905a565d58cf0b4687c1ddf002ce8fa
skafev/Python_fundamentals
/07.Seventh_week_exersice/05SoftUni_parking.py
787
3.828125
4
num = int(input()) registered_cards = {} for n in range(1, num + 1): command = input().split() reg = command[0] if reg == "register": name = command[1] plate = command[2] if not name in registered_cards: registered_cards[name] = plate print(f"{name} registere...
2e743720f34319261233944a9c374dccce8a1778
skafev/Python_fundamentals
/04.Fourth_week_exersice/03Character_in_range(ASCII).py
302
3.890625
4
def characters(a, b): new_str = "" if ord(a) <= ord(b): for i in range(ord(a) + 1, ord(b)): new_str += chr(i) + " " else: for i in range(ord(b) + 1, ord(a)): new_str += chr(i) + " " return new_str a = input() b = input() print(characters(a, b))
2f3d25b53c0e55f3a917e608de0b82b26f8df2bd
skafev/Python_fundamentals
/04.Fourth_week_exersice/07Perfect_number.py
325
3.75
4
def perfect_number(number): half = number // 2 perfect = 0 for i in range(1, half + 1): if number % i == 0: perfect += i if perfect == number: return "We have a perfect number!" else: return "It's not so perfect." number = int(input()) print(perfect_number(num...
3dc0d2b569c39af9c8fe60a9abc1d62efc0537ab
victortaksheyev/algorithms
/phil422/recursive.py
3,857
3.578125
4
wff = "a>b>c>d" # wff = "a" wff2 = "a" # for each connective connectives = '>' # returns index of wff def findConnective(wff, indexes): if (len(wff) == 1): return -1 # it's an atomic for i in range(len(wff)): # looping through all chars in wff ...
db64c4552a3eef0658031283a760edc8cf20b3c0
mprzybylak/python2-minefield
/python/getting-started/functions.py
1,568
4.65625
5
# simple no arg function def simple_function(): print 'Hello, function!' simple_function() # simple function with argument def fib(n): a, b = 0, 1 while a < n: print a, a, b = b, a+b fib(10) print '' # example of using documentation string (so-called docstring) def other_function(): """Simple gibbrish print...
4e74d5c2daab465fb953d7cc42b1cab47ae1618e
mprzybylak/python2-minefield
/python/getting-started/list_comprehensions.py
336
3.796875
4
# generate list # syntax = [ <expression> <for_expression> ] # for_expression = <for_statement> <if_statment(optional)> squares_list = [x**2 for x in range(10)] print str(squares_list) even_list = [x for x in range(10) if x % 2] print even_list # tuple has to be in parenthesis tuples = [(x,x*2) for x in range(10)] p...
336522ccc3314a8dc4e7e3d0b361a2538152ed46
mprzybylak/python2-minefield
/python/getting-started/for.py
1,128
4.40625
4
# Regular for notation acts as an interator words = ['first', 'second', 'third'] print 'Regular loop over list: ' + str(words) for w in words: print w # If we want to modify list inside for - it is best to create copy of list list_to_modify = ['1', '22', '333'] print 'example of modifiaction list in loop: ' + str(li...
0f13bc560c2fc59fb9cae90911f91a0357d01e42
mines-nancy-tcss5ac-2018/td1-phmoisset
/problem16.py
337
3.734375
4
# Projet Euler ## Problem 16 def solve(n): """Solve the 16th Euler problem. Return the sum of the digits of 2**n.""" number = str(2**n) sum = 0 for digit in number: #run through the number sum+=int(digit) #convert each digit of the string into an integer and sum it return sum assert(solv...
8541c2deb4d9e04e5d66ab0a00caf0b177659a6d
surenderpal/Durga
/OOps/operators.py
2,438
4.09375
4
a= 10 b= 3 # print(a+b) # print(a-b) # print(a*b) # print(a/b) # print(a%b) # print(15/3) # 5.0 # print(15.0/3) # 5.0 # print(15//3) # 5 # print(15.0//3) # 5.0 # print(20/2) #10.0 # print(20.5/2) #10.250 # print(20/2) # 10.0 # print(20.5//2) #10.0 # print(30//2) #15 # print(3**3) #27 # prin...
fee998cab71707967dde3294cca064613fe6a2da
surenderpal/Durga
/OOps/string.py
596
3.84375
4
# s =input('enter any string:') # i=0 # for x in s: # print('The character present at positive index {} and yet negative index {} is {}'.format(i,(i-len(s)),x)) # i+=1 # s='surenderpal' # print(s[2:7]) # print(s[0:7]) # print(s[:]) # print(s[0:8:0]) # print(s[:0]) s='abcdefghij' # print(s[1:6:2]) #bdf # pri...
457c259a8515b806833cf54ccd0c79f8069f874c
surenderpal/Durga
/Regular Expression/quantifiers.py
481
4.125
4
import re matcher=re.finditer('a$','abaabaaab') for m in matcher: print(m.start(),'...',m.group()) # Quantifiers # The number of occurrences # a--> exactly one 'a' # a+-> atleast one 'a' # a*-> any number of a's including zero number also # a?-> atmost one a # either one a or zero number of a's # a{num}-> Ex...
0c2a22ffa7093edd9382419857559807d262c0ab
surenderpal/Durga
/Decorator/with_&_without_decorator.py
565
3.625
4
def decor_for_wish(func): def inner(name): names=['CM','PM','MINISTER','surender','upika'] if name.lower() in names: print('*'*50) print('Hello {} you are very important Asset to India, \nThanks for coming here, \nWe are honored.'.format(name)) print('@'*50) ...
b11cabd8b56030b9eeec1d150be3a4b5985d371f
surenderpal/Durga
/Multithreading/condition.py
499
3.5
4
from threading import * c=Condition() def consumer(c): c.acquire() print('consumer waiting for updation.') c.wait() #now thread will entered into the waiting state print('consumer got notification & consuming the item') c.release() def producer(c): c.acquire() print('Producer producing i...
90de96c254f6adfe468d20fee4b048d9fe4a5eab
surenderpal/Durga
/OOps/Inner_inner_class_part2.py
710
3.609375
4
class Human: def __init__(self,name): print('Human object creation....') # self.name=name self.head=self.Head() # def info(self): # print('Hello, Myself:',self.name) # print("I'm full busy with...") # self.head.talk() # self.head.brain.think() class He...
7236fc5b11d50e6ca6b62a406ee0c9063a03d30b
surenderpal/Durga
/Serialization & Deserialization/pickling.py
505
3.546875
4
import pickle class employee: def __init__(self,eno,ename,esal,eaddr): self.eno=eno self.ename=ename self.esal=esal self.eaddr=eaddr def display(self): print("Emp NO: {}, Emp Name: {}, Emp Salary:{}, Emp Adderess:{}".format(self.eno,self.ename,self.esal,self.eaddr)) e=em...
f1bf06f8b5ca3ca4af8a0c0127d758f83f4cbff8
surenderpal/Durga
/OOps/input&output.py
1,204
4.03125
4
# x=input('enter val:') # print(id(x)) # print(type(x)) # sum of two no # a=int(input('enter one num:')) # b=int(input('enter two num:')) # sum=a+b # print('sum of two no is:',sum) # print('sum is:',int(input('enter one num:'))+int(input('enter one num:'))) # employe detail # e_no=int(input('Enter emp no:')) # e_name...
03a5464fbdab40308bd45b22ada8f457f6e8aa9d
surenderpal/Durga
/OOps/super.py
665
3.703125
4
class P: def m1(self): print('parent method') class C(P): def m1(self): super().m1() print('Child mehtod') c=C() c.m1() #=================== class P: a=10 def __init__(self): print('Parent Construcor') def m1(self): print('Parent Instance method') @classm...
f371ade073957c6f5406d2910a724ba120cd64de
surenderpal/Durga
/OOps/adding3objects.py
425
3.796875
4
class Book: def __init__(self,pages): self.pages=pages def __add__(self,other): return Book(self.pages + other.pages) def __str__(self): return "Total no of pages in book are {}".format(self.pages) def __mul__(self,other): return Book(self.pages * other.pages) b1=Book(10...
58d4f35fdf640388fc60b84aaf5828dd38614495
surenderpal/Durga
/OOps/set.py
1,960
3.640625
4
# s={} # s=set() # print(type(s))ß # s.add(10) # s.add(23) # s.add(43) # s.add(234) # s.add(10) # print(s) # print(s[0]) # print(s[::]) # s=set() # empty set # print(type(s)) # s.add(1) # s.add(23.44) # s.add('A') # print(s) # st={10,20,30,'A',10.233,10} # print("Declared with data:",st) # l=[10,20,30.90,10,33] # sp=se...
9e4d38f698d07cacac143d144ce67e9dc52d5032
slckmndl/6.-Hafta-Odevler
/1 - SAyi Tahmin Oyunu.py
1,726
3.625
4
print(""" ==============================================" | | | SELCUK DAL | | SAYI TAHMIN OYUNU | | V 2.3 | | HOSGELDINIZ ...
6b646a2ce403fa5570ea78be2fb0802e8b03a399
jpeters280/pylottest1
/app/controllers/Users.py
2,491
3.875
4
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * class Users(Controller): def __init__(sel...
a96a230251cd1a9146b0098d56ca2e9b5a89a0c8
nilecui/nile_python_swk
/thread/myqueueAddThread.py
742
3.671875
4
#!/usr/bin/python #-*- coding:utf-8 -*- import Queue import threading import time import random q=Queue.Queue(0) NUM_WORKERS=3 class MyThread(threading.Thread): def __init__(self,input,worktype): self._jobq=input self._work_type=worktype threading.Thread.__init__(self) def run(self): while True: if self...
19b0da8da04f63b7b93bfbb9832068e175fc4780
nilecui/nile_python_swk
/xml/parsexml.py
1,798
3.609375
4
#!/usr/bin/python #-*- coding:utf-8 -*- from xml.etree import ElementTree def print_node(node): '''打印节点信息''' print "="*30 print "node.attrib:%s"%node.attrib if node.attrib.has_key("age")>0: print "node.attrib['age']:%s"%node.attrib['age'] print "node.tag:%s"%node.tag print "node.text:%...
7a63cbf95a390839f512b603a5d13088bae69252
nilecui/nile_python_swk
/yield/test4.py
164
3.515625
4
#!/usr/bin/python #-*- coding:utf-8 -*- def h(): print "one" yield 1 print "two" yield 2 print "three" yield 3 for i in h(): print i
9bb03d5dbcf2bdb271e2d62bc71f8cbcae14a5df
nilecui/nile_python_swk
/xml/xmltree.py
2,791
3.59375
4
#!/usr/bin/python #-*- coding:utf-8 -*- #**************************************************** # Author: nile cui - nile.cui@gmail.com # Last modified: 2013-03-29 17:01 # Filename: xmltree.py # Description: #**************************************************** from xml.etree import ElementTree def pr...
2a64b41180c804ed75daa846f6918ff136088438
L200180213/Prak_algostruk
/L200180213_Modul3-4-6_H/Modul3-4-6.py
5,529
3.703125
4
def det(a): if len(a)>=3: for i in range(len(a)): #loop ini berguna untuk a[i]=a[i]+a[i][:-1] #mengubah menjadi sorrus print(a) b2=[ 1 for i in range(len(a))] #determinan kekiri negatif b1=[ 1 for i in range(len(a))] ##determinan kekanan positif for i in r...
3bdb2125a9f82dfa94df013c418e042e7eb33e6d
adreena/DataStructures
/LeetCode-DP-Rec/LongestValidParenthesis.py
479
3.78125
4
''' Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. ''' def longestValidParent(s): stack = [-1] max_len = 0 while i < len(s): if s[i] == ')': stack.pop() if len(stack)==0: st...
2c53a0967ba066ca381cc67d277a4ddcd9b3c4e7
adreena/DataStructures
/Arrays/MaximumSubarray.py
358
4.125
4
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. ''' def maxSubarray(nums): max_sum = float('-inf') current_sum = nums[0] for num in nums[1:]: current_sum = max(current_sum+num, num) max_sum = max(max...
9def2db98f31e5beac29238cc1d1bdfc33a111ed
adreena/DataStructures
/LeetCode-graph-tree-bt/SubtreeofAnotherTree.py
406
4.03125
4
def isSubtree(t1, t2): if t1 is None and t2 is None: return True if t1 is None or t2 is None: return False if t1.val ==t2.val and isSubtree(t1.left, t2.left) and isSubtree(t1.right, t2,right): return True return False def traverse(t1, t2): if t1 is not None: return...
4aedee9a32b35e7d508d46867c3ba20f047affa8
adreena/DataStructures
/P0/Task3.py
3,369
4.21875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixe...
0b39b10980443f80988327082b16ff9b0733bd57
adreena/DataStructures
/LeetCode-DP-Rec/LongestPalindromic.py
689
4.0625
4
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" ''' def longestPalindromic(s): dp = [[False]*(len(s)+1)]*(len(s)+1) for i in range(len(s)+1): dp[i][i]=True k=0 max_len = 0 start...
bc98f10b6a444d53b32ecc62fcd80548b25f0cac
adreena/DataStructures
/LeetCode-Array/pow.py
255
3.828125
4
def pow(x, n): if n == 0: return 1 if n == 1: return x temp = pow(x, int(n/2)) if n >0: if n%2 == 0: return temp*temp else: return temp*temp*x else: return temp*temp/x
cf2b6794d3d6dbe17d5ee7d88cabecae3b9894d2
xuyuntao/python-code
/2/def.py
1,049
4.125
4
print("来学习函数吧") def MySun(*args): sum = 0 for i in args: sum += i return sum print(MySun(1,2,3,4,5,6)) def func(**args): print(args) print(type(args)) func(x=1, y=2, z=3) """ lambada的主体是有一个表达式,而不是代码块,仅仅只能在lambda中 封装简单逻辑 lambada的函数有自己的命名空间 """ sum = lambda num1, num2: num1 + num2 print(s...
f5b7673a8c092aa49bec8f2d464f01acb67c6d80
xuyuntao/python-code
/2/turtle_test.py
496
4.125
4
""" 一个简单绘图工具 提供一个小海龟,可以把它理解为一个机器人,只能听懂有限的命令 其他命令 done()保持程序不结束 """ import turtle turtle.speed(10) turtle.forward(100) turtle.right(45) turtle.forward(100) turtle.left(45) turtle.forward(100) turtle.goto(0,0) turtle.up() turtle.goto(-100,100) turtle.down() turtle.pensize(5) turtle.pencolor("red") turtle.goto(100,-100...
bdaf415fd7ec5fe7fe07e12163d327ddc9634ded
iliff/atla-2019
/compare_files.py
1,900
3.6875
4
import pandas as pd # load data ebooks1_df = pd.read_csv('https://raw.githubusercontent.com/msaxton/atla2019_workshop/master/ebooks1.csv') ebooks2_df = pd.read_csv('https://raw.githubusercontent.com/msaxton/atla2019_workshop/master/ebooks2.csv') # prepare data ebooks2_df['ISBN'] = ebooks2_df['ISBN'].str.replace('-', ...
eac6ea97416a99011a76406db5da615b700506b6
alexey-ernest/codility
/7_stacks_and_queues.py
962
3.765625
4
""" Stacks and queues """ N = 10 """ Stack """ stack = [0] * N size = 0 def push(x): global size stack[size] = x size += 1 def pop(): global size size -= 1 return stack[size] # push(1) # push(2) # print stack, size # print pop() # print stack, size """ Queue """ queue = [0] * N head = tail = 0 def pu...
9d1ddaa1e3578d3e048a01670798b751c0548d63
brenn502/PersonlProjects
/Rotate2dArray.py
1,177
3.65625
4
def rotate90(table): size = len(table) layer_count = size // 2 for layer in range(0, layer_count): first = layer last = size - first - 1 for element in range(first, last): offset = element - first temp = table[element][last] # r...
da5351865dade70a2cc4e8606c3533572927cab8
IEEE-WIE-VIT/Awesome-DSA
/python/Algorithms/Recursion/bal-paranthesis.py
391
3.515625
4
#Generate all balanced Parenthesis n = int(input("Enter number: ")) o = n c = n op = "" a = [] def sol(w, x , y, z): if (w==0 and x ==0): z.append(y) return if (w!=0): op1 = y op1 += "(" sol(w-1, x, op1, z) if (x > w): op2 = y op2 += ")" ...
855817e03fa062cb755c166042bdb16037aefe5c
IEEE-WIE-VIT/Awesome-DSA
/python/Algorithms/quicksort.py
898
4.28125
4
# Function that swaps places for to indexes (x, y) of the given array (arr) def swap(arr, x, y): tmp = arr[x] arr[x] = arr[y] arr[y] = tmp return arr def partition(arr, first, last): pivot = arr[last] index = first i = first while i < last: if arr[i] <= pivot: # Swap if curr...
5d81d3e6f16f4fc1d5c9fcc5ed452becefa95935
IEEE-WIE-VIT/Awesome-DSA
/python/Algorithms/Queue/reverse_k_queue.py
1,231
4.46875
4
# Python3 program to reverse first k # elements of a queue. from queue import Queue # Function to reverse the first K # elements of the Queue def reverseQueueFirstKElements(k, Queue): if (Queue.empty() == True or k > Queue.qsize()): return if (k <= 0): return Stack = [] ...
b37943107098a282133a2ebb7d1fbd5203bcd024
The1ntern/INA
/NetworkCardSelection.py
1,996
3.765625
4
import os import time #This script is to allow the user to select a wireless interface and then use that interface through the duration of the attack... # PYTHON VERSION 2.7.13 def interfaceSelectionChoice(): try: print("***Below will be your available wireless interfaces, please type any, but with no spa...
f60568c97371bee243b94e50d703ce87e1d7a90d
Yertle-The-Turtle/Practice-Python
/playVideoTimeUdacity.py
747
3.546875
4
#play video evey two hours import webbrowser #imprt webbrowser module import time #import time module count = 0 breaks = int(input("please enter amount of breaks you wish to take within the next 12 hours:\n"))#get number from user sleepTime = 12/breaks #caculate time sleep time needed print ("this programe started on"...
f0cfa90d7588409e26a780b6ddf0cd9a244ff154
Diegokernel/holbertonschool-machine_learning
/math/0x00-linear_algebra/4-line_up.py
263
3.65625
4
#!/usr/bin/env python3 """Add a function to calculate the element wise sum""" def add_arrays(arr1, arr2): """calculate element wise sum""" if len(arr1) != len(arr2): return None return [sum(element_wise) for element_wise in zip(arr1, arr2)]
6980c0139ced2383031a8d2c73c263d1497d2a2d
Diegokernel/holbertonschool-machine_learning
/math/0x06-multivariate_prob/multinormal.py
1,593
3.90625
4
#!/usr/bin/env python3 """ Multivariate Normal distribution """ import numpy as np class MultiNormal(): """Multinormal class""" def __init__(self, data): """ Class constructor Args: data: data is a numpy.ndarray of shape (d, n): - n is the number of data points ...
bd89328d44a1e87c227c35afbf1080065c215d84
Diegokernel/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/0-l2_reg_cost.py
423
3.671875
4
#!/usr/bin/env python3 """ calculates the cost of a neural network with L2 regularization: """ import numpy as np def l2_reg_cost(cost, lambtha, weights, L, m): """ calculates the cost of a neural network with L2 regularization: """ sum1 = 0 for i in range(L): l2 = np.linalg.norm(weights["W"+str(i...
8998532f0ef384cfdaa02264bc962cfa0fc6076b
BiswaCodes/BiswaCodes
/PythonProjects/Hello World/AlterNativeSort.py
671
3.515625
4
import numpy print("enter the numbers : \n") num_List = [int(x) for x in input().split()] print(num_List) #sort the collection num_List.sort() print(num_List) lengthOfList = len(num_List) minIndex = 0 maxIndex = lengthOfList-1 #decalre an empty where to store the values #numpy ensures fixed lenth array which length...
b03fe3e1a2d046a0984e02e22b8b63ba2b21b636
Victorjcb28/Psp
/nacimiento.py
212
3.625
4
from datetime import datetime, date, time, timedelta dia=22 mes=04 ano=1989 d=date.today() ano1= d.year-ano cadena="hola" if d.month <= mes: if d.day < dia: ano1=ano1-1 print ano1 print cadena.center(50," ")
7a317fb745bd34828ef0811f33366877d6cfff37
abdulmuneer/Labs
/src/betting.py
892
3.546875
4
''' Created on May 9, 2012 @author: MUNEER ''' def get_final_amount(initial_amount, bet_results): if initial_amount < 1: print 'Initial amount is not a sufficient for the bet' return None inhand_amount, next_bet = initial_amount, 1 multiplying_factor = {'W':1,'L':-1} for re...
0baad778a238a508f7b45a09def403575a88a1e9
abdulmuneer/Labs
/src/string_similarity.py
722
3.609375
4
''' Created on May 12, 2012 @author: MUNEER ''' def similarity_index(mystring, start_index): count = 0 try: while mystring[count]==mystring[start_index+count]: count += 1 else: return count except: return count def get_output(mystring): length = len...
3df47fc1cccfeb17731be15a771614589da17699
DostEducation/voicemail_processing
/volume_cuts.py
1,503
3.6875
4
""" These functions detect and then remove empty or low-volume audio at the beginnings and ends of a wav file. """ from pydub import AudioSegment def detect_leading_silence(sound, silence_threshold, chunk_size=10): """ Iterate over audio chunks until you find the first one with sound sound is a pydub.AudioS...
3505ed6a3dd08a3406a5d099371fa9f2b90135b4
cindywindy/SAP
/counter.py
1,271
3.53125
4
from flask import Flask app = Flask(__name__) #constructor @app.route("/") def welcome(): return "Welcome!" #time & space complexity- linear. O(n) @app.route("/<int:countey>") def countey(countey): retVal = "" for x in range(1,countey+1): retVal += str(x)+" " return retVal #time & space comp...
43012784b596503267cd6db2beb45bd19a7d1b0a
cuongnguyen139/Course-Python
/Exercise 3.3: Complete if-structure
262
4.1875
4
num=input("Select a number (1-3):") if num=="1": num="one." print("You selected",num) elif num=="2": num="two." print("You selected",num) elif num=="3": num="three." print("You selected",num) else: print("You selected wrong number.")
8559731e0b4f67c44caee265237563bdfbaa5160
austinmcconnell/pycon-sponsors
/sponsors/models.py
1,333
3.75
4
""" Define database table structure. Functions that connect to the database and create all necessary tables are included. """ from sqlalchemy import create_engine, Column, String, Text, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL from . import settings BASE = ...
0e00c6e02b35819397620dabeb10dc7b3d8f9150
divx89/100DaysOfCode-Python
/Day023-21231-The_Turtle_Crossing_Game/car_manager.py
862
3.9375
4
from turtle import Turtle import random INIT_SPEED = 5 SPEED_INCREMENT = 10 COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] class CarManager: def __init__(self): self.cars = [] self.speed = INIT_SPEED def add_car(self): if random.randint(1, 6) == 3: new_c...
b5c7e38440dc79cc9c063835aadd6694b96f2035
divx89/100DaysOfCode-Python
/Day010-21218-Functions_with_Outputs/02-calculator(basic).py
1,153
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 7 00:20:02 2021 @author: divxd """ from art import logo def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return (n1 / n2 if n2 != 0 else None) operations = { '+': ...
a4b83d3f621e0e451f0ea7d944d6af1ca82c385b
divx89/100DaysOfCode-Python
/Day026-21235-List_Comprehension/List_Comprehension_Exercises/C03-Data_Overlap.py
210
3.53125
4
with open("file1.txt") as file1: num_list1 = file1.readlines() with open("file2.txt") as file2: num_list = [int(num) for num in file2.readlines() if num in num_list1] print(num_list1) print(num_list)
1097b2ec5df3b5d1ce66a52db21476db601174a3
divx89/100DaysOfCode-Python
/Day001-21209-Working_With_Variables/05-Variables.py
198
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 8 20:53:01 2021 @author: divxd """ #Day 001 - 05 - Variables a = input("a: ") b = input("b: ") c = b b = a a = c print("a: " + a) print("b: " + b)
0843ba84075b74304f9bf1fe376d42c3506480f2
divx89/100DaysOfCode-Python
/Day055-21272-HTML_URL_Parsing_in_Flask/URL_Parsing/hello.py
1,770
3.734375
4
from flask import Flask app = Flask(__name__) def make_bold(function): def wrapper(): return f"<b>{function()}</b>" return wrapper def make_underline(function): def wrapper(): return f"<u>{function()}</u>" return wrapper def make_emphasized(function): def wrapper(): ...
49ef57b0ab3467cfd22b408bdce4bbcfc0cecffd
divx89/100DaysOfCode-Python
/Day030-21242-Errors_Exceptions_and_JSON_Data/password-manager/password_generator.py
613
3.671875
4
# -*- coding: utf-8 -*- """ Password Generator, using loops and random Created on Sun Aug 1 17:05:16 2021 @author: divxd """ # Password Generator Project import random import string letters = string.ascii_letters numbers = string.digits symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] def gen_pwd(): p...
1389a276a68c9e6bc459ba5a25bc9a884496c669
divx89/100DaysOfCode-Python
/Day008-21216-Function_Parameters_and_Caesar_Cipher/01-Calc_Num_Cans_Required.py
778
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 4 12:14:09 2021 @author: divxd """ from math import ceil def paint_calc(height, width, cover): """ Function to find out how many paint cans are needed to paint a wall with given height and width Prints out the required information Parameters --...
bd2ec4f23240e2c2d3a4c757a1159ef1fd743f4b
divx89/100DaysOfCode-Python
/Day004-21212-Randomization_and_Lists/04-Lists_X_Marks_the_Spot.py
592
4.0625
4
# 🚨 Don't change the code below 👇 row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") # 🚨 Don't change the code above 👆 #Write your code below this row 👇 try: number = int(po...
d3d1c85e8c51a9e44ecdcb37e1a7883d795c9ab3
digimutts/xyz
/inversions.py
1,270
3.78125
4
from operator import itemgetter import math def countInversions(itemlist, n): if n == 1: return 0 elif n == 2: if itemlist[0] > itemlist[1]: return 1 def eras(n): # enumerate all odd primes primes = [True] * (n +1) # print(primes) i = 2 while i <= math.sqrt(n): ...
297071abe7a2bbfdb797a7cc84cc1aeac99f4850
RickyCode/CursoProgramacionBasico
/Codigos Clase 4/04_cuadrado.py
309
4.15625
4
# Se le pide un número al usuario: numero = int(input('>>> Ingresa un número: ')) # La función int() transformará el texto a número. # Se calcula el cuadrado del número: cuadrado_num = numero ** 2 # Se muestra en la pantalla el resultado: print('El cuadrado del número es: ', cuadrado_num)
559b4d30f9ff9edf9ef32e0471b2d0642cd633a5
blitzmann/adventofcode
/2016/day6/solve.py
404
3.578125
4
from collections import Counter lines = [] with open('input.txt', 'r') as file: for line in file: lines.append(line) # Part 1 answer = '' for i in range(len(lines[0])-1): answer += Counter([x[i] for x in lines]).most_common(1)[0][0] print(answer) # Part 2 answer = '' for i in range(len(lines[0])-1...
0321fb3720900a8ae0ec0e8acc90c6148701b32e
blitzmann/adventofcode
/2017/day1/solve.py
414
3.546875
4
with open("input.txt", "r") as ins: string = ins.read() length = len(string) half = int(length / 2) digits = [] # Part 1 for i, x in enumerate(string): t = (i+1) % length if x == string[t]: digits.append(int(x)) print(sum(digits)) # Part 2 digits.clear() for i, x in enumerate(string): t = (...
8e3d2e98da17dffb9597dbf661a734da8de30b58
blitzmann/adventofcode
/2018/day13/solve.py
4,397
3.640625
4
from enum import IntEnum # Define directions class Direction(IntEnum): NORTH = 1 WEST = 2 EAST = 3 SOUTH = 4 # define various map elements class Map(IntEnum): HORIZONTAL = 1 VERTICAL = 2 INTERSECTION = 3 CORNER_BACK = 4 CORNER_FORWARD = 5 # define some mappings direction_mapping...
b963650eadf5b332ecc4dc90e7afe34084afce64
SavaGeekbrains/Python-1
/Домашняя работа/задание 1.6.py
225
3.96875
4
a = float(input("Результат первого дня : ")) b = float(input("Цель которую хотите достичь :")) day = 1 if a > b: print(day) while a < b: a = a + a/10 day += 1 print(day)
b74e5d29ea6f8c4a0a4e13681c062493d51315ef
Eladtopaz/CodeWars-Walkthrough
/6 kyu/Decode the Morse code/python_solution.py
721
3.953125
4
def decodeMorse(morse_code): """ So, to mange doing this in 1 line: I took the string I got and removed the leading or trailing spaces using strip() Then, I used split(" ") to split it to a list, by the spaces in the string. Then, If the item is in the MORSE_CODE table, get it value, if not,...
854422da641a6bb84e8cc48e3f572a02f99763af
Eladtopaz/CodeWars-Walkthrough
/5 kyu/Decimal to Factorial and Back/python_solution.py
1,103
3.578125
4
import math converter = { "10": "A", "11": "B", "12": "C", "13": "D", "14": "E", "15": "F", "16": "G", "17": "H", "18": "I", "19": "J", "20": "K", "21": "L", "22": "M", "23": "N", "24": "O", "25": "P", "26": "Q", "27": "R", "28": "S", "29"...
1affa9d36597d8201474447b42048e37b95fec01
Eladtopaz/CodeWars-Walkthrough
/5 kyu/Greed is Good/python_solution.py
806
3.5
4
def score(dice): score = 0 if dice.count(6) >= 3: if dice.count(6) == 6: return 1200 score += 600 if dice.count(4) >= 3: if dice.count(4) == 6: return 800 score += 400 if dice.count(3) >= 3: if dice.count(3) == 6: return 600 ...