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
1e89c6cb5a20d3bb706f1e433a8e20a47467362f
rosmoke/DCU-Projects
/week22/wordcomps_32.py
1,603
3.9375
4
import sys a = [] #each line is added to a for line in sys.stdin: a.append(line[:-1]) # Print a list of all words that contain exactly 17 letters. print(("Words containing 17 letters: {}").format([w for w in a if len(w) == 17])) # Print a list of all words that contain more than 17 letters. print(("Words containing ...
4212c3df2fe22bcbdac009a3a527d64da2fed79c
rosmoke/DCU-Projects
/week20/middle_11.py
177
3.90625
4
import sys word = sys.argv[1] def middle(x): if len(x) % 2 != 0: center = int(int(len(x)) / 2) return x[center] else: return "No middle character!" print(middle(word))
7a9673f15d019e3d98f5f4584ceec3f3d496a2f3
rosmoke/DCU-Projects
/bucketlist/bl-binary-to-decimal.py
359
4.125
4
import sys binary = sys.argv[1] i = len(binary) # here we set the counter to how many numbers we have power = 0 result = 0 while i > 0: # here we set the counter to do something i times result += int(binary[i-1]) * 2 ** power # we convert each number to decimal i = i - 1 power = power + 1 # now we increase the powe...
726bb767516fc21e1d146f53297453c07144846b
rosmoke/DCU-Projects
/sample_exam/file_111.py
1,305
3.59375
4
class File(object): FILE_PERMISSIONS = "rwx" def __init__(self, name, owner, size=0, permissions="null"): self.name = name self.owner = owner self.permissions = permissions self.size = size def has_access(self,name, permission): if name == self.owner: return("Access granted") if permission in self.per...
84e286681449216d891a0db9cf871a4ed7631d58
rkatipally/python-study
/src/excercises/black_jack/black_jack.py
7,364
3.65625
4
import random from functools import reduce class BlackJack: def __init__(self): self.deck = Deck() self.playing = True self.dealer = Dealer() self.player = Player('Raj', 1000) self.start_game() def start_game(self): self.take_bet() self.deal_cards(Fals...
66ca15efa16809fbc024caef9c42cccccc93666b
rkatipally/python-study
/src/oops/classes.py
597
3.9375
4
class Simple(): pass simple = Simple() print(simple) print(type(Simple)) print(type(simple) == Simple) class Person(): name = "Raj" person1 = Person() print(person1.name) person1.name = "Priya" print(person1.name) person1.surname = "Katipally" print(person1.surname) print(Person.name) del person1.name print...
ea4712cbf7bb4675e7e5ad9490e97c009ac32942
rkatipally/python-study
/src/datatype/number.py
447
3.546875
4
import sys from decimal import Decimal as D def showNumbers(): print(2/5) print(2//5) print(-7/4) print(-7//4) #Floor print(int(-7/4)) #Truncate to an integer print('Reminder:: ' + str(10%3)) print('=========Real===========') print(sys.float_info) print('=========Decimal===========...
5a4f103ab0692123d08ca0c44314a7655517f1d1
EricSeverson/MontyHall
/MontyHall.py
963
3.765625
4
""" This Program will simulate the Monty Hall problem over a large iteration to test its validity. """ from random import randint iterations = int(input("Please Enter the Number of Iterations you would like to use: ")) # doors[0] holds goats, doors[1] holds car doors = [[0, 0], 0] num1correct = 0 num2correct = 0 for...
c7c9521f8b47ca527007484d707a03226f04ecdf
pythontlh/intro_to_python_meetup
/increment.py
246
3.90625
4
A = "B" #A is a string print(A) A = 1 #A is now an Integer print(A) A+=1 print(A) #means to take the value of A (which is 1), and then add 1 to it A+=5 print(A) #means to take the value of A (which is 1), and then add 5 to it A-=5 print(A)
78b83921162655ff266cb7dba8a434bbcda3739e
pythontlh/intro_to_python_meetup
/while_loop.py
176
3.90625
4
b = 0 #defines the variables we are using outside of the loop while b < 100: # while this condition is true print (b) # do this b += 1 # very important step...why?
c3c6148181f8bebe09fdbcfa9111c4456f855110
ubbabubba/training2
/lottery.py
640
3.84375
4
import random def create_lotto(start_num:int, end_num:int, numb_game:int, extra_start:int, extra_end:int)->list: ''' Create a list of lotto number with extra ball if needed \n Parameters: --------------------------------------------------------------- Output: List ------------------...
2cfa75f3bee7a6515c90aadd1c45c327419d8b82
ankitdutta318/MorePython
/6_Functions.py
3,036
4.4375
4
# Functions are used for code reusablity # We use the keyword 'def' to define a function followed by the nem of the function # Even if the function o not have any parameters, the '()' and ':' is required # sample function def hello () : print ("Hello user") # calling the function hello() # now lets take name fr...
544b1d0fc22282ff73c7c3aa359e3c75a030e993
weddige/kcenter
/src/graph/kcenter.py
6,663
3.578125
4
""" Algorithms for k-center problems on graphs """ __author__ = 'Konstantin Weddige' import networkx import random import itertools import pulp import numpy import scipy.optimize from graph import squared_graph, dominating_set, add_missing_edges def objective(graph, centers): """Calculates the distance between n...
557f05e0ea84892c57e4becbfe65062478a7ecc7
aseemmehta/DecisionTreeClassifier
/HW06_Mehta_Aseem_Trainer.py
15,825
3.5
4
""" HW06_720_DecTrees_2191 Author: Aseem Mehta email: am1435@rit.edu Program uses a tarining dataset to train a decision tree classifier, and write another program to use the classifier on testing data """ # Importing the libraries import math as m import pandas as pd import numpy as np """ Imports the data set using...
d5e908a37334acc14814d3887169c0e8cc2ad877
rafaoncins/EP1
/Exercício_Programa(5).py
3,878
3.84375
4
import random Fichas = 100 print ('Você tem 100 fichas') quer_jogar = 'sim' quer_jogar = input ('quer jogar? ' ) while Fichas > 0 and quer_jogar == 'sim': print ('Fase Come Out') aposta = input('Muito bem, escolha qual tipo de aposta vai querer fazer, podendo ser: Line Bet, Fields, Any Craps ou Twelve: ') ...
08ef8f971812f815cf41a5b56050eb3bfeaf3917
abdullaheemss/abdullaheemss
/My ML Projects/Data Visualization Exercises/01 - Understanding plotting.py
626
4.125
4
# --------------------------------------------------------- # Understand basics of Plotting # --------------------------------------------------------- # Import pyplot from matplotlib import matplotlib.pyplot as plt # Create data to plot x_days = [1,2,3,4,5] y_price1 = [9,9.5,10.1,10,12] y_price2 = [11,12,...
c881cb79be62134645d52d2832debd6eaa37ef88
arjan-hada/bioinformatics_algorithms
/findIsolatedCycles.py
688
3.546875
4
def findIsolatedCycles(g, nodes): """Find isolated cycles given a list of one-in-one-out nodes""" paths = [] for node in nodes: isolatedCycle = [] def visit(n): while len(g[n]) > 0: nodes.remove(n) dst = g[n].pop() visit(dst) ...
ab8f166f68cb1bb13fa24aa3fe0d140809f6f5bf
webclinic017/data-pipeline
/linearRegression/lrSalesPredictionOnAddData.py
1,026
4.375
4
# https://towardsdatascience.com/introduction-to-linear-regression-in-python-c12a072bedf0 import pandas as pd import numpy as np from matplotlib import pyplot as plt import statsmodels.formula.api as smf # Import and display first five rows of advertising dataset advert = pd.read_csv('advertising.csv') print(advert.h...
bbb651918c14f3d6845d051b18a61a727a5c719c
Yuri-Santiago/yuri-mateus-poo-python-ifce-p7
/Atividades[Presença] - Etapa 1/Atividade 05/teste_triângulo.py
573
3.90625
4
from verifica_triangulo import verificar print('Nesse programa você escreverá 3 lados de um Triângulo e ele falará se esses lados formam um Triângulo.') comprimento_a = int(input('Digite o Primeiro Lado do Triângulo: ')) comprimento_b = int(input('Digite o Segundo Lado do Triângulo: ')) comprimento_c = int(input('Digi...
91f5f4f68693379c27a50535639b70fa9555e57b
lunar0926/codeup-for-problem-solving-and-python
/1228_16940743(AC).py
274
3.625
4
h, w = map(float, input().split()) standard_Weight = (h - 100) * 0.9 obesity = (w - standard_Weight) * 100 / standard_Weight if obesity <= 10: print('정상') elif obesity > 10 and obesity <= 20: print('과체중') elif obesity > 20: print('비만')
cf3e1b85600a0865feeaf925c843530dce4b2efe
lunar0926/codeup-for-problem-solving-and-python
/1078_16830227(AC).py
396
3.6875
4
# 값 입력 n # 1부터 해당 값까지 나열. 그 중에서 2로 나누어지는 수는 리스트에 # 리스트에서 반복문으로 요소들 합하기 n = int(input()) evenList = [] for i in range(1, n+1): # ex 5가 입력되면 5까지 반복 if i % 2 == 0: evenList.append(i) # 리스트 요소들 합하기 sum = 0 for j in evenList: sum += j print(sum)
b9373468c7b1870643b989ce801c47ed5652554f
sven-walser/Python-test
/python-test5.py
356
3.9375
4
#!/usr/bin/env python3 age = int(input("Alter des Hundes: ")) if age < 0: print("Das stimmt wohl kaum!") elif age == 1: print("entspricht ca. 14 Jahre") elif age == 2: print("entspricht ca. 22 Jahre") elif age > 2: human = 22 + (age -2)*5 print("Menschenjahre ", human) # wenn man wie oben bei int etwas castenmus...
310d5545758fc462c4269353a15beb122762f660
sven-walser/Python-test
/selbstprojekte/namensbewerter.py
479
4.125
4
#!/usr/bin/env python3 print("Sag mir wie du heisst dann bewerte ich deinen Namen") name = input("Dein Name: ") name = name.lower() if name == "sven": print("so ein schöner Name") elif name == "claudio": print("Das ist der schlechteste Name den ich je gehört habe") elif name == "simon": print("wow du warst also ...
df7743a2893838cc8512071be06be7356665f97a
Steven79203/sorting_collection-
/insert_sort
408
3.734375
4
#!/usr/bin/env python from random import sample def insert(lst): print('Insertion Sort') n = len(lst) for i in range(1,n): pvt = lst[i] p = i while p >= 1 and pvt < lst[p-1]: lst[p] = lst[p-1] p -= 1 lst[p] = pvt return lst cnt = 10000 lst = sa...
fbb0795ba919e94c074eaf007888eb4fd4578d81
Tugbaaa38/PythonBilgiler6
/python7.py
2,411
3.65625
4
# if/else if/elif bir ornegi bir kac farkli sekilde cozelim.... print("*****************************************************************************\n") system_mail="bilgi38@gmail.com" system_password="12345TK" kullanici_mail=input("Mail adresinizi girin:") kullanici_password=input("Sifrenizi girin:") bas...
47297b79e54ff9cd0f89d6f03b749c40b2709dde
imgauravsin/HackerEarth
/Basic Programming/Prime Minister's number.py
621
3.875
4
def prime(): # Write your code here num1=int(input('NUM1')) num2=int(input('NUM2')) for i in range(0,num2-num1): b=i+num1+1 if b%2!=0 and b%3!=0 and b%5!=0 and b%7!=0: a=str(b) length=len(a) sum1=0 for i ...
1e66737b1bd378f26994ec0c10990ceb7a19261a
Hardik3296/TwitterSentimentAnalysis
/create_dictionary.py
302
3.71875
4
#Function to create dictionary from the words already present in words.txt def create_dictionary(): str1=[]; dictionary={}; file=open("words.txt","r"); for line in file: str1 = line.split(); dictionary[ str1[0] ] = int(str1[1]); file.close(); return dictionary;
c3206f66f8b4036db5ba5c90610ce42f8f0e9cd5
JiazijingBc/Bc-cbg
/109.py
1,853
3.8125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ###方法一 class Solution...
b5b1c86fb56252dd43f80bbf1bbaa5dea6aaef1e
JiazijingBc/Bc-cbg
/9.py
120
3.734375
4
def func(x:int): if str(x)[::-1] == str(x): print('true') else: print('false') func(1231)
100358090d3ba184b5f31dc74278438342fc0664
JiazijingBc/Bc-cbg
/20.py
1,263
3.671875
4
#方法一 class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == '' #方法二 class Solution: def isValid(self, s: str) -> bool: dic = {'(':1,'...
fb3b0509a9806f49bb2f361ce331114385d25c2c
JiazijingBc/Bc-cbg
/28.py
832
3.671875
4
###自己的方法(倒序) class Solution: def strStr(self, haystack: str, needle: str) -> int: lens=len(needle) if needle == '': return 0 if needle not in haystack: return -1 while len(haystack)>0: lens=len(needle) ss = haystack[-lens:] ...
ee09885bb0250a223d4ddf2dd989701d96ac632b
lambdaxyzt/python_crash_course_book
/(5-1_5-2)_Chapter4_Numbers_try_it_yourself_page78.py
387
4
4
#5-1 car = "ford" print("is car == 'ford' ? I predict True ") print(car == "ford") car = "Audi" print("is car == 'audi' ? I predict false") print(car == "Audi") pizza = "mixed8" print("is pizza =='mixed8' I predict true ") print(car == 'mixed8') car = "toyota" print("is pizza =='toyota' I predict true ") print(car...
b754fde9580f0301d218b1edaa884c664e532ae5
lambdaxyzt/python_crash_course_book
/(4-13)_Chapter4_Numbers_try_it_yourself_page68.py
251
4.0625
4
#4-13 food_list = "chicken salad" , "spicy chicken" , "hamburger" for food in food_list : print (food) food_list[0] = "Changed!" food_list = "chicken salad" , "spicy chicken" , "hamburger" , "egg" , "baken" for food in food_list : print (food)
3b4cf0c32068ac3ea19937400c5f01719090cbb5
AngeloESFM/All_programs
/listas_o_vectores.py
330
3.71875
4
# 26 Listas # Sirven para tener elementos guardadados entre corchetes como vectores # Colección de elementos, las listas están ordenadas y son mutables frutas = ["Naranja", "Manzana", "Banana", "Kiwi", "Mandarina", "Uva"] 0 1 2 3 4 5 print [frutas] print [5] pr...
f5e80e66c29e91e122dd89773242450ab8db49ef
AngeloESFM/All_programs
/19_20_generadores.py
2,099
4.09375
4
# 19, 20 GENERADORES I y II # Se obtiene con la instrucción YIELD y se recorre con un búcle # SIrve para obtener una lista de uno por uno los datos, es más eficiente que un método normal # Su útildad más exacta es cuando se tenga que generar una lista infiníta # Comando YIELD FROM # Sirve para obtener información de l...
a12f8edb0fda9985d3739772c338b45f6ae9ad7c
AngeloESFM/All_programs
/raiz_cuadrada.py
231
4.125
4
import math num1 = input("inserte número para sacarle raiz cuadrada:") num1 = float(num1) print(math.sqrt(num1)) def raiz_c(n): num1 = 0 while num1 * num1 <= n: num1 += 0.00001 return num1 print(raiz_c(num1))
cd45b01a927da04ee7b2d8a9ecb434ccf1f723d9
AngeloESFM/All_programs
/All_programs_3.py
13,068
3.75
4
# 46 APRENDER A ABRIR Y CERRAR ARCHIVOS DE TEXTO # Para abrir el archivo se hace de la siguiente forma """ # Para abrirlo sólo en lectura se pone una "r" open("Alumnos.txt","r") # Para abrirlo sólo en escritura se pone una "w" open("Alumnos.txt","w") # Para abrirlo sólo en escritura se pone una "a" open("Alumnos.txt",...
3f7e8cbe8ec1617d5125b361167de964b513998d
AngeloESFM/All_programs
/listas_o_vectores2.py
588
4.375
4
# 26 Listas # Sirven para tener elementos guardadados entre corchetes como vectores # Colección de elementos, las listas están ordenadas y son mutables frutas = ["Naranja", "Manzana", "Banana", "Kiwi", "Mandarina", "Uva"] # 0 1 2 3 4 5 # Imprime toda la lista pri...
2aea44071bfb354f7bf2fe0764af7288ec331b21
AngeloESFM/All_programs
/archivos_(abrir_cerrar).py
742
3.796875
4
# 46 APRENDER A ABRIR Y CERRAR ARCHIVOS DE TEXTO # Para abrir el archivo se hace de la siguiente forma """ # Para abrirlo sólo en lectura se pone una "r" open("Alumnos.txt","r") # Para abrirlo sólo en escritura se pone una "w" open("Alumnos.txt","w") # Para abrirlo sólo en escritura se pone una "a" open("Alumnos.txt",...
78f1c6964d911bc1cf7ed67c595c1710037e8894
AngeloESFM/All_programs
/for_ejercicios.py
6,944
4.0625
4
# EJERCICIOS CICLO FOR # EUP que pida dos números enteros y escriba qué números son pares y cuáles impares desde el primero hasta el segundo. """ num1 = int(input("Escribe un número: ")) num2 = int(input(f"Escribe un número mayor o igual a {num1}: ")) while num2 < num1: num2 = int(input(f"Escribe por favor un núme...
8dbb709cbc3ae8429b9a4bda6ea357e5a52e87d9
kyledhebert/PyZombie
/player.py
352
4.0625
4
import random from dice_cup import DiceCup class Player(): hand = [] health = 3 score = 0 turn_score = 0 def add_dice_to_hand(self, dice_cup): """adds dice to the player's hand from the cup""" while len(self.hand) < 3: self.hand.append(dice_cup.dice_in_cup. pop(random.randint(0,(len(dice_cup.dice_...
1ba4ec70a94bc045aed0c94ab1c46a13041910ca
helia1385mir/rasm-mar
/mar.py
148
3.640625
4
vorodi = int(input('mikhahid maretan chetor bashad')) for i in range (vorodi): if i % 2 == 0: print('*' , end='') else: print('#' , end='')
60608152eda3f3afab694db05d577be54d5c51f0
Etothepowerof26/Gclightshow
/dev/light.py
5,078
3.734375
4
#!/usr/bin/python import RPi.GPIO as GPIO import time class Light: '''light object''' def __init__(self, pin, name, state = False): self.pin=pin self.state=state self.name=name def setState(self, state = False): self.state = state GPIO.output(self.pin, state) print("Light ...
e84d6844fa2d7c63fa300054a797152dffe3b322
adarsh161994/python
/part 2.py
811
4.40625
4
# Addition of strings # stri = "My name is" # name = " Adarsh" # print(stri + name) # How to make temp # name1 = "ADARSH" # name2 = "YASH" # temp = "This is {} and {} is my best friend".format(name1, name2) # print(temp) # Now introducing 'f' string It is also doing same thing which we have done above. # ITS also...
5d17c527fd95f9ffdecb7391d9fc475c3d207163
Qamberhasnain/T20series_Autoplay
/T20Series_Autoplay.py
3,872
4
4
'''This code is created by Qamber Hasnain Student of Lovely Professional University\n Section:- K19EG\n Roll no.:- B64\n This will give you results of three matches and announce the winner of the series played between any two random teams selected from allteam list\n All the numbers taken are random but results will be...
44aaab2c934f321a4bd2e6ac77a1bd325b5a61bb
damarkrisnandi/CP_With_Python3
/codeforces/educational99/problem_b.py
279
3.5625
4
def solve(): x = int(input()) i1 = 1 i2 = 1 # step 1 x1 = 1 # next step while x1 < x: i1 += 1 x1 += i1 if x - x1 == 1: print(i1 + 1) else: print(i1) tests = int(input()) for t in range(tests): solve()
6131f079d0e5d4d92272f0778e561c91b9317e54
damarkrisnandi/CP_With_Python3
/hackerearth_januaryCircuit_day0/replace_str.py
653
3.5
4
from collections import defaultdict def countObj(arr): res = defaultdict(int) for i in arr: res[i]+=1 return res t = int(input()) while t>0: t-=1 ls = int(input()) s1 = input() s2 = input() s1_cts = countObj(s1) s2_cts = countObj(s2) s1s2 = set.union(set(s1_cts), s...
56097afa703b8f523368b6197473762dc95016c8
lzybb/ljbgit
/普通课程/3-高级语法/多线程/19.py
357
3.53125
4
import multiprocessing from time import sleep, ctime def clock(i): while True: print('The time is %s' % ctime()) sleep(i) if __name__ == '__main__': p = multiprocessing.Process(target=clock, args=(5,)) p.start() # 做一个死循环,防止主进程结束 while True: print('sleeping......') s...
a3ff8da7693f0a7a0374e669e667b6d2e69db776
lzybb/ljbgit
/习题课程/http项目/v01-技术验证/ws.py
772
3.515625
4
import socket # 理解两个参数的含义 # 理解创建一个socket的过程 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 注意addr的格式是tuple # 以及tuple两个元素的含义 sock.bind(("127.0.0.1", 7852)) print('已经绑定端口....') # 监听 sock.listen() print("正在监听....") # 接受一个传进来的socket print("准备接受socket传入....") skt, addr = sock.accept() print("已经接受到传入socket:{0...
bf06ff5806fb9ffb65caf40f3e128399bdc4180b
splashdude25/code
/FilePractice.py
4,356
3.71875
4
from datetime import datetime as dt import matplotlib.pyplot as plt filename = 'Netflix_stock_history.csv' file = open(filename, 'r') #print(file.readlines()) #desired structure: dictionary: Key = Date, Value = List of the attached data dict = {} lines = file.readlines()[1:] #Header is: Date,Open,High,Low...
965feb2d0a82e44e00e11251a91c4a53c6f4b3cd
mnanabayin/Lab_Python_01
/zellers.py
968
4.09375
4
fname = raw_input('Enter your first name: ') lname = raw_input('Enter your last name: ') print 'Enter your date of birth: ' A = raw_input('Month from (1-12) Mar=1, Apr=2...Jan=11 and so on? ') A = int(A) if A < 1 or A > 12: print'Month should be from 1 to 12' exit() B = raw_input('Day? from 1-31') B = int(B) ...
b9493b0aff09b8d85742aca2025bd298e6f91ef6
Saichep/PythonLearning
/src/Dictionaries_Operations.py
1,961
3.734375
4
#!/usr/bin/env python __author__ = "Sudheer Veeravalli <veersudhir83@gmail.com>" __copyright__ = "Copyright (c) 2017. Sudheer Veeravalli. Free for general use and re-distribution" __license__ = "Public Domain" __version__ = "1.0" lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": ...
4e1a943dc0e3c2cfbec842510e7c30143e574425
albertsunn/working
/Assignment_2_Covid-19.py
645
4
4
age = input("Are you a cigarette addict older than 75 years old? (please answer yes or no) :") if age == "yes" : age = True elif age == "no": age = False chronic = input("Do you have a severe chronic disease? (please answer yes or no) :") if chronic == "yes" : chronic = True elif chronic == "no": chron...
af26e1489a9ae2956c4c8163c57d88282ef4e239
Urielglb/Curso-Python-Raccoons
/clase2/listas.py
1,956
4.21875
4
#Declarando listas vacio = []#Lista vacia, se le puede meter elementos despues supermercado =["Lechuga","Crema","Pan"]#Lista de strings edades = [10,45,60]#lista de numeros mixto = ["Lechuga",10,4.5,"Pan"]#Lista de varios tipos de dato, no se recomienda mezclar datos #Accediendo a la lista print(edades[0])#Primer eleme...
31db8ca83ca57eecc50b8eb38eb13a33ca3d5cba
girlwhodrawsandstuff/CS50-2020
/pset6/readability/readability.py
734
3.953125
4
# User input text = input("Enter your text: ") # Number of letters in given input numLetters = 0 for char in text: if char.isalpha(): numLetters += 1 # Number of words in the given numWords = len(text.split()) # Number of sentences in the given input numSentences = 0 for char in text: if char in ['?'...
1ddfd189b3c9fc183dfe8a1dd4037a8ecb4a8351
vitrioil/MusicRecombiner
/separator/main/separate/base.py
379
3.546875
4
from pathlib import Path from typing import Any from abc import ABC, abstractmethod class Separator(ABC): """ABC is the abstract base class for music separation. """ # custom separator _separator: Any def __init__(self): pass @abstractmethod def separate(self, audio_file: ...
18c5000cf96d5c6ce35e8202e387f844aea4202e
Holysalta/pp2-tsis5-
/8sequencelowerupper.py
279
3.96875
4
import re def check(text): patterns = '^[a-z]+_[a-z]+$' if not re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(check("aab_cbbbc")) print(check("aab_Abbbc")) print(check("Aaab_abbbc"))
2f4acc5edf365e73cbef71c2c7d71ad95376d5ec
abrar2008/Python_-PRACTICE
/Four.py
2,151
4
4
#tuples like list but this Fixed Elemennt state = ("Del " , "Alt" , "New " , "Four ") #print(state) #Loop #for a in state: # if state == : "dada" # print("Welcome ") # else: # print("Sorry ") #loop Nested first_name = ["Blue " , "upchuck" ,"lojack", "Gizmo" , ] last_name =["khan" , "a...
c0ece596323cfcd837849a7fa5513a2daad6ddd2
Renato-moura/PrgBancoFatec
/prgBancoEx1_3.py
278
4.28125
4
#3 Escreva um programa que calcula e mostra a rea de um crculo, uma vez que o usurioinforme o raio. Use math.pi para obter um valor aproximado de pi. (Use import math antes). import math raio = float(input("digite o raio: ")) area = math.pi * (raio ** 2) print(area)
95451780778a80ba364d857addb9e23ac67b856f
spradeepv/dive-into-python
/hackerrank/domain/artificial_intelligence/bot_building/bot_saves_princess.py
2,769
4.3125
4
""" Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess? Input format The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed ...
ccfe895e27c01f03f8a277528d35f306d89e56ea
spradeepv/dive-into-python
/hackerrank/domain/artificial_intelligence/bot_building/bot_clean_large.py
2,103
4.40625
4
""" In this challenge, you must program the behaviour of a robot. The robot is positionned in a cell in a grid G of size H*W. Your task is to move the robot through it in order to clean every "dirty" cells. Input Format The first line contians the position x and y of the robot. The next line contains the height H a...
fb7ba7d24fb20f28a94da9d41cc4cd716bacdf8a
spradeepv/dive-into-python
/hackerrank/domain/python/numpy/dot_cross.py
1,053
4.0625
4
""" Problem Statement dot The dot tool returns the dot product of two arrays. import numpy A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) print numpy.dot(A, B) #Output : 11 cross The cross tool returns the cross product of two arrays. import numpy A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) ...
1394705079047a866b1bb164ee4916ed6e8af9fb
spradeepv/dive-into-python
/hackerrank/domain/python/itertools/combinations_with_replacement.py
673
4.0625
4
""" Task You are given a string S. Your task is to print all possible combinations with replacement of size k, of the string in lexicographic sorted order. Input Format Single line containing space separated , string S and value k. Constraints 0<N<10 0<k?len(S) String contains only UPPERCASE characters. Output Fo...
c33c7cb5c1af790e169ed7339204d8e537f664cc
spradeepv/dive-into-python
/hackerrank/domain/algorithms/greedy/sansa_and_xor.py
1,797
3.84375
4
""" Sansa has an array. She wants to find the value obtained by XOR-ing the contiguous subarrays, followed by XOR-ing the values thus obtained. Can you help her in this task? Note : [5,7,5][5,7,5] is contiguous subarray of [4,5,7,5][4,5,7,5] while [4, 7,5][4,7,5] is not. Input Format First line contains an integer T,...
234888a13b3fe18628b6b91a32e824e4cef153e2
spradeepv/dive-into-python
/hackerrank/contests/30_days_of_code/operators-class-instance.py
4,437
3.921875
4
""" Problem Statement Welcome to Day 4! Check out a video review of logical operations here, or just jump right into the problem. Note: This task is focused on Object Oriented concepts, so it is only enabled in a few languages. You will create a class Person and write a constructor that takes an integer, initial_Age...
7c54a3e4de30e706ff577367a5ed608d93b6233f
spradeepv/dive-into-python
/hackerrank/domain/python/sets/intro_mickey.py
975
4.40625
4
""" Task Now, lets use our knowledge of Sets and help 'Mickey'. Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student 'Mickey' to compute an average of all the plants with distinct heights in her greenhouse. Formula used: Average=SumofDistinctHeightsTotalNumberofDistinctHeigh...
27bfbdf5c091578eb18e5a88f7ff00252f06f79e
spradeepv/dive-into-python
/hackerrank/domain/python/collections/deque.py
1,688
4.09375
4
""" Problem Statement collections.deque() Deque is a Double-Ended QUEue. It can be used to add or remove elements from both ends. Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Learn more about , deque() m...
3e09c61d5a62a3e00412522aa5e0895402696f87
spradeepv/dive-into-python
/hackerrank/domain/python/built_in/any_or_all.py
1,386
4.3125
4
""" any() This expression returns True if any element of the iterable is true. If the iterable is empty, it will return False. Code ---- any([1>0,1==0,1<0]) True any([1<0,2<1,3<2]) False all() This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return Tr...
1edb0b1d6aa44f02d38d7a37608f84dc754c8ee7
spradeepv/dive-into-python
/hackerrank/domain/algorithms/sorting/quicksort3.py
2,901
3.953125
4
""" Problem Statement The previous version of Quicksort was easy to understand, but it was not optimal. It required copying the numbers into other arrays, which takes up space and time. To make things faster, one can create an "in-place" version of Quicksort, where the numbers are all sorted within the array itself. ...
ef7602c8424a459af12473769231ad85d0dcd839
spradeepv/dive-into-python
/hackerrank/contests/codestorm/emmas_notebook.py
1,264
3.828125
4
""" Problem Statement Emma is writing bits (1s and 0s) in her notebook. Every second, she writes some more bits. In the 1st second, she writes two bits in her notebook. She starts with 0 and alternates between 0 and 1. They look like this: 0 1 In the 2nd second, she writes three more bits in her notebook. This time, ...
f89ec17a3bdfda7f957bb15f42f02386c5be2264
spradeepv/dive-into-python
/hackerrank/domain/python/strings/swap_case.py
241
3.640625
4
s = raw_input() new_s = "" for c in s: ascii_val = ord(c) if ascii_val >= 65 and ascii_val <= 90: ascii_val += 32 elif ascii_val >= 97 and ascii_val <= 122: ascii_val -= 32 new_s += chr(ascii_val) print new_s
a9a0244639d86b78693a7e393ce72cb6b7426f63
spradeepv/dive-into-python
/hackerrank/domain/algorithms/sorting/countingsort-1.py
2,204
3.578125
4
""" Problem Statement Comparison Sorting Quicksort usually has a running time of n*log(n), but is there an algorithm that can sort even faster? In general, this is not possible. Most sorting algorithms are comparison sorts, i.e. they sort a list just by comparing the elements to one another. A comparison sort algorith...
a2a8c9c0040e9d1f66a839eae3f7d16cb5131439
spradeepv/dive-into-python
/hackerrank/contests/30_days_of_code/dictionaries-and-maps.py
1,682
4.0625
4
""" Problem Statement Welcome to Day 8! Check out a video review of dictionaries and hashmaps here, or just jump right into the problem. You are given a phone book that consists of your friend's names and their phone number. After that you will be given your friend's name as query. For each query, print the phone num...
ef2519d9d3d5e4c0071d198d2f8c14739f423f3a
spradeepv/dive-into-python
/hackerrank/domain/algorithms/sorting/running_time.py
475
3.703125
4
""" """ def insertionSort(ar): length = len(ar) stop = False index = 1 running_time = 0 while not stop: num = ar[index] for i in range(index - 1, -1, -1): if num < ar[i]: ar[i + 1], ar[i] = ar[i], num running_time += 1 index += 1 ...
acca6f82af8e6c4bd84b2e8e460501f838e222e4
spradeepv/dive-into-python
/hackerrank/contests/zenhacks/primedist.py
1,033
3.828125
4
def is_prime(num): is_prime = True if num > 1: for i in range(2,num): if (num % i) == 0: is_prime = False break else: is_prime = False #print num, " is prime ", is_prime return is_prime def primes2(n): """ Input n>=6, Returns a list of...
abc4b59db59660232c5ee767870f41b686fe526b
spradeepv/dive-into-python
/hackerrank/domain/python/numpy/min_max.py
1,838
4.5625
5
""" Problem Statement min The tool min returns the minimum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.min(my_array, axis = 0) #Output : [1 0] print numpy.min(my_array, ax...
04feba3450c89143142f6dab78bda9a0f2f115fb
spradeepv/dive-into-python
/hackerrank/domain/algorithms/sorting/quicksort2.py
2,707
3.84375
4
""" Problem Statement In the previous challenge, you wrote a partition method to split an array into two sub-arrays, one containing smaller elements and one containing larger elements than a given number. This means you 'sorted' half the array with respect to the other half. Can you repeatedly use partition to sort an...
7c5c86da342258cbe51310f7ef859ec7e25dc73c
spradeepv/dive-into-python
/hackerrank/domain/python/regex/validating-named-email.py
1,589
4.4375
4
""" Problem Statement You are given N names and email addresses. Your task is to print the names and email addresses if they are valid. A valid email address follows the rules below: - Email must have three basic components: username @ website name . extension. - The username can contain: alphanumeric characters, -,....
7f3728d816cb7cf6f379be15ba073c704d34315c
spradeepv/dive-into-python
/hackerrank/domain/python/regex/re-start-end.py
806
3.921875
4
""" Problem Statement start() & end() These expressions return the indices of the start and end of the substring matched by the group. Code import re m = re.search(r'\d+','1234') m.end() 4 m.start() 0 Task You are given a string S. Your task is to find the indices of the start and end of string k in S. Input Forma...
3c8a72043f647c130993476ddb1c05757631d809
spradeepv/dive-into-python
/hackerrank/domain/algorithms/search/sherlock_array.py
1,783
3.84375
4
""" Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, ...
431beebe8bbee36e19003119fbae6040357a94bb
spradeepv/dive-into-python
/hackerrank/domain/algorithms/bit-manipulation/counter_game/solution.py
521
3.703125
4
def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) def log2(n): assert n > 0 exp = 0 while n: n >>= 1 exp += 1 return exp def largest_exp_of_2_less_than(n): return log2(n) - 1 for _ in range(int(raw_input())): n = long(raw_input()) start = 0 while n != 1: st...
4b515141658658453c0500a45709865d39be9cca
spradeepv/dive-into-python
/hackerrank/domain/python/sets/difference.py
1,353
3.71875
4
""" Task Students of District College have subscription of English and French newspapers. Some students have subscribed to only English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of roll numbers of students, who have subscribed to English and French newspap...
8a9883e70d36953d7cfae8a7951fbc75333a2072
spradeepv/dive-into-python
/hackerrank/domain/artificial_intelligence/bot_building/bot_clean.py
3,367
4.1875
4
""" The goal of Artificial Intelligence is to create a rational agent ( Artificial Intelligence 1.1.4). An agent gets input from the environment through sensors and acts on the environment with actuators. In this challenge, you will program a simple bot to perform the correct actions based on environmental input. Meet...
6b5de90e6a7c0f30c48cb6cf8f5258f4daf6f029
AdamCorbinFAUPhD/CEN5035-Software-Engineering-Course-Project
/code/keypad.py
3,606
3.5625
4
from queue import Queue from threading import Thread import logging import RPi.GPIO as GPIO """ This class is used to intercept the keypad entries Here are the following steps in order to achieve our matrix 4x4 for all 16 keys 1. Set the columns as outputs to High 2. Set the rows pints as inputs with pull-up resistor...
a87e63e9dde8120040dd87541a2399f698967909
Littlegump/pythonNotes
/pythonScript/filter.py
331
3.59375
4
#/usr/bin/env python #coding=utf8 # 将一个列表传递给filter,该列表中的元素满足func的元素将会被添加到一个新的列表中并作为filter的返回值, # filter(func,seq) l1 = [1,2,3,44,50] def func(x): if x > 20: return True else: return False l2 = filter(func,l1) print l2
781cec3f49ffa09c184f91b6c9abcf24a835624c
Mechanicalbird/Python
/ex114.py
220
4.03125
4
while True: try: number = int(input("what is your number!\n")) print(18/number) break except: print("Make sure you enter a number") finally: print("Thank you")
42e68098bad96202ee9b9bab367ae7067120dd7b
Mechanicalbird/Python
/stu-jp8.py
127
3.609375
4
classmates = {"tony": ' man1111',"watwat1": ' man', "ashish": 'my man'} for k, v in classmates.items(): print (k + v)
3bab81528e78aa449048b9a521250b478d0b6620
shawgree/Beaglebone
/tantrum_motors.py
2,473
3.578125
4
from motor import Motor from motor_driver import MotorDriver # We will use the following pins for the front motor: # <Func> <BB Website> <pin> <GPIO Num> <Mapping> # FM Dir: gpio_30 p9:11 30 gpio0[30] # FM En: PWM1A p9:14 50 gpio1[18] # [Unsupported] LM SA: gp...
a742faab2a832c3baac81b5475066ec7a386d94f
shawgree/Beaglebone
/test1.py
985
3.953125
4
#!/usr/bin/python from motor import Motor, MotorMaster # Read speed from command line and then verify the input is an integer. leftSpeed = raw_input('Input left motor speed: ') try: leftSpeed = int(leftSpeed) except ValueError: print "Speed must be an integer, forcing to 0" leftSpeed = 0 else: print 'Use...
d2a5846b74f5c2b003eee17507cbc577989ce25b
rohan345798/MyCode
/encrypt.py
1,122
3.6875
4
from random import randint def generate_key(): original = ['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'] copy = original.copy() encrypted = [] randomrange = 25 for i in range(26): newElem = copy[randint(0,randomrange)] encr...
2e3d4a6e0b9e422950f56f77255a56424bcfcae0
zuzanadostalova/The-Python-Bible-Udemy
/5_Section_Strings.py
3,071
4.28125
4
# 19. lesson - Section overview # for data analysis - pandas, NumPy, SciPy # 20., 21., 22., and 23. lesson - Hello world print("hello") name = "Ziyad" print(type(name)) # message = "John said "See you later"" # how to correct this faulty string? -> message = 'John said "See you later"' # How to fit a long text into ...
33e672ec8d42bf4f655a9eb08d406108b041f025
zuzanadostalova/The-Python-Bible-Udemy
/6_Section_Conditional_logic.py
667
4.28125
4
# 30. lesson - Future lesson overview # 31. lesson - Booleans # Boolean is not created through typing its value - we get it from doing logical comparison print(2<3) # Output: True print(2>3) # Output: False print(type(2<3)) # Output: <class 'bool'> # print(2 = 3) # Output: Error - cannot assign to literal print(2 ...
0caac48689854309f5e867a07cd148287a9a376e
zuzanadostalova/The-Python-Bible-Udemy
/8_Section_For_loops.py
1,918
4.46875
4
# 50. lesson - For loops # most useful loops # "for" loops - variable (key) - changing on each cycle of the loop # and iterable (students.keys()) - made up from elements # In each cycle, the variable becomes the next value in the iterable # operation on each value # range function - set up number, create number iterabl...
c604aa45162882e9085311986cb42ebd1c3e636d
gidpfeffer/CS270_python_bootcamp
/9-Imports/Course.py
532
3.765625
4
""" CLASS DEFINITION """ class Course: # arguments needed to invoke an instance of the object def __init__(self, teacher, course_name): # instance variables self.teacher = teacher self.course_name = course_name self.students = dict() def addStudent(self, new_student): self.students[new_student.student_i...
1ef901e075f7b922099badb7e1a62ea826317a21
gidpfeffer/CS270_python_bootcamp
/2-Conditionals/2_adv.py
866
4.21875
4
""" cd into this directory run using: python 2_adv.py """ a = 10 if a < 10: print("a is less than 10") elif a > 10: print("a is greater than 10") else: print("a is 10") # also could do if a == 10: print("a is 10") # or if a is 10: print("a is 10") # is checks for object equality where == does value equality #...
8a96f25f94b5f008c11075e2667f8b34ae850f04
gidpfeffer/CS270_python_bootcamp
/4-Functions/2_optional_args.py
979
4.3125
4
""" cd into this directory run using: python 2_optional_args.py """ def printName(firstName, lastName=""): print("Hi, " + firstName + lastName) # uses default lastname printName("Gideon") # uses passed in lastname printName("Gideon", " Pfeffer") def printNameWithAge(firstName, lastName="", age=25): print("Hi, " ...
86eeb5c87486e9a120a6cbe3d13787efb7ace5bf
bmbuwir/RL-for-MCES
/battery.py
2,387
3.515625
4
''' Created on 15 apr. 2018 @author: MBUWIRB ''' class Battery(): DISCHARGE = -1 CHARGE = 1 IDLE = 0 def __init__(self, capacity, charging_rate): self.capacity = capacity # Energy capacity in Wh self.charging_rate = charging_rate # Power in...
82dd026658d9711a8936dd9a69d3f64772872027
juzten/pythonRosalind
/003_revc.py
3,365
3.5
4
#----------------------------------------------------------------------------- # Name: Justin Spain # Email: juzten@gmail.com # Date: # File: 003_revc.py #----------------------------------------------------------------------------- # Edit log # 11/17/2013 edit log here # #--------------------------------------------...
2e8e164fa2f005a2021a627ffc0169bbdbdb3d94
nspirellis/hello-world
/PracticeExs/Exercise1.py
717
3.796875
4
euros_sum = 0 fifty_banknotes = input("Enter number of 50 euro banknotes:") fifty_banknotes = int(fifty_banknotes) twenty_banknotes = input("Enter number of 20 euro banknotes:") twenty_banknotes = int(twenty_banknotes) ten_banknotes = input("Enter number of 10 euro banknotes:") ten_banknotes = int(ten_banknotes) five_b...
afbf391c16b361b19ecf98a060c2c4f5cd61c41d
remylavergne/CsvToJson
/Converter.py
921
3.546875
4
import csv import json import os def main(): # CSV format = separators = , & separator number = . # Open the CSV f = open('Book1.csv', 'r') json_file = open('parsed.json', 'w') # Change each fieldname to the appropriate field name. I know, so difficult. fieldnames = ("Number", "Lastname", "F...