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
87f3692eb4df2e6e113a4c71f00a09712d29b89c
MrWater/XPyTest
/Python/GUI/test_listbox.py
1,019
3.546875
4
import tkinter root = tkinter.Tk() # selectmode: single multiple browse(移动鼠标进行选中,而不是单击选中) EXTENDED支持shift和ctrl listbox = tkinter.Listbox(root, selectmode=tkinter.MULTIPLE) listbox.pack() for i in range(19): listbox.insert(tkinter.END, i) listbox = tkinter.Listbox(root, selectmode=tkinter.BROWSE) listbox.pack() ...
1d1a37c8933d54fe5f697a5718b13d09233dda7c
MrWater/XPyTest
/cv/test.py
121
3.546875
4
#-*-coding:utf8-*- import numpy as np arr = np.random.random((2, 2, 2, 3)) print(arr) np.random.shuffle(arr) print(arr)
1e629e6a649ca028d7eef107d2e51f98a96c0f46
D4N-W4TS0N/Python-Lockdown
/while_loops.py
75
3.671875
4
i = 1 while i <= 10: print(i * "this is a while loop") i = i + 1
4d4c2670577d87081d1404c1414ecda037d8f769
psk264/rock-paper-scissors
/game.py
3,680
4.15625
4
# game.py # Rock-Paper-Scissors program executed from command line #import modules to use additional third party packages import random import os import dotenv #Input command variation, using print and input # print("Enter your name: ") # player_name = input() #Above statements can be reduced to single line of cod...
ecbd94b636438891fa11ed64943fa66eef961d00
ezeutno/All_Comp_Math_Assignment
/Exam Simulation/Data.py
2,014
3.84375
4
from sympy import * import numpy as np import math as m import matplotlib.pyplot as plt #Latihan Exam BiMay #Number 1 def fact(num): res = 1 for i in range(1,num+1): res *= i return res def Maclaurin(x,n): res = 0 if type(n) is np.ndarray: data = [] for a in np.nditer(n):...
caded9115b67830a704ea736272a43d4923b7a90
Jeduroid/intermediate-python-course
/dice_roller.py
537
3.953125
4
import random def main(): dice_rolls = int(input('\nHow many dice you want to roll : ')) dice_size = int(input('\nHow many sides a dice have : ')) dice_sum = 0 for i in range(0,dice_rolls): roll = random.randint(1,dice_size) dice_sum += roll if roll == 1: print(f'You rolled a {roll} ! Critic...
f0b385abec60ac9edaa7d68ea9cceb83c52062e1
ktheylin/ProgrammingForEveryone
/Python-GettingStarted/assg4-6.py
278
3.828125
4
def computepay(hrs, rate): if hrs <= 40: gross_pay = hrs * rate else: gross_pay = 40 * rate + ( (hrs - 40) * (rate * 1.5) ) return(gross_pay) hrs = float(raw_input("Enter Hours: ")) rate = float(raw_input("Enter Rate per Hour: ")) print computepay(hrs,rate)
3abb8b828e114b048fd19d232e858e0f204f2901
ktheylin/ProgrammingForEveryone
/Python-WebAccessData/week4-followLinks.py
733
3.5
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib from BeautifulSoup import * tag_index = 17 loop = 7 count = 0 #url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret....
36f889bbd9010c826012a2e0b12600aba9ab9ee3
Leo-Simpson/c-lasso
/classo/stability_selection.py
5,674
3.59375
4
import numpy as np import numpy.random as rd from .compact_func import Classo, pathlasso """ Here is the function that does stability selection. It returns the distribution as an d-array. There is three different stability selection methods implemented here : 'first' ; 'max' ; 'lam' - 'first' will compute the w...
bb18f87d4e9fe1d0489fe3f833200955d9d80e80
ysabhi1993/Python-Practice
/Queue_imp.py
1,305
3.953125
4
class Node: def __init__(self, data): self.data = data self.nextnode = None class Queue: def __init__(self): self.head = None self.size = 0 def IsEmpty(self): return self.head == None def enqueue(self, data): currentnode = None ...
c4c527c574ca40c828dacc7da03a6216a946f53c
ysabhi1993/Python-Practice
/useful_functions.py
7,609
3.984375
4
#Checks if a number is even or odd def checkOE(): num = int(input("Enter a number:")) if num%2 == 1: print('The number you entered is odd') elif num%4 == 0: print('The number you entered is divisible by 4') else: print('The number is even') #prints out a string th...
47358be77fec8fc5229dfb73736cb8a92f74e406
nan0314/RRTstar
/RRTstar.py
12,203
3.640625
4
import pygame import random as r import pylineclip as lc ############################################ ## Constants ############################################ # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0,0,255) YELLOW = (255,255,0) PURPLE = (128,0,128) #...
4f32d0b2293ff8535a870cd9730528ecf4874190
comedxd/Artificial_Intelligence
/2_DoublyLinkedList.py
1,266
4.21875
4
class LinkedListNode: def __init__(self,value,prevnode=None,nextnode=None): self.prevnode=prevnode self.value=value self.nextnode=nextnode def TraverseListForward(self): current_node = self while True: print(current_node.value, "-", end=" ") ...
85f7053fa27c235f58c6042f625a691c47f622c0
comedxd/Artificial_Intelligence
/0-13-Nested_Function_NON_Local_variables.py
297
3.578125
4
# Defining the nested function only def print_msg(msg): def printer(): print(msg) #nested function is accessing the non-local variable 'msg' printer() print("i am outer function") printer() # calling the nested function # driver code print_msg("this is message")
b45abb8df2533c41170f40dcbd293c6c58ab29fc
comedxd/Artificial_Intelligence
/0-5-dataprotection.py
403
3.890625
4
class Square: def __init__(self): self._height = 2 self._width = 2 def set_side(self,new_side): self._height = new_side # variables having name starting with _ are called protected variables self._width = new_side # protected variable can be accessed outside class square = Squar...
76348acf643b1cd9764e1184949478b3b888b014
jdipendra/asssignments
/multiplication table 1-.py
491
4.15625
4
import sys looping ='y' while(looping =='y' or looping == 'Y'): number = int(input("\neneter number whose multiplication table you want to print\n")) for i in range(1,11): print(number, "x", i, "=", number*i) else: looping = input("\nDo you want to print another table?\npress Y/y for yes and...
e6e94d3d50a56f104d1ad9993d78f8c44394b753
jdipendra/asssignments
/check square or not.py
1,203
4.25
4
first_side = input("Enter the first side of the quadrilateral:\n") second_side = input("Enter the second side of the quadrilateral:\n") third_side = input("Enter the third side of the quadrilateral:\n") forth_side = input("Enter the forth side of the quadrilateral:\n") if float(first_side) != float(second_side) and flo...
a7b9b32d1a9e5ee6c7cf1a3b1556a5140a0c98d9
jdipendra/asssignments
/mine calculator.py
4,012
4.46875
4
import sys menu = True def calculator(): print("You can do the following mathematical operations with BRILLIANT-CALCLATOR APP") print("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Square Root\n6.Square\n7.Exponential\n8.nth Root") choice = int(input("Enter Your choice")) condition = 'Y' ...
a45c34fe97086442b252db0c6f9fd373d5cb6100
potroshit/Data_science_basic_1
/home_work_1/home_work_1_Avdeev.py
644
3.859375
4
# задание 1 arr = [1, 2, 3, 4, 5, 6, 7, 8] for i in arr: if i % 2 == 0: a1 = i a2 = [i] * i print(a1, a2) # задание 2 x = int(input()) y = int(input()) if -1 <= x <= 1 and -1 <= y <= 1: print("принадлежит") else: print("нет") # задание 3 A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ...
bacbbfa0ee5a53bbf8d572568d0555d2696e0514
potroshit/Data_science_basic_1
/home_work_1/Клачев_Максим_10И2.py
760
3.609375
4
#a = input('Ввести имя: ') #a = list(a) #a = a[1:-1] #b = input('Ввести класс: ') #a.append(b) #c = input('Ввести фамилию: ') #a+=c #print(a) #1 j = [1, 2, 3, 4, 5, 6, 7] u = [[i]*i for i in j if i % 2 == 0] print(j[i], u) #2 x = int(input()) y = int(input()) if -1<= x <= 1 and -1 <= y <= 1: ...
2675e7a9424696fc2a057cca1ff8d093a6139c2f
potroshit/Data_science_basic_1
/class_work1/classwork1_Мезенцева.py
257
3.984375
4
name = [ "k", "s", "e", "n", "i", "a", 16] print(name) #проверка print(name[1:-1]) #задание 1 name.append("10п") print(name) #задание 2 surname = "Mezenceva" surname = list(surname) name = name + surname print(name) #задание 3
398472bec52a37a71af162adce1b17ec71fb388a
MouseOnTheKeys/small_projects
/recursion_palindrom.py
853
3.765625
4
# -*- coding: utf-8 -*- """ Created on Mon May 19:30:57 2020 @author: Nenad Bubalo 1060/19 Domaci zadatak 13: 1. U programskom jeziku Python, napisati funkciju koja rekurzivno proveravada li je dati string palindrom. String je palindrom ako se s desna na levo i s leva na desno isto čita "...
c6d950474777fdc034c6b0d086478eb3f9de12c1
skynette/30-days-code-challenge-day-1
/day1.py
219
3.546875
4
def twofer(name="you"): # Enter your code here. Read input from STDIN. Print output to STDOUT if name: return("One for {}, one for me.".format(name)) else: return("One for you, one for me.")
95bf80fc821ee37718c25869f217b5da8a3e83f6
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex33.py
195
3.703125
4
""" Leia o tamanho do lado de um quadrado e imprima como resultado sua área. """ tam = float(input("Lado do quadrado: ")) area = tam * tam print("Resultado de sua área = {:.2f}".format(area))
e103f7dc1bdb8ddfeaccba17c2661cf1692aae2c
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloII/Exercicio2.1.py
252
3.875
4
""" Exercicio 2.1 Converta as seguintes expressões matemáticas para que possam ser calculadas usando o interpretador python. 10 + 20 x 30 4² ÷ 30 (9⁴ + 2) x 6-1 """ # Resposta print(10+20*30) print(4**2/30) print((9**4 +2)* 6-1)
24b16e3a48c7688365a31738ad2e12f2f41bc5dc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex03.py
247
4.1875
4
""" .3. Faça um algoritmo utilizando o comando while que mostra uma contagem regres- siva na tela, iniciando em 10 e terminando em 0. Mostrar uma mensagem 'FIM!' após a contagem. """ i = 10 while i >= 0: print(i) i = i - 1 print('FIM')
12b0ad3a799b83888c413ba1499b78b3cbe05170
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex08.py
725
4.15625
4
""" Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas. Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota possua um valor válido, este fato deve ser informado ao usuário e o programa termina. """ nota1 = float(inpu...
6e253a61bbec738313c6751af19db42204402edf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex27.py
287
3.578125
4
""" Leia um valor de área em hectares e apresente-o em metros quadrados m². A fórmula de conversão é: M = H * 10.000, sendo M a área em m² e H a área em hectares. """ area = float(input("Valor da hectares: ")) convert = area * 10.000 print("Em m² fica: {:.4f}".format(convert))
677274c5c2e5ef86e3090e5501182c28e1d7acf3
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex21.py
1,216
4.15625
4
""" Escreva o menu de opções abaixo. Leia a opção do usuário e execute a operação escolhida. Escreva uma mensagem de erro se a opção for inválida. Escolha a opção: 1 - Soma de 2 números. 2 - Diferença entre 2 números. (maior pelo menor). 3 - Produto entre 2 números. 4 - Divisão entre 2 números (o denominador não pode ...
6bdaa9fca5f74779af13721837fc1bf30625af36
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_22_ao_41/S05_Ex28.py
1,237
4.15625
4
""" .28. Faça um programa que leia três números inteiros positivos e efetue o cálculo de uma das seguintes médias de acordo com um valor númerico digitado pelo usuário. - (a) Geométrica : raiz³(x * y * z) - (b) Ponderada : (x + (2 * y) + (3 * z)) / 6 - (c) Harmônica : 1 / (( 1 / x) + (1 / y) + (1 / z)) - (d) Aritm...
a3922a8d8afbea816fa87015c6fd318ef1eb4efc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex18.py
307
3.875
4
""" Leia um valor de volume em metros cúbicos m³ e apresente-o convertido em litros. A formula de conversão é: L = 1000*M, sendo L o volume em litros e M o volume em metros cúbicos. """ volume = float(input("Valor Volume(m³): ")) convert = volume*1000 print("Em Litros fica: {:.2f}".format(convert))
031f74a6547ec84a7815735874badd864e191acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex29.py
309
3.609375
4
""" .29. Faça um programa para calcular o valor da série, para 5 termos. - S = 0 + 1/2! + 1/4! + 1/6 +... """ from math import factorial soma = 0 termos = 5 for i in range(1, termos + 1): if i % 2 == 0: # Condição para encontrar valores pares soma = soma + 1/factorial(i) print(soma)
cf90f34f7fac4c7ec15afdb130ccc715ca5b9598
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex06.py
412
3.984375
4
""" Escreva um programa que, dado dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos. """ n1 = int(input("Informe um número: ")) n2 = int(input("Informe outro número: ")) dif = 0 if n1 > n2: print(f"O maior: {n1}") dif = n1 - n2 print(f"A diferença: : {dif}") ...
28473894237479028f7090828351d147a1f439b5
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex24.py
345
4
4
""" .24. Escreva um programa que leia um número inteiro e calcule a soma de todos os divisores desse numero, com exceção dele próprio. EX: a soma dos divisores do número 66 é 1 + 2 + 3 + 6 + 11 + 22 + 33 = 78 """ n = int(input('Informe um numero: ')) soma = 0 for i in range(1, n): if n % i == 0: soma = som...
ab98f9c6ff4f60984dba33b33038588020bae6bc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex13.py
645
4.21875
4
""" Faça um algoritmo que calcule a média ponderada das notas de 3 provas. A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final, mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado. A nota para aprovação deve ser igual ou superior a 60 pontos. """ nota1 = float(input("nota1: ")...
47d4adf6d6e33bc0578eaf576cb5d81821261d60
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex04.py
354
4.09375
4
""" Faça um programa que leia um número e, caso ele seja positivo, calcule e mostre: - O número digitado ao quadrado - A raiz quadrada do número digitado """ n = float(input("Informe um número: ")) rq = pow(n, 1/2) if n >= 0: print("{} ao quadrado é = {:.2f}: ".format(n, n ** 2)) print("Raiz Quadrada de {} é ...
51f0f4a8aecd6bdff88482d13c6813501689f2b4
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex17.py
602
3.921875
4
""" Faça um programa que calcule e mostre a área de um trapézio. Sabe-se que: - A = ((baseMaior + baseMenor)*altura)/2 Lembre-se a base MAIOR e a base menor devem ser números maiores que zero. """ baseMaior = float(input("BaseMaior: ")) baseMenor = float(input("BaseMenor: ")) altura = float(input("Altura: ")) if ...
efef90bd4f05f5d84f10e44e9422e3329e1d3e98
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloV/Exercicio5.2.py
182
4.40625
4
""" # O programa do livro x =1 while x <= 3: print(x) x = x +1 #Modifique o programa para exibir os números de 1 a 100 """ x = 50 while x <= 100: print(x) x = x +1
bb84e63b12ca692da1a1277fa62b6400bfe278a2
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloIV/Exercicio4.3.py
754
3.9375
4
""" Escreva um programa que leia três números e que imprima o maior e o menor """ n1 = int(input()) n2 = int(input()) n3 = int(input()) if (n1>n2) and (n1>n3): # n1 > n2 and n3 if (n2>n3): #n1>n2>n3 print("maior:",n1) print("menor:",n3) if (n3>n2): # n1>n3>n2 print("maior:", n1) ...
d80274fec662b690fff77f8900d4c6b5c25bb132
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/MinAndMax.py
1,784
4.28125
4
""" Min() e Max() max() -> retorna o maior valor ou o maior de dois ou mais elementos # Exemplos lista = [1, 2, 8, 4, 23, 123] print(max(lista)) tupla = (1, 2, 8, 4, 23, 123) print(max(tupla)) conjunto = {1, 2, 8, 4, 23, 123} print(max(conjunto)) dicionario = {'a': 1, 'b': 2, 'c': 8, 'd': 4, 'e': 23, 'f': 123} p...
a7b48d30123753ea5c87b79acff9e6ef0c1e0fba
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex15.py
239
3.921875
4
""" .15.Faça um programa que leia um número inteiro positivo impar N e imprima todos os números impares de 0 até N em ordem crescente. """ n = int(input('Informe um numero: ')) for i in range(0, n): if i % 2 == 1: print(i)
0d330f98177358d5bf90bae0b6b73d6c73668a4a
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex08.py
333
3.875
4
""" .8. Escreva um programa que leia 10 números e escreva o menor valor lido e o maior valor lido. """ maior = 0 menor = 999999 for i in range(0, 5): num = int(input(f'Informe o valor {i+1}: ')) if num > maior: maior = num if num < menor: menor = num print(f'maior = {maior}') print(f'menor ...
0f387b4432f970d10a67347d58f4e1aa6983b75d
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex48.py
289
3.765625
4
""" Leia um valor inteiro em segundos, e imprima-o em horas, minutos e segundos. """ x = int(input()) hora = x // 3600 resto = x % 3600 minutos = resto // 60 resto= resto % 60 seg = resto // 1 print("{}h:{}m:{}s".format(hora, minutos, seg)) # print("{} horas : {} min: {} seg".format())
d57e86a7d82801e5c0485ffa94211f0025e08acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex16.py
336
3.890625
4
""" Leia um valor de comprimento em polegadas e apresente-o convertido em centimetros. a formula de conversão é: C = P*2.54, sendo C o comprimento de centimetros e P o comprimento em polegadas. """ comprimento = float(input("Valor Comprimento(pol): ")) convert = comprimento * 2.54 print("Em centimetros fica: {:.2f}".fo...
79b58db5b932f19b7f71f09c37c3942554507803
RjPatil27/Python-Codes
/Sock_Merchant.py
840
4.1875
4
''' John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n = 7 socks with colors arr = [1,2,1,2,3,2,1] . There is one pa...
bbc6900a6123bd2cfe9c1bb832bee170e7c025d8
RjPatil27/Python-Codes
/PrimeNo.py
419
4.0625
4
# Python Program - Check Prime Number or Not print("Enter 'x' for exit.") num = input("Enter any number: ") if num == 'x': exit(); try: number = int(num) except ValueError: print("Please, enter a number...exiting...") else: for i in range(2, number): if number%i == 0: print(number, "is no...
6fc26692c43e63efbce1678792fff2845a3953a5
VIKGO123/Using-Pandas-library-in-python
/csvshow.py
374
3.53125
4
import matplotlib.pyplot as plt import csv x=[] y=[] with open('test.csv','r') as csvfile: plots=csv.reader(csvfile)#reads file for row in plots: #accessing row by row x.append((row[0])) #accessing first element of row y.append((row[1])) #accessing 2nd element of row plt.plot(x,y,lab...
05432b48af09dc9b89fded6fb53181df2645ee53
Mat4wrk/Working-with-Dates-and-Times-in-Python-Datacamp
/1.Dates and Calendars/Putting a list of dates in order.py
569
4.375
4
"""Print the first and last dates in dates_scrambled."" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) """Sort dates_scrambled using Python's built-in sorted() method, and save the results to dates_ordered.""" """Print the first and last dates in dates_ordered.""" # Pr...
df540eae1ad91815ed2a578cc9fbf175b0fcb7e9
vytran0710/CS106.K21.KHCL
/TH/TH1/Bai 3/Bai3_IDS.py
1,117
3.609375
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def DLS(self,src,target,maxDepth): if src == target : return True if maxDepth <= 0 ...
dbd92d328c883c792554926aae4de04d22ccb149
changzheng1993/map
/recommend.py
8,834
3.59375
4
# CS 61A Spring 2015 # Name: Zheng Chang # Login: cs61a-aep """A Yelp-powered Restaurant Recommendation Program""" from abstractions import * from utils import distance, mean, zip, enumerate, sample from visualize import draw_map from data import RESTAURANTS, CATEGORIES, USER_FILES, load_user_file from ucb import mai...
619f65ba890f6fa2e891f197581b739f02baae40
Jmwas/Pythagorean-Triangle
/Pythagorean Triangle Checker.py
826
4.46875
4
# A program that allows the user to input the sides of any triangle, and then # return whether the triangle is a Pythagorean Triple or not while True: question = input("Do you want to continue? Y/N: ") if question.upper() != 'Y' and question.upper() != 'N': print("Please type Y or N") elif question...
6273ea18be6a76f5d37c690837830f34f7c516e4
cahill377979485/myPy
/正则表达式/命名组.py
1,351
4.46875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Python 2.7的手册中的解释: (?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defin...
bf359f264311bd83105764a70207a67360835493
valerie-bernstein/Moon-and-Magnetotail
/x_rotation_matrix.py
300
3.703125
4
import numpy as np def x_rotation_matrix(theta): #rotation by the angle theta (in radians) about the x-axis #returns matrix of shape (3,3) rotation_matrix = np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)]]) return rotation_matrix
6b1aa9476e1deb167321b3c37c88e8c517b13e8a
sivaprasad0/AssignmentsDaily
/Aug11/palindrome.py
237
3.859375
4
name=input("enter a palindrme: ") l= len(name) i=0 count=0 for i in range(0,(l+1)//2): if name[i]==name[l-1-i]: pass else: count=count+1 break if count==0: print(name," is palindrome") else: print(name,"is not a palindrome")
0c6fcfa855bc02ebc378e1f5d0c1e5bc5014d5b1
HeloiseKatharine/Bioinformatica
/Atividade 1/3.py
821
4.125
4
''' Crie um programa em python que receba do usuário uma sequência de DNA e retorne a quantidade de possíveis substrings de tamanho 4 (sem repetições). Ex.: Entrada: actgactgggggaaa Após a varredura de toda a sequência achamos as substrings actg, ctga, tgac, gact, ctgg, tggg, gggg, ggga, ggaa, gaaa, logo a saída do pro...
7a3f6276f0a8346e840ab8069e1802370a2abcf5
JimmyBowden/IT780
/C4.py
1,484
3.546875
4
#Jimmy Bowden #IT780 #C4 import csv #-----------------Var #-----------------Functions def readNameCSV(): myList = [] fName = 'People.csv' with open(fName, 'r') as inFile: line = inFile.readline() while line != "": nameList = line.split(",") myList.append(nameLi...
0d43af9ffd13bc33c8691eba0cb4a01ec2f2efae
JimmyBowden/IT780
/C8.py
4,778
3.734375
4
#Jimmy Bowden #C8.py from math import sqrt import C4 class myRecommender: def __init__(self): from math import sqrt def manhattan(self, rating1, rating2): """Computes the Manhattan distance. Both rating1 and rating2 are dictionaries """ distance = 0 commonRatings = Fal...
068596b0d357250adba6202530cd94d150e71532
dpdi-unifor/juicer
/juicer/scikit_learn/util.py
1,439
4
4
import numpy as np def get_X_train_data(df, features): """ Method to convert some Pandas's columns to the Sklearn input format. :param df: Pandas DataFrame; :param features: a list of columns; :return: a DataFrame's subset as a list of list. """ column_list = [] for feature in featur...
ce47e80b7965d38045d0c2a6aac967fca7435217
sophiezeng1215/Algorithms
/Algorithm/Binary Tree Preorder Traversal.py
766
3.9375
4
#Time O(n), space O(n) #append node.val, use a stack to store node.right(only), and then move node to the left, and # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def...
eea37504d1e1776291a20d3517bb601bc31e1970
sophiezeng1215/Algorithms
/Algorithm/Reverse Linked List.py
536
3.859375
4
#Use "prev" and 'temp' = node.next; return prev #Time O(n), space O(1) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode ...
c78396501abd25be740492c42842b70d60532af0
yugalsherchan1991/python-project
/funcitons.py
2,133
4
4
#%% def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' return (a * x*x) + (b * x) + c evalQuadratic (1,2,3,4) # %% def f(x,y): x = x + y print ("In f(x,y) : x and y: ",x ,y) ...
dfaf1ef03730da91c867e734c4c33efb86310c06
mbernste/bio-sequence-tools
/bio_sequence/rand_seq.py
800
3.796875
4
#!/usr/bin/python import sys import random from sequence import Sequence import fasta NUCLEOTIDES = ['A', 'C', 'T', 'G'] def randNucleotide(): i = random.randint(0, 3) return NUCLEOTIDES[i] def randNucleotideExlude(excludedNucleotides): pickFrom = [nucl for nucl in NUCLEOTIDES if nucl not in excludedNuc...
498986037d33c74ded5f9aba97d7448979aca830
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 32/remove nth node.py
545
3.53125
4
# username: shantanugupta1118 # Day 32 of 100 Days # 19. Remove Nth Node From End of List # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: start, curr = [], head while curr: sta...
52f97e7f4eccf88f0eb1930ee8a8527b6420eaa7
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 8/xor-equality.py
316
3.546875
4
MOD = 10**9+7 def equality(n, x=2): res = 1 x %= MOD if x==0: return 0 while n>0: if n&1 != 0: res = (res*x)%MOD n = n>>1 x = (x*x)%MOD return res def main(): for _ in range(int(input())): n = int(input()) print(equality(n-1)) main()
3e5f2ef814933ff40deb61305404d9c6c1e055b6
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 27/106. Construct Binary Tree from Inorder and Postorder Traversal.py
2,749
3.90625
4
# Github: Shantanugupta1118 # DAY 27 of DAY 100 # 106. Construct Binary Tree from Inorder and Postorder Traversal # https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # Solution 2-- class TreeNode: def __init__(self, val): self.val = val self.left = None ...
f7da868b7a723c2ff02967a213fd6bc11cbddc04
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 20/215. Kth Largest Element in an Array.py
607
3.71875
4
# Contribution By: Shantanu Gupta # Github: Shantanugupta1118 # DAY 20 of DAY 100 # 215. Kth Largest Element in an Array - Leetcode # https://leetcode.com/problems/kth-largest-element-in-an-array/ from heapq import * ''' First Approach without inbuilt fnc ''' ''' def k_largest(arr, k): heap = [] for i in arr...
e3ac99530b606e0675d1f5cef956d063808e26b7
alphapk/Python_learnings
/Add_two_nums.py
291
4.09375
4
__author__ = 'Praveen Kumar Anbalagan' #Program to add two numbers #get input from the user num1 = input('Enter the 1st number: ') num2 = input('Enter the 2nd number: ') #add two numbers sum = float(num1)+float(num2) #print the sum print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
e6779f734aa8b8ca02d9b43933825ca90f5c6bdb
ItamarMu/university-stuff
/Introduction to CS - Python/HW1/s1.py
247
3.78125
4
import time num = eval(input("Please enter a positive integer: ")) m = num cnt = 0 t0 = time.clock() while m>0: if m%10 == 0: cnt+=1 m = m//10 t1 = time.clock() print(num, "has", cnt, "zeros") print("Running time: ", t1-t0, "sec")
8058a5f3841dc1d7147b0cdfbd3b5f43cd95b1ac
ItamarMu/university-stuff
/Introduction to CS - Python/HW4/elp.py
318
3.828125
4
import time def elapsed(expression,number=1): ''' computes elapsed time for executing code number of times (default is 1 time). expression should be a string representing a Python expression. ''' t1=time.clock() for i in range(number): eval(expression) t2=time.clock() return t2-t1
87302ce1cb35e41aa75795d92b9568222deeb3bc
valeeero/Hillel_HW
/Home_work_7/Home_work_7.py
3,667
3.6875
4
# 1 from collections import OrderedDict user_info = OrderedDict({'Имя': 'Валерий', 'Фамилия': 'Лысенко', 'Рост': 184, 'Вес': 81, 'Пол': 'Мужской'}) print(user_info, id(user_info)) first_user_info = list(user_info.items())[0] last_user_info = list(user_info.items())[-1] user_info.move_to_end(key=first_user_info[0]) ...
908ca14a8df570182f00437af6406410e2340953
CrazyDi/Python2
/Week2/screensaver_my.py
10,990
3.875
4
import math import random import pygame class Vec2d: """ Класс вектора """ def __init__(self, x, y): self._vector = (x, y) def __get__(self, instance, owner): # получение значения вектора return self._vector def __getitem__(self, index): # получение координаты вектора по индексу ...
b98ec4d5a55d11ad62cbf8fc725774719669a7e7
junbaih/OthelloGame
/model.py
7,831
3.703125
4
## global constant , with value of 1 and -1 easy to switch around EMPTY = 0 BLACK = 1 WHITE = -1 ##exception class GameOverError(Exception): pass class InvalidMoveError(Exception): pass #### Class part with methods make a move if it is valid and flip accessble discs #### get the nu...
9174bbd6390284af1d29bca9e5b6d783367b5302
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__011.py
332
3.71875
4
# pintando parede larg = float(input('Qual é a largura da parede que você deseja pintar?')) alt = float(input('E qual é a altura desta mesma parede?')) area = float((larg*alt)) tinta = float((area/2)) print('Você precisará pintar {} m² de área de parede\nE para isso precisará usar {} L de tinta'.format(area, tinta...
c3912498bdd7197cd60c10943fefc448909f27f5
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__037.py
628
4.125
4
# conversor de bases numéricas n = int(input('Digite um número inteiro: ')) print('''Escolha umda das bases para a conversão:' [ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para BINÁRIO é igu...
b27eb11a268eb165af970993edad89d4f4c7694a
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__059.py
1,526
4.15625
4
# criando um menu de opções from time import sleep n1 = float(input('Digite um número qualquer: ')) n2 = float(input('Digite mais um número: ')) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção =...
4e42cfc44d1e1a84c11fb66682b1d7760e262b25
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__018.py
357
4.03125
4
# seno, cosseno e tangente import math a = float(input('Digite o ângulo que você deseja:')) print('O SENO do ângulo de {} vale {:.2f}'.format(a, math.sin(math.radians(a)))) print('O COSSENO do ângulo de {} vale {:.2f}'.format(a, math.cos(math.radians(a)))) print('A TANGENTE do ângulo de {} vale {:.2f}'.format(a, m...
044b28a4f77671479e15a7620c9b0b6feb37ece6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__085.py
487
3.671875
4
lista = list() pares = list() impares = list() for c in range(1, 8): n = int(input(f'Digite o {c}º valor: ')) lista.append(n) print('--' * 50) print(f'Você digitou os valores: {lista}') for v in range(0, len(lista)): if lista[v] % 2 == 0: pares.append(lista[v]) else: impares....
54d1c9b14fecd247df7d3230fa4a3125e40e3ab0
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__005.py
191
4.09375
4
# sucessor e antecessor num = int(input('Digite um número qualquer:')) n1 = num-1 n2 = num+1 print('Analisando seu número, o antecessor é {} e o sucessor é {}'.format(n1, n2))
6b2d874c613182e7e45222686b4824aa40e2521f
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__031.py
267
3.578125
4
# custo da viagem d = float(input('Qual é a distância da sua viagem em km? ')) p1 = d*0.5 p2 = d*0.45 if d<= 200: print('O preço da sua passagem será de R${:.2f}'. format(p1)) else: print('O preço da sua passagem será de R${:.2f}'.format(p2))
2cdc4ee9ce0f59cf33147284a9d7b165a599284d
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__Classes_4.py
1,093
4.0625
4
# atributos class Pessoa: num_de_pessoas = 0 @classmethod def num_de_pessoas_(cls): return cls.num_de_pessoas @classmethod def add_pessoa(cls): cls.num_de_pessoas += 1 def __init__(self, nome): self.nome = nome Pessoa.add_pessoa() p1 = Pe...
0eed0a6a10c8b1a522b927c0afd10d5dcf34a5b1
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__047.py
387
4.0625
4
# contando pares for contagem in range(2,52,2): print(contagem, end=' ') # outra forma de fazer for contagem in range(1,51): if (contagem%2) == 0: print(contagem, end=' ') # neste segundo método, a interação é feita de 1 em 1, mesmo que o resultado não seja mostrado. No primeiro método, só # f...
2517c1c7c6ada14bb1bdef025828624a676573cd
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__051.py
527
3.796875
4
# progressão artimética print('='*30) print(' 10 TERMOS DE UMA PA ') print('='*30) a1 = int(input('Digite o primeiro termo: ')) r = int(input('Razão: ')) for c in range(0, 10): c = a1 + c * r print(c, end=' ') print('->', end=' ') print('ACABOU') # refazendo # an = a1 + (n - 1) * r ...
5dd2a28ae62cf46d8a3d296ddbbc8df758527596
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__lista_5.py
801
3.875
4
'''pessoal = [['Joana', 33], ['Marcelo', 45], ['Otávio', 50], ['Jorge', 12], ['Bárbara', 14]] print(pessoal[1]) print(pessoal[1][1]) print(pessoal[1][0]) print() turma = list() turma.append(pessoal[:]) print(turma) print(turma[0]) print(turma[0][4]) print(turma[0][4][1])''''' galera = list() dado = li...
73a76de770942df37edb4958c3bb3267b4335dd6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__060.py
423
4.09375
4
# calculando um fatorial num = int(input('Digite um número para calcular seu fatorial: ')) c = num f = 1 # pra começar uma multiplicação limpa, assim como usamos 0 pra começar uma soma limpa print('Calculando {}! = '.format(num), end='') while c > 0: print('{}'.format(c), end='') print(' x ' if c > 1 els...
7473b81569f4aa4ff56d53372a670e3816876131
natrajitpoint/python
/classmethod.py
590
3.78125
4
class employee: def setdata(self,eno, ename, esal): self.eno = eno self.ename = ename self.esal = esal def getdata(self): print("\n*** Employee Info ***\nEmployee Id : {}\n\ Employee Name : {}\nEmployee Salary : {}"\ .format(self.eno,self.ename,self.esal)) #main e...
3cdb31a1ce22e86265fd5ad8e5e4b4c9fe08e6ea
natrajitpoint/python
/insertexecute.py
804
3.5
4
import pymysql # Open database connection conn = pymysql.connect(host="localhost", user="root", passwd="itpoint", db="DB5to6") # Create a Cursor object to execute queries. cur = conn.cursor() # Insert records into Books table insertquery = "Insert in...
b9908917407ec89e662b804ced360417491bcc98
mmalek06/amazon-interview
/AmazonInterviewPy/sum_of_two.py
275
4
4
find_sum_of_two([2, 1, 8, 4, 7, 3],3) def find_sum_of_two(A, val): pairs = dict() for cnt in range(0, len(A)): if (A[cnt] in pairs): return True the_other_number = val - A[cnt] pairs[the_other_number] = A[cnt] return False
e8d204ed131a1baa1f694ece35d9984700901ed2
averni/Simplify_with_Topology
/trianglecalculator.py
1,111
3.828125
4
#! /usr/bin/env python # encoding: utf-8 __author__ = 'asimmons' class TriangleCalculator(object): """ TriangleCalculator() - Calculates the area of a triangle using the cross-product. """ def __init__(self, point, index): # Save instance variables self.point = point self.ring...
790cdcb6e2eb5f734c6ccc27bc58596685a1a2a2
vijay092/Optimal-Control-RL
/minecraftControl/uquat.py
2,517
3.59375
4
""" A collection of operations on unit quaternions """ import numpy as np def normalize(q): norm = np.sqrt(np.dot(q,q)) return q/norm def vec_to_uquat(v): dt = np.array(v).dtype if dt == np.int or dt == np.float: dt = float else: dt = object input_array = np.zero...
5acdea7afe5a64f6aee54842b3800d8966f13686
gauravaror/programming
/reOrderList.py
1,274
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ fp = hea...
089443a83c95a5caf8f211a18559963edbef9b8b
gauravaror/programming
/linked_list_in_binary_tree.py
1,956
3.859375
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: de...
4268f60fc2cfdff90d1da67a16d88544fbe7693f
gauravaror/programming
/myCalender1.py
1,340
3.65625
4
class MyCalendar: def __init__(self): self.starts = [] self.ends = [] def bs(self, array, target): start = 0 end = len(array) while start < end: mid = start + (end-start)//2 if array[mid] > target: end = mid el...
1c741e95677effe1805363a8ac8a4b7ebce2c91b
gauravaror/programming
/binary-tree-level-order-traversal_2.py
882
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: answer = [] stack = [] current_level = 0 i...
916ca7c13f04b1d9f401941a6cdba3a21e20f500
gauravaror/programming
/lrucache_double_linked_list_solution.py
2,048
3.5625
4
class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.hh = {} self.head = Node(0,0) self.tail = Node(0,0) self.capacity = capacity...
15f3a8fbce221a05aff3f14531cb122b80f816cd
gauravaror/programming
/reconstructQueue_SORT_sol.py
287
3.53125
4
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda h: (-h[0],h[1])) print(people) queue = [] for p in people: #print(queue) queue.insert(p[1], p) return queue
9527fc836db1dfa78746035db321aa262d9d6da9
gauravaror/programming
/tweet_count_per_frequency.py
1,385
3.515625
4
from collections import Counter class TweetCounts: def __init__(self): self.hours = Counter() self.days = Counter() self.minutes = Counter() def recordTweet(self, tweetName: str, time: int) -> None: minute = time//60 hour = time//3600 self.hours[tweetNa...
ec08f2a7bd1c0a73cdd7a032d962b74b31e73549
gauravaror/programming
/avgwaittime.py
373
3.59375
4
class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: currtime = 1 wait = 0 for arrival, prep in customers: if currtime < arrival: currtime = arrival currtime += prep wait += (currtime-arrival) return wa...
66ba54e0e35f8db59e76f5df17dc5f4e392c47ba
gauravaror/programming
/reverseBits.py
317
3.578125
4
class Solution: def reverseBits(self, n: int) -> int: st = 1 num = 32 output = 0 while num >= 0: num -= 1 bit = n&st if bit: output += pow(2,num) st = st << 1 #print(st, num, output) return output
16ac1e3175ed3d36d0203505f5573c4223a7446e
gauravaror/programming
/maximum-product-of-splitted-binary-tree.py
1,416
3.5
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def dfs(self, node): left_tree = 0 right_tree = 0 if node.left: left_tree = self.dfs(...
2454e54711aa57ac5fd43599a85ab5ab1584f44b
gauravaror/programming
/streamChecker.py
1,042
3.609375
4
class Trie: def __init__(self): self.chars = {} self.finishing = False #self.wrd = word def add(self, word): if len(word) == 0: self.finishing = True return if word[0] not in self.chars: self.chars[word[0]] = Trie() self.ch...