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
b065ea0430428bf407530c2645833af77da65b30
NirmalVatsyayan/data_science_pipeline
/natural_language_processing/03_stemmer.py
855
4.09375
4
''' The idea of stemming is a sort of normalizing method. Many variations of words carry the same meaning, other than when tense is involved. Ex: I was taking a ride in the car. I was riding in the car. Both means the same thing. One of the most popular stemming algorithms is the Porter stemmer, which has been ar...
600e7893f4e4f7cb0e6b8819d4e17cc718427ec8
dihogoteixeira/fiap-ctp-exercises
/exercicios-aula-08/AULA_08_Exercicio03.py
443
4.1875
4
contaCliente = input("Digite seu codigo de verificacao de 3 digitos: ") verificadorCliente = contaCliente[::-1] somaNumeroConta = int(contaCliente) + int(verificadorCliente) multiplicaDigito = list(str(somaNumeroConta)) digitoVerificador = int(multiplicaDigito[0]) *1 + int(multiplicaDigito[1]) *2 + int(multiplicaDigito...
58f0f4d93c61b56f99bb3382760730b13ca4dc32
dihogoteixeira/fiap-ctp-exercises
/exercicios-aula-08/AULA_08_Exercicio04.py
509
4.0625
4
numero_1 = int(input("Digite o primeiro numero inteiro: ")) numero_2 = int(input("Digite o segundo numero inteiro: ")) numero_1Lista = list(str(numero_1)) calculo01 = int(numero_1Lista[1]) *3 calculo02 = int(13 - 2) calculo03 = calculo02 + numero_2 resultado = (calculo01) + (calculo02) + (calculo03) if resultado <=...
d699957c766f7b967450c4aa0155a6aeed2b5cad
dihogoteixeira/fiap-ctp-exercises
/exercicios-aula-08/AULA_08_Exercicio01.py
458
3.734375
4
nomeFuncionario=input("Digite o nome do funcionario: ") salarioBruto=float(input("Digite o valor do Salario Bruto: ")) valorParcela=float(input("Digite o valor da parcela: ")) valorPermitido = salarioBruto / 100 * 30 if valorParcela > valorPermitido: print(nomeFuncionario + ", o Valor da parcela e maior que 30% d...
1d1cdc9a6a0bc4341487cd035d194cb9a687b156
vbusy/basics_py
/Lesson_3/hw_3_4.py
244
4.0625
4
# первое решение # def my_func(x, y): # return 1 / (x**y) # print(my_func(4,-2)) # второй вариант def my_func(x, y): mul = 1 for i in range(y): mul = mul * x return 1 / mul print(my_func(5,2))
594ca84da2339f689f89de0f28c8b99be27ffc36
vbusy/basics_py
/Lesson_2/hw_2_6.py
334
3.546875
4
def check_password(n): str(n) s = 0 if len(n) >= 10: for i in n: if i.isdigit(): if i.isupper(): if i.isalnum(): s = s + 1 if s >= 10: print("Perfect password") else: print("Easy peasy") check_password(...
ed5cd3271767a7fa0c5000fd0c80af09394973a6
acarnevali/python
/votacao-dias.py
783
3.96875
4
seg = int(input('Insira votos para Segunda: ')) ter = int(input('Insira votos para Terça: ')) qua = int(input('Insira votos para Quarta: ')) qui = int(input('Insira votos para Quinta: ')) sex = int(input('Insira votos para Sexta: ')) if seg > ter and seg > qua and seg > qui and seg > sex: print('O dia escolhido pa...
d08ff4db74ab999d302e946a807c79120725f818
alexander6896/Conexion_BD_Py
/Base de Datos/prueba.py
589
3.5
4
#!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", # tu host, usualmente localhost user="root", # tu usuario passwd="", # tu password db="regitstro") # el nombre de la base de datos # Debes crear un objeto C...
0027528b1ccf339670d29341a02343e559fa2128
huangchaoRestart/AI-For-CV
/lesson3_homework/2. logistic_regression_vectorized.py
3,267
3.875
4
''' author:huangchao content: 1.logistic regression realized by vector 2.code is organized by class 3.calculate accuracy of train set ''' import numpy as np class logistic_regression_vectorized: def __init__(self): print(">>>>construct logistic regression model") #config hyper parameters def fit(...
36eceaf68d9cf884bbe26380a906469e13aa15bc
dmitrime/ttt
/ai.py
2,490
3.609375
4
# -*- coding: utf-8 -*- from player import Player class AIPlayer(Player): ''' Computer player. ''' def __init__(self, xo, other, size): super(AIPlayer, self).__init__(xo, other, size) self.MAX_DEPTH = 10 if size == 4: self.MAX_DEPTH = 7 elif size == 5: ...
57aa3b69319ecab7f50b5b2a8457759a2c33f629
giannich/Computer-Systems-Projects
/JackCompiler/symbolTable.py
3,069
3.921875
4
class Symbol: """A symbol containing data type, segment, and index""" def __init__(self, type, segment, index): self.type = type self.segment = segment self.index = index # Returns the type def getType(self): return self.type # Returns the segment def getSegmen...
1a3753adfe4509d5e356bb9c150a53e7af7ff67b
ignacioct/biome-text
/src/biome/text/modules/heads/task_prediction.py
6,699
3.765625
4
import dataclasses from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import cast import numpy # this sentinel is used to omit certain dataclass fields when the dataclass is converted to a dict SENTINEL = cast(None, "SENTINEL TO SKIP DATACLASS FIELDS WHEN ...
87ad752db919140e588cdecc91b82c321195d008
margaret-jihua/Intro_to_python
/bank.py
1,173
3.90625
4
class BankAccount(): def __init__(self, kind, pin): self.kind = kind self.balance = 0 self.overdraft_fees = 0 self.pin = pin def deposite(self, amount): self.balance += amount def withdraw(self, amount, pin): if (self.pin == pin): if (self.balanc...
a41f67faa0c5514f18d8ee90320bd38f27c0fe83
AilanPaula/Curso_em_video_Python3
/ex030.py
237
4.03125
4
''' Crie um programa que leia um número inteiro e mostre se ele é par ou ímpar. ''' n = int(input('Digite um número: ')) if (n % 2 == 0 ): print('O número {} é par'.format(n)) else: print('O número {} é impar'.format(n))
8affb78c5437c46dd50dea2e6da8d8bca1163a85
AilanPaula/Curso_em_video_Python3
/ex071.py
789
4
4
''' Crie um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. ''' n = [] maior = menor = 0 for c in range(0, 5): n.append(int(input(f'Digite um valor para a posição {c}: '))) if c == 0: maior ...
ae24f87a6bfaa6868ed1e17a02bd31ac00860b2a
AilanPaula/Curso_em_video_Python3
/ex012.py
285
3.578125
4
''' Crie um programa que leia o salário de um funcionário e mostre o seu novo salário com 15% de aumento. ''' n = float(input('Qual é o salário do funcionário?: ')) s = n + (n*15/100) print('Um funcionário que ganhava {}, com 15% de aumento, passa a ganhar {:.2f}.'.format(n,s))
6185ccae596ac60ad46d2788c30e035eb7153701
AilanPaula/Curso_em_video_Python3
/ex052.py
753
4.28125
4
''' Crie um programa onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' from random import randint print('Sou seu computador...') print('Acabei de pensar em um número entre 0 e 10.') p...
acc830fa259137641c7dcda20abd8b2b1a08a802
AilanPaula/Curso_em_video_Python3
/ex094.py
824
4.15625
4
''' Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. ''' def LeiaInt(resp): num = str(input(resp)) if num.isnumeric(): num = int(num) return num while not num.is...
ee123e4beeaaeef72dda2766b85a7ef6a3795504
AilanPaula/Curso_em_video_Python3
/ex091.py
618
4.09375
4
''' Crie um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL e OBRIGATÓRIO nas eleições. ''' from datetime import datetime def voto(ano): idade = datetime.now().year - ano ...
0d0a6ba3572934f510f66d13f4c3e72962bdb7e2
AilanPaula/Curso_em_video_Python3
/ex048.py
332
3.9375
4
''' Crie um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o. ''' soma = 0 for c in range(1, 7): n = int(input('Digite um número: ')) if n % 2 == 0: soma = soma + n print('A soma dos valores digitados são: {}'. format(...
967dcd6db4fe9f7c087c113b0736a9031999f309
AilanPaula/Curso_em_video_Python3
/ex086.py
1,392
3.921875
4
''' Crie um programa que gerencie o aproveitamento de vários jogadores de futebol. ''' jogador = {} time = list() partida = list() while True: jogador.clear() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantas partidas {jogador["nome"]} jogou?')) partida.clear() for c in ra...
4cc1e53231d01ca6445afab717339048af2cf378
AilanPaula/Curso_em_video_Python3
/ex053.py
1,214
4.28125
4
''' Crie um programa que leia dois valores e mostre um menu na tela: [ 1 ] somar [ 2 ] multiplicar [ 3 ] maior [ 4 ] novos números [ 5 ] sair do programa Seu programa deverá realizar a operação solicitada em cada caso. ''' n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) op = 0 while op !=5: ...
2a04e50ee49757c2ba2c9ae5ceeb5940e97c482e
AilanPaula/Curso_em_video_Python3
/ex090.py
767
4.125
4
''' um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior. ''' from random import randint from time import s...
084cb1de7fece4e3f74452233bd61c03af0812b8
amitp-ai/Resources
/leet_code.py
1,353
4.65625
5
#test """ Syntax for decorators with parameters def decorator(p): def inner_func(): #do something return inner_func @decorator(params) def func_name(): ''' Function implementation''' The above code is equivalent to def func_name(): ''' Function implementation''' func_name = (decorator(para...
fb55395ee175bdce797e17f48c6c04d7f2c574a2
dukeofdisaster/HackerRank
/TimeConversion.py
2,484
4.21875
4
############################################################################### # TIME CONVERSION # Given a time in 12-hour am/pm format, convert it to military (24-hr) time. # # INPUT FORMAT # A single string containing a time in 12-hour clock format (hh:mm:ssAM or # hh:mm:ssPM) wehre 01 <= hh <= 12 and 00 <= mm, ss <...
22062eade13e7c0fe29334a9b2e7c9da382caf4b
yourSprite/LeetCodeExcercise
/110平衡二叉树.py
1,124
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' 方法一:自顶向下 空间复杂度O(N^2),时间复杂度O(N) N为节点数量 ''' class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return Tru...
2d4f3f6f1a5b84afad88d1decc98997b569e2de8
yourSprite/LeetCodeExcercise
/169求众数.py
872
3.671875
4
''' 方法一:哈希表 空间复杂度O(n), 时间复杂度O(n),n为nums长度 ''' class Solution: def majorityElement(self, nums: List[int]) -> int: counts = collections.Counter(nums) return counts.most_common(1)[0][0] ''' 方法二:排序后取中间值 空间复杂度O(1), 时间复杂度O(nlogn),n为nums长度 ''' class Solution: def majorityElement(self, nums: List[...
34301e251fe8c318ff2ef2242b0f22573ebb6b01
yourSprite/LeetCodeExcercise
/37.py
1,688
3.8125
4
class Solution: def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if board is None or len(board) == 0: return self.solve(board) def solve(self, board): """ 填充数字 ...
84ce968a9c3d246eb1fc9f119cc53997e846a9d7
yourSprite/LeetCodeExcercise
/234回文链表.py
1,312
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None ''' 方法一:使用列表存储链表 空间复杂度O(n),时间复杂度O(n) ''' class Solution: def isPalindrome(self, head: ListNode) -> bool: l = [] while head: l.append(head.val) ...
8e2f9318a0ccc40a06bbd4fb92d84c1d89232d76
yourSprite/LeetCodeExcercise
/101对称二叉树.py
1,606
3.984375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' 方法一:递归 空间复杂度,O(N),用于维护递归栈,时间复杂度O(N) N为节点数量 ''' class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: ret...
46638e3591e2705c390d8904a22ee9824b439146
manish-panwar/python-examples
/src/variables-types.py
141
3.78125
4
age = 30 name = "Manish" print(age) print(name) print(name + age.__str__()) if isinstance(age, int) and age > 29: print("this is age")
8a9b7f28f517f0b2fc95c42f2a7473198e9129ff
mmanishh/codilitysolution
/greedy/max_overlap.py
706
3.59375
4
def solution(A, B): # No overlapping is possible. if len(A) < 2: return len(A) count = 1 # The first segment starts a new cluster. end = B[0] index = 1 # The second segment. while index < len(A): # Skip all the segments in this cluster. while index < le...
cee469956ffe9d3afc5d82e2da873e001f0f0958
jhont285/lenguajes-de-programacion
/Proyecto/ejemplos de uso/tablasOutput.py
186
3.796875
4
print "\n\t TABLAS DE MULTIPLICAR\n\n" i = 2 while(i < 10): j = 2 while(j <= 10): print "\t" , i , "*" , j , "=" , (i * j) j = (1 + j) print i = (i + 1)
878e428a2f1ed3e383e111def0e1a353182e910f
rsw0/Amazon-Review-Classification
/starter-code/initial-exploration.py
2,562
3.640625
4
import pandas as pd import matplotlib.pyplot as plt trainingSet = pd.read_csv("./data/X_train.csv") testingSet = pd.read_csv("./data/X_submission.csv") print("train.csv shape is ", trainingSet.shape) print("test.csv shape is ", testingSet.shape) print("first 5 rows of the training set") print(trainingSet.head()) pri...
4e0818f3e0817361b3424ba8939e254c21c23004
mikimaja4/Coding-is-Life
/questionList.py
762
3.90625
4
import random, question class QuestionList: def __init__(self, questions): #List of Question objects self.questions = questions #Shuffle the questions before selecting which will be first self.shuffle() #Which question is currently being displayed self.current...
f709827f0e9864abda524adaf5c89e0d6523e104
cau777/Smart-Calculator
/calculator.py
6,719
3.515625
4
import string from collections import deque def main(): print('/help for info') while True: s = read_input() if s.count('=') > 1: print('Invalid Assignment') continue if s.count('|') > 0: print('Invalid Assignment') continue i...
d7a2d6f890bf3a3c85c5a327d209712408b1c988
singhpawan/op_challenge
/code/nycjobs.py
3,447
3.703125
4
# Contains analysis of the nycjobs and find insights import sys import os from collections import Counter import csv from datetime import datetime import numpy as np import scipy import scipy.stats # parameter: tuple or list # returns: the last elementt of a list or a tuple def last_key(item): return item[-1] ...
ca3e2b41bdbfdaf47caed60dc5f2c00a522fc3a9
Bryan-20/tr08_Santamaria_Vasquez
/santamaria/libreria.py
7,292
3.59375
4
# Pregunta nro1 def es_respuesta_validad(strRspta): # verifique si la respuespuesta es valida. puede ser A,E,I,O o U # Parametro strRspta #retornar: bool #1. si la longitud de strRspta es 1 if( len(strRspta) == 1 ): #1.1.si la strRspta no es A o E o I o O o U, devolver False, sino retornar True if( strRspt...
11e0b8edc94e4457dd11d2608d53ee817ea3be52
bmorris3/linea
/linea/linalg.py
1,590
3.5
4
import numpy as np def linreg(X, flux, error): r""" Least squares linear regression. We solve for the least-squares estimators :math:`\hat{\beta}`, .. math:: \hat{\beta} = ({\bf X}^{\rm T} {\bf N}^{-1} {\bf X})^{-1} {\bf X}^{\rm T} {\bf N}^{-1} f. Uncertainties on each of the least-squ...
b6196777719e69bfbf8690ca966913e8fc049689
dustMa009/Leetcode
/009PalindromeNumber.py
779
3.734375
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x>=0: return x==int(str(x)[::-1]) else: return False ''' 题目说不能用额外空间,但是上面自己写的也通过了 class Solution: # @param x, an integer # @return ...
53492ce05f7ce6d2074f4433c5e00ebd9337d5f5
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio27.py
878
4.03125
4
# Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade de turmas e a quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos. quantidade_turmas = int(input("Informe a quantidade de turmas: ")) def calcula_media_por_turma(quantidade_turmas): contado...
348934260c196bcb6d4c8072c290bb6200c49085
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio9.py
348
3.75
4
# Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50. ultimo_numero = 50 index = 1 listagem_numero = [] def executa_numeros_impares(index, ultimo_numero): while index <= ultimo_numero: listagem_numero.append(index) index += 2 print(listagem_numero) executa_numeros_impa...
b500774449d17ede116b123f293a89969d2a01c9
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio38.py
1,331
4.21875
4
# Um funcionário de uma empresa recebe aumento salarial anualmente: Sabe-se que: # Esse funcionário foi contratado em 1995, com salário inicial de R$ 1.000,00; # Em 1996 recebeu aumento de 1,5% sobre seu salário inicial; # A partir de 1997 (inclusive), os aumentos salariais sempre correspondem ao dobro do percentual do...
9ca3941797ceb5460c5337861706b2ce0a19046f
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio44.py
2,404
3.984375
4
# Em uma eleição presidencial existem quatro candidatos. Os votos são informados por meio de código. Os códigos utilizados são: # 1 , 2, 3, 4 - Votos para os respectivos candidatos # (você deve montar a tabela ex: 1 - Jose/ 2- João/etc) # 5 - Voto Nulo # 6 - Voto em Branco # Faça um programa que calcule e mostre: # O ...
a002314808da079b257d10be7f429636c7f88715
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio22.py
700
3.828125
4
# Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é divisível. numero_fornecido = int(input("Informe um número inteiro para validação: ")) def valida_numero_primo(numero_fornecido): lista_primos = [] div = 0 for divisor in range(1, numero_for...
a897c23b3c138529b38590d482a3f8d9622e456d
jimbrunop/brunoperotti
/Python - Projects/Aulas/Exercicio1.py
4,590
4.4375
4
#Faça um algoritmo que apenas imprima o seu nome na tela e em seguida finalize a aplicação. print("Bruno") print() #Faça um algoritmo que solicite ao usuário digitar o seu nome e em seguida envie a seguinte frase para a saída padrão: "O seu nome é: [nome do usuário]". nome = input("Digite o seu nome") print("O seu ...
7a225d2e1f0ac5450917eb22f8f5537bac4be099
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio24.py
735
4.15625
4
# Faça um programa que calcule o mostre a média aritmética de N notas. quantidade_notas = int(input("informe a quantidade de notas do aluno: ")) def calcula_media(quantidade_notas): contador = 0 listagem_notas = [] while contador < quantidade_notas: nota_aluno = float(input("informe a nota: ")) ...
a4919306f68d5f9d983ae7773da6ce608ba098b0
jimbrunop/brunoperotti
/Exercicios-Python/DecisaoExericico12.py
2,401
4.03125
4
# Faça um programa para o cálculo de uma folha de pagamento, sabendo que os descontos são do Imposto de Renda, que depende do salário bruto (conforme tabela abaixo) e 3% para o Sindicato e que o FGTS corresponde a 11% do Salário Bruto, mas não é descontado (é a empresa que deposita). O Salário Líquido corresponde ao Sa...
a8f8878c553a1ec9da4e70fb13af9223bebdb35d
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio1.py
414
4.21875
4
# Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido. def valida_numero(): numero = float(input("informe um numero de 0 a 10: ")) while (numero > 10) or (numero < 0): numero = float(input("in...
91e9b3a3adcf6a7b8cfc066737fa8e85d97f47aa
jimbrunop/brunoperotti
/Exercicios-Python/DecisaoExercicio3.py
415
3.9375
4
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. sexo = input("Informe M para masculino ou F para feminino") def valida_sexo(sexo): if sexo == 'm' or sexo == 'M': print("Sexo masculino") elif sexo == 'f' or sexo ...
a1341bfa2c5cf74e8055d5ce7089fbcfd3c44ed7
sachinbak/Python-Practice
/nested.py
356
3.875
4
#print F with for loop number = [5, 2, 5, 2, 2] for x_count in number: output = '' for count in range(x_count): output += 'x' print(output) print(" ") #print L with for loop number = [2, 2, 2, 2, 5] for x_count in number: output = '' for count in range(x_count): ...
f7c35cd71de55bd957da4338110c3343918c641d
Dr-A-Kale/Python-intro
/str_format.py
669
4.125
4
#https://python.swaroopch.com/basics.html age = 20 name = 'Swaroop' print('{0} was {1} years old when he wrote this book'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) print(f'{name} was {age} years old when he wrote this book') print(f'Why is {name} playing with that python?') print("Wh...
cee046945a5a6143a1de93b15c4a61acfd5816d7
akshitagit/CPP
/Greedy_Algorithm/Dijsktras_algorithm.cpp
2,665
3.53125
4
// VishnuGaneshan @ github // https://github.com/VishnuGaneshan/ #include <limits.h> #include <stdio.h> // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum distance value, from // the set of vertices not yet included in shortest path tree int minDistance(int dist[], ...
371a19e616c5cf15f1bf682a29f3a41936b8c9ec
alyssalukpat/foundations_homework
/02-hw/homework-2-part2-lukpat.py
2,698
4.0625
4
# Alyssa Lukpat # Oct. 28 # Homework 2, Part 2 # Lists countries = ["Botswana", "Panama", "Egypt", 'Albania', "Taiwan", "Canada", "France"] tally = 0 for country in countries: print(country) tally = tally + 1 countries.sort() print(f'The first item in the list is {countries[0]}.') reverse_countries = sort...
de1a73529f5a254b567bae357f758594f65bb028
manojkumar-ch/py-thony-three
/mnk.py
139
3.75
4
print('enter the starting on:') j=int(input()) print('enter the ending on:') k=int(input()) for l in range (j,k+1): if l%2!=0: print(l)
597447d024d178066077d36c3cae84f147a0e8bd
manojkumar-ch/py-thony-three
/vowelandconstant.py
135
3.796875
4
k=['a','e','i','o','u','A','E','I','O','U']; r=str(input("Enter the letter:")) if(r in k): print("vowel") else: print("consonant")
9f2746e31a83d79aa09914464118ff7dc54e96bb
antoniojmf/Practicing-Python
/My bank/account.py
1,450
4.0625
4
import sqlite3 conn = sqlite3.connect("database.db") c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS account(AccountName TEXT, Password INT, Money REAL, LastTransaction TEXT)") def data_entry(tpl): c.execute("INSERT INTO account VALUES (?, ?, ?, ?)", tpl) c.execute("SELECT * FROM account") ...
03b4609e13f7b1f3bafbdc8c9ffc83e04ca49b04
KartikeyParashar/FunctionalPrograms
/LeapYear.py
322
4.21875
4
year = int(input("Enter the year you want to check that Leap Year or not: ")) if year%4==0: if year%100==0: if year%400==0: print("Yes it is a Leap Year") else: print("Not a Leap Year") else: print("Yes it is a Leap Year") else: print("No its not a Leap Year...
e8a7d8f68b1f231639df1baa75f6405fe207a582
KartikeyParashar/FunctionalPrograms
/tic_tac_toe_game.py
2,044
4.0625
4
from random import randint print("Welcome to tic tac toe Game: ") name = input("Type your name: ") print(f"In this Game: Player 1 is {name} and player 2 is Computer") #set player to 1 player = 1 # Set the initial state state = [0, 0, 0, 0, 0, 0, 0, 0, 0] def show_state(state): print(state[0], state[1], state[2]...
0d7a00fea038256191cdcd960d31b048730aa4d4
Pattaraponggg/Programming
/Test3.py
519
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[25]: #3.จงเขียนโปรแกรมวนซ้ำโดยบังคับใช้คำสั่ง while ให้แสดงคำว่า"Hello"จำนวน ๕ บรรทัด a=0 n=5 while a < n : print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") a +=5 # In[ ]: # In[ ]: # In[ ]: # In[ ...
7e1c7487f39587e00cf14058830df0e604da41a1
xuke829/pycode
/pycode/Day3/narcissistic.py
360
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """code_info @Time : 2020 2020/6/29 14:58 @Author : Xuke @File : narcissistic.py """ count = 0 for i in range(100, 1000): t = i a = int(t / 100) b = int((t / 10) % 10) c = int(t % 10) if t == a ** 3 + b ** 3 + c ** 3: count = count + 1 ...
e5e99f5c42d7ad6c1ef62d81ec617cb391363692
nullptr-exception/pyDS
/NodeBased_Queue.py
2,162
3.828125
4
import Node as node # F.I.F.O def create(): """ -> <- @param: None @return: an empty queue """ queue = {} queue['size'] = 0 queue['front'] = None queue['back'] = None return queue def size(queue): """ -> <- @param: queue -> a queue c...
a7d92bc5608be2975062afa7f8f3832378a01d7e
vltian/some_example_repo
/lesson_2_types/hw_22.py
895
4.0625
4
"""2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ a = list() b = 1 while b != "0": a....
914d4fa9aeacfdb617b936cd783f52a0c4687f59
vltian/some_example_repo
/lesson_6_OOP/hw_62.py
1,195
4.53125
5
"""2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать форму...
1bb30066223e69f44a4966e31e906099d91f7907
vltian/some_example_repo
/lesson_1/hw_4.py
517
3.96875
4
#hw4 # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. user_num = int(input("Enter a whole positive number: ")) a = user_num % 10 b = user_num // 10 max = a while b > 1: a = b % 10 b = b // 10 if a > max: ...
c784c74ddd750cc8ba50a077e1f8dea84691b6d2
vltian/some_example_repo
/lesson_3_func/hw_34.py
711
3.984375
4
"""4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. """ def my_func(x, y)...
e207b58e90ad039f7887fe1fbe6fae979420e569
vltian/some_example_repo
/lesson_5_files/hw_51.py
608
3.65625
4
""" 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка. """ with open("my_2.txt", 'x', encoding="utf-8") as f_obj: while True: txt_inp = input(":") if txt_inp != "": if f_obj.t...
459eb006dcd7172ae716c7f6543d2921cddeffea
vltian/some_example_repo
/lesson_6_OOP/hw_64.py
2,584
3.515625
4
"""4. Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда). Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. ...
4c1951879f308bd04a1bc0909c6a2973f678b10b
yeonloca/python-class
/kim 0810/숫자퀴즈.py
281
3.65625
4
import random as r x = r.randint(1,100) c = 0 while True: answer = int(input("숫자입력:")) if x == answer: break if x > answer: print("up") if x < answer: print("down") c+=1 print("맞았습니다. 시도횟수:",c)
4ab0c626cbe099e923fe76feb3b8f72f816ae507
jackiechen0708/tweet
/tweet.py
9,886
3.90625
4
"""Assignment 3: Tweet Analysis""" from typing import List, Dict, TextIO, Tuple HASH_SYMBOL = '#' MENTION_SYMBOL = '@' URL_START = 'http' EOT = "<<<EOT" DETECT_FAIL = "unknown" # Order of data in the file FILE_DATE_INDEX = 0 FILE_LOCATION_INDEX = 1 FILE_SOURCE_INDEX = 2 FILE_FAVOURITE_INDEX = 3 FILE_RETWEET_INDEX = ...
b0609b820a07d819bb215d2a6a8a73770427507e
ShahriarShovo/Python-if-else-problems
/if_else_Basic_Problem.py
7,667
4.4375
4
#1.Write a program to find maximum between two numbers. # number_1=int(input("Enter the First Number : ")) # number_2=int(input("Enter the Second Number : ")) # if number_1>number_2: # print(number_1,"is Grater than",number_1) # else: # print(number_2,"is Grater than",number_1) #2.Writ...
7f066eb80b3fa9444baa6eb30997760ac0c1dbb4
bradelement/coding_exercise
/leetcode-master/179/main.py
457
3.765625
4
class Solution(object): def compare(self, x, y): x, y = x+y, y+x return cmp(x, y) def largestNumber(self, nums): """ :type nums: List[int] :rtype: str """ nums = sorted(map(str, nums), cmp=lambda x, y:self.compare(x, y), reverse=True) ...
1c1e5aeb509f69ec91b948ac1fd8185f4cc7026d
bradelement/coding_exercise
/zoj/misc/1073.py
504
3.5625
4
import sys def circle(line, n): n = str(n) if len(n) < len(line): n = '0'*(len(line) - len(n)) + n return line in n+n def gao(line): nn = int(line) for i in xrange(len(line)): n = nn * (i+1) if not circle(line, n): return False return True def main(): ...
1d1d72128430d0a84a67a6c9563e23f445541119
hbjornoy/higgs-boson-classification
/Python/dataprocessing.py
5,925
3.859375
4
import numpy as np ## Buld poly: builds a polynomial of degree "degree" ########################################################################### def build_poly(x, degree): # this function should return the matrix formed # by applying the polynomial basis to the input data n,m=x.shape phi=np.zeros((n...
e9b0183df623cca692c8d9628b0aa36c71862403
lpensler/lpensler-projects
/proteinsynthesisfinalproject.py
4,155
3.90625
4
""" Leah Pensler Protein Synthesis Final Project COMP-112-01 05/03/17 """ def import_DNA (path): try: f = open(path, 'r') sequence = '' for line in f: sequence += line f.close() return sequence except FileNotFoundError: return -1 def verify_DNA(s...
169d013c1c226c53da4c2e5d0fa6444d7f8bb087
natalya-patrikeeva/interview_prep
/binary-search.py
1,672
4.3125
4
"""You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated values, and elements are in ...
64bd8abd65531cd0cad27142cd2c347d9b2ba05e
jamesoneill54/ca4012-statistical-machine-translation-labs
/final_lab_exam/compute_translation_probability.py
1,313
3.84375
4
# ID: 16410652 # Name: James O'Neill def calculate_translation_probability(c): ''' Calculates the translation probabilities given the fractional counts :param c: fractional counts (dictionary) :returns: translation probabilities (dictionary) ''' # Must divide the fractional counts by the ...
07bbfc873c4645a2dfefae22355027d20536e905
ssslc0707/python
/day16/test.py
351
3.625
4
#fun = lambda x,y:x+y #print(fun(1,2)) # fun = lambda x,y:list({x[i]:y[i]}for i in range(len(x))) # # print(fun((('a'),('b')),(('c'),('d')))) # fu = lambda x:{x:x+1} # # print(list(map(fu,[1,2,3,3]))) # # def m(): # return (lambda x:i*x for i in range(4)) #[]和()的区别 # print([mu(2) for mu in m()]) # print(m()) t...
e8ae1fe67117f3419154dccb0ed97b2ce0ff99e0
mactavish10/APS-2020
/Sherlock and Date.py
1,329
3.828125
4
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' # Write your code here def leap(year) : if (( ye...
e371bddfba2c7dc1e4c618704b12606e9202f328
sarthakjain95/UPESx162
/SEM IV/Algorithms for Intelligent Systems and Robotics/6/josephus.py
464
3.859375
4
#! /usr/bin/env python def josephus_reduce(people, start, k): print(people, start, k) if len(people) == 1: return people[0] else: start = (start + k - 1) % len(people) del people[start] return josephus_reduce(people, start, k) if __name__ == "__main__": n = int(input("Enter n: ")) k = int(input(...
5ef265f819249d27c32068fae30e70901359f598
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/concat-func.py
148
4.0625
4
def concat(str1, str2): s = str1 + str2 return s s1 = input("Enter string 1:") s2 = input("Enter string 2:") res = concat(s1, s2) print(res)
f1c2c4e35e89319d3f0caa57a17a60a2ebac02a4
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/dictionaries.py
1,123
4
4
#### Dictionary basics #### # d = {1:'one', 2:'two'} # d2 = {2: "a", "foo":"b"} # print(d[1]) # d[1] = 'New one' # print(d[1]) # print(len(d2)) # d2.update(d) # print(d2) # print(d2.items()) # print(d2.values()) # print(d2.pop("foo")) #Pops element with key # print(d2) #Element is removed from the dictionary # d...
64c200487c14f7eb5bbacb194dfedd2fbef7de62
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON CLASS/CLASSx1.py
627
3.90625
4
#! /usr/bin/env python3 import random,math,os,sys # r_int = random.randint(2,45) # print(r_int) x=3 y=32 x+=y # same as x = x+y print("sum x,y \t",x) x=32 y=45 x-=y # same as x = x-y ... -13 here print("subtraction x,y\t",x) x=32 y=9 x%=y print("Remainder\t",x) # 5 27+5 x=32 y=9 x//=y print("Floor Division\t...
eed9c8739eb2daa6ecbc47e10693e3d9b1970d82
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON CLASS/CLASSx8.py
1,757
4.71875
5
# -*- coding: utf-8 -*- #! /usr/bin/env python3 # Classes and Objects # Suppose there is a class 'Vehicles' # A few of the other objects can be represented as objects/children of this super class # For instance, Car, Scooter, Truck are all vehicles and can be denoted as a derivative # of the class 'Vehicle' # Furthe...
6bdecc0f5a98b0acf1c5abe676650b3afef8566b
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/displayMultiplicationTable.py
437
4.09375
4
# UPESx162 # CSE / Python3 Programs # DisplayMultiplicationTable # Recommended execution on https://repl.it/languages/python3 def displayTable(n): for i in range(1,11): print("{0} times {1} is {2}".format(n,i,n*i)) if __name__=='__main__': try: val=input("Enter number for table: ") val=int(val) ...
08439f0b24820eb14316611c6950a07fa6c452b5
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/factorial.py
96
3.9375
4
n = int(input("Enter a number:")) fact = 1 while n != 0: fact *= n n-=1 print(fact)
5b8469d92c04fa43b341d4e54267707cbc5fc4ff
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/reverse_string.py
78
4.03125
4
str_ = input("Enter the string:") y='' for i in str_: y = i+y print(y)
4a2e11f9e2202e00c2978b7209350fc030a8a123
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/assignment-operators.py
117
3.546875
4
a = 9 b = 5 c = b c+=b print(c) c-=b print(c) c*=b print(c) c/=b print(c) c%=b print(c) c//=b print(c) c**=b print(c)
9966d55ab8affef9d1ea0f6db246e0dfc90a4295
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON/BATCH-1/string-special.py
213
3.71875
4
s1 = input("Enter sentence 1: ") s2 = input("Enter sentence 2: ") mod_str = "" size = 0 if len(s1) > len(s2): size = len(s2) for i in range(size-1): mod_str = mod_str+s1[i]+s2[i] print(mod_str)
f87f1f7c943f2b754de1c35a0f994c18201ca2fe
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON PRACTICALS/PRACTICALx4B.py
2,687
4.125
4
# -*- coding: utf-8 -*- # PRACTICAL 4B # Q1) Find a factorial of given number. def getFacto(num): facto= 1 for i in range(1,num+1): facto*=i return facto n= int( input("Enter a number for factorial:") ) print( "Factorial is", getFacto(n) ) # Q2) To find whether the given number is Armstrong number. def isArms...
a54edd869d7518e222e924f5fb542602eb795d94
Ineeshya/PYTHON
/areaofcircle.py
62
3.671875
4
R = float(input()) pi = 22/7 AREA = (R**2)*pi print(AREA)
925e2d31f53ebff48af32385cd04d89c131b2cff
chasepeak/data_structures
/Stack/stack.py
1,266
3.6875
4
''' Chase M. Peak -stack abstract data structure -array-based implementation -All operations are O(1) -Last In First Out ''' class Stack(): def __init__(self, capacity): if (type(capacity) != int): raise ValueError("invalid capacity input") self.capacity = capacity self.it...
65ce5ec070e7fe81ada052941f841cfb0097ae3f
AiB2020/Wzorce_Projektowe
/prototype/client.py
860
3.859375
4
"Prototype Use Case Example Code" from document import Document ORIGINAL_DOCUMENT = Document("Original", [[1, 2, 3, 4], [5, 6, 7, 8]]) print(ORIGINAL_DOCUMENT) print() DOCUMENT_COPY_1 = ORIGINAL_DOCUMENT.clone(1) DOCUMENT_COPY_1.name = "Copy 1" DOCUMENT_COPY_1.list[1][2] = 200 print(DOCUMENT_COPY_1) print(ORIGINAL...
97b1d1e3ba121bb01dae55a9d183de1e4e050a9c
xiaolealyssaliu/Group6
/Test.py
1,592
3.5
4
import unittest import love import complexity import length import mood import kid_safe class Test(unittest.TestCase): def test_kid_safe(self): #test for kid_safe word1='having sex should receive clear consent; otherwise, doing so may raise legal issues' self.assertEqual(kid_safe.kid_safe(word1),...
d4a2481208750dac58cb6d48278b40d4de15610d
cleonard1261/DAT3
/code/05_pandas_class.py
2,961
3.953125
4
# pandas tutorial # adapted from: # http://www.gregreda.com/2013/10/26/intro-to-pandas-data-structures/ # files used: # ../data/u.user # ../data/u.data # ../data/u.item # source: # main page - http://grouplens.org/datasets/movielens/ # zip file - http://files.grouplens.org/datasets/movielens/ml-100k.zip #...
e2cfe03db7f0a4ae8f48bbd2eede74777493796f
yurika-jim0401/PythonWorkSpace
/Python_Advanced_Grammar/multithreading/ex10.py
775
3.75
4
# 多线程共享变量 import threading sum1 = 0 loopsum = 100000 # 生成一个锁的实例 lock = threading.Lock() def myadd(): global sum1, loopsum for i in range(1, loopsum): # 上锁/申请锁 lock.acquire() # 使用被锁资源 sum1 += 1 # 使用完毕,释放锁 lock.release() def myminu(): global sum1, loopsum ...
066f51e05f46e42e58a698c9986b4133f4d2f51d
yurika-jim0401/PythonWorkSpace
/Python_OOP/ex06.py
3,128
4.28125
4
# 属性案例 # 创建Student类,描述学生类 # 学生具有Student.name属性 # 但name格式不统一 # 这里可以增加一个函数,然后用自动调用,但是多此一举 class Student(): def __init__(self,name,age): self.name = name self.age = age # 初始化函数中直接调用,大写姓名,这样做虽然可以,但是很麻烦 self.setName(name) def introduce(self): print("hi,my name is {0}".format(...
3531ef651a6d96ccd1c67e97e1fb3b95a0bb70c1
yurika-jim0401/PythonWorkSpace
/Python_Advanced_Grammar/function_program/ex02.py
524
3.78125
4
# map案例 # 有一个列表,想对列表里的每一个元素乘以10,并得到新的列表 from functools import reduce l1 = [i for i in range(10)] print(l1) l2 = [] for i in l1: l2.append(i*10) print(l2) # 上述功能还可以利用map来实现 def mulTen(n): return n*3 l3 = map(mulTen,l1) for i in l3: print(i,end=" ") print() # reduce 案例 # 定义一个操作函数 # 加入操作函数只是相加 def myAdd(...
6ea37c57fe6ed58930091bc9bc58231ad44ecf97
plamenr-ios/PythonAdvancedExcercises
/comprehensions/diagonals.py
546
3.71875
4
n = int(input()) matrix = [] primary = [] secondary = [] for _ in range(n): matrix.append([int(x) for x in input().split(', ')]) for i in range(len(matrix)): primary.append(int(matrix[i][i])) # get bottom left to top right diagonal from matrix corr_i = 0 for i in range(len(matrix) -1, -1, -1): seco...
aee7daf00e9bfed168b3b1d0d88527a9c7d1cdd8
plamenr-ios/PythonAdvancedExcercises
/multidimensional_lists/diagonaldifference.py
554
3.609375
4
count = int(input()) matrix = [] primary = [] secondary = [] # get matrix for i in range(count): matrix.append([[x] for x in input().split()]) # get top left to bottom right diagonal from matrix for i in range(count): primary.append(int(matrix[i][i][0])) # get bottom left to top right diag...