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 |
|---|---|---|---|---|---|---|
5e67810ff3209d7b311791b1f4c2d145dc4dc3e5 | vishal-B-52/Documentation_of_Python | /F-StringTEST.py | 604 | 4 | 4 | print("Price of 1kg Rice is 16.75.")
print("Price of 1kg Sugar is 15.\n")
Rice_Quantity = float(input("Enter quantity of rice: "))
Sugar_Quantity = float(input("Enter quantity of Sugar: "))
Price_of_Rice = Rice_Quantity * 16.75
Price_of_Sugar = Sugar_Quantity * 15
Total_Bill = Price_of_Rice + Price_of_Sugar
... |
4b3fd151726e2692179e72be9fb71e4b3fb632a3 | vishal-B-52/Documentation_of_Python | /GuessTheNumberModified.py | 1,693 | 4.25 | 4 | # Guess the number :-
print("This is a 'Guess the Number Game'. You have 10 Life(s) to guess the hidden number. You have to win in 10 Life(s) "
"else You lose!!! ")
Life = 10
while True:
N = int(input("Enter the number:- "))
Life -= 1
if 0 <= N < 18:
if Life == 0:
pr... |
b8593645446a616db6f48d2617bc72933ee104d1 | vishal-B-52/Documentation_of_Python | /operators&funct.py | 4,638 | 4.09375 | 4 | # Different Operators and examples.
# A. Arithmatic Operators - Used for mathematical purpose.
"""
'+'= Addition purpose.
'-' = Subtraction Purpose.
'*' = Multiplication purpose.
'/' = Division purpose.
'//' = Divides and displays round figured value. For.ex;- Result= 2.3 then it will show 2 as answer.
'**'... |
1aa50ee627ccd3ecdf4b0ca8469c8ffab360a0d2 | vishal-B-52/Documentation_of_Python | /OOPExercise9.py | 7,059 | 4.25 | 4 | # Multiple Inheritance -
"""
Multiple Inheritance means inheriting a class from two classes . The inherited class contains an ability which allows it
to gain a direct access to the attributes of it's parent classes.
For Ex:- I have inherited 'Expert' class from 'Seniors' and 'Juniors'.
"""
class Seniors:
P... |
b75bf4d0adc74dba4e95f9cdb8031d90b1507587 | davibelini/pickle | /nodes.py | 1,325 | 3.8125 | 4 | class NumberNode:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"({self.value})"
class PlusNode:
def __init__(self, node):
self.node = node
def __repr__(self):
return f"(+{self.node})"
class MinusNode:
def __init__(self, node):
self.node = node
def __repr... |
fa3ca900af1dd757f89447460e40c487cb4bc65a | yiidiplom/cs50 | /py/hello.py | 350 | 4 | 4 | #print ("hello")
#name = input("Name: ")
#print("Hello, "+ name+"!")
#print(f"Hello {name}!")
# n = int(input("Number: "))
# if n>0:
# print (f"{n} - is positive")
# elif n<0:
# print ("n - is negative")
# else:
# print ("n - is zero")
class Point():
def __init__(self,x1,y1):
self.x = x1
self.y = y1
p=Point(5... |
2a20b1ed0b1948b5b396e818f3e65240cd4a843d | saijannali/PracticeProblems | /129. Sum Root to Leaf Numbers.py | 686 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
return self.helper(root, 0)
def help... |
ba24d0b5a6d5adc538acdf9a01d5a0ac57dbe30a | MuhammadZainAmmad/OOP-Assignment1 | /Assignment1.py | 11,054 | 3.90625 | 4 | #Employee
def getBasicSalary(name):
name=name.title()
print(basicSalary[name])
def getNetSalary(hours,basicSalary):
'''This function takes overtime hours
and basic salary of employee and return
total salary'''
print(hours*overTimeRate +basicSalary)
def getOverTimeRate():
'''This function ... |
1dcb950b1214d841282613bee89c10af225e8233 | laurenmallay/projectEuler | /problem3.py | 553 | 3.859375 | 4 | """
Project Euler Problem 3
Largest prime factor up to some number mx
"""
def isPrime(n):
for i in range(2, int(n**(0.5)) + 1):
if n%i == 0:
return False
return True
def largest_prime_factor(mx):
if int(mx**(0.5)) % 2 == 0:
rng = int(mx**(0.5)) - 1
else:
rng = int(mx**(0.5))
for i in range(rng,1,-2):
i... |
49c4616936d232e68349f3deb6a73fd263b4c7fa | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio9.py | 502 | 3.796875 | 4 | """
9. Leia o salário de um trabalhador e o valor da prestação de um empréstimo. Se a prestação
for maior que 20% do salário imprima:Emprestimo não concedido, Caso contrário imprima:
Empréstimo concedido
"""
salario = float(input('Insira o salário do trabalhador:'))
prestacao = float(input('Insira o valor da pres... |
b15d153e861eeed43c8b9c77c6a4f00198580892 | Kaiquenakao/Python | /Coleções Python/Exercicio58.py | 1,433 | 4.125 | 4 | """
58. Faça um programa que leia uma matriz de 4 linhas e 4 colunas contendo as seguintes informações
sobre alunos de uma disciplina, sendo todas as informações do tipo inteiro:
º Primeira coluna: Número de matrícula (use um inteiro)
º Segunda coluna: Média das prova
º Terceira coluna: Média dos trabalhos
º Qu... |
d739400bb42505ad92ad5b7dda4bd27fac667fdd | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio7.py | 387 | 4 | 4 | """
7 - Leia uma temperatura em graus Fahrenheit e apresente-se a convertida em graus Celsius.
a fórmula é: C = 5.0 * (F - 32.0) / 9.0, sendo C a temperatura em Celsius e F a temperatura
Fahrenheit
"""
F = float(input("Insira o seu valor em Graus Fahrenheit para converter para Graus Celsius:"))
C = 5.0 * (F - 32.... |
664299169891c1447c0bd8180191fcf97f57e8b0 | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio11.py | 652 | 4.09375 | 4 | """"
11. Escreva um programa que leia um número inteiro maior do que zero e devolva, na tela, a
soma de todos os seus algarimos. Por exemplo, ao numero 251 corresponderá o valor 8
( 2 + 5 + 1). Se o número lido não for maior do que zero, o programa terminará com a mensagem
"número invalido".
"""
try:
numero ... |
f93fabfa855116141634a5d022eaf3d4edad5349 | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio25.py | 363 | 3.78125 | 4 | """
25. Leia um valor de área em acres e apresente-o convertido em metros quadrados m², A fórmula
de conversão é: M = A * 4048.58, sendo M a área em metros quadrados e A a área em acres.
"""
A = float(input('Insira o seu valor em acres para converter em metros quadrados: '))
M = A * 4048.58
print(f'O seu valor c... |
ac95c2666c923119653f31376e715f7d2b233d59 | Kaiquenakao/Python | /Coleções Python/Exercicio57.py | 762 | 4.375 | 4 | """
57. Faça um programa que permita ao usuário entrar com uma matriz de 3 x 3 números inteiros. Em seguida,
gere um array unidimensional pela soma dos números de cada coluna da matriz e mostrar na tela esse
array. Por exemplo, a matriz:
[5 -8 10]
[1 2 15]
[25 10 7]
[31 4 3]
"""
matriz = [[0, 0, 0], [0, 0... |
e1d620c79a180d61918ce3ff6cf64a0a72b260af | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio48.py | 288 | 3.921875 | 4 | """"
48. Leia um valor inteiro em segundos, e imprima-o em hora.
"""
try:
inteiro = int(input('Insira um valor em segundos: '))
print(f'O seu valor convertido em horas: {inteiro // 60 // 60}')
except ValueError:
print('ERRO!!! O valor tem que ser números inteiros')
|
b907811cd06f03f55b3df9afc7fbc9309cb1f96e | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio2.py | 358 | 4.21875 | 4 | """
2. Leia um número fornecido pelo usuário. Se esse número for positivo, calcule a raiz quadrada do número
Se o número for negativo, mostre uma mensagem dizendo que o número é inválido.
"""
import math
num = int(input('Insira um número:'))
if num >= 0:
print(f'A raiz do número:{math.sqrt(num)}')
else:
... |
4a72a5656a63fbd3a14ec2bfe8b7656dbd69a76d | Kaiquenakao/Python | /Coleções Python/Exercicio30.py | 594 | 4.125 | 4 | """
30. Faça um programa que leia dois vetores de 10 elementos. Crie um vetor que seja a intersecção
entre 2 vetores anteriores, ou seja, que contém apenas os números que estão em ambos vetores.
"""
conjuntoA = []
conjuntoB = []
print('Conjunto A')
for i in range(0, 9+1):
n = float(input(f'Conjunto : {i... |
089e6bb7c56e4a5847f62da36d54f598bc6ed974 | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio12.py | 342 | 3.75 | 4 | """
12. Leia uma distância em milhas e apresente-a convertida em quilômetros. A fórmula de
conversão é: K = 1.61 * M, sendo K a distancia em quilômetros e M em milhas.
"""
M = float(input('Insira o valor da distância em milhas para converter para quilômetros:'))
K = 1.61 * M
print(f'O seu valor convertido em quil... |
7dbbdacbfd8ce304a0de43a175ec23f5088e7470 | Kaiquenakao/Python | /Coleções Python/Exercicio51.py | 719 | 4.21875 | 4 | """
51. Leia uma matriz de 3 x 3 elementos. Calcule e imprima a sua transporta
"""
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrizt = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range(0, 3):
matriz[i][j] = float(input(f'[[{i}] [{j}]] digite um valor: '))
print('----------... |
8500ebcac29603d9dab11cb4a4df9be5d4d6b64c | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio27.py | 361 | 3.734375 | 4 | """
27. Leia um valor em hectares e apresente-o convertido em metros quadrados m², A fórmula
para conversão é: M = H * 10000, sendo M a área em metros quadrados e H a área em
hectares
"""
H = float(input('Insira o seu valor em hectares para converter em metros quadrados: '))
M = H * 10000
print(f'O seu valor co... |
d9201fc8083a5422572465a51c9579f70828d75f | Kaiquenakao/Python | /Coleções Python/Exercicio13.py | 601 | 4 | 4 | """
13. Fazer um programa para ler 5 valores e, em seguida, mostrar a posição onde se encontram o maior
e o menor valor.
"""
maior = 0
menor = 0
posicaomaior = 0
posicaomenor = 0
for i in range(1, 5 + 1):
n = float(input(f'{i} - Insira um número: '))
if i == 1:
maior = n
menor =... |
187cbf102755a732eb301e86f46208907572a272 | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio3.py | 302 | 4.03125 | 4 | """
3. Leia um número real. Se o número for positivo imprima a raiz quadrada. Do contrário, imprima
o número ao quadrado
"""
import math
num = float(input('Insira o seu valor:'))
if num >= 0:
print(f'A raiz quadrada:{math.sqrt(num)}')
else:
print(f'Número ao quadrado:{num ** 2}') |
56fd4034c918e42ff0e6dc6eeeb0958cb67b8eac | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio29.py | 436 | 3.5 | 4 | """
29. Leia quatro notas, calcule a média aritmética e imprima o resultado.
"""
soma = 0
for n in range(1, 4+1):
notas = float(input(f'Prova {n} - insira a sua nota de 0-10: '))
if notas < 0 or notas > 10:
del notas
break
else:
soma = soma + notas
try:
print(f'A méd... |
5d1bdfe08339cfa4b84a9d57e439aa0763ae282f | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio26.py | 838 | 4.0625 | 4 | """
26. Leia a distância em Km e a quantidade de litros de gasolina consuminados por um carro
em um percurso, calcule o consumo em Km/L e escreva uma mensagem de acordo com a tabela
abaixo:
----------------------------------------------
| CONSUMO | (Km/l) | MENSAGEM |
| Menor que | 8 | Ven... |
f3bc9942cf77b94e4e8c4f9136f1189699fc39bc | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio4.py | 371 | 4.34375 | 4 | """
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.
"""
import math
num = float(input('Insira o seu valor:'))
if num > 0:
print(f'O número digitado ao quadrado:{num ** 2}')
print(f'A raiz q... |
6c4898d4ce815e43431af015f327686d428c3233 | Kaiquenakao/Python | /Coleções Python/Exercicio45.py | 1,383 | 4.0625 | 4 | """
45. Leia duas matrizes 4 x 4 e escreva uma terceira com os maiores valores de cada posição das
matrizes lida.
"""
matriz1 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
matriz2 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
contador = 0
matriz3 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0,... |
23d3421eeb7a67da939dceb1b2de5293a53fb83f | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio47.py | 424 | 3.65625 | 4 | """"
47. Leia um número inteiro de 4 dígito (de 1000 a 9999) e imprima 1 digíto por linha.
"""
try:
num = int(input('Insira 4 dígito de 1000 a 9999: '))
x = str(num)
if (num >= 1000) and (num <= 9999):
for i in x:
print(int(i))
else:
print('ERRRO!! O valor tem que ... |
9633c0c62a8cd7310135b6dcb7a2ee5d626785e0 | Kaiquenakao/Python | /Coleções Python/Exercicio7.py | 563 | 3.859375 | 4 | """
7. Escreva um programa que leia 10 números inteiros e os armazene em um vetor. imprima
o vetor, o maior elemento e a posição que ele se encontra.
"""
global contador
contador = 1
vetor = []
for i in range(1,10+1):
numeros = int(input(f'Posição{i}:Insira o seu valor:'))
vetor.append(numeros)
print(... |
414a16158fee0e9ec4c110b0ac7bd75bcbb3e021 | Kaiquenakao/Python | /Coleções Python/Exercicio32.py | 2,009 | 4.03125 | 4 | """
32. Leia dois vetores de inteiros x e y, cada um com 5 elementos (assuma que o usuário não informa
elementos repetidos). Calcule e mostre os vetores resultantes em cada caso abaixo:
• Soma entre x e y: soma de cada elemento de x com o elemento da mesma posição y
• Produto entre x e y: multiplicação de c... |
c740260a42fd2ecda2ccf6fc33e4c709160d8957 | Kaiquenakao/Python | /Coleções Python/Exercicio1.py | 1,023 | 4.3125 | 4 | """
1. Faça um programa que possua um vetor denominado A que armazene 6 números inteiros. O
Programa deve executar os seguintes passos
(a) Atribua os seguintes valores a esses vetor:1,0,5,-2 ,-5,7;
(b) Armazene em uma variável inteira(simples) a soma entre os valores da posições A[0], A[1]
e A[5] do vetor e mostre... |
4a071cbae917e42234d4afdfd18bd9b8fa36d402 | Kaiquenakao/Python | /Estruturas Logicas e Condicionais/Exercicio14.py | 1,318 | 4.0625 | 4 | """
14. A nota final de um estudante é calculada a partir de três notas atribuídas entre o intervalo
de 0 até 10. respectivamente, a um trabalho de laboratório, a uma avaliação semestral e a um
exame final. A média das três notas mencionadas anteriormente obedece aos pesos: Trabalho
de Laboratório: 2; Avaliação sem... |
bbaa640f05c59ee9347ae2e708de6171d8c16c95 | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio35.py | 543 | 4.125 | 4 | """
35. Sejam a e b os catetos de um triangulo, onde a hipotenusa é obtida pela equação
hip = √a² + b². Faça um programa que receba os valores de a e b e calcule o valor da
hipotenusa através da equação. Imprima o resultado dessa operação.
"""
import math
try:
a = float(input('Insira o valor de a: '))
... |
be3ac6805fc4f046f54e54c0488ff5c7621c80ed | Sukhkaur15/movie-project | /kk.py | 153 | 3.765625 | 4 | def add(n1,n2):
print(n1+n2)
add(2,3)
def sub(n1,n2):
print(n1-n2)
sub(2,3)
def multiply(n1,n2):
print(n1*n2)
multiply(2,3)
|
24024282fc63a08acbe45bab52ea3f11c2e4a48b | Conqu3red/PolyEditor | /math_objects.py | 6,946 | 3.5625 | 4 | import math
from typing import *
from itertools import zip_longest
Number = Union[int, float]
def is_iterable(value):
return hasattr(value, "__iter__")
def is_dict(value):
return hasattr(value, "items")
class Vector(Tuple[Number, ...]):
"""A tuple with useful element-wise operations as well as point operation... |
3cd7433ce4165c9c19c70e1adcd74f271cc14860 | JIVESH2212/ARTIFICIAL-INTELLIGENCE- | /DFS_&_BFS.py | 999 | 3.796875 | 4 | def dfs(graph,start,goal,path=[]):
q=[start]
while(q):
v = q.pop(0)
if v not in path:
path = path+[v]
if v==goal:
return path
q=q+graph[v]
return path
def bfs(graph, start, goal,path=[]):
'''iterative breadth first search from start'... |
bb214981effb5233620c5b4c8cf597225cc971a6 | sylrie/P3_MacGyver | /backend/player.py | 2,755 | 3.71875 | 4 | """ player
manage player
"""
#!/usr/bin/python3
# -*- coding: Utf-8 -*
# programs import
from backend.game_events import GameEvents
class Player():
""" Create a player and manage palyer attribut
"""
def __init__(self, maze):
self.maze = maze
self.line_pos = None
self.column... |
ea1afad3a3f1bcc383015fae2811ac8b52213d32 | aurelm95/NEAT | /neat6.py | 60,511 | 3.734375 | 4 | # https://github.com/Luecx/NEAT/tree/master/vid%209/src
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.28.5457&rep=rep1&type=pdf
# https://neat-python.readthedocs.io/en/latest/neat_overview.html
# http://nn.cs.utexas.edu/downloads/papers/stanley.cec02.pdf
# https://stackoverflow.com/questions/53798089/how-d... |
38a64b7616a34b4da1dc18d6a4e93c27ca57d91e | LienNguyen79/nguyenthilien-labs-c4e19 | /lab02/homework/ex01.py | 1,138 | 3.515625 | 4 | # 1dowload webpage
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.apple.com/itunes/charts/songs"
html = urlopen(url).read()
# 2.extact ROI
soup = BeautifulSoup(html,"html.parser")
section = soup.find("section","section chart-grid")
div = section.find("div","section-content")
li_li... |
7e8c6a4aa6aa2af7f53b572ba9ec4b1557cd72fa | LienNguyen79/nguyenthilien-labs-c4e19 | /lab03/freaking_math_trên_lớp.py | 790 | 3.8125 | 4 | from random import *
# from eval import calc
import eval
x = randint(1,10)
y = randint(1,10)
ops = ["+","-","*","/"]
op = choice(ops)
errors = [-1,0,0,0,0,0,0,0,1]
error = choice(errors)
# res = 0
# if op == "+" :
# res = x + y
# elif op == "-" :
# res = x - y
# elif op == "*" :
# res = x*y
# else:
# r... |
e135b876abb7f44d8522b5246e61e7643bd40ca6 | browniebroke/dailycodingproblem | /1095_overlapping_rect/exercise.py | 880 | 3.75 | 4 | TEST_DATA = [
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
},
{
"top_left": (-1, 3),
"dimensions": (2, 1)
},
{
"top_left": (0, 5),
"dimensions": (4, 3)
}
]
def are_overlapping():
area_covered = set()
for rect in TEST_DATA:
... |
b3158fa29043a03d886c37e9d330d97f19b1b404 | ShahradX/Term2 | /example_clock.py | 281 | 3.84375 | 4 | second = 0
minute = 0
hour = 0
from time import sleep
for i in range(1000):
sleep(0.001)
print(hour,":" ,minute,":" , second)
second += 1
if second == 59:
minute += 1
second = 0
if minute == 59:
hour += 1
minute = 0
|
94114e47b45cf8723c4dc67a559924590fc51696 | ShahradX/Term2 | /somthing.py | 141 | 3.84375 | 4 | list = []
while True:
code = int(input("please enter the number : "))
list.append(code)
if code == 0 :
break
print(list) |
daf2e7d0813c78dab6d8377376a1890c972400dc | ShahradX/Term2 | /example_if01.py | 531 | 4.09375 | 4 | number01 = int(input("please enter a number: "))
number02 = int(input("please enter another number: "))
vari01 = number01 + number02
vari02 = number01 - number02
vari03 = number01 / number02
vari04 = number01 % number02
vari05 = number01 * number02
vari06 = number01 ** number02
print("vari01 is : " + str(vari01) + "\... |
b6986bc73aad49c8513bcad19bf52eba55655a6e | JaydipMagan/codingpractice | /leetcode/September-30-day/week3/max_xor_of_two_numbers_in_array.py | 684 | 3.578125 | 4 | """
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: The maximum result is 5 ^ 25 = 28.
"""
class Solution:
def findMaximumXOR(... |
e87b08e40690796d31ae16fdddd7ba6623811943 | JaydipMagan/codingpractice | /leetcode/minimum_time_visiting_points.py | 1,230 | 3.734375 | 4 | """
On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.
You can move according to the next rules:
In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit ve... |
396fa782d9eba23c96c6d4c7be1ee77824761e6c | JaydipMagan/codingpractice | /leetcode/April-30-day/week5/bin_max_path_sum.py | 1,269 | 4 | 4 | """
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
... |
a025ecdc5d702971bf4d2e09d822c97e213dcf20 | JaydipMagan/codingpractice | /leetcode/May-31-day/week4/contiguous_array.py | 1,021 | 4 | 4 | """
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous ... |
bbea891103c1c7f05817e83ebb8d8a5c35342007 | JaydipMagan/codingpractice | /leetcode/May-31-day/week2/valid_perfect_square.py | 511 | 3.890625 | 4 | """
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
"""
class Solution:
def isPerfectSquare(self, num: int) -> bool:
... |
2bec715e7c70e441600902d451876e361320fd21 | JaydipMagan/codingpractice | /leetcode/September-30-day/week1/image-overlap.py | 1,196 | 3.796875 | 4 | """
Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation... |
9124799ce0d881842d24dfb8f0c4465d33dfba33 | JaydipMagan/codingpractice | /leetcode/April-30-day/week4/jump_game.py | 1,140 | 4.09375 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step fr... |
052a886d1c11996c7020c0957953ec55c5e577d9 | JaydipMagan/codingpractice | /leetcode/September-30-day/week1/largest_time_given_digits.py | 942 | 3.84375 | 4 | """
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time can be made, return an empty stri... |
4d94c3e8be8ae842abf6789d62f6d265a508ad1a | JaydipMagan/codingpractice | /leetcode/valid_number.py | 994 | 3.765625 | 4 | import re
class Solution:
# try:
# x = float(s)
# return True
# except:
# return False
without_space = s.strip(" ")
if without_space=="":
return False
pattern = re.compile(r"^([\s]*[+-]?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)|([0-9]+))[\s]... |
e35602a4b6a5547c8593701d91b06fabbdfe3b24 | JaydipMagan/codingpractice | /leetcode/September-30-day/week2/maximum_product_subarray.py | 850 | 4.03125 | 4 | """
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1... |
94deee61e9db32507ddd6dcada051a0714b6e432 | innovatorved/BasicPython | /Python Programs/21. dictionaries 1.py | 186 | 4.125 | 4 | # dictionaries :
d={'name':'abhishek','age':'23 years'}
#1. add any key-value pair :
d['hieght']='182 cm'
print(d)
#2. to remove any key-value pair from dict.
del d['hieght']
print(d)
|
13b9e2a2c47dbae90056f95d0b0a89ad9864eece | innovatorved/BasicPython | /list/x29-use of in.py | 85 | 3.71875 | 4 | l=['banana','apple','ved']
if "banana" in l:
print('yes')
else:
print('NO')
|
131ab2d255278ca65b04ce264e8644b62e886137 | innovatorved/BasicPython | /Python Programs/2. requesting input function.py | 170 | 4.125 | 4 | #requesting input
print ('Hello')
name=input('what is your name : ')
print('nice to meet you dear '+name)
#len function : to find the string length
a=len(name)
print(a)
|
b315ae5c794db79b52f574da561a4a7445991700 | innovatorved/BasicPython | /x52-GUI.py | 655 | 3.5625 | 4 | from tkinter import *
from tkinter.ttk import *
window= Tk()
window.title('Welcome Chore')
def click():
tech_2.configure(text="Button was clicked!")
def claw():
box = Combobox(window)
box['values'] =(1,2,3,4,5,'Other')
box.current(5)
box.grid(column=4,row=4)
tech_1 = Label(window, text='Hi',font... |
7ddd6b454fd261b25a5fd3cf433b44a7e51d4e2b | innovatorved/BasicPython | /Python Programs/15.print table.py | 113 | 3.59375 | 4 | #prime no
while(1):
a=int(input('Enter a no : '))
i=1
while(i<=10):
print(a*i)
i+=1
|
1f89f87bfc97d135b2bfac102d4a4c3936c0a940 | innovatorved/BasicPython | /RegX/regX - operation - 1.py | 267 | 4.03125 | 4 | import re
sentence = "we need to inform(related to tech) him about a new elex. technology(matlab)"
#search operation is use to check the one value from a long string
#--------------search in sentence
if re.search("tech" , sentence):
print("Word is find!")
|
d18376aed663185d68c2267177b76f68c655afef | innovatorved/BasicPython | /Python Programs/19. even no printing.py | 109 | 3.53125 | 4 | a=int(input('Enter a no : '))
b=list(range(a))
for i in b:
c=i%2
if(c==1):
print(i)
|
177dcdb5a4c892407095ce1b94ec2ae76aed141c | innovatorved/BasicPython | /pi2.py | 366 | 3.953125 | 4 | from RPi import GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(3,OUT)
print('\nEnter ON for led on-')
print('Enter OFF for led off-')
a=input('Enter ur choice:')
if a=='ON' or 'on':
GPIO.output(3,1)
print('LED on')
elif a=='OFF' or 'off':
GPIO.output(3,0)
prin... |
634680d0706b1e0463f801422c5373084089d8c0 | innovatorved/BasicPython | /x63- matplotlib bar graph.py | 286 | 3.609375 | 4 | from matplotlib import pyplot as plt
x=[1,3,5,7,9,11]
y=[55,33,56,60,85,99]
x2=[2,4,6,8,10,12]
y2=[54,60,85,33,56,77]
plt.bar(x,y,label='fri',color='k')
plt.bar(x2,y2,label='Abhi',color='r')
plt.title("Information Data")
plt.xlabel("num")
plt.ylabel("Per")
plt.legend()
plt.show()
|
9790f37381a1455af2fbb10777525caa9b8d0ab0 | innovatorved/BasicPython | /x80 - Tuples.py | 541 | 4.3125 | 4 | #turple
#turple is immutable
#once u defined turple u cannot change its elements
bmi_cat = ('Underweight' , 'Normal', 'Overweight' ,'very Overweight')
#type
print('Type: ',type(bmi_cat))
#access element of turple
print(bmi_cat[1]) #we use positive value
print(bmi_cat[-2]) #and we also use negative value
print(b... |
e1a5d436b1f84b610497ecd003bd9e10625c54b1 | innovatorved/BasicPython | /RegX/regx op - 3 compile , sub.py | 348 | 3.78125 | 4 | import re
str_2 = "today is sunny day we can except a match between india and aus"
#re.compile --------(used for what you change in string)
regX = re.compile(" ")
#sub() ----------------(used for saying what is new world)
#-------- str = re.compile("what your change")sub("what new come" , str_name)
str_3 = regX.sub... |
148217c908310e10d032b8b6b789c6321f281b28 | innovatorved/BasicPython | /RegX/regX op - 2 findall, finditer.py | 785 | 3.890625 | 4 | import re
sentence = "we need to inform(related to tech) him about a new elex. technology(matlab)"
#---------------findall (return a list of all find value)
store_value = re.findall("tech" , sentence)
print(store_value)
#---------------finditer (use to find the location of the word)
it = re.finditer("tech" , sent... |
aea710e29bcb686e445ba69a2106438174297296 | innovatorved/BasicPython | /x17- factorial of a number.py | 147 | 4.34375 | 4 | #program for find factorial of a number
a=int(input("Enter a number to find its factorial: "))
b=1
for a in range(a,0,-1):
b=b*a
print(b)
|
5420bc925afcf34c1f40ffe0ad9ed93f05afcba7 | innovatorved/BasicPython | /GUI/g2.py | 2,164 | 3.875 | 4 | import tkinter as tk
from tkinter import messagebox
from tkinter.ttk import*
window = tk.Tk()
#User define function
def clicked():
label.configure(text = 'Button was Clicked!')
butt.configure(text = 'Clicked')
def clicked2():
text = str.get()
label.configure(text = text)
butt2.configure(text = 'cl... |
de14985879dbe59075b1bc0fd357609ce9e13d71 | innovatorved/BasicPython | /Python Programs/19.AP using for loop.py | 232 | 3.796875 | 4 | #for loop : start stop step argument
def ap(a,l,d):
s=0
for s in range(a,l+1,d):
print(s)
while(1):
a=int(input('Enter a no : '))
l=int(input('Enter a no : '))
d=int(input('Enter a no : '))
ap(a,l,d)
|
2271577d49f2ee99fc6e78b9b4c4aac5a0280574 | innovatorved/BasicPython | /x9.py | 58 | 3.78125 | 4 | a=input("enter a word to find its type: ")
print(type(a))
|
7f820523fbade86b6b869d4d610ba5cbd88c2b26 | innovatorved/BasicPython | /Matplotlib/x62- matplotlib style.py | 388 | 3.71875 | 4 | from matplotlib import pyplot as plt
from matplotlib import style
style.use("ggplot")
x=[2010,2011,2012,2013,2014,2015]
y=[55,33,56,60,85,99]
y2=[54,60,85,33,56,77]
plt.plot(x,y,'b',label='Ved Gupta', linewidth=1)
plt.plot(x,y2,'g',label='Abhishek Yadav', linewidth=1)
plt.title("Information Data")
plt.xlabel("Yea... |
f0ea8078254e2ba7233ff12d3c5645728de950b3 | SonnyTosco/python_crash_course | /greeter.py | 433 | 3.828125 | 4 | def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
count = 0
#This is an infinite loop
while count < 5:
print("\nPlease tell your name:")
f_name = input("First Name:")
l_name = input("Last Name:")
if l_name == 'q':
break
... |
a6bd195e771491165b3f4b65c870ca83155cd1d0 | y2030/road_leecode | /just_do.py | 2,547 | 3.53125 | 4 | def compare_version(v1, v2):
"""比较版本号大小"""
idx = 0
len1, len2 = len(v1), len(v2)
if len1 > len2:
v2.extend([0 for _ in range(len1-len2)])
if len2 > len1:
v1.extend([0 for _ in range(len2-len1)])
while idx < len1:
item1, item2 = str(v1[idx]), str(v2[idx])
if item1.isdigit() and item2.isdigit(... |
8ef7912f570467dd3567f09c9cb02e435f61590f | hyper-77/LeetCode_practice | /34.Search for a Range.py | 599 | 3.578125 | 4 | def SearchRange(list,T):
tmp=[-1,-1]
left=0
right=len(list)
while(left<right):
mid=(left+right)//2
if list[mid]<T:
left=mid+1
else:
right=mid
if (list[right]==T):
tmp[0]=right
left = 0
right = len(list)
while (left... |
8d643c749af269c2d24405a4ed0a50e44346cba2 | hyper-77/LeetCode_practice | /20.Valid Parentheses.py | 385 | 3.859375 | 4 | def check_valid_parentheses(s):
dict={')':'('}
temp=[]
for char in s:
if char=='(':
temp.append(char)
else:
if len(temp)==0:
return False
last=temp.pop()
if not last==dict[char]:
return False
re... |
db38a5d445e95dc799cf94226602abd27fcbc5e0 | hyper-77/LeetCode_practice | /2.Add Two Numbers.py | 1,136 | 3.546875 | 4 | import chaintable
a=chaintable.ChainTable()
b=chaintable.ChainTable()
for i in range(3):
a.append(i)
b.append(i+6)
a.append(4)
b.append(9)
b.append(3)
print(a)
print(b)
def addTwoNumber(n1,n2):
dummy=chaintable.Node(-1)
cur=dummy
carry=0
while(not n1==None and not n2==... |
f87feaf3586e52b89e09f3dae7b534a68e8462e1 | Charlesyyun/data-structure-and-algorithm | /merge_sort.py | 1,080 | 3.84375 | 4 | def merge(li, low, mid, high):
# 一次归并,前提是两个有序列表
# low到mid是一段有序列表,mid+1到high是另一段有序列表
# 初始化i和j所指的位置
i = low
j = mid+1
ltmp = []
while i<=mid and j<=high:#只要左右两边都有数,那就比一下这两数
if li[i] < li[j]:
ltmp.append(li[i])
i += 1
else:
ltmp.ap... |
d7fbf20505347d9f2130c5d1b4393fc45ca16cb0 | Sukruti/Test_Exams | /flask/create_board.py | 2,786 | 3.546875 | 4 | import numpy as np
GRID_R=6
GRID_C=9
def play_board():
board = np.zeros((GRID_R,GRID_C))
#board = np.chararray((GRID_R,GRID_C))
print(board)
return board
def is_valid_place(board , column):
print(column)
if board[GRID_R - 1 ][column]!=0:
print('This column is full')
r... |
43fd97252b25c653bfdbe8a1349cd89475d40e60 | HananeKheirandish/Assignment-8 | /Rock-Paper-Scissor.py | 876 | 4.125 | 4 | import random
options = ['rock' , 'paper' , 'scissor']
scores = {'user' : 0 , 'computer' : 0}
def check_winner():
if scores['user'] > scores['computer']:
print('Play End. User Win!! ')
elif scores['user'] < scores['computer']:
print('Play End. Computer Win!! ')
else:
pri... |
a0880a795bf478647e46b41b6f08763ab1650132 | luroto/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 282 | 4 | 4 | #!/usr/bin/python3
"""This is the documentation for this module. This time we have to add
a string into a given file, no matter if file previously existed or not"""
def write_file(filename="", text=""):
with open(filename, 'w') as archivo:
return(archivo.write(text))
|
e2a0c342c90cd07b387b7739b9869aee46df4090 | luroto/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 761 | 4.15625 | 4 | #!/usr/bin/python3
"""
Function handbook:
text_identation("Testing this. Do you see the newlines? It's rare if you don't: all are in the code."
Testing this.
Do you see the newlines?
It's rare if you dont:
all are in the code.
"""
def text_indentation(text):
""" This function splits texts adding newlines when... |
7391b75fb89293723ec10d5180b7e455edd00fbc | luroto/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 801 | 3.5625 | 4 | #!/usr/bin/python3
""" This script connects to a database and list its content based on a
given field"""
if __name__ == '__main__':
import MySQLdb
import sys
databba = MySQLdb.connect(
host='localhost',
user=str(sys.argv[1]),
password=str(sys.argv[2]),
... |
af554dd3b3256ace5f17e31275fcbdd641fcaff0 | TheRubick/Piplined-Processor | /Assembler/assembler2.py | 24,139 | 3.53125 | 4 | import re
import sys
#Return a list containing every occurrence of "ai":
def calReg(instruction,oneTwoThreeOp,instructionFunction,errorFlag):
regField = list("000000000")
Reg = re.findall("[R-r][0-7]", instruction)
#print(Reg)
isImmediate = not(len(Reg) == len(oneTwoThreeOp)+1 or instructionFunct... |
433a67d17dbb66ddf87bb5d1b7540aea1b613502 | TFabijo/euler2 | /euler-46.py | 1,204 | 3.515625 | 4 | def goldbach():
prastevila = [2,3,5,7,11,13,17]
i = len(prastevila)
d = True
stevilo = 3
while d == True:
if stevilo in prastevila:
stevilo += 2
elif stevilo > prastevila[-1]:
i += 1
s = prastevila[-1]
while len(prastevila) !... |
890af84001f5b2e9268c4f7a848ab116e114ecbf | Radar3759/fuzzy-palm-tree | /heads_tails.py | 235 | 3.8125 | 4 | #random heads or tails
#Write your code below this line 👇
#Hint: Remember to import the random module first. 🎲
#import random module
import random
b = random.randint(0,1)
if b == 1:
print("Heads")
else:
print("Tails")
|
418cdaf9d6fdd1b2e5da75123096307edcac99c3 | mtocco/ca_solve | /Python/CA010.py | 882 | 3.703125 | 4 | #Code Abbey 10
def main():
file1 = open("test010.txt","r")
file1.readline()
array = remNewLines(file1.readlines())
array = convArray(array)
answer = ""
for i in array:
answer = answer + solve010(i) + " "
print(answer)
def remNewLines(array):
for i in range(len(array)):
... |
3b0fe27b3dc3448de0bdcdd034ff6220af9bad2d | mtocco/ca_solve | /Python/CA041.py | 2,774 | 4.28125 | 4 | ## Code Abbey
## Website: http://www.codeabbey.com/index/task_view/median-of-three
## Problem #41
## Student: Michael Tocco
##
##
##
## Median of Three
##
##
## You probably already solved the problem Minimum of Three - and it was
## not great puzzle for you? Since programmers should improve their logic
## (and not o... |
72e3d96a7053b48efff1fc31ebff14eaff4f451d | tranthanhtrung/research | /big-o/Lecture4/ThrowingCardsAwayI.py | 422 | 3.546875 | 4 | n = []
while True:
tmp = int(input())
if tmp == 0:
break
n.append(tmp)
for i in n:
queue = [j+1 for j in range(i)]
dis = []
while len(queue) > 1:
dis.append(queue.pop(0))
queue.append(queue.pop(0))
if len(dis) > 0:
print('Discarded cards:', ', '.join(str(x) ... |
3b40792a7692227eddb152f01f664fc5c7eae17a | martinamalberti/BicoccaUserCode | /FakeRate/EffAnalysis/batch/test.py | 1,176 | 3.765625 | 4 | #! /usr/bin/python
import sys
import os
import stat
args=sys.argv
# check the command line and if wrong raise an error
if len(args)!=2:
print 'Usage:\n'+\
'%s CMSSW_dir rootfilelistfile basedir castor_dir queue\n' %args[0] +\
'Example:\n'+\
'%s ./CMSSW_1_2_3 mylist.txt /tmp 8nm... |
b527c79e7306a1727aa92211f0fe75507d3cec34 | Honyoung/LeetCode | /com/jensen/coding_fun/generator_coding.py | 1,612 | 3.8125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
combinations ( iterable, r )
Return r length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as uniq... |
f637e1d46296d30af8f8210c3bea25cc3168bcbe | SindhuHG280699/gittrng | /case study.py | 1,125 | 3.53125 | 4 | class Employee:
def __init__(self, empid, empname,empsal, empdept):
self.empid= empid
self.empname = empname
self.empsal=empsal
self.empdept = empdept
def display(self):
print('Name: ' self.empname)
print('Empid:' self.empid)
prin... |
5ab00171b776954ffe7c2f2f6fd4bcd3b0f7e08c | SrishtiPatil/Leet-Code | /Easy/Reverse Integer.py | 336 | 3.53125 | 4 | class Solution:
def reverse(self, x: int) -> int:
if(x<0):
x = abs(x)
y = "".join(reversed(str(x)))
y = int("-"+y)
else:
y = int("".join(reversed(str(x))))
temp = abs(y)
if temp > 1<<31:
return 0
else:
re... |
eb65d246b62b3e3c5081a22edc153a57533a57e0 | KellyHLe1/david_phone.book | /PhoneBook_2.py | 1,136 | 3.734375 | 4 | # start with creating class and dictionary
# Good start. Next step would be making it repetitive so I can add multiple users and query multiple people. How do that?
# DAVID: x is a bad name: this should be something more meaniful like command_text, or user_prompt_text
# DAVID: secondly as file size gets bigger try s... |
871f4c608f076b0491df42f7257c8db6818bfbb2 | tsur2131/python-training | /ex2/ex2_012345678.py | 549 | 3.734375 | 4 | ## 1.
my_string = "Nell fed her Electric EEL!"
# begin your code here
# end your code here
## 2.
my_string = "Nell fed her Electric EEL eggs"
# begin your code here
# end your code here
## 3.
my_list = [1, 7, 9, 15, 2, 8]
# begin your code here
# end your code here
## 4.
my_list = [[1,3,5], [3,2], [], [-17]]
# be... |
fbec208c8dae08742e23d199f4a4debc8d125430 | unknownpgr/algorithm-study | /code-snippets/02. permutation.py | 724 | 4.15625 | 4 | '''
Recursive function may not be recommanded because of stack overflow.
However, permutation can be implemented with recursive function without warring about overflow.
That is because n! grows so fast that it will reach at time limit before it overflows.
'''
def permutation(array):
'''
This function returns ... |
6c294f0fa914d9322762283757cfcc639d8f3f93 | chris-Dog/lpthw | /exercise7/more_printing.py | 743 | 3.671875 | 4 | # Exercise 7: More Printing
# I wont be explaining much since it is just more of the same.
# A bunch of exercises where youy just type code in and make it run.
# I won`t be explaining much since it is just more of the same
# The purpose is to build up your chops. Do Not Skip! Do Not Paste!
print " Mary had a little la... |
cc90efe6a38bceb8f738a7ffcf09e34b29789d21 | lvandervoort89/analyzing_how_millennial_women_spend_time_and_money | /web_scrape_money_diaries.py | 4,871 | 3.578125 | 4 | '''
This script connects to Refinery29's Money Diaries website and uses Selenium to
get the unique links for 500 money diaries. Using those links, it uses
Beautiful Soup to scrape the diarist metadata and text of their diary and saves
this to a dictionary. Then the data is broken into 2 dataframes: the metadata
and th... |
6ee51998a0bcf1f2ce4073776b4b832417ae1925 | hitalorm/threads | /pi_mc.py | 2,001 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from random import random #biblioteca para gerar numeros pseudo aleatorios
import matplotlib
matplotlib.rcParams.update({'font.size': 18})
plt.subplots_adjust(left=0.16, bottom=.13, right=.98, top=.95,
wspace=None, hspace=None)
#vetor com o numero de ... |
e1db05c9c3876c0a67048d9041320a27df722bef | shafferz/Public-Projects | /Code-Based Projects/Finished Programs/Coursework Programs/CS312-Databases/Basic-Query-Program/query_demo.py | 4,447 | 4.59375 | 5 | #!/usr/bin/env python3
# date: 1 March 2019
# Zachary Shaffer
import sqlite3
# use a dictionary to keep track of how many attributes there are per table.
tables_dict = {"instructor": 5,
"teaches":5,
"student": 4,
"course": 4,
"department": 3
}
# define a function to get user-in put for the name of the table
def getT... |
ffa1dc44b74a94a8d80962a0db70901c4042cbf2 | simon-ritchie/numdoclint | /numdoclint/cli.py | 8,558 | 3.609375 | 4 | """Module for command line interface.
"""
import argparse
import os
from typing import List, Optional
import numdoclint
from numdoclint import py_module
def _get_list_of_str_from_csv(csv: str) -> List[str]:
"""
Get a list of strings from one line CSV.
Parameters
----------
csv : str
One... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.