blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d09b78eb5881c7b6e0e5c0d93a267323284e16cc | behtak/clucifers | /run.py | 1,804 | 3.546875 | 4 | import argparse
import os.path
import classf
def is_valid_file(argparser, arg):
"""
ref: https://stackoverflow.com/questions/11540854/file-as-command-line-argument-for-argparse-error-message-if-argument-is-not-va
:param argparser:
:param arg:
:return:
"""
fpath = os.path.abspath(arg)
... |
80d680ff36924dce0ce47cd94b2daa04cdd90599 | santoscarlo/Binary | /binary.py | 776 | 4.34375 | 4 | def decimal_to_binary(number):
binary_list = [] # make sure empty number
old_number = number # Reference number
while(number >.5): #loop
if number % 2 != 0: #if the number is .5
binary_list.append(1)
else:
binary_list.append(0)
number /=2 # set the number to t... |
a022104124aff6d91a1f68059c4c5752b40657da | kamaihamaiha/Tutorial | /python_tutorial/com/python/chapter2/number.py | 179 | 3.9375 | 4 | print(0.1 + 0.2)
# Python3 整数除法:/ 结果不是取整,Python2 是取整。
print(21 / 5)
print(21 // 5)
print(1 / 3)
age = 18;
print(str(age) + '岁生日快乐!') |
5434d1b580f4a63091323f6fc25221cf5cf4b682 | kamaihamaiha/Tutorial | /python_tutorial/com/python/chapter3/list.py | 1,717 | 4.25 | 4 | # 1.列表:由一系列按特定顺序排列的元素组成
bicycles = ['自行车1号', '自行车2号', '自行车3号']
print(bicycles)
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(nums)
# 2.访问列表的元素
print(bicycles[1])
# 3.访问列表的最后一个元素
print(bicycles[-1])
print(nums[-1])
message = "我的第一辆自行车是:" + bicycles[0]
print(message)
# 4.修改列表元素
bicycles[0] = 'Honda'
bicycles[2] = 'Suzuki'
p... |
3242c8d456b5f1db448f8650296c879d1f6f7a75 | kamaihamaiha/Tutorial | /python_tutorial/hello.py | 344 | 3.984375 | 4 | print("hello!")
print('hello!')
# 注释
# 注释2
# 注释2
# 注释2
print("这么短,就不需要专门用一行来写注释了吧!") # 这样注释也可以的!
"""
这是个多行注释,也可以叫块注释
"""
# 下面开始计算简单的运算
print(1 + 2)
print(1 - 2)
print(1 * 2)
print(1 / 2)
print(1 // 2)
print(2 ** 3) |
7ff04681d25858e081c0f189b168361a7528ed3f | kamaihamaiha/Tutorial | /python_tutorial/com/python/chapter10/demo.py | 4,880 | 4.25 | 4 | # 动手试一试
# 10-1 Python 学习笔记
file_name = '/home/kk/PycharmProjects/python_tutorial/com/python/chapter10/file/learning_python.txt'
print('++++++++++++++++++++ 第一次打印,读取整个文件')
with open(file_name) as file_object:
content = file_object.read()
print(content)
print('++++++++++++++++++++ 第二次打印,遍历文件对象')
with open(file_... |
3d5f3fcad6c584cc3d66b6a625dd93091ff92ac2 | kamaihamaiha/Tutorial | /python_tutorial/com/python/chapter11/test_cities.py | 458 | 3.59375 | 4 | import unittest
from com.python.chapter11.city_functions import get_city_info
class TestCityInfoCase(unittest.TestCase):
def test_city_country(self):
city_info = get_city_info('santiago','chile')
self.assertEqual(city_info,'Santiago, Chile')
def test_city_country_population(self):
ci... |
fb8a18254a1d319d9b75d0fd552b794cd54a1c55 | angrymushroom/Hot-Topics | /Tabu_Search/main.py | 534 | 3.859375 | 4 | from algorithms import launch
def main():
"""
Main function.
Try different alpha value to test which greedy level is the best.
"""
experiment_number = 15 # run the experiment 15 times
temp_cost = []
# run 30 times to calculate the mean cost of each alpha value
for i in range(experi... |
ba869a35ce9e0861a962260447f63800ba079b6b | ianmcloughlin/problems-python-fundamentals | /solutions/sortlist.py | 508 | 4.28125 | 4 | # Ian McLoughlin, 2018-03-14
# https://github.com/ianmcloughlin/problems-python-fundamentals
def sortlist(l):
# Loop through the elements of the list.
for i in range(len(l)):
# Loop through the remaining elements of the list.
for j in range(i+1, len(l)):
# If the i^th element is greater than the j^th... |
8c5ad861cf9b6bc876cbc31c9c4bb2069f30a92c | msbhosale/python_workshop | /12_Function_Demo.py | 564 | 3.8125 | 4 | def say_hello():
print("Hello, from MS")
#say_hello()
def display_number(number):
print(f"Your number is {number}")
#display_number(24)
def add_two_numbers(number1,number2):
answer = number1 + number2
print(answer)
#add_two_numbers(20,27)
def get_square(number):
"""
T... |
8396b8e6242ff5256054ed4b5c9a364582a53dfe | msbhosale/python_workshop | /13_Arrays.py | 265 | 3.9375 | 4 | students = ["Shweta","Kaivalya","Shubhangi"]
print(students)
#for name in students:
# print(name)
students.append("Vinayak")
#print(students)
#students.pop(1)
#print(students)
#students.remove("MS")
students.sort()
print(students)
|
5a6d06a17ac045360bfb8097aef7799e21cb9b2c | msbhosale/python_workshop | /22_Try_Except.py | 188 | 4 | 4 | x = 25
y = 10
try:
answer = x / y
except ZeroDivisionError:
print("Can not divide by zero")
except TypeError:
print("Y should be a number")
else:
print(answer) |
e02489fe8d6b28a4e7ec890226945dd914e923bf | holicAZ/Numerical-Analysis | /Bisection.py | 644 | 3.546875 | 4 | from numpy import linspace, zeros,sign,array
import matplotlib.pyplot as plt
def f(x):
return -x**2+6.0*x-5.0
a=-2.0
b=3.0
n=14
c=zeros(n)
error = zeros(n)
xrange = array(range(1,15))
for i in range(n):
c[i] = (a+b)/2.0
if(sign(f(c[i]))==sign(f(a))):
a=c[i]
else:
b=c[i]
... |
0f241029e7ec6031130019163f1f6c44e0721f48 | igorkoury/cev-phyton-exercicios-parte-2 | /Aula19 – Dicionários/Aula 19 – Dicionários.py | 1,266 | 4.625 | 5 | '''Nessa aula, vamos aprender o que são DICIONÁRIOS e como utilizar
dicionários em Python. Os dicionários são variáveis compostas que permitem
armazenar vários valores em uma mesma estrutura, acessíveis por chaves literais.'''
# dicionário - dic = {} ou dic = dict()
# EXEMPLO 01
dados = {'Nome': 'Pedro', 'Id... |
583adc0756f175f50f0a62139b2e4b3fbaed3e44 | igorkoury/cev-phyton-exercicios-parte-2 | /Aula20 – Funções (Parte 1)/aula 20 – Funções (Parte 1).py | 1,955 | 4.625 | 5 | '''Nessa aula, vamos aprender o que são funções ou rotinas e como utilizar
funções em Python. Funções são trechos de código que podem ser executados
em momentos diferentes de nossos códigos em Python. Veja como funciona o
comando def em Python e como utilizá-lo com parâmetros simples e múltiplos.'''
def mostralin... |
cf8d8ab2f3396b206ad48bbd6af95983a41b2957 | igorkoury/cev-phyton-exercicios-parte-2 | /Aula17 - Listas (Parte 1)/ex083 – Validando expressões matemáticas.py | 628 | 4.1875 | 4 | '''Exercício Python 083: Crie um programa onde o usuário digite
uma expressão qualquer que use parênteses. Seu aplicativo deverá
analisar se a expressão passada está com os parênteses abertos e
fechados na ordem correta.'''
expressao = str(input('Digite a sua expressão: '))
lista = []
for simb in expressao:
... |
cad183e7a0e9a51b1b628af881588c64d60a4a24 | igorkoury/cev-phyton-exercicios-parte-2 | /Aula18 - Listas (Parte 2)/ex087 – Mais sobre Matriz em Python.py | 941 | 4.25 | 4 | '''Exercício Python 087: Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.'''
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somaPar = somaCol = maior2Lin = 0
for l in range(0, 3):
for c i... |
9172c66c8e19cfa3853baf0d272a486cdf77f718 | SLongofono/EECS_563 | /sockets/client_TCP.py | 2,271 | 3.875 | 4 | """
client_TCP.py
This file demonstrates a simple TCP client which sends data to a remote server
and gathers the reply.
Usage:
python client_TCP.py --help
"""
import socket
import argparse
# Trims input to expected maximum size
def trim(myStr):
if len(myStr) > 2048:
print("Your input was large... |
619dfcbf7d14462729db2913a6611f93909047c0 | onurasln55/Data-Destruction | /license.py | 966 | 3.5 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()#main window
def page3():#next page
list = Listbox(root)
list.insert(END, "disk")
list.pack()
buttons["check"].pack_forget()
license.pack_forget()
def check(a):#license check
print("check ediliyor")
if license.get() != "":
... |
792ce39ea4286432cb7e6402548d447c844a45f4 | kbathina/sentiment-tools | /moodscores/afinn.py | 1,234 | 3.65625 | 4 | import afinn
import numpy as np
class Afinn(object):
def __init__(self):
"""
initilization of class
initializes Afinn
"""
self.afinn = afinn.Afinn()
def Score(self,tweet, calculation_type):
"""
Scoring function
Takes "Sum" or "Average" as in... |
c28ce5ef26fa0c3140585ba1176fdcd3ac6a7201 | Arbagen/algorythms | /search/binary_search_string.py | 987 | 3.828125 | 4 | def binary_search(list, target):
first = 0
last = len(list) - 1
while first <= last:
midpoint = (first + last) // 2
if list[midpoint] == target:
return midpoint
elif list[midpoint] < target:
first = midpoint + 1
else:
last = midpoint - 1
return None
names = ['Alanna Penton'... |
92c76c099515aedf73eb9303edc6f53902d43d34 | Nyyen8/Attendance | /Testing/PersonClassTests.py | 1,135 | 4.1875 | 4 | """
Program: PersonClassTests.py
Author: Paul Elsea
Last Modified: 07/31/2020
Program to define tests for person class.
"""
import unittest
from Classes.Person import Person as per
class PersonTestCases(unittest.TestCase):
'''Method to set up a test object'''
def setUp(self):
self.Person = per('Bob', ... |
48c59efbe0194e90ae5b2cea7ddca751b2056894 | Nyyen8/Attendance | /Testing/ValidationTests.py | 3,003 | 3.671875 | 4 | """
Program: ValidationTests.py
Author: Paul Elsea
Last Modified: 07/31/2020
Program to define tests for validation utilities.
"""
import unittest
from Validation import Utilities as util
class ValidationTestCases(unittest.TestCase):
'''Test to ensure valid_name_check returns proper bool'''
def test_valid_nam... |
06a385ab781fef9aa4768cab778853718571efef | ison-grazer/Advent-of-Code-19 | /Day One/Day1_part1.py | 661 | 3.640625 | 4 | import math
path_name = 'Day One/AoC_day1.txt'
def launch_module(mass):
fuel_rec = math.floor((mass / 3) - 2)
return fuel_rec
# Sums all separate fuel requirements in the list
def tot_fuel_required(lst):
all_fuel_rec = 0
for a in lst:
all_fuel_rec = all_fuel_rec + launch_module(a)
retur... |
81bf56e1a1b1ce4f8674bd15d4dc4c96d6444a08 | yitongw2/Code | /algorithm/graham_scan.py | 1,508 | 3.859375 | 4 | import __init__
import random
import stack
import matrix_determinant
class Point:
def __init__(self, x, y):
self.x=x
self.y=y
def makeMatrix(*points):
"""
create a 2D list representing an nx3 matrix given all
points.
"""
matrix=[]
for p in points:
matrix.append([p.x, p.y, 1])
return matrix
def grahamS... |
ed15a6e7422e0d85cd5a91582d84b283e479293d | yitongw2/Code | /algorithm/power_mod.py | 269 | 3.9375 | 4 |
def power_mod(x, y, z):
"""
x^y mod z
short cut: x^y ==> (x^(y/2))^2
"""
if y==0:
return 1%z
if y==1:
return x%z
a=power_mod(x, y//2, z)
if y%2==0:
return (a*a)%z
else:
return (x*a*a)%z
if __name__=="__main__":
print (power_mod(2, 4, 5))
|
63e7432fd34fb4e4421c79338a28ca48b37ed61e | yitongw2/Code | /algorithm/nextperm.py | 1,082 | 3.6875 | 4 |
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# k = the index before the longest non-increasing sequence
k = -1
for i in range(1, len(nums)):
if nums[i-1] < nums[i]:
... |
ba83e77e4c6ad556db182fab8a6c569e1216da5a | obit91/Wakeful | /src/facial_detection.py | 7,141 | 3.609375 | 4 | import cv2
from generate_eyes_model import WIDTH, HEIGHT, load_trained_model
import numpy as np
EYES_OPEN = 'open'
EYES_CLOSED = 'closed'
# The prediction threshold is very low because there are almost no false-positives for open eye detection, On the other
# hand, closed eye detection amounts to values far below 0.1... |
496c98807091afbe0e6bd225f95c477a4744029b | szagot/python-curso | /2-Básico/exercicios/5-Listas/2-Evitar-Duplicidade.py | 511 | 3.890625 | 4 | # Evitando duplicidades
valores = []
opcao = 'S'
while opcao != 'N':
valor = abs(int(input('Digite um valor a ser adicionado: ')))
if valor in valores:
print(f'O valor {valor} já foi adicionado anteriormente...')
else:
valores.append(valor)
print(f'O valor {valor} foi adicionado com ... |
0321b6367ef91d89f5ef6c103dc07f33e670b495 | szagot/python-curso | /blackjack/modulos/Card/__init__.py | 1,101 | 3.6875 | 4 | class Card:
symbols = ('♥', '♦', '♣', '♠')
numbers = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
def __init__(self, symbol, number):
self.symbol = symbol
self.number = number
def get(self):
return f'{self.symbol}{self.number:>2}'
def get_symbol(self)... |
80db55b945f0cfa879234476383bb80e357d5d91 | szagot/python-curso | /1-Iniciante/4-Modulos.py | 1,234 | 4.34375 | 4 | """
Para adicionar módulos ao Python, é necessário importar suas bibliotecas
isso é feito com o comando import. Exemplos:
import math # isso irá importar todas os módulos matematicos do Python
from math import sqrt # isso irá importar apenas o módulo sqrt da biblioteca math
fr... |
8b526089c3d68c71413dadc70e3dd6285cd1c581 | szagot/python-curso | /2-Básico/9-Funcoes-Avancado.py | 1,851 | 4.5 | 4 | # Variáveis criadas no corpos do programa são globais por padrão.
# As criadas dentro de uma função, são locais
# Se for criada em uma função uma variável já existente no escopo global,
# ela não irá afetar a variável global, a menos que antes se use, dentro da função, o comando:
# -> global variavel
#
# Os tipos de p... |
0b8000a830e715c595dc82c5569ec4e847e17439 | szagot/python-curso | /1-Iniciante/7-Cores-Terminal.py | 1,506 | 3.921875 | 4 | """
Mudando as cores do terminal com o padrão ANSI
Código ANSI para cores que funciona melhor pro Python: 033
Estilo ; Texto ; Background
\033[ 0 ; 33 ; 44 m
Códigos para Estilo:
0: None (Padrão se omitido)
1: Bold
4: Underline
7: Negative
Códigos para Texto:
3{cor}
Códigos para Fundo:
4{... |
19816984a87f59aad235286368c2a4aabaa8ea13 | szagot/python-curso | /2-Básico/exercicios/1-Condicoes-Aninhadas/2-Conversor-Bin-Octa-Hexa.py | 441 | 4.28125 | 4 | # Converte um decimal para Binario, Octadecimal ou Hexadecimal
base = int(input('Digite a base de conversão - (1) Binário | (2) Octal | (3) Hexadecimal: '))
num = int(input('Digite o número a ser convertido: '))
if base == 1:
print('Binário: {}'.format(bin(num)[2:]))
elif base == 2:
print('Octal: {}'.format(o... |
bc5eb21656a7ccef28765be64fd2d975296ec5f5 | szagot/python-curso | /2-Básico/exercicios/7-Dicionarios/1-Boletim.py | 1,155 | 3.734375 | 4 | # Boletim
tela = 40
print('#' * tela)
print(f'#{"Boletim - Entrada de dados":^{tela - 2}}#')
print('#' * tela, end='\n\n')
alunos = []
aluno = {}
opcao = 's'
while opcao not in 'Nn':
aluno['nome'] = input('Nome: ').strip().title()
aluno['n1'] = float(input(f'Nota 1: ').strip())
aluno['n2'] = float(input(f... |
21d75ec89fca6c38de5a8284b4d55d978ed4eaa2 | szagot/python-curso | /1-Iniciante/exercicios/6-Condicionais/7-Aumento-Salario.py | 333 | 3.59375 | 4 | # Aumento de salário conforme taxa
limite = 1250
taxMin = 15
taxMax = 10
salario = float(input('Digite o salário do funcionário: '))
if salario > limite:
novoSalario = salario + (salario * taxMax / 100)
else:
novoSalario = salario + (salario * taxMin / 100)
print('Seu novo salário é R$ {:.2f}'.format(novoSa... |
715366dcdafeaa9f450ec2d8caf171ddcb0fbc32 | szagot/python-curso | /2-Básico/exercicios/1-Condicoes-Aninhadas/3-Definindo-Maior.py | 281 | 3.984375 | 4 | # Definindo qual número é maior
num1 = int(input('Número 1: '))
num2 = int(input('Número 2: '))
if num1 > num2:
print('O primeiro número é maior')
elif num2 > num1:
print('O segundo número é maior')
else:
print('Não existe número maior, ambos são iguais')
|
fbd8d93836f082d27edde76e8fd0596b116aafcd | szagot/python-curso | /1-Iniciante/exercicios/4-Modulos/5-Random-Lista.py | 262 | 3.734375 | 4 | from random import shuffle
aluno = [
input('Nome do aluno 1: '),
input('Nome do aluno 2: '),
input('Nome do aluno 3: '),
input('Nome do aluno 4: ')
]
# Embaralha a lista
shuffle(aluno)
print('A ordem de apresentação será {}'.format(aluno))
|
ecb928e947744d4bcde6f53a6144b5db457121af | szagot/python-curso | /1-Iniciante/exercicios/1-Interagindo-Usuario/2.py | 244 | 3.875 | 4 | # Solicitando data de nascimento separadamente e imprimindo formatado
print('===== DESAFIO 2 =====')
dia = input('Dia\n')
mes = input('Mês\n')
ano = input('Ano\n')
print('Você nasceu no dia {} de {} de {}, correto?'.format(dia, mes, ano))
|
34154da7a9255c2b041f225fbe2be6e64c10b9b1 | szagot/python-curso | /2-Básico/exercicios/3-Laco-While/3-PA.py | 378 | 3.78125 | 4 | # Progressão aritmética
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
termos = 10
qt = 0
while termos > 0:
qt += termos
for n in range(a1, a1 + (termos * r), r):
print(n, end=', ')
termos = int(input('... Quer ver mais quantos termos? '))
a1 = n + r
... |
c8051a075fe1839ce0269b97e744390795529342 | szagot/python-curso | /2-Básico/2-Laco-For.py | 887 | 4.1875 | 4 | """
Laço de repetição for com variavel de controle
# Repita o laço de 0 a 9. A cada repetição, variavel conterá o numero referente ao range em que o ponteiro estiver
for variavel in range(0,9):
comandos
comandos_fora_do_laço
O último índice do range será o índice de quebra, e, portanto, será ignorado
"""
# Impri... |
c7962d69882aef57cbd6c2fcd177d88c5c0ffba8 | Sedreh/python-course | /Task9.py | 7,104 | 3.5 | 4 | import os
class FileSystemError(Exception):
''' Class for errors in filesystem module '''
def __init__(self, message):
super(FileSystemError, self).__init__(message)
class FSItem(object):
def __init__(self, path):
''' Creates new FSItem instance by given path to file '''
... |
f9f43a53bea980c0cc9f151118d62ffc6d3c36d9 | ottoguz/My-first-steps-in-Python | /exercício004.py | 2,058 | 4.03125 | 4 | #EXERCÍCIO 4: LISTA DE CONTATOS DE TELEFONE EM ORDEM ALFABÉTICA + DICIONARIO DE MAIORES E MENORES DE IDADE
#Função para ordenar a lista de contatos em ordem alfabetica
#printa o nome, idade e o telefone de forma legível ao usuário
def ordena_printa(dado):
dado = sorted(dado, key=lambda nome: nome[0])
for... |
d8a14de2aca20325b637b174e7c29946bdaf1780 | KinggCode/Python-Files | /Assignments /Eugene_Parker_hwk3/countWords.py | 497 | 3.75 | 4 | #Eugene Parker
#Assignment 3
#Source : Programming for Cs by John Zella
def fileViewer():
filename = input("Enter the filename: ")
outputFile = input("Enter the dest file: ")
fileToken = open(filename,"r")
destFile = open(outputFile,"w")
view = fileToken.read()
wlist = view.split()
f... |
35d2a4e07859f43a1aba6e23b407e283cbabd92b | KinggCode/Python-Files | /code/Registrar/register.py | 2,272 | 3.71875 | 4 | import csv
class Registration:
def __init__(self,fname,lname,birthdate,phone,address,email,password,pin):
self.fname = fname
self.lname = lname
self.birthdate = birthdate
self.address = address
self.email = email
self.password = password
self.phone = phone
... |
64f07fcdab6adea9014d8e4d036883a454406d63 | KinggCode/Python-Files | /Reading Files/classTest.py | 816 | 3.96875 | 4 | class Person:
def __init__(self,fname,lname,age,height,weight):
self.fname = fname
self.lname = lname
self.age = age
self.height = height
self.weight = weight
def getFullname(self):
return self.fname + " " + self.lname
def getLname(self):
return self... |
8008e96481478ffe15cc18768c13bea2906d74bd | KinggCode/Python-Files | /Python Projects/PythonF/opperands/arithmeticoperator.py | 201 | 3.828125 | 4 | a,b = 10,5
print("Addition :", a + b)
print("Subtraction :", a - b)
print("Multiply :", a * b)
print("Division: ", a/b)
print("Modolus :", a%b)
print("Exponent :", a**b)
print("Int Division :", a//b)
|
9b1ec0e587fa4e9a74e36cd56886be0ccd96fad2 | KinggCode/Python-Files | /Python Projects/PythonF/basic/Assignments/Assignments2.py | 1,066 | 4.71875 | 5 | #Name = Eugene Parker
#Task : Created a list with three Countries in it.
# 1. Update the list
# 2. Remove any element using the indexing approach
# 3. Add a country in the middle of the list.
# * Do the same of set *
#Creating a country list
country_list = ["Algeria","Canada","Morocco"... |
70e2613d9613b3a4c455e597c413b9e6af030104 | KinggCode/Python-Files | /Python Projects/PythonF/Functions/calc.py | 132 | 3.703125 | 4 | def calc(a,b):
x = a + b
y = a - b
z = a * b
u = a / b
return x,y,z,u
result = calc(5,10)
print(result)
|
1d7a519575c80ea9b8a84fc60aa005a7a7e761e3 | KinggCode/Python-Files | /code/newexam.py | 972 | 3.75 | 4 | class Door:
def __init__(self,openDoor,lockedDoor):
self.openDoor = openDoor
self.lockedDoor = lockedDoor
def isLocked(self):
if(self.isLocked() == True & self.isOpen() == False):
return "Locked"
def isOpen(self):
return self.openDoor
def unlockDoor(self):... |
de78ff7c966ceb549a18ead89284756e452e449f | KinggCode/Python-Files | /Python Projects/PythonF/basic programs /areaofcircle.py | 134 | 4.25 | 4 | r = float(input("Enter the radius of the circle: "))
pi = 22/7
area = pi * (r**2)
print("The area of the circle is {}".format(area))
|
863e7095e0cadfdbc10e78dd698a74a26c896348 | KinggCode/Python-Files | /Classes/introclass.py | 556 | 3.59375 | 4 | import random as r
class Person:
def __init__(self,fullname,age,nickname):
self.fullname = fullname
self.age = age
self.nickname = nickname
def myfunc(self):
print("Hello my name is",self.fullname)
p1 = Person("Eugene Parker",22,"KP")
p2 = Person("Narnia Hull",20,"coolaid")
p3 ... |
dab46c99a75ccc610f766c9f0ae100a7f7081346 | KinggCode/Python-Files | /Python Projects/PythonF/Modules/mymath.py | 155 | 3.890625 | 4 | def sum(x,y):
return x + y
def diff(x,y):
return x - y
def even(x):
if(x%2== 0 ):
return "Even"
else:
return "Odd"
|
b2a41206f812075210a04ca1cb4ad5da4cec7a64 | KinggCode/Python-Files | /Python Projects/PythonF/List_Comprehension/cubes.py | 138 | 4 | 4 | '''lst = []
for x in range(11):
y = x ** 3
lst.append(y)
print(lst)'''
lst = []
lst=[x**3 for x in range(1,11)]
print(lst)
|
f392ae9ffc2c81c6033e3e3d3fd2c523122ff5e6 | KinggCode/Python-Files | /Assignments /Assignment 1/Kilometers2Miles.py | 1,130 | 4.125 | 4 | #Arthur : Eugene Parker
#Tasks : KiloMile is a program that converts distances in kilometers to miles
def Temperature():
print("KiloMile \n This program converts distances measured in kilometers to miles")
response1 = eval(input("Simulator Run Time: ")) #Program Runtime
response2=input("Do ... |
2d1783a8d63ec19ca208329648cf1034139408e4 | matramir/Python3-Scripts | /renameDates.py | 1,728 | 4 | 4 | #! python3
# renameDates.py - Renames filenames with American mm-dd-yyyy date format to european dd-mm-yyyy
# usage: renameDates.py <directory location>
import sys, os, shutil, re
if len(sys.argv) != 2:
print('Please enter the directory path when calling the script.')
print('python3 renameDates.py <directory... |
9f56cdc7f028214fd0d7e3929c3d0d35abb27e05 | bcgov/wps | /api/app/db/crud/stations.py | 2,600 | 3.53125 | 4 | """ Methods relating to reading station data from database.
"""
from datetime import datetime, timedelta, timezone
from sqlalchemy.orm import Session
from sqlalchemy.engine.cursor import CursorResult
from app.utils.time import get_hour_20
from sqlalchemy import text
def _get_noon_date(date_of_interest: datetime) -> d... |
987b9f5b207484e7ce22bb0e46f8bef56cb2432a | bcgov/wps | /api/app/utils/singleton.py | 1,175 | 3.5625 | 4 | """ Singleton utility class for creating a single instance of something """
class Singleton:
""" Non thread-safe singleton decorator.
Stolen from: https://stackoverflow.com/a/7346105
"""
def __init__(self, decorated):
self._decorated = decorated
self._instance = None
def inst... |
5cdb22a266c818fd5d36f051b0beb81e3d846f56 | yogif000/oop-nilai-mahasiswa-with-python | /Mahasiswa.py | 1,624 | 3.609375 | 4 | class Mahasiswa:
def __init__(self, nama, n_absen, n_tugas, n_uts, n_uas):
self.nama = nama
self.n_absen = n_absen
self.n_tugas = n_tugas
self.n_uts = n_uts
self.n_uas = n_uas
self.percentageAbsen = 0
self.percentageTugas = 0
self.percentageUts = 0
... |
0e4144e13e0c90a921d6f64a2d28c650f022b723 | Gsllchb/4interview-python | /src/merge_sort.py | 1,037 | 3.625 | 4 | import itertools
_THRESHOLD = 64
def merge_sort(arr, lo, hi):
if hi - lo <= _THRESHOLD:
_insert_sort(arr, lo, hi)
return
mi = (lo + hi) // 2
merge_sort(arr, lo, mi)
merge_sort(arr, mi, hi)
_merge(arr, lo, mi, hi)
def _insert_sort(arr, lo, hi):
for i in range(lo, hi):
... |
3a187eed540abd32bd84952333f0c595c5dce90c | Gsllchb/4interview-python | /src/trie_tree.py | 1,901 | 3.796875 | 4 | ALPHABET_SIZE = 26
FIRST_LETTER = 'a'
class TrieTree:
def __init__(self):
self._root = _TrieTreeNode()
self._size = 0
def insert(self, key: str) -> bool:
node = self._root
for char in key:
index = _char2index(char)
if node.children[index] is None:
... |
206d5be7acee78a62aba42941657d63a60d853c7 | tcrasset/Classification-algorithms | /knn.py | 3,427 | 4.3125 | 4 | """
University of Liege
ELEN0062 - Introduction to machine learning
Project 1 - Classification algorithms
"""
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
from data import make_dataset1, make_dataset2
from sklearn.neighbors import KNeighborsClassifier
from skle... |
0beb5a295e6066b6c9b7592a5368a818220789f4 | chanshik/problem-solving | /acmicpc/1157.py | 1,247 | 3.984375 | 4 | """
단어 공부
https://www.acmicpc.net/problem/1157
"""
import unittest
import sys
def find_most_alphabet(word):
alphabet = [0 for _ in range(26)]
for ch in word:
alphabet[ord(ch.upper()) - 65] += 1
answer = None
max_count = 0
for idx, count in enumerate(alphabet):
if count > max_cou... |
5b0df849640b0e7539b6a10813981a262b412b50 | gwylim/hexnet | /game.py | 4,073 | 3.921875 | 4 | import numpy
import sys
import random
def flip_move(move):
return move[1], move[0]
def new_board(size):
return numpy.zeros((2, size, size))
def make_move(board, move):
'''
Mutably make a move, flipping the board so that vertical is still the next
player to move.
'''
board[0,move[0],move[1... |
a17c7ad467595f243d4479da8a35c81fd6c4b5d2 | yingz1985/pythonTurtleGraphics | /expenditureChart.py | 2,917 | 4.21875 | 4 | #The purpose of this exercise is to create a column chart based on the user's entered values.
#Besides creating the columns, the program also highlights the value that has the largest value.
from turtle import*
bob= Turtle()
scr=bob.getscreen()
rent= int(scr.numinput("How much for rent?","How much will you spend on r... |
46af1263e553b62350ea55f891906e8529618e5d | nicogoulart/Learning-Python | /4_print.py | 4,589 | 3.984375 | 4 | var1 = 10
var2 = 8.55
var3 = 'a'
var4 = 'nicolas'
#Imprimindo algo na tela.
print("Isto é uma string que irá ser impressa na tela.\n")
#Colocando uma variável entre strings (separadas por vírgula) é possível chamar a variável e a imprimir na tela.
print("A variável var1 =", var1, "foi impressa na tela, e a variável v... |
f6d4586026c518b928a15802e249a0d62851a968 | KristinaBulatovic/ProsecnaTemperatura | /temperatura.py | 924 | 3.796875 | 4 | import txt
def main():
txt.txtFile()
while True:
try:
mesec = input("Izaberite mesec: ").lower()
folder = open(mesec + ".txt", "r")
except:
print("Unesite mesec!")
else:
break
temp = []
for i in folder:
te... |
0e583130c6225411d79ea27e4e8fd30196859e66 | jimmy-long/connect4-ai | /connect4.py | 7,217 | 4.03125 | 4 | import math
import numpy as np
RED = "R"
YELLOW = "Y"
EMPTY = None
BOARD_WIDTH = 7
BOARD_HEIGHT = 6
CENTER_WEIGHT = 3
MAX_THREE_IN_A_ROW_WEIGHT = 5
MAX_TWO_IN_A_ROW_WEIGHT = 2
MIN_THREE_IN_A_ROW_WEIGHT = -4
MIN_TWO_IN_A_ROW_WEIGHT = -1
def initial_board():
"""
Generates a 7x7 Conncet 4 board with no piece... |
5b3371770f329a6378cdb62fe5073d55487f40c1 | merianherrera/python-fundamentals-training | /Session 04/session_04.py | 884 | 3.6875 | 4 | # Decorators
def stars(func):
def wrapper(msj):
print("********")
func(msj)
print("********")
return wrapper
# Can also be written as hello = stars(hello)
@stars
def hello(msj):
print(msj)
hello("Hello world")
# Generators
def my_generator():
n = 1
print "this prints... |
ad28facebf0c1f2f6791d61ea805d4895ccadb87 | genaropass/Python-Ieetba | /pruebafecha.py | 514 | 3.921875 | 4 | import datetime
'''while True:
try:
fecha = input("Introducir Fecha dd-mm-aaaa: ")
fecha = datetime.datetime.strptime(fecha, "%d-%m-%Y")
break
except:
print ("Fecha incorrecta\n")
print(fecha)'''
def comprobar_fecha(fecha):
try:
datetime.datetime.strptime(fecha, ... |
87326df135d59037044955f31582f8472a2d1276 | MinardW/PythonRoad | /function.py | 819 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def Func(a,b,x):
if(x == 1):
print('{0}+{1}={2}'.format(a,b,a+b))
elif(x == 2):
print('{0}/{1}={2}'.format(a,b,a/b))
elif(x == 3):
print('{0}*{1}={2}'.format(a,b,a*b))
elif(x == 4):
print('{0}-{1}={2}'.format(a,b,a-b))
else:
print('Input Invail... |
dbf90ba509f6171973ded036d6a309e24e18bf43 | tuian/cipher | /solutions/prob5.py | 979 | 3.9375 | 4 | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 5
# Write the code to encrypt the string:
# Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal
# Under the key "ICE", using repeating-key XOR. It should come out to:
# 0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d6334... |
4b3764b29e8e9036ced9d00c41e9c31d877ac47d | hasirto/5 | /7.py | 196 | 3.90625 | 4 | metin=input("metni gir kardeşim")
yeni_metin=""
for harf in metin:
if harf not in yeni_metin and harf!=" ":
yeni_metin=yeni_metin+harf
print(yeni_metin)
print(len(yeni_metin)) |
d8e81e4d1b6c32fab3a115fbbf4b2d85e086b790 | mondolmridul007/Data-Structure-Algorithm-with-Python | /Data Structure & Algorithm with Python/Sorting/Radix Sort/radix_sort.py | 822 | 3.75 | 4 | def counting_sort(arr, d):
n = len(arr)
sorted_array = [0 for _ in range(n)]
count = [0 for _ in range(10)]
for i in range(0, n):
index = (arr[i] / d)
count[int(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i ... |
2a61b4fe763f328b6be6c8cb77b77921546a61be | simrann20/CodingPracticals | /Python Practicals/po.py | 48 | 3.515625 | 4 | a=[1,2,3,3,3,3,3,2]
for i in a:
print(i)
|
ec213609b16cddf0b4aecb1a647733ee5b57c24a | easyeah/githubtutorial | /Container/1.py | 263 | 3.546875 | 4 | print(type('easyeah'))
name = 'easyeah'
print(name)
print(type(['easyeah','leezche','graphittie']))
names = ['easyeah','leezche','graphittie']
print(names)
print(names[0])
print(names[1])
easyeah = ['programmer', 'seoul', 25, True]
easyeah[2] = 26
print(easyeah)
|
7c3f1be31b76c2889ac6336c21bccce912cbeb15 | league-python-student/level0-module5-Jorgie99 | /_01_function_writing/_c_obedient_turtle.py | 460 | 4.53125 | 5 | """
Make an obedient turtle that will obey commands to draw shapes.
"""
from tkinter import messagebox, simpledialog, Tk
import turtle
if __name__ == '__main__':
# TODO)
# 1. Create a turtle.
# 2. Write 3 method definitions for drawing a square, triangle, and
# circle.
# 3. Ask the user... |
bdf491085c9a2169006b66307b9072d7678251b6 | badouralix/daily-coding-problem | /day-52/main.py | 3,658 | 3.84375 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, key, value, prev=None, next=None):
self.key = key
self.value = value
self.prev = prev
self.next = next
def __str__(self):
output = ""
if self.prev is not None:
output += "> "
output += f"... |
cb0bc114ffd0a09e889d6642fd7b695e7df8d04d | scoutnolan/School | /GEN/ENG 101/Python/letters2ways.py | 1,439 | 3.890625 | 4 | import string
lc = list(string.ascii_lowercase)
v_list = []
c_list = []
for x in lc:
if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'):
v_list += x
else:
c_list += x
string = input('Please enter a string ')
v_count = 0 # initial vowel count
c_count = 0 # initial consonant count
ot... |
f677f59ee583019256b4b24aa1849787d2b5c078 | scoutnolan/School | /GEN/ENG 101/Python/pizza_io.py | 585 | 3.828125 | 4 | new_pizza=0
new_name_list=[]
new_topping_list=[]
slices=[]
while new_pizza<3:
new_name=input('Enter your name. ')
new_top=input('What do you like on your pizza? ')
s_pref=int(input('How many slices do you want? '))
new_name_list.append(new_name)
new_topping_list.append(new_top)
slice... |
eefce098bad92250a41ecc33a4ae07c7a865406c | scoutnolan/School | /GEN/ENG 101/Python/functionss.py | 1,240 | 4 | 4 | def greet1():
"""Display a simple greeting"""
print("Hello!")
greet1()
################################
def greet2(username):
"""DIsplay a simple greeting"""
print("Hello.", username.title() + "!")
greet2("Nolan")
################################
def pet_info(animal,name):
"""Display info a... |
ce4ec2916842cef0578665a4838f821d1fee8362 | scoutnolan/School | /GEN/ENG 101/Python/anderson-factors.py | 472 | 3.875 | 4 | ## Divisible by four and nine
# Nolan Anderson
# ENG 101
#3/6/2019
factors = [] # Empty list to put numbers into
for i in range(1,101,1): # range from 1-100, counting by 1. # i is the new variable
if i%4 == 0 or i%9 == 0: # If the remainders of i/4ori/9 = 0, do this.
factors.append(i) # Puts the numb... |
2b25f95f7c1eb512015812cf746bdf02a5b47e2d | Elvirangel/MyDicom | /Point.py | 248 | 3.65625 | 4 |
class Point:
def __init__(self,index,X,Y,pix):
self.index=index
self.x=X
self.y=Y
self.pix=pix
def displayPiont(self):
print("The point is:({},{},{},{})".format(self.index,self.x,self.y,self.pix))
|
17194bfc63648b1d938657f728691e8c34752be7 | katrinamariehh/Exercise03 | /calculator.py | 1,902 | 4.3125 | 4 | # take the input from the user
# tokenize the string
# evaluate the second and third tokens based on the first
from arithmetic import *
while True:
user_input = raw_input("> ")
command = user_input.split()
# need to deal with if command has more than two items
# need to deal with if command other than comma... |
069ceaf8bb374bbf2d7a43c7b6a1b684344d5994 | cermakondrej/aoc2020 | /2/silver.py | 295 | 3.515625 | 4 | valid = 0
for line in open('input.txt'):
line = line.strip()
numbers = line.split('-')
letter = line.split()[1][:1]
string = line.split(':')[1].strip()
cnt = string.count(letter)
if int(numbers[0]) <= cnt <= int(numbers[1].split()[0]):
valid += 1
print(valid)
|
5e66f9bb36b706350e0608aef38879b712c0ffa0 | kellyvonborstel/sorting | /mergesort.py | 3,271 | 3.890625 | 4 | # getInput code is partially based on code found here:
# https://www.w3resource.com/python-exercises/file/python-io-exercise-7.php
# getInput function takes a file name as input, reads the file one line at a
# time, and adds the contents of that line (converted from string of numbers to
# individual integers) to an ar... |
74981bf6b6d49c9b73d648c226f5b2a85d93c1f7 | ParvezAzizBoruah/traffic-sign-rec | /krs5.py | 1,810 | 3.546875 | 4 | #Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#Initialising the CNN
classifier = Sequential()
#1st Convolution with 32 filters
classifier.add(C... |
fbbb0cde12f2e3b436dace5137e2bce4a2fa7629 | shreeyash/LearningPython | /2.FormattingStrings.py | 537 | 4.0625 | 4 | '''
Author - Shreeyash Haritashya
Date - 29th June 2019
Description - Formatting Strings, using String interpolation
'''
#using f strings
x = 10
formatted = f"Your guess of {8} was incorrect!"
print(formatted)
#performing math inside {}
formatted = f"Your guess of {8 + 10} was incorrect!"
print(formatted)
#using ... |
61bd489af98005a6392d63f08368729abb5ebe45 | AHartNtkn/Intro-Python-II | /src/container.py | 190 | 3.546875 | 4 | class Container():
""" A generic class which can hold a list of items.
"""
def __init__(self, items = None):
if not items:
self.items = []
else:
self.items = items |
76c3c140727baebf48d5938a09299db1707cb5b1 | umang-sinha/virtual-assistant | /venv/Lib/site-packages/source.py | 422 | 4.09375 | 4 | """A simple function to print a list"""
def print_list(the_list,iden=False,level=0):
for each_item in the_list:
if isinstance(each_item,list):
print_list(each_item,iden,level+1)
else:
if iden:
for tab_stop in r... |
a47a48f6bbe70b5f4e824d50671f500f36c1ae8d | sudh29/Stack-Queues | /stack.py | 191 | 3.875 | 4 | # implement stack using deque LIFO
from collections import deque
q = deque()
q.append("a")
q.append("b")
q.append("c")
print("Queue")
print(q)
q.pop()
q.pop()
print("After pop")
print(q)
|
bf130b56b88bedc3a1920bfa1962140201b58ff6 | antholo/real-python-test | /sql/sqld.py | 553 | 3.796875 | 4 | # INSERT Command
import sqlite3
# create the connection object
connection = sqlite3.connect("new.db")
#cursor for executing SQL commands
cursor = connection.cursor()
try:
# insert data
cursor.execute("INSERT INTO populations VALUES('New York City', 'NY', 8200000)")
cursor.execute("INSERT INTO population... |
5ae55f28dc473efeef2aa80747bc79ae180af640 | FranklinMa810/MissedQuiz2015 | /Check_Function.py | 1,532 | 3.8125 | 4 |
def multiple(n, cards):
for c in cards:
if cards.count(c) == n: return c
return None
def flush(hand):
# check same suit
suits = [s for c, s in hand]
return len(set(suits)) == 1
def straight(cards):
# check a straight
return (max(cards ) -min(cards) == 4) and len(set(cards)) == 5
... |
a819f9c7ce91856c5f508f9911cc81a4b5a42c3d | iibrahimli/ai_final_project | /main_mlp.py | 4,912 | 3.984375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mlp import data, functions, metrics, network
np.random.seed(25)
# importing the dataset
"""
Chapter 1
1. We want to predict the attribute 'target'
2. Binary classification, since there are 2 possible cases (healthy or not)
3. 's... |
6c9d1e4710f618aca3e1a6e71c6b7f70542d7b2b | KirillA1702/KirillA | /module2_3.py | 426 | 4.09375 | 4 | months_by_season = {
'зима': [12, 1, 2],
'весна': [3, 4, 5],
'лето': [6, 7, 8],
'осень': [9, 10, 11]
}
num_month = int(input('Введите номер месяца: '))
answer = ''
for season in months_by_season:
if num_month in months_by_season[season]:
answer = season.capitalize()
break
else:
answer = ... |
5d2b4ac7b7aa5ba1d03d70e19da1efba29a322bb | KirillA1702/KirillA | /module5_5.py | 433 | 3.5 | 4 | with open('test5.txt', 'w', encoding='UTF-8') as f:
typing = 1
while typing:
str_int = input(': ')
f.write(str_int + ' ')
if str_int == ' ' or str_int == '':
typing = False
with open('test5.txt', 'r+', encoding='UTF-8') as f:
num = []
lines = f.readlines()
for li... |
fec3f464f95b6748bfce13f70c38a5f185903129 | dtran39/Programming_Preparation | /05_Stack/032_Longest_Valid_Parentheses/LongestValidParenthesis.py | 1,072 | 3.796875 | 4 | '''
Problem:
- Given a string containing just the characters '(' and ')',
- find the length of the longest valid (well-formed) parentheses substring.
----------------------------------------------------------------------------------------------------
Examples:
- For "(()", the longest valid parentheses substring i... |
3f76dbd84e430fe469a52f9fe733ab7e041d3daa | dtran39/Programming_Preparation | /01_Arrays/026_Remove_Duplicates_Sorted/RemoveDuplicateSorted.py | 1,388 | 3.921875 | 4 | '''
Problem:
- Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
---------------------------------------------------------------------------------------... |
753fbf834c8bc8683201e083175bcdb663a5a2dd | dtran39/Programming_Preparation | /01_Arrays/414_Third_Max_Number/thirdMaxNumber.py | 2,069 | 4.03125 | 4 | '''
Problem:
- Given a non-empty array of integers, return the third maximum number in this array.
If it does not exist, return the maximum number. The time complexity must be in O(n).
----------------------------------------------------------------------------------------------------
Examples:
Example 1:... |
15864442923bff61ff7693a1097f01ca9fe7bd73 | dtran39/Programming_Preparation | /04_Linked_List/Templates.py | 434 | 3.78125 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def arr_to_linked_list(arr):
dummy = ListNode(0)
ptr = dummy
arrLen = len(arr)
for a_num in arr:
ptr.next = ListNode(a_num)
ptr = ptr.next
return dummy.next
def to_str_linked_list(head):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.