blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
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...
b00639462737fce6440a481c232abbd3ce6abf91
ccirelli2/mutual_fund_analytics_lab_sentiment_analysis
/scripts/functions_decorators.py
1,413
3.65625
4
""" Decorator functions for this program """ ############################################################################### # Import Python Libraries ############################################################################### import logging; logging.basicConfig(level=logging.INFO) from functools import wraps from...
1a076304c384df34684971effecc69c702342683
jarroba/Curso-Python
/Casos Prácticos/6.2-math_stirling.py
565
3.6875
4
import math # 1 num = 100 primera_parte = math.sqrt(2 * math.pi * num) segunda_parte = math.pow(num/math.e, num) # == (num / math.e) ** num resultado = primera_parte * segunda_parte print("Por fórmula de Stirling: {numero}!= {resultado}".format(numero=num, ...
a4644a5aa54ed966e76a12b18651173ba15682f9
jarroba/Curso-Python
/Casos Prácticos/5.5-funcion_return_none_espacio.py
234
3.59375
4
# 1 def espacio(velocidad, tiempo): resultado = velocidad * tiempo # 2 if resultado < 0: return None else: return resultado # 3 tiempo_retornado = espacio(120, -10) print(tiempo_retornado)
34b47f5f402c625167dd07b74dde3a50af7abb3e
jarroba/Curso-Python
/Casos Prácticos/4.15-tuplas.py
497
3.875
4
# 1 tupla1 = ("manzana", "rojo", "dulce") tupla2 = ("melocotón", "naranja", "ácido") tupla3 = ("plátano", "amarillo", "amargo") print(tupla1) # 2 lista_de_tuplas = [] lista_de_tuplas.append(tupla1) lista_de_tuplas.append(tupla2) lista_de_tuplas.append(tupla3) # 3 for fruta, color, sabor in lista_de_tuplas: print...
042b6738c14747adbe173d1b09239927f92d2aa9
binit-singh/python-datastructures
/3_fibonacci_number/fibonacci_last_digit.py
581
4.0625
4
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_fibonacci_last_digit_fast(n): if n < 1: return 1 previous_last = ...
688f45329b2e7371b61189f3cd3b2d5a77d3a0f5
codacy-acme/pythest
/main.py
1,029
3.640625
4
import httpoxy def square(a): """item_exporters.py contains Scrapy item exporters. Once you have scraped your items, you often want to persist or export those items, to use the data in some other application. That is, after all, the whole purpose of the scraping process. For this purpose Scrapy provides a collec...
843061e943b25fa172636d9f77017ea2294aa96d
ramza007/Password-Locker
/credentials-test.py
2,276
3.765625
4
import unittest from credentials import Credentials class TestCredentials(unittest.TestCase): ''' test class that defines test cases for the credentials class ''' def setUp(self): ''' set up method that runs before each test case ''' self.new_credentials = Credenti...
4885fd3b53635d85138d7987793f5159eab172bd
charboltron/artificial_intelligence
/genetic_8_queens/genetic_alg_8_queens.py
8,873
3.546875
4
#%% import sys import random import math import numpy as np import matplotlib.pyplot as plt test_boards = [[2,4,7,4,8,5,5,2],[3,2,7,5,2,4,1,1],[2,4,4,1,5,1,2,4],[3,2,5,4,3,2,1,3]] #constants/twiddle factors num_iterations = 10000 def print_board(board): for i in range(8, 0, -1): print('\n') for ...
470d83e0c57151a4ac54e15c22a5a36befc592c5
JansherKhantajik/Python
/first program.py
613
4.03125
4
#print a program which input number from user and you will give 5 guess to equvalate with your answer print("Word of Guess Number, Input Your Guess that You have five chance") guess = int(input()) i=0 while (True): if (guess <15): print("Please Enter more then",guess) break elif guess <20 and gu...
409ef68a67f735a647f22040ad7c1086cd991de2
sleevewind/practice
/0217/列表的复制.py
133
3.71875
4
# 可变类型和不可变类型 a = 12 b = a print('a={},b={}'.format(hex(id(a)), hex(id(b)))) # a=0x7ff95c6a2880,b=0x7ff95c6a2880
0b8fd9d19b5e21325b8499480ed594c2a33a9740
sleevewind/practice
/0217/列表的排序和反转.py
396
4.0625
4
# sort()直接对列表排序 nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.sort() print(nums) # [1, 2, 3, 4, 5, 6, 7, 8] nums.sort(reverse=True) print(nums) # [8, 7, 6, 5, 4, 3, 2, 1] # sorted()内置函数, 返回新的列表, 不改变原来的列表 print(sorted(nums)) # [1, 2, 3, 4, 5, 6, 7, 8] # reverse() nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.reverse() print(nums) #...
f889d7e66bf7bd2b2dd2647cf64cdfe91189052e
sleevewind/practice
/0217/列表的增删改查.py
1,466
3.5625
4
# 操作列表, 一般包括 增删改查 heroes = ['镜', '嬴政', '露娜', '娜可露露'] # 添加元素的方法 # append heroes.append('黄忠') print(heroes) # 在列表最后面追加 # insert(index, object) 在指定位置插入 heroes.insert(1, '小乔') print(heroes) newHeroes = ['狄仁杰', '王昭君'] # extend(iterable) 添加可迭代对象 heroes.extend(newHeroes) print(heroes) # 删除元素 pop print(heroes) # ['镜', '...
bb22aef9984883cee87a02c39b509e7d496a4107
innovatorved/python-recall
/py51-python-cahching-by-funtools.py
386
3.578125
4
# python3 py51-python-cahching-by-funtools.py import time from functools import lru_cache @lru_cache(maxsize = 3) # save last 3 value def sleep_n_time(n): time.sleep(n) return n if __name__ == "__main__": print(sleep_n_time(3)) # it create an cahe for this same def for for reducing time and sp...
2c55330c7204f8bceaa6eed1e9533f05a6e18b1e
innovatorved/python-recall
/py40-access-specifier-public-private.py
918
3.796875
4
# Access Specifier # public # protected # private class Student: public_var = "this variable is public" _protected_var = "this is private var" __private_var = "this is private var" def __init__(self ,public , protected , private): self.public = public self._protected = prot...
a32d740aaec9947b0f5b7d64a72a47f10a28718a
innovatorved/python-recall
/py49-genrators-ex1.py
288
3.609375
4
# python3 py49-genrators-ex1.py n = 10 def fib(a=0 , b = 1): for x in range(n): yield (a+b) a , b = b , b+a a = fib(0,1) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__())
8207d31429cc76165b8136f1c186f7d0f39bd62b
innovatorved/python-recall
/py20 - enumeratefin.py
522
3.90625
4
#enumerate function a = ["ved" , "Prakash" , "Gupta" , "hello"] i = 1 for item in a: #print(item) if i%2 != 0: print(f"item {item}") i+= 1 #with enumerate function print(enumerate(a)) # Output : <enumerate object at 0x000002452601E700> print(list(enumerate(a))) # Output : [(0, '...
7d828ae6dabb5d3283927d7ec88800acd45164d2
innovatorved/python-recall
/py6 - list.py
643
3.671875
4
# List Name = [ "Ved Gupta" ," Ramesh Prasad" , "Anand Kumar" "Shrish Guptas" , "Rishi sharma" ] Age = [20,56,89,12,45] print(type(Name),type(Age)) # Age.sort() print(Age) print(sum(Age)) print(min(Age)) print(max(Age)) print(len(Age)) Age.reverse() print(Age) Age.sort() print(Age) new = sorte...
7f71835bcdea55a10aef9e2602161ea23d979484
innovatorved/python-recall
/start-dynamic/fibonachi-sequence.py
138
3.65625
4
# python3 fibonachi-sequence.py def fib_seq(n ,a=0,b=1): if n != 0: print(a+b) fib_seq(n-1 ,b,a+b) fib_seq(5)
382a67dd059c8a7b93b9e01bfeacc25424f32307
innovatorved/python-recall
/py17 - Fabonachi Sequence.py
306
3.71875
4
# Fabonachi Sequence # find fabonachi sequene def fab(n,a = 0 , b = 1): if n > 0: c = a+b print(c) fab(n-1,b,c) a = int(input("How much No . of sequence you want to find :")) fab(a) """ How much No . of sequence you want to find :10 1 2 3 5 8 13 21 34 55 89 """
d393755ca2b2661c053f02573f582213d0bd1f32
innovatorved/python-recall
/py48-genrators-yield.py
574
4.0625
4
# python3 py48-genrators-yield.py """ Iterable : __iter__() or __getitem__() Iterator : __next__() Iteration : """ # genrators are iteraators but you can only iterate ones def range_1_to_n(n) : for x in range(1 , n): yield x print(range_1_to_n(10)) num = range_1_to_n(10) print(num.__n...