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
f146f3a9ae71402b89dbe8bd861fbda0e8b6e65f
arunnjoshi/Python
/ListTuplesDir/listExcersie.py
131
3.953125
4
numbers = [1,1,2,3,4,4,2,4] unique = [] for item in numbers: if item not in unique: unique.append(item) print(unique)
db184990b62eb4d0324b771d9904ba8b44dbabd1
arunnjoshi/Python
/Basic/weightConversion.py
282
3.828125
4
import math weight = int(input("weigth: ")) uint = input('kg or lbs(k or l) :').lower() if uint == 'l': converted = weight*0.45 print(f'your weight is {math.ceil(converted)} kg') else: converted = weight//(0.45) print(f'your weight is {math.ceil(converted)} lbs')
9efb53813f05e91f313b7e761000d4375ab0a660
charbileigh/Aircraft-Load-Distribution
/Aircraft_Wing_Load_Distribution.py
7,206
3.78125
4
# Name : Mmasechaba Justicia Francesca Seopa # Student no : 834758 # Date : 10 May 2015 """ Background info of the program: This code is created to open a csv file, then create a matrix of our distances. then it is bound togo to an extent where is uses the guassian elimination method to get the ...
f8f90786e70779b61464625f4fa50dae778f239f
rpinedat/python-project
/1_20 triangulos.py
490
4.09375
4
# Recibe medida de tres lados de un triangulo # El programa entrega si es un triangulo válido y de que tipo. a = float(input("Ingrese a: ")) b = float(input("Ingrese b: ")) c = float(input("Ingrese c: ")) if a+b > c and b+c > a and c+a > b: if a != b and b != c: print("Es un triángulo escaleno") eli...
cbca79d913c90d17ea6ff5426834e9a79dcbc2d8
rpinedat/python-project
/1_19 set_de_tenis.py
891
3.84375
4
# el usuario da el puntaje que lleva un partido de tenis y el programa regresa # cuál es el estado del partido # Rocio Pineda jug_a = int(input("Juegos ganados por A: ")) jug_b = int(input("Juegos ganados por B: ")) if jug_a <= 7 and jug_b <= 7: if jug_a == 6 and jug_b == 4: print("Ganó A ") elif jug...
21f844c7a4a021222e27204e8a43ac1002843acb
rpinedat/python-project
/2_6_Nov/adivinar_el_numero2_45.py
899
3.984375
4
# Escriba un programa que intente adivinar el número pensado por el usuario del 1 al 100. # Cada vez que el computador haga un intento, # el usuario debe ingresar <, > o =, # dependiendo si el intento es menor, mayor o correcto. # http://progra.usm.cl/apunte/ejercicios/1/adivinar-numero.html from random import randr...
61a2c163417820b1cc95cf3c5d97ed3d1cb9be35
rpinedat/python-project
/1_24suma_entre_numeros.py
371
3.796875
4
# Se ingresan dos núms y el resultado es la suma de los que estan entre ellos num_1 = int(input("ingrese num 1: ")) num_2 = int(input("ingrese num 2: ")) menor = int() mayor = int() res = int() if num_1 >= num_2: mayor = num_1 menor = num_2 else: mayor = num_2 menor = num_1 for i in range(menor, mayo...
a09b8a25f5f6bc8cad67388582150def10e09db8
rpinedat/python-project
/1_13division_exacta.py
543
3.875
4
# programa que al dividir dos números dice si la división es exacta o si # tiene un residuo y cual es dividendo = input("Dividendo: ") divisor = input("Divisor: ") dividendo_int = int(dividendo) divisor_int = int(divisor) cociente, residuo = divmod(dividendo_int, divisor_int) print(cociente) print(residuo) if residuo...
310e3b7e322f9044e82f45d541ff054511b37097
rpinedat/python-project
/enero_2021(lista 2)/tabla_de_verdad_58.py
943
3.625
4
# Escriba la función tabla_de_verdad(predicado) que reciba como parámetro un predicado lógico de tres parámetros # e imprima la tabla de verdad del predicado # for anidados # http://elclubdelautodidacta.es/wp/2012/11/python-los-operadores-logicos-y-sus-tablas-de-verdad/ booleanos = [True, False] # Tabla de verdad de ...
facdaaf8a6131914e650714c7687b471e7eb81b9
rpinedat/python-project
/2_6_Nov/numeros_primos_2_48.py
621
3.875
4
# http://progra.usm.cl/apunte/ejercicios/1/numeros-primos.html # https://www.youtube.com/watch?v=bCXL8_loqzQ # Escriba un programa que muestre los n primeros números primos, # donde n es ingresado por el usuario: i = int() def num_primos(numero): for i in range(2, numero): x, y = divmod(numero, i) ...
be3b9331e60f7bac70a9c6fdcc83bf6380d6d314
rpinedat/python-project
/22_Dic/multiplicacion_rusa_52.py
720
4
4
# reciba como entrada el multiplicador y el multiplicando, # y entrege como resultado el producto de ambos, # calculado mediante el método de multiplicación rusa. multiplicador = int(input("Ingrese multiplicador: ")) multiplicando = int(input("Ingrese multiplicando: ")) suma = 0 def par(var): res, mod = divmod(var...
85b20a6e7dcb680ce677e1e254f697d2053a901c
cynthiachuang72/Python-Bootcamp
/Beginner/Day4_Project_Rock_Paper_Scissors/main.py
1,370
4.15625
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ...
f9a6db7ed20a3239f624cebf30eb2953400756f2
cynthiachuang72/Python-Bootcamp
/Beginner/Pizza_Order/main.py
798
4.1875
4
print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want (S, M, or L)? ") add_pepperoni = input("Do you want pepperoni (Y or N)? ") extra_cheese = input("Do you want extra cheese (Y or N)? ") additional_price = 0 if (extra_cheese == 'Y' or extra_cheese == 'y'): additional_price += 1 i...
6732f39c2c928e4d600d21ff2ffa999ed7a9a0f0
Mirela22/Formation-Mars---Mai-2017
/1-Exercices Programmation en python/agecate.py
537
4.0625
4
age=eval(input("Quel est votre age ?:")) print (age) if age<15: print ("l'individu est de la catégorie enfant") elif age>14 and age<19: print ("l'individu est de la catégorie ado") elif age>18 and age<31: print ("l'individu est de la catégorie jeune") elif age>30 and age<51: print ("l'individu est d...
0fee889988efa12e844b6b0c52e33b4feb60f203
Mirela22/Formation-Mars---Mai-2017
/1-Exercices Programmation en python/exo4flyers.py
250
3.609375
4
flyers=eval(input("Quel est le nombre de flyers:")) price=0 b=0 if flyers < 100 : price=flyers*0.15 elif flyers<=300: prix=100*0.15+(flyers-100)*0.10 else : prix=100*0.15+200*0.10+(flyers-300)*0.06 print ("Le prix total est:", price)
55148863acbda89e6d6f450945469d608ecce21b
Mirela22/Formation-Mars---Mai-2017
/1-Exercices Programmation en python/square.py
54
3.609375
4
a=eval(input("entrez un nombre:")) a= a * a print (a)
6222ce34271b95a9432060cd6aab43c94fc456b5
Mirela22/Formation-Mars---Mai-2017
/1-Exercices Programmation en python/condition2.py
387
4.09375
4
numerateur=eval(input("entrez le numérateur:")) denominateur=eval(input("entrez le dénominateur:")) resultat = 0 if numerateur>0 : if denominateur!=0 : resultat = numerateur / denominateur print ("le résultat est :", resultat) else : print ("le dénominateur ne peut être égal à 0") els...
a3ceeed3025eb5641d7871f23f7d6f7a074765a2
Dejesusj9863/CTI110
/M5HW2_DeJesusJose.py
705
4.125
4
# CTI 110 # M5HW2 - Running Total # Jose De Jesus # October 12, 2017 # user enters numbers and once the user inputs a negative number # the program will stop asking and then add the numbers excluding the negative def main(): # Variables total = 0 sum = 0 # User input for number in...
2e9927050cf5e54af8575e5d03dd5422ef1dee22
Dejesusj9863/CTI110
/M5T1_Turtle_Bonus_DeJesusJose.py
1,434
4.1875
4
# CTI 110 # M5T1 - Bonus # Jose De Jesus # October 19, 2017 # Create a snowflake with turtle import turtle # Allows me to use turtles wn = turtle.Screen() # Creates a playground for turtles wn.bgcolor("lightblue") ...
39db66391d9c20836cf5eaf651b805c2f6a2409e
myprojecthub1/pythonByme
/for_q4.py
185
4.125
4
#Print Table of a Given Number in Python x=int(input("Enter Number=")) for y in range(1 , 11 ): print(x*y) x=int(input("Enter number=")) y=1 while(y<=10): print(x*y) y=y+1
ec93877c4b9cb28c64542e4c5cb69554766fb91d
fredcorpuz06/candidate-mentions
/wesmedia/wmp/collect/download.py
2,510
3.5
4
'''Download files from link. ''' import re import requests import urllib class FileDownload: def __init__(self): pass def download_image(self, uri, folder, file_name, default_format=None): '''Downloads image to specified file name, preserving file type.''' if not uri: re...
6dc59cbcccd2c160628ef6ac59dbf543764e7de9
goareum93/K-digital-training
/01_Python/17_exception/exception_처리.py
1,626
4
4
# 예외 발생 상황 처리 # ZeroDivisionError: division by zero # print(10/0) # try: # print(10/0) # #print(10/2) # except : # print('오류가 발생') # finally: # print('나누기') # 예외처리 클래스 지정 # try: # print(10/0) # #print(10/2) # except Exception: # print('오류가 발생') # finally: # print('나누기') # try: # p...
4398e9b53f0062653be0d0eea4170d9cf4af3603
goareum93/K-digital-training
/01_Python/07_string/string_ex1.py
448
3.96875
4
# email type 을 체크 # email = input('input email : ') if(email.find('@') == -1 or email.find('.') == -1 or email.index('@') > email.index('.') or email.index('.') - email.index('@') < 2 or email.index('@') == 0 or len(email) - email.index('.') <= 1 or email.count('@') >=2 o...
4659b5c3a688cebd8ef3b87d384d136bb2af95a4
goareum93/K-digital-training
/01_Python/12_funtion/function3_parameter.py
3,108
3.953125
4
# 함수의 매개변수(parameter) # 함수에 전달(입력)되는 값 (함수 정의할 때) # 인수(argument) : 함수에 실제로 전달되는 값 # def showInfo(name, age): # print('이름은 %s이고 나이는 %d에요' %(name, age)) # # showInfo('홍길동', 18) # # # def getArea(width, height): # return width*height*0.5 # # w = int(input('밑변:')) # h = int(input('높이: ')) # print(getArea(w, h)) ...
7646263b04650ed405f53de53f9b72f7ad510c0e
goareum93/K-digital-training
/01_Python/09_tuple/tupleSet_Ex.py
1,349
3.765625
4
# 1. # 2. # 3. num = (1,) num = 1, # hi=tuple() # hi=(1,) # print(type(hi)) # print(*hi) # num = tuple() # num = list() # num.append(1) # num = tuple(num) # print(type(num)) # print(num) # 5. t = ('a', 'b', 'c') listt=list(t) print(listt) listt[0]='A' t=tuple(listt) print(t) # 6. 다음 튜플을 리스트로 변환하라. # interest = ('...
14b84759d769f7f3ebddef1d361621224145357e
goareum93/K-digital-training
/01_Python/11_set/set.py
772
3.765625
4
# set # s1 = set() # print(type(s1)) # s1 = {3, 5, 7, 1, 3, 4} # print(s1) # # # s2 ={[10, 20, 40]} # s2 = {(10, 20, 40)} # print(s2) # # # 인덱스 사용 불가 # # s1[0] # # # 데이터 추가 .add() # s2.add(90) # print(s2) # # s1.add(-9) # print(s1) # # # 데이터삭제 .remove() # s1.remove(-9) # print(s1) # #s1.remove(8) # 값이 에러 발생 # print(s...
8507a64c4d113ed362a90c9bc602d09c00b8fcf8
goareum93/K-digital-training
/01_Python/18_OOP/08_클래스메소드.py
653
3.90625
4
# 클래스메소드 (class mehod) : self 를 통하지 않고 바로 클래스가 메소드 호출 # @classmethod : 클래스메소드임을 표시 # 클래스 변수를 이용하는 메소드를 정의 class Person: count = 0 # 클래스변수 def __init__(self, name): Person.count += 1 self.name = name @classmethod def showCount(cls): print('%d명 태어났습니다' % cls.count) # cls로 클래스 ...
0a42f24b9add516a2b79a571e61a9575375cc225
junpil-an/beakjun_coding
/기본 문제/14888(보류).py
289
3.828125
4
''' 연산자 끼워넣기 ''' n = 3 num = [3,4,5] operator = ['+','-','*','/'] op = [1,0,1,0] Sum=[] for i in range(len(op)): for j in range(op[i]): Sum.append(operator[i]) print(Sum) cnt = 0 Find = [] for i in range(num): # for i in num: # i # print(i)
e63862945dc59ded277637a6eb595896ccd32035
ELKHALOMAR/py_snippets
/test.py
699
3.875
4
def power(inp): q = 0 y = 0 lenght = 12 o = ["weak", "medium", "strong"] while not y > 1: user = inp q += 1 if q > 1: user = input("please enter how strong: ") else: user = inp for x in o: if x == user: k = ...
7127ca22d1fa3d3cd9a40a09bea386e9feb284da
ELKHALOMAR/py_snippets
/exo9.py
1,003
4.15625
4
#Generate a random number between 1 and 9 (including 1 and 9). # Ask the user to guess the number, then tell them whether they guessed too low, too high, # or exactly right. (Hint: remember to use the user input lessons from the very first exercise) #Extras: #Keep the game going until the user types “exit” #Keep trac...
2cd1eba7b063449ef41ffd9c5e787be091a00504
Novomlinov/Lab2
/individual.py
129
3.578125
4
V1 = int(input("V1 км/ч")) V2 = int(input("V2 км/ч")) S = int(input("S км")) VS = V1 + V2 t = S / VS print("t=", t, "ч")
9813153978f76d20d59ab7b9b9a63fe014a01285
cocochief4/FunStuff
/game/slife.py
974
3.90625
4
# -*- coding: utf-8 -*- print('You are a slave in Virginia. Your master gives you shovel. What do you do? \n A)You obey B)You hit him') a = input() print("You chose %s" % a) if a == "A" or a == "a": b = input('You work hard until it is dark. Your master calls you in. Do you obey? \n A)Yes B)No \n') if b == "A...
c65c6a51e087b61a6c086c33f0d3213fd86ee0d1
Charles2mx/hongkong.marksix
/src/function/common.py
7,694
3.59375
4
#!/usr/bin/env python # coding=utf-8 import json import os import function.marksixdata data = function.marksixdata.MarksixData() class Common: @staticmethod def bubble_sort(lists): # 大小排序(冒泡排序) count = len(lists) for i in range(0, count): for j in range(i + 1, count): ...
c9de69dd37d3f1b1ab0823191992b48ba2e0131a
demirkeseny/algorithms_cookbook
/karatsuba_multiplication.py
645
3.890625
4
def karatsuba(x,y): """ multiplying two integers with karatsuba multiplication """ if len(str(x)) == 1 or len(str(y)) == 1: return x*y n1 = len(str(x)) n2 = len(str(y)) a = x // 10**(n1//2) b = x % 10**(n1//2) c = y // 10**(n2//2) d = y % 10**(n2//2) ...
78d03ae7a91355ae2ea8fd9b08cc74765f7d91c8
Serrones/xperience
/arc.py
347
3.828125
4
# Capítulo 4 livro PenseAllen # circun = 2 * pi * r #Criação de Pacote, e import de módulo from math import pi import turtle import Desenhos bob = turtle.Turtle() def circle(t,r,angle): circun = 2 * pi * r n = int(circun / 3) + 1 length = circun / n Desenhos.desenhar(t,length,n) circle(bob,100,3...
a533811973572dcc0b16925cb751de110a5a1137
Serrones/xperience
/calculadora.py
1,309
4.1875
4
# Calculadora com funcoes def mais(a,b): soma = a + b print('A soma de {} e {} é {}\n\n\n'.format(a,b,soma)) def subtrai(a,b): menos = a - b print('A subtração de {} por {} é {}\n\n\n'.format(a,b,menos)) def multiplica(a,b): vezes = a * b print('A multiplicação de {} por {} é {}\n\n\n'.format...
e4c73e8d39b37aef84776ba2581b7acb6b17b5f6
Serrones/xperience
/calculos.py
1,135
4.03125
4
# Capítulo 02 do livro Pense Allen """ Suponha que o preço de capa de um livro seja R$ 24,95, mas as livrarias recebem um desconto de 40%. O transporte custa R$ 3,00 para o primeiro exemplar e 75 centavos para cada exemplar adicional. Qual é o custo total de atacado para 60 cópias? """ def atacado(valor_livro,quant...
7a1ccf95e7fe932d43b1dd873b9d1b48a7a12c1a
GianAndreaSechi/DailyCodingProblemSolution
/5 - Jane Street/solution.py
295
3.5625
4
def cons(a, b): def pair(f): return f(a, b) return pair def car(p): return p(lambda a, b: a) def cdr(p): return p(lambda a, b: b) def main(): v_car = car(cons(3,4)) v_cdr = cdr(cons(3,4)) print("car: ", v_car, " - cdr: ", v_cdr) main()
534addc78c09e6325aeb5aea1b7283edbf5cb60d
R-Mct98/Python-Pong
/paddle.py
711
3.71875
4
class Paddle(pygame.sprite.Sprite): #Class represents a car def __init__(self, color, width, height): #Call the parent class constructor super().__init__() #Pass in the color, position, width and height #Set the background color and set it to transparent self.image = pygame.Surface([width, height]) self.image.fill(BL...
a8fa9530ce21a0435e97be580708715a5c9f3d68
MaxwellFB/Chrome_T_Rex_Rush_IA
/src/captura_teclado.py
1,220
3.828125
4
""" PRONTO Monitora teclado para realizar acoes no jogo e informar quando deve salvar o model (treinamento) """ from pynput.keyboard import Listener class CapturaTeclado: """Monitora algumas teclas do teclado""" def __init__(self): self.salvar_model = False self.tecla = 0 self.tecla_...
d91c2f17972fcd79df9a11590337354724179ed1
Julia673/Python-home_tasks
/lesson_11.py
926
3.703125
4
#task 1 def abc(): x = 1 y = 2 str1= "w3resource" print("Python Exercises") print(abc.__code__.co_nlocals) # task 2 def test(a): def add(b): nonlocal a a += 1 return a+b return add func= test(4) print(func(4)) # task...
965b1c09aa1fd9874ca6f30b25d9f884f92a1f7a
Julia673/Python-home_tasks
/lesson_3.py
1,004
3.859375
4
#22.02 #task 1 a='helloworld' c=a[0:2]+a[-2:] if len(a)==2: print ('Empty String') else: print(c) #task2 a=str(input()) if len(a)==10 and a.isdigit(): print('It is phonenumber ') else: print ('Error') #task3 a=3 b=4 c=5 l=0 d=(a4+c-ca)//b-c k=input() if d=...
0ba7bacbe98b6a38cb4d2910953ef741cb545920
Julia673/Python-home_tasks
/order_car_2.py
12,686
3.625
4
import csv from random import randint import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np class Order: '''зразок замовлення''' def __init__(self,name,speed,distance_max,weight_min,weight_max,size_min,size_max, cost,price): self.name = name self.speed = speed ...
06bc49be584773c80f3d100cffffc27df5c10b89
zhatch5201/portfolio0
/Python/calcTest.py
1,897
3.96875
4
import os def main(): def userNumbersX(): userNumbersX.x = float(input("Please input the 'x' operator: ")) try: float(userNumbersX.x) == float() == True print("{} is an integer".format(userNumbersX.x)) except ValueError or TypeError or SyntaxError: ...
b2e5dff89b56e50ab19b45c260e08938ff12d528
desk467/query.py
/example.py
1,249
3.59375
4
from query_py.query import create_runner, Types from random import choice import sqlite3 connection = sqlite3.connect('test.db') cursor = connection.cursor() query = create_runner(cursor) @query(Types.MANIPULATION) def create_user_table(): return ''' create table if not exists user ( id integer not n...
221c745b6cd5b0dc54c569e025ccb4dee01e2557
swathi20202/Pyramid-Patterns
/patterns_with_numbers.py
324
4.03125
4
//pattern1 rows = 6 for num in range(rows): for i in range(num): print(num, end=" ") # print number # line after each row to display pattern correctly print(" ") //pattern2 rows = 5 for row in range(1, rows+1): for column in range(1, row + 1): print(column, end=' ') print(...
918dcb180067973dc4feaffffa733770bdc75832
ijhajj/Django-RestApi-Celery-RabbitMQ-Redis
/django15_project/my_django15_project/tasks1.py
597
3.859375
4
import time import threading def countdown(count): while(count>=0): print("'{0}' count down -> {1}".format(threading.current_thread().name, count)) count -= 1 time.sleep(3) def countup(): count=0 while(count<=10): print("'{0}' count up -> {1}".format(threading.current_thread...
3bb2bcbe03ceac57be760c8eb770ec6360f809f9
chrisaddington96/Machine-Learning
/k-NN.py
11,133
4.03125
4
# -*- coding: utf-8 -*- """ Author: Chris Addington Assignment: k-NN and k-Means Course: CS 460 Machine Learning Some code provided by Dr. Siddique at the University of Kentucky File Description: File to implement k Nearest Neighbor algorithm and work with datasets. """ # Import statements from math import * from deci...
601a682e2c1a40c7d723e82ee1590abe523ec841
heweiblog/bind_stat
/test/thread.py
649
3.53125
4
import time, threading def loop(): print('d') t = threading.Thread(target=loop, name='LoopThread') print(type(t)) def res(a,b): print(a,b) return a+b class MyThread(threading.Thread): def __init__(self,func,args=()): super(MyThread,self).__init__() self.func = func self.args = args def run(self): s...
6e66659ce3ffc68c9ff578aede4be2768e5bc762
rover9632/machine_learning
/codes/utils/learn_bpe.py
7,763
3.734375
4
"""Use byte pair encoding (BPE) to learn a variable-length encoding of the vocabulary in a text. Unlike the original BPE, it does not compress the plain text, but can be used to reduce the vocabulary of a text to a configurable number of symbols, with only a small increase in the number of tokens. Reference: Rico Senn...
3f6262aa45565d826e06bcaa9e510ac0f1b69dd2
ArekBlej/Python-projects-for-beginners
/Totolotek.py
330
3.515625
4
import random liczba = random.randint(1,10) print("Wylosowana liczba:", liczba) i = 3 while i>0: odp = int(input(f"Zgadnij jaka jest wylosowana liczba. Masz {i} próby: ")) if odp == liczba: print("Zgadłeś!") i=0 else: print("Nie zgadłeś :(") i -= 1 print("\nKoniec g...
fc00b91806e5a966a74dbfe45ecdb34b3a87ee65
Lion0209/py15
/ATM+shopping_mall/core/shopping_mall_main.py
1,442
3.546875
4
from core import atm_main from core import auth def interactive(): dict_list = { "iphone":5888, "mac":12000, "cloth": 300, "durex": 58, "shoes": 500, "apple": 10, "pen": 20, } buy_list = [] account = 0 print('我们有如下商品:'.center(50,'...
d76ba238499b268a22c20d609340ae641981ac9b
forhadmethun/my-data-structure
/linked_list/CircularLinkList.py
774
3.953125
4
class Node: def __init__(self, data = None): self.data = data self.next = None class CircularLinkList: def __init__(self): self.head = None def insert(self,data): self.newNode = Node(data) if(self.head == None): self.head = self.newNode se...
1ee0785b3f729c1715782b9d84c941452ad8c022
NiksanGeorgiev/Python_Learning
/Games/Hangman/Console/main.py
1,422
4
4
import random #Functions def printWord(): for i in range(wordLength): if letters[i] == True: print(word[i], end = "") else: print("-", end = "") print() print("Welcome to Hangman!") attempts = 5 words = list(("apple", "banana", "carrot", "dragon", "egg","fish","green"...
726c028b7497eea1f76c8cc78ce57fe75860f041
saketkc/hatex
/2017_Fall/CSCI-599/EntranceTest/2170058637.py
4,632
3.578125
4
"""CSCI599 -- Take home exam Author: Saket Choudhary <skchoudh@usc.edu> """ from collections import Counter import pickle import sys import numpy as np from sklearn.decomposition import PCA #import matplotlib.pyplot as plt def read_pickled_data(path): """ data -- a 10000x3072 numpy array of uint8s. Each row ...
c53f6b45585d6e5d22240ee68f1bcde6414cb453
saketkc/hatex
/2014_Fall/coursera/algo-t/hw1.py
1,621
4
4
#!/usr/bin/env python """ Assignment 1 """ EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])} EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])} EX_GRAPH2 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3, 7]), 3: set([7]), 4: set([...
2cc0271f15eec84f3553df3e9cbc888851ccf748
khatriamit/Bigdata-word-count
/word_count.py
1,201
3.5
4
import sys class Mapper(object): def __init__(self, text): super(Mapper, self).__init__() self.text = text def map(self): self.words = self.text.split() self.map_output = [] for words in self.words: self.map_output.append({words: 1}) class Reducer(object)...
9e64e8c76115c96b3ae231be84daf920bfa1fb2c
Rutuja427/read-and-write
/character_sum.py
346
3.859375
4
def str_test(s): upper_case=[] lower_case=[] for i in s: if i.isupper(): upper_case.append(i) u=len(upper_case) elif i.islower(): lower_case.append(i) l=len(lower_case) else: pass print("sample string=",s) print("No. of upper case characters:", u) print("No. of loer case characters:", l) str_...
6170a225521d7f0db0ba06cfce5dfb27b70e5ff6
josephinius/algorithms-and-data-structures-practice
/lru_cache/lru_cache.py
7,396
3.71875
4
""" Least Recently Used (LRU) cache - LRUCacheDict: implementation based on dictionary; O(n) time-complexity - LRUCacheHeap: implementation based on dictionary and min-heap; O(log(n)) time-complexity - LRUCacheQueue: implementation based on dictionary and queue; O(1) time-complexity """ class LRUCacheDict: ...
df7af2a3aaf4ef3cf2e55dfcf7c0c558ce88830f
fremindmm/myleetcode
/num/count_prime.py
1,068
3.59375
4
#!/bin/env python class Solutions(object): if n < 3: return 0 preme = [1] * n preme[0] = preme[1] = 0 for i in range(2, int(n ** 0.5) +1): if preme[i] == 1: preme[i*i:n:i] = [0] * len(preme[i*i:n:i]) return sum(preme) def getPrimeCount(n)...
137376645d2184a1f9882bc7e5052e6448969bc9
fremindmm/myleetcode
/Array_deduplication.py
970
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/18 下午7:58 # @Author : Jeckxie # @CopyRight : 2018-2020 OpenBridge by yihecloud # @File : Array_deduplication.py # @Product : PyCharm # @Docs : # @Source : def removeDuplicates(nums): for i in n...
ac67a94ccda743852375ee440558c36bae11ee1e
fremindmm/myleetcode
/string/binary_one_count.py
634
3.546875
4
#!/bin/env python class Solutions(): @staticmethod def cout_and_return(string): #error -n not in return bin(int(string,10)).count('1') class Solutions2(): @staticmethod def cout_and_return(string): return bin(int(string,10) & 0xf11111111).count('1') class Solutions3(): @s...
db40e59c52c1423fee1ccd871f65fff5e4cb1907
fremindmm/myleetcode
/tree/maxDepth.py
1,167
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/12/24 上午11:17 # @Author : Jeckxie # @CopyRight : 2018-2020 OpenBridge by yihecloud # @File : maxDepth.py # @Product : PyCharm # @Docs : # @Source : # Definition for a binary tree node. # class TreeNod...
7797ffad17520dde2c8c009f74d93703e2cf3e2c
fremindmm/myleetcode
/link/removenfromend.py
919
3.796875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ ...
fb291a277a35ccd1d77a162b6a3487009e3ed6a4
tushargoyal02/Python_training_begineers
/basicsPython.py
754
4
4
# common object a=10 b=10 c=10 print(a,id(a), b, id(b), c, id(c)) c=11 b=12 print(a,id(a), b, id(b), c, id(c)) c=c-1 print(a,id(a), b, id(b), c, id(c)) # Garbage collection a=10 b=10 c=10 print("before deleting ",a,id(a), b, id(b), c, id(c)) # deleting the reference del a pr...
452e73bf8d54b57d91d3b2e186c2d3e55a865257
rishavpathania1995/code
/python/learn-bootcamp/learn-bootcamp/learn_bootcamp05.py
446
3.875
4
# simple guessing game import random cpu_num = random.randint(1,10) State = True while State: user_input = int(input( "please gusses he no from 1 to 10 :")) if user_input==cpu_num : print( "user wins") else: print( f"computer wins:{cpu_num}") con_inp...
99391972d21394ffa858d5f109f7f10277c23fd8
rishavpathania1995/code
/python/learn-bootcamp2/csv_learn.py
787
3.59375
4
import csv ''' with open("cars.csv") as file: read = csv.reader(file) lis = list(read) for x in lis: print(x) with open("cars.csv") as file2: read2 = csv.DictReader(file2, delimiter=";") for y in read2: print(y) with open("cats.csv","w") as file: csv_writer = csv.writer(file) ...
3965cedd860bdf5946b90a052922b1642d1d53cb
rishavpathania1995/code
/python/learn-bootcamp2/learn_bootcamp_try.py
467
3.921875
4
""" # raise #Typeerror #Valueerror # zerodivision error def display(name,colors): color=["red","blue","green"] if type(name) is not str: raise TypeError("Name is not string") print(f"{name}{colors}") display(1,"hello") # finally # else try: var=int(input("enter a integer")) except: prin...
eb40b90081f707b130208030c3d02e710fe75489
rishavpathania1995/code
/python/learn-bootcamp2/learnbootcampclass1.py
1,450
3.96875
4
''' class abc: def __init__ (self, name, rollno): self.name=name self.rollno=rollno #user1=abc("harry", 25) user2=abc("rohit", 26) print(type(user1)) print(type(user2)) print(user1.name) print(user2.rollno) # A User class with 3 attributes but no methods (aside from __init__) class User: def __i...
ce00b0fd5adb4a3c542af28f93c71415e3e4995d
vini-2002/LeetCode-Solutions
/Stack/1700. Number of Students Unable to Eat Lunch/1700. Number of Students Unable to Eat Lunch.py
1,199
3.84375
4
# The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. # The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
830bc292cfc30261a2a405d9a38a019e2d4b9665
vini-2002/LeetCode-Solutions
/Array/23.Merge k Sorted Lists/Python Solution/Solution.py
1,194
4.125
4
""" 23.Merge k Sorted Lists Link:- https://leetcode.com/problems/merge-k-sorted-lists/ You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1...
518793f8347a0e195016e15aa3eb57ab4ea63b8e
vini-2002/LeetCode-Solutions
/Trie/14. Longest Common Prefix/solution.py
1,176
3.8125
4
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lower-case En...
1bd817ec51e540a4a1be8bb11538e515fdfaaa10
DFrancis84/CodeLouisville-Python
/pythonmisc/combo.py
165
3.75
4
def combo(iter1, iter2): output = [] for i in range(0, len(iter1)): output += (iter1[i], iter2[i]), return output print(combo([1, 2, 3], 'abc'))
d536e8604d26d0209d857082c7b995be4884913d
SamJamaloff/hackerrankdailychallenges
/day_6/main.py
318
3.78125
4
t = int(input()) for i in range(t): s = input() odd_order = "" even_order = "" for order in range(len(s)): if (order + 1) % 2 == 1: odd_order = odd_order+s[order] elif (order + 1) % 2 == 0: even_order = even_order+s[order] print(odd_order+" "+even_order)
ce6d1668b168f4644dd4103e96ce3b6ddab50aea
anshulrts/pythonconcepts
/05_Functions.py
880
4.375
4
# Functions in Python start with def keyword # The return value of a Python function can be any object. # Everything in python is an object. So you functions can return numeric, collections, user # defined objects, classes, functions even modules & packages. # They always return a value, even if you don't specify a ret...
cbf31a6b929499a545d451adff1c067b65277165
Casimistico/Billboard-Lyrics-Analysis
/part_speech.py
4,414
3.546875
4
"""This module extracts information about "part of speech" of words in the lyrics""" from datetime import datetime import pandas as pd from nltk.tokenize import word_tokenize, PunktSentenceTokenizer import nltk import matplotlib.pyplot as plt from scipy import stats from song_analysis import dataframe_cleani...
2e565c39fe57994a33ead56ab0f87a6629cc03c8
LoseNine/DataStructureAndAlgorithms
/二叉树/3.求一棵二叉树的最大子树和.py
920
3.671875
4
class Node: def __init__(self,x=None): self.data=x self.left=None self.right=None class Test: def __init__(self): self.maxSum=-2**31 def FindMaxSubTree(self,root,maxRoot): if root==None: return 0 lmax=self.FindMaxSubTree(root.left,maxRoot) ...
5ddd08d9e2097760caef43a73c1e4b17bf938652
LoseNine/DataStructureAndAlgorithms
/二叉树/5.如何把二叉树转化为双向链表.py
867
3.796875
4
class Node: def __init__(self,x=None): self.data=x self.left=None self.right=None class Test: def __init__(self): self.phead=None self.pend=None def arrayTotree(self,arr,start,end): root=None if end>=start: root=Node() mid=(sta...
d290f4c7d5fdecdd527f7dbb0e7652bec8fcd860
LoseNine/DataStructureAndAlgorithms
/基本数字运算/4.不用除法实现两个正整数除法.py
156
3.90625
4
def Divide(n,m): res=0 while n>=m: n-=m res+=1 print("商为%d 余数为%d"%(res,n)) if __name__ == '__main__': Divide(6,3)
30504dc603058b50d4a692638718cb6c8842b1d7
LoseNine/DataStructureAndAlgorithms
/栈/1.数组实现栈.py
471
3.90625
4
class Stack: def __init__(self): self.items=[] def size(self): return len(self.items) def is_empty(self): return len(self.items)==0 def push(self,x): self.items.append(x) def pop(self): self.items.pop() def top(self): if self.is_empty(): ...
4cc83698ae5724a7cdebb16ae047f89d9e971e21
LoseNine/DataStructureAndAlgorithms
/链表/9.合并两个有序链表.py
1,412
3.984375
4
class Node: def __init__(self,x): self.data=x self.next=None def merge(head1,head2): cur1=head1.next cur2=head2.next t=Tree() while cur1 and cur2: if cur1.data>cur2.data: t.append(cur2.data) cur2=cur2.next elif cur1.data<cur2.data: ...
118bd314c9d6bc4e055c9b621617393821438d0f
Ritikajain18/Problem-Solving
/Designer PDF Viewer.py
960
4.125
4
''' When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In this PDF viewer, each word is highlighted independently. In this challenge, you will be given a list of letter heights in the alphabet and a string. Using the letter heights given, determine the ...
2c7cc0fd65078e4609401f78204b81afd453dcfe
Ritikajain18/Problem-Solving
/Bon Appétit.py
692
4
4
''' Function Description Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna. bonAppetit has the following parameter(s): bill: an array of integers representing the cost o...
7246c9a274f9046e1b41c963ad8d832d5f48d059
Ritikajain18/Problem-Solving
/Divisible_Sum_Pairs.py
863
4
4
''' You are given an array of n integers and a positive integer,k . Find and print the number of (i,j) pairs where i<j and ar[i] + ar[j] is divisible by k . For example,ar=[1,2,3,4,5,6] and k=5. Our three pairs meeting the criteria are[1,4],[2,3] and [4,6]. Function Description Complete the divisibleSumPair...
394502005f25b506fd08218bbb55dda6894fc110
Ritikajain18/Problem-Solving
/Grading_Students.py
1,131
4.21875
4
''' HackerLand University has the following grading policy: Every student receives a grade in the inclusive range from 0 to 100. Any grade less than 40 is a failing grade. Sam is a professor at the university and likes to round each student's grade according to these rules: If the difference between the gr...
5901182dde67dad51e43cf1118f8da175bab0db5
Ritikajain18/Problem-Solving
/Staircase.py
534
4.46875
4
''' Consider a staircase of size n : # ## ### #### Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n .''' import math import os import random impo...
c1f1e23625ee9bf6927b7e1f2d2df27e8bd8ec16
c-geisel/Surfs_Up
/climate_analysis/app.py
4,310
3.796875
4
#Creating a python file to create Flask apps that will showcase the analysis results #import dependencies import datetime as dt import numpy as np import pandas as pd #import SQLAlchemy dependencies to access SQLite import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session f...
78a13ad6bd617372539003687fba6260b4a9711c
LuanCantalice/StringProjeto
/StringUtil.py
611
3.765625
4
def output(texto): print(texto) def tamanho(texto): TamanhoTexto = len(texto) return TamanhoTexto def maiusculo(texto): MaiusculaT = texto.upper() return MaiusculaT def minusculo(texto): minusculaT = texto.lower() return minusculaT def contador(texto): letraBusca = input("Qua...
3474aa3fb9c5305802c630be6d5224910c2e7ca1
dilyanpenev/advent-of-code
/python/day7.py
1,198
3.609375
4
def count_overbag(rules, color): overbags = set() for key, values in rules.items(): for value in values: if color in value: overbags.add(key) overbags.update(count_overbag(rules, key)) return overbags def count_innerbags(rules, color): count = 0 ...
07cb17094f26cfbbb2e2a122835352e7b80239a1
Danistry/Python
/tparrays2.py
3,409
3.84375
4
# act1 # Señor programador el codigo debe aceptar numeros flotantes, e imprimirlos en el orden que entra y a su vez # eliminarlos 1 a uno, puede modificar el existente o hacer el propio, good luck! def cajero(): caja = [] for i in range(1, 11): caja.append(float(input('Ingrese los valores de l...
8987b14304f8155c88bbd54690952dac08db2133
khatamirock/snakePY
/snakeMove.py
1,938
3.5
4
from turtle import Turtle, done # snls=[] item=5 UP=90 DOWN=270 RIGHT=0 LEFT=180 from random import randint as rint class Snake: def __init__(self,it) -> None: self.snls=[] self.ls=[-20*x for x in range(it)] self.crate() # self.ls.reverse() self.head=self.snls[0] se...
695a7cca2f48d4ec09150e3f9c7afdbb27994923
dyotahutomo/basic-python-5
/condition.py
276
3.734375
4
# a = 10 # b = 10 # if a > b: # # execution some command # print("a lebih besar dari b") # elif a == b: # print("a sama dengan b") # else: # print("a lebih kecil dari b") print(True and True) print(True and False) print(True or True) print(True or False)
b4cd24234b0b85f8bd269e18053c5d6946400f35
dyotahutomo/basic-python-5
/nested_loop.py
360
4.25
4
for i in range(3): print("i: {}" .format(i)) for j in range (3): print("j: {}" .format(j)) for baris in range(5): for kolom in range(5): print("{},{}" .format(baris + 1, kolom +1) ,end=" ") print() count = 1 for baris in range(5): for kolom in range(5): print (count, end = ...
3de5ad8480fc10e0617f8124691b44eadac9e73b
peak27/ML-Regressions-Python-R
/Random Forest Regression/Random Forest Regression (PK).py
897
3.640625
4
# Random Forest Regression # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import Dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values Y = dataset.iloc[:, 2].values # Fitting Random Forest Regression to the dataset from sklearn.ens...
d7e00d150d41fe04bdf5b18c3a9c285de188d228
llenroc/facebook-interview-question-data
/python/monotobnic.py
464
4.28125
4
## Given an array of integers, we would like to determine whether the array is monotonic (non-decreasing/non-increasing) or not. ## https://www.geeksforgeeks.org/python-program-to-check-if-given-array-is-monotonic/ -- One solution available here # Monotonic - def isMonotonic(A): return (all(A[i] <= A[i + 1] for i...
4fb6bd6da04ab83698b226851ce9e44e477b0e16
llenroc/facebook-interview-question-data
/python/validateIP.py
591
3.625
4
def validIPAddress(IP): def isIPv4(s): print(s) if str(int(s)) == s and 0 <= int(s) <= 255: return True return False def isIPv6(s): if len(s) > 4: return False elif int(s, 16) >= 0 and s[0] != '-': return True ...
596341427f286705bfb6ca0bb292e069f6b733d0
llenroc/facebook-interview-question-data
/python/delete_duplicates_list.py
311
3.875
4
# Delet duplicates from python list def remove_duplicates_list(lst): if len(lst) == 0: return "Empty List" mlist = [] for i in lst: if i not in mlist: mlist.append(i) return mlist ## Driver l1 = [10,10,10,20,30,40,40,50,60,70] print(remove_duplicates_list(l1))
9d1afd99bdee2b45960522d60675bb1029f962b3
yasminezakaria/predict-nba-all-stars
/src/Data Collection/scrape_All-Star_game_stats_.py
1,743
3.609375
4
# import libraries import urllib2 from bs4 import BeautifulSoup import requests import pandas as pd # specify the url quote_page = "https://www.basketball-reference.com/allstar/NBA_2019.html" # Get column headers from each page # Assigns a new list of column headers each time this is called def get_column_headers(sou...
36d4ca6415c75d10d736b9fc50d259e476944a31
xyxiaoYU1992/PythonLearning
/ifinout.py
276
4.09375
4
# -*- coding: utf-8 -*- height = 1.75 weight = 80.5 bmi = weight/(height * height) if bmi < 18.5: print('too light') elif bmi>=18.5 and bmi <25: print("normal") elif bmi>=25 and bmi<28: print("too high") elif bmi>=28 and bmi<32: print("fat") else: print("very fat")
098b1b6175cd89403c4f049d27d84490d1ab96bd
ankuagar/educative.io
/search_rotated.py
1,167
3.828125
4
#!/usr/bin/env python3 def binary_search_rotated(arr, key): def binary_search(arr, low, high, key): if low > high: return -1 mid = (low + high) // 2 if arr[mid] > key: return binary_search(arr, low, mid-1, key) elif arr[mid] < key: return binary_search(arr, mid+1, high, key) ...