blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fe1119b8a617a552ecaa3a972712ee048933ed23 | charleycodes/calculator-2 | /calculator.py | 1,450 | 4.21875 | 4 | """
calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic_further import *
# def evaluate_expression(user_string):
# pass
def prefix_calc():
while True:
user_input = raw_input("> ")
user_input_list = user_input.s... |
88ff9c59581adbb57f62ba4895a5e41457043090 | Kaushalmam/Searching-Techniques-in-AI | /AStar/src/Astar_search.py | 7,296 | 3.5625 | 4 | import random
import math
import time
import psutil
import os
from collections import deque
class Board:
def __init__(self, tiles): #Constructor that initialize the values to a Board type variable
self.size = int(math.sqrt(len(tiles)))
self.tiles = tiles
... |
d42ff36791d444fea6694d1b93c496e2a61e3339 | kyshel/chart-ocr | /util/snippets.py | 491 | 3.703125 | 4 |
# https://pythonexamples.org/python-opencv-cv2-resize-image/
import cv2
src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)
# percent by which the image is resized
scale_percent = 50
# calculate the 50 percent of original dimensions
width = int(src.shape[1] * scale_percent / 100)
height = ... |
f0a708fdca6cd5df4678ba51195f86701fce0c2d | Kalalie/introduction_to_python | /Python_Exercise/Lists_Exercise.py | 931 | 4.25 | 4 | #Q1
foods = [
"orange","apple","banana","strawberry","grape","blueberry",["carrot","cauliflower","pumpkin"],"passionfruit","mango","kiwifruit",
]
print(foods)
print(foods[0])
print(foods[2])
print(foods[-1])
print(foods[0:3])
print(foods[-3:])
print()
print(foods[6][-1])
print()
#Q2
mailing_list = [
["Roar... |
20ff12829a84496be78b8e03d1eb974a0d89ee1f | gringobrasiliero/Python-Camp | /Python Camp July 23/goFish.py | 2,781 | 3.765625 | 4 | from random import randint
face_cards = [ "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
deck = []
h_hand = []
c_hand= []
h_score = 0
c_score = 0
for i in face_cards:
deck.append(i)
deck.append(i)
deck.append(i)
deck.append(i)
#print(deck)
def deal():
global cards_left
x = 0
... |
26a7c9f348f9fe42e516d6f4eae99bc62a0197a6 | gringobrasiliero/Python-Camp | /Python Camp July 16/intro.py | 813 | 4.46875 | 4 |
# Pseudo Code
# get the marker
# stand up
# walk over to the board
# take off the cap of the marker
# place tip of marker against the board
# draw a horizontal line from left to right
# rotate the marker 90 degrees R
# draw a vertical line (Go forward)
# turn marker 90 degrees R
# draw another horizontal line from R ... |
5deff2ca3f804b7b8f6588ff95b59e0c6dd27c69 | gringobrasiliero/Python-Camp | /Students/AlexaEsdras/challenge.py | 487 | 3.609375 | 4 | from random import randint
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# for k in letters:
# for j in letters:
# for i in letters:
# print(i + j + k)
def randomLetters():
words = []
while x < 17576:
a = randint(0, 25)
b = randint(0, 25)
c = randint(0, 25)
wo... |
53071ceb5c0580a160fd40b839e555e4a0115869 | JKrymarys/sem1 | /AD/cats.py | 2,158 | 3.546875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as st
import pylab as py
#define statistical significance
alpha = 0.05
df = pd.read_csv('datasets/cats-data.csv', sep=",", index_col=0)
print(df)
df_female = df[df["Sex"] == "F"]
df_male = df[df["Sex"] == "M"]
def test_normal_... |
8200a40c56ecbf614ed4f724e06b2f915b5282c6 | Kodsport/swedish-olympiad-2015 | /katt/kohagen/data/generator_random.py | 454 | 3.65625 | 4 | #Usage: python generator_random.py n_min n_max r_min r_max seed
import random
import sys
if len(sys.argv) != 6:
print 'Wrong number of arguments'
sys.exit(1)
s = int(sys.argv[5])
random.seed(s)
n = random.randint(int(sys.argv[1]), int(sys.argv[2]))
r = random.randint(int(sys.argv[3]), int(sys.argv[4]))
m = in... |
be6e9ec77d2c5415bffd17f3d77bc1ac4e6fe3d1 | payneal/Programming-Katas | /Python_TDD_Katas/vendingMachine/vendingMachineTest.py | 13,344 | 3.671875 | 4 | # System test
import unittest
#so that I can test the money
from vendingMachine import machine
#so that I can make buys
from Products import products
#used for random testing
from random import randint
# create the test
test = machine()
# create the test that can test buying
test2 = machine()
#did this for new t... |
bde919f90d586ea97ac42d8a17faf40c4f45d891 | LauraValentinaGonzalezNeira/TrabajosPython | /py4_comprension/palabras.py | 166 | 3.75 | 4 | A=["comprension","lista","sumatoria","laura","palabras","operaciones","gonzalez","testamento","aun","trabajos","isabella"]
l="a"
[print(i) for i in A if l in i[-1:]] |
57acb62ffea43b37e4fff478a63f4d6ccafa6ad0 | LauraValentinaGonzalezNeira/TrabajosPython | /py2_retos1/reto20.py | 294 | 3.765625 | 4 |
def bisiesto(año):
cua=año%4
cien=año%100
cuatro=año%400
if cua==0:
if cien==0:
if cuatro==0:
print("El año es bisiesto")
else:
print("El año no es bisiesto")
else:
print("El año es bisiesto")
else:
print("El año no es bisiesto")
bisiesto(1985) |
2ea53f82c4637be1ec7cf2f5fc3e1c6619ca611e | LauraValentinaGonzalezNeira/TrabajosPython | /py6_retos2/reto09.py | 182 | 3.625 | 4 | num0=0
numf=50
pasos=3
suma =0
for i in range(num0, numf, pasos):
suma = suma + i
print(i)
print('La suma de los entre ',num0 ,' y ' , numf ,' con pasos de ',pasos,' es ',suma)
|
daacec3790f949f11980cacbe7876eb48e74d2a3 | dubonzi/estudos | /python/Lista2CT/exe8.py | 271 | 3.734375 | 4 | valor = input("Número de CAMISAS:")
x_camisa = int(valor)
valor = input("Número de CALÇAS:")
y_calca = int(valor)
valor = input("Número de SAPATOS:")
z_sapato = int(valor)
calculo = x_camisa*y_calca*z_sapato
print(f"Resultado:{calculo} combinações possíveis.") |
960123502e58aa1936100cd32db6b791a1bfda4a | dubonzi/estudos | /python/Lista2CT/exe10.py | 381 | 3.734375 | 4 | valor = input("Distância Percorrida (metros):")
corrida = float(valor)
valor = input("Tempo (segundos):")
tempo = float(valor)
delta_s = corrida - 0
delta_t = tempo - 0
vm = delta_s/delta_t
# CONVERSÃO m/s para km/h > MULTIPLICA POR 3,6
# CONVERSÃO km/h para m/s > DIVIDE POR 3,6
km = vm * 3.6
print(f"VELOCIDADE MÉD... |
513f4d07298e65e4dbaf5c3e2e3c13ed83431eb9 | Malfunction13/PySnake | /PySnake v1.py | 5,417 | 4.4375 | 4 |
"""A simple program that utilizes Turtle to create a snake game."""
import turtle
import time
import random
paused = False
running = True
body_parts = []
colors = ["red", "orange", "blue", "pink"]
"""Initialize game screen"""
window = turtle.Screen()
window.title("PySnake")
window.bgcolor("black"... |
16bf7cc5b4c2fa7499537a91f01e1597285898c0 | lauradiane/Coursework | /MIT/recursionExercises/ps5_recursion.py | 1,308 | 4.15625 | 4 | # 6.00x Problem Set 5
#
# Part 2 - RECURSION
#
# Problem 3: Recursive String Reversal
#
import string
def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are all... |
48400f39d88f4ed561f1ffc7aa7bbee195218b95 | Zatyi94/input_value | /input_value.py | 1,276 | 3.671875 | 4 | def jatek():
num = input("Irj be egy szamot: ")
# ez csak kipróbálás volt: print("A szam amit kaptam: {}".format(num))
try:
test_num = int(num)
test_num = test_num + 1
print('\n {}, én nyertem'.format(test_num))
except ValueError:
print('ez nem szám')
# jat... |
ae409fe1bedbd32731161a8f487398850dfdb26d | Chenhao4869/207-- | /2-1-207-drawPython.py | 517 | 3.625 | 4 | import turtle
def drawSnake(rad,angle,len,neckrad):
colors = ["red","orange","yellow","green","cyan","blue"]
for i in range(len):
turtle.color(colors[i])
turtle.circle(40,80)
turtle.circle(-40,80)
turtle.color("purple")
turtle.circle(40,80/2)
turtle.fd(rad)
turtle.circle(neckr... |
0e837085f39d64a564b5e6063cc08a2cb9274777 | yuyuefan002/DPtutorial | /72_edit_distance.py | 2,829 | 3.78125 | 4 | '''
At the first step, we should use a more straight forward
way to solve the problem, recursion is recommended. This
method is called use-it-or-lose-it. The idea is aligned
with the way you read the problem.
'''
class Solution:
def minDistance(self, word1, word2):
"""
:type word1: str
:typ... |
6b9cc71b2c2d5763b43294e2599e5a9888f01a3a | gregoryhooks/FarmersMarketRegister | /discountFunctions/BXGD.py | 1,312 | 3.890625 | 4 | # Buy X Products, get them all at any percentage off
# Written by Gregory Hooks
# Expected input: List of items in basket, the rule to define the discount
# Expected output: The total number of times the discount needs to be applied
# Verify that the requirements for product x is satisfied and return the approp... |
37d1c400ae7998ead8eeede359abb6fbf344e7ea | AndrewLighten/euler2 | /euler018.py | 2,291 | 3.59375 | 4 | import inspect
import os
from termcolor import colored
from timeit import default_timer as timer
def collapse(rows, n):
for i in range(len(rows[n])):
rows[n][i] += max(rows[n + 1][i], rows[n + 1][i + 1])
if len(rows[n]) == 1:
return rows[n][0]
else:
return collapse(rows, n - 1)
... |
40ba76c6d029b305ec289dff184ebe0789f68b45 | AndrewLighten/euler2 | /functions.py | 4,709 | 4.25 | 4 | import doctest
import math
from typing import List
def sum_digits(n: int) -> int:
"""
Sum the digits in a value.
>>> sum_digits(123)
6
>>> sum_digits(159)
15
:param n: The number whose digits we need to sum.
:return: The sum of the digits.
"""
return sum(int(x) for x in str(... |
ee44564e85e8696ac5c58e49ca4b7668544fa6f8 | AndrewLighten/euler2 | /euler020.py | 910 | 3.640625 | 4 | import inspect
import math
import os
from termcolor import colored
from timeit import default_timer as timer
from functions import sum_digits
def calculate():
"""
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum
of the digits in the number 10!... |
ad25743608ecc9a437fa04489d059842347cd1e3 | DrageonLee/wecode | /test.py | 195 | 3.859375 | 4 | def even_num() :
nums = [i for i in range(1,51)]
even_nums=[]
for i in nums :
if i%2 == 0:
even_nums.append(i)
return even_nums
print(even_num()) |
de6faffef418ba0ef826a33099ae44061a3491ef | ahmedazab888/scikit-design | /skdesign/power/means/means_base.py | 3,970 | 3.640625 | 4 | import math
from skdesign.power import (PowerBase,
is_integer,
is_numeric,
is_positive,
is_boolean)
import scipy.stats as stats
class MeansBase(PowerBase):
""" The base for means specific hypothesis obj... |
054536a386173f72e240925ac3a80ba9cf6619a4 | ahmedazab888/scikit-design | /skdesign/design/latin_squares.py | 8,229 | 4.25 | 4 | """ Functions of Latin Square and related designs """
import random
from math import floor
MAX_ITERATIONS = 10000
def latin_square(k, factor_labels=None, seed=None):
""" Creates a k by k Latin Square Design
A Latin Square design is a block design with 2 blocking factors. Each
blocking factor has the sa... |
cfe028ef50a174d54ebd1bd701090e81f4385850 | waws520waws/waws_spider | /urllib2_test/urllib2_test_5.py | 507 | 3.5625 | 4 | # encoding:utf-8
"""
解决编码问题:
有的浏览器不支持中文,必须要将中文转化成编码后的字符格式才能完成搜索功能
统一规范,编码解码
"""
# python2
import urllib
word = {"kw":"王伟"}
print(urllib.urlencode(word))
print(urllib.unquote(urllib.urlencode(word)))
"""
kw=%E7%8E%8B%E4%BC%9F
kw=王伟
"""
# python3
import urllib.parse
word = {"kw":"王伟"}
print(urllib.parse.url... |
bbe6f0a334750f4b6296bdb09a2fe2f91a84c1c0 | waws520waws/waws_spider | /bs4_test/bs4_test_2.py | 1,697 | 3.625 | 4 | #coding:utf-8
"""
极其常见:
1.标签
2.name,attrs
3.string
"""
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters;
and their name... |
3a1b0d4f2d4608402f494a72ddb726f6a5687828 | DamienLan/hangman-game | /main.py | 1,131 | 3.78125 | 4 | """
Main program for the "Jeu du Pendu"
"""
import argparse
import re
import modules.game as g
def parse_arguments():
"""parse argument function
"""
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--level")
return parser.parse_args()
def ask_new_letter():
"""
Ask a new let... |
b924546d24f2df2d8d1c5f26599944e88faf45eb | richchang0/euler | /problem5.py | 453 | 3.765625 | 4 | def brute(n):
num = 0
check_range = list(reversed(range(1,n+1)))
while True:
if num != 0 and check_divisible(num, check_range):
return num
else:
#num += n
num += 2520 #given smallest number divisible by 1-10.
#adding this makes this solution specific to inputing 20
d... |
446e5b87098e11b9317eb8899e1d46ac83e17c0f | purple828/python-auto | /logintest/login.py | 1,447 | 3.71875 | 4 | myfile = open("myfile.txt",'r')
lines =myfile.readlines()
context = [x.rstrip() for x in lines]
accounts = [x.split(':')[0] for x in context]
print('accounts----------{}'.format(accounts))
islogin = 1
oklogin = 0
while True:
if oklogin == 0:
if islogin == 4:
print("密码输入三次错误,再见")
bre... |
c3f9b4dde5cb54b2a39f5d0f713a082ce7255afb | SDhn2a/cs321 | /connect4/MCTS.py | 9,425 | 3.828125 | 4 | """
MCTS starter code. This is the only file you'll need to modify, although
you can take a look at game1.py to get a sense of how the game is structured.
@author Bryce Wiedenbeck
@author Anna Rafferty (adapted from original)
@author Dave Musicant (adapted for Python 3 and other changes)
"""
# These imports are used ... |
ab662e2f300fa846444763498724f6c2bfee422c | adithak/place | /bb.py | 178 | 3.5 | 4 | q,w = map(int,input().split())
a1=list(map(int,input().split()))
a2=list(map(int,input().split()))
if (all(x in a1 for x in a2)):
print("YES",end="")
else :
print("NO",end="")
|
c9fbfa7faa7dec769c376dd6be5c980819155242 | AdriAriasAlonso/Python | /Practica4/E3P4.py | 646 | 4.03125 | 4 | #Ejercicio 3 Practica 4: Adrián Arias
print ("Este programa puede calcular el area de un triangulo o de un cuadrado.\n")
a=input("Que area quieres calcular? Triangulo(T),o Cuadrado(C)\n")
if a!="C" and a!="T":
print("Tecla incorrecta")
if a=="T":
base=float(input("Dime la base de tu triangulo:\n"))
altura=f... |
8e7a1cace5fb3842b829960ba0c3e7baa0b889aa | AdriAriasAlonso/Python | /Practica5/E3P5.py | 271 | 3.765625 | 4 | #Ejercicio 3 Practica 5: Adrian Arias
n1=int(input("Porfavor, introduzca un número:\n"))
n2=int(input("Porfavor, introduzca otro numero mayor que el primero:\n"))
suma = n1
for i in range ((n1+1),(n2+1)):
suma = suma+i
print ("La suma desde", n1, "hasta", n2, "es", suma)
|
7d16ee3f194ddd59f6bbdc71110ab11125b1c0cc | AdriAriasAlonso/Python | /Practica5/E12P5.py | 374 | 3.65625 | 4 | #Ejercicio 12 Practica 5: Adrián Arias
"""Escribe un programa que pida un número y escriba si primo o no."""
n1=int(input("Escribe un número mayor que 1 y te diré si es primo o no:\n"))
patata = 0
for i in range (1,n1+1):
if n1%i==0:
patata = patata + 1
if patata == 2:
print ("El número", n1, "es prim... |
aadd396f3d0c805860c9ae8f400bf8ef17fdd564 | AdriAriasAlonso/Python | /Practica4/E1P4.py | 1,175 | 4.125 | 4 | #Ejercicio 1 Practica 4: Adrián Arias
print ("Este programa, dados 5 números,indica cual es el de mayor y el de menor valor. \n")
a=float(input("Introduce el primer número\n"))
b=float(input("Introduce el segundo número\n"))
c=float(input("Introduce el tercero número\n"))
d=float(input("Introduce el cuarto número\n"))
... |
27860ea192d01ca903dd0bb565e9afaec116d809 | bc2h-bis/CodeWars-Python | /8-kyu/simple-calculator.py | 1,873 | 4.78125 | 5 | # You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers.
# Your function will accept three arguments:
# The first and second argument should be numbers.
# The third argument should represent a sign indicating the operation to perform ... |
3eef0dcbeeb7ecec4ae68c0fa5ba095c1f18a986 | derekforesman/CMPSC-131 | /Python/cars.py | 568 | 4.125 | 4 | #!/usr/bin/env python3
people = int(input("How many people will be going? ")) # grab the number of people going
car = people % 5 # get the remainder of people divided by the max amount of people in a car
if car == 0: # check to see if people is divisible by 5
final = int(people / 5) # convert it to an integer
... |
f2ef91deeaee58a6cc89744881f3ec32ed529ce8 | nehayd/calculator | /main.py | 1,053 | 4.15625 | 4 | from replit import clear
from art import logo
def addition(n1, n2):
return n1 + n2
def subtraction(n1,n2):
return n1 - n2
def multiplication(n1,n2):
return n1 * n2
def division(n1,n2):
return n1 / n2
operations = {
"+" : addition,
"-" : subtraction,
"*" : multiplication,
"/" : division
}
def calcu... |
6faa3deaedcf872f9963f3fe91d61dc2a1d8ac6c | Johnsona8497/CIS-115 | /m2lab_Johnson.py | 694 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
M2LAB
Johnson
9/12/19
"""
##// M2LAB
##// Anthony Johnson
##// 9/12/19
##
##// Greet the user by name,
##// then tell them their age
##// on their next birthday
##
##//Declarations
##Declare string name
##Declare Interger age
##
##//Ask for their name
print("What is your... |
dc43e1941e83f78905c4212dd0f95f523a465b07 | dukedududu/yunsuanfu | /jjj.py | 231 | 3.828125 | 4 |
a=11;b=20
c=0
c=a+b
print('c的值为',c)
c=a-b
print('c的值为',c)
c=a//b #//是整除 ,/是除出来可以是小数
print('c的值为',c)
c=a**b
print('c的值为',c)
c=a/b
print('c的值为',c)
c=a*b
print('c的值为',c)
|
249b442622f5e8013854c4a804bde2896759dfd0 | MaduMitha-Ravi/ImageResizing | /Assignment1_Q3.py | 2,373 | 3.984375 | 4 | """
---------------------------------------------------------------------------------------------------------------
Author: Madu Mitha Ravi
Purpose: Assignment 1 - Question 3
Algorithm: Bit Masking
Description: Performs update to intensity level of an image
Time Taken: Takes less than 1 minute
-------------------------... |
9dc36068b504e71767d771ae0646fe8de50422e0 | LukasEder1/ML | /mnist/data_conversion.py | 592 | 3.671875 | 4 | from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
def convert_image_to_pixel(path):
img = Image.open(path).resize((28,28)).convert('L') # convert image to 8-bit grayscale
WIDTH, HEIGHT = img.size
data = list(img.getdata())
data = [data[offset:offset+WIDTH] for offset in range(... |
3f1e4bd303336d00765a673b99dfcd2fe2f533be | cirlabs/pairwise-mapreduce | /inv-index-mapper.py | 1,369 | 3.96875 | 4 | #!/usr/bin/python
import sys
def read_mapper_input(stdin):
"""
Generator to limit memory usage while reading input.
"""
for line in stdin:
yield line.rstrip()
def main():
"""
Takes input as a document ID and string of words and returns a list of term
counts, which will be consolid... |
e1bf67d32afe28a718b5bf781d03ef9d45c8c764 | aalorro/python-projects | /factorial.py | 373 | 4.375 | 4 | #!/usr/bin/python
# This python program executes the factorial of a given number
print("This python program calculates the factorial of a user input\n")
num_1 = int(input("Enter a positive integer to get its factorial: "))
init_num = num_1
num_2 = 1
while num_1 > 0:
num_2 *= num_1
num_1 -= 1
print("The fac... |
3dba6937c87418c6a2b70a22a1c483fe6ef65573 | GMarsh0218/AdventOfCode2020 | /Day3/day3.py | 684 | 3.796875 | 4 | with open("input.txt") as fo:
treeMap = [[c for c in line.rstrip()] for line in fo]
def traverseMap(slope):
pos = slope[0]
treesHit = 0
for i in range(slope[1], len(treeMap), slope[1]):
row = treeMap[i]
if row[pos] == "#":
treesHit += 1
pos = (pos + slope[0]) % len... |
1a8d70110baf01858814a0c567a385e473e381ca | davidmargolin/Mem-Track | /backend/vartable.py | 546 | 3.515625 | 4 | class VarTableException(Exception):
pass
class VarTable:
def __init__(self):
self.table = []
def getTable(self):
return self.table
def addVar(self, name, type, address, varCount):
self.table.append({"number": varCount, "name": name, "type": type, "address": address})
def ... |
a6eef891c3bec9747328e1726c86e59570b1969e | davidmargolin/Mem-Track | /backend/components.py | 2,944 | 3.59375 | 4 | class Function:
def __init__(self, returnType, functionName, parameter, instruction):
self.returnType_ = returnType
self.functionName_ = functionName
self.parameter_ = parameter
self.instruction_ = instruction
def get_object(self):
obj = {
'returnType': self.... |
924a950f09bd8ddbff4f5c9a4097c8454e2faa68 | redSlug/scrabble-ai | /ai.py | 2,197 | 3.609375 | 4 | import random, string
class Ai:
def __init__(self):
self.tiles = [random.choice(string.ascii_lowercase) for _ in range(7)]
def make_move(self, board):
pass
class Board:
def __init__(self):
self.rows = [[None] * 15 for _ in range(15)]
def print_b(self):
for row in self... |
98f41529b88659dfcf581c6d2ea9306ab75e0cc4 | sjtuzwj/PythonCrashCoursePractice | /Attack on Alien/ship.py | 1,700 | 3.609375 | 4 | #飞船的抽象
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""description of class"""
def __init__(self,aoa_settings,screen):
super().__init__()
self.screen=screen
self.image=pygame.image.load('images/ship.bmp')#返回表示飞船的surface
self.image=pygame.transform.s... |
be9bc74f8b06dec90f6de2746e84ed6455279c14 | mounatjar/figura | /figuras.py | 711 | 3.53125 | 4 | import math
class Figura():
def dame_perimetro(self):
print("Esta figura no tiene perímetro")
def dame_area(self):
print("Esta figura no tiene área")
class Cuadrado(Figura):
def __init__(self,lado):
self.lado = lado
def calculo_area(self):
return self.lado * self.lado
... |
e9bd2e585b706ce19b283976d96b77f9d07bc9d3 | myoder020/Projects | /Python/CalcNumsFirstFreqTwice.py | 633 | 3.703125 | 4 | f = open("numsToCalc.txt", "r");
num = 0;
freqList = [];
numList = [];
search = 0;
freqTwice = 0;
for x in f:
# print(int(x));
numList.append(int(x));
while search == 0:
for x in numList:
num += x;
# print(num);
if num == 0:
freqTwice = 0;
search = 1;
... |
8ec88710464a4a17487dc728cc8a294603ffcd65 | whitneysteward/blackjack_python | /blackjack1.py | 4,738 | 3.84375 | 4 | ''' Blackjack
rules: dealer freezes at 17, player plays until they reach 21 or bust (more than)
list of player
get name
Deck
cards
dealer
Deck
cards
face cards
value for cards
sum of cards
shuffle
'''
import random
class Card:
def __init__(self, value, suit):
self.va... |
cd66f36578a48510c4496ce7cae9aafa646ac206 | gambine/Introduction-to-AI | /extrapackage/kNearestNeighbours.py | 1,296 | 3.78125 | 4 | '''
COMP3308 Assignment 2
@cgoh2475
K-Nearest Neighbours Implementation based on Euclidean distance
'''
import math
# Calculates Euclidean distance between 2 instances t1 and t2.
def __euclidean(t1,t2):
d=0
l=len(t1)
if t1[l-1].strip()=="yes" or t1[l-1].strip()=="no":
l-=1
for i in range(l):
d+=(float(... |
c0c0a76ab57dea0cf1e4b6971360feb818b00c06 | aallooss/CSquared-2021 | /0_Comments.py | 428 | 3.96875 | 4 | # authored by >Haden Sangree< for >Coding with Character Camp<
# Lesson 0
# put a pound sign before the text to make a comment
# Comments help to explain to the code to a programmer
# they can also help is removing code for a couple moments to expirement the code
# CHALLENGE: Try commenting several rows at o... |
ff68a366076cefbbd8c19d21621ccf48fa0e7cf4 | aallooss/CSquared-2021 | /7_Loops.py | 275 | 3.9375 | 4 | # authored by >Haden Sangree< for >Coding with Character Camp<
# Lesson 7: Loops
# CHALLENGE:
string1 = input("Enter a string: ")
# i indicates the index you are calling
for i in range(len(string1)):
print("The Character at %d Index Position = %c" %(i, string1[i])) |
634ccce41e9ff165019466f044b9858fe1a919a6 | MD365/untitled | /ex43_classes.py | 3,154 | 3.75 | 4 | from sys import exit
from random import randint
class Scene(object):
'''场景'''
def enter(self):
print("this scene is not yet configured.subclass it and implement enter().")
exit(1)
class Engine(object):
'''引擎'''
def __init__(self,scene_map):
self.scene_map = scene_map
def... |
23d4817238b0ba9cb08f5875a6f4d6fe432b5176 | ntuan19/CSClass110 | /PlagiarismDetector.py | 6,931 | 4.03125 | 4 | #Part 1:
def rh_get_match(X, Y, k):
#created empy tuples list so later we can append values in
tuples = []
#we calculated the number of unique characters from two substrings X and Y.
#set() will provide the unique characters from input. For instance, x ="learninglearninghoc".
#set(x) will give onl... |
f7a6653a1231fff8c7cfd604ac37d99ebc4bfd6c | 07Satyam/Write-Text-on-images-in-real-time-using-OpenCV-Python | /Write Text on images in real-time using OpenCV-Python.py | 462 | 3.53125 | 4 | #Import OpenCV
import cv2
# Read the image
img = cv2.imread('P:\Sea.jpg')
# initialize counter
i = 0
while True:
# Display the image
cv2.imshow('Sea',img)
# wait for keypress
k = cv2.waitKey(0)
# specify the font and draw the key using puttext
font = cv2.FONT_HERSHEY_SIMPLEX
cv2... |
66ae021da5f8fbdf360a9fe36166d5df7a2335a7 | Vyshnavmt94/IOT | /client-server messenger/client.py | 651 | 3.6875 | 4 | # Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server
pri... |
9e2e5ae7618354e96816ce12878124a6683316ab | qwazzy1990/LeetCode | /MaxLengthOfWood/Solution.py | 1,318 | 3.671875 | 4 |
import os
import sys
import math
class Solution:
def __init__(self):
pass
def solution(self, dividends:[], k:int):
## Set the divisor to largest dividend +1
dividends.sort(reverse=True)
divisor = dividends[0]+1
##while the sum of the quotients i... |
e351ea32dac8931c9f3f777d06f2cb1ebb5c9b7c | jlucartc/MetodosNumericos20182 | /codigos_de_cada_membro/natan/eliminacaoGauss.py | 3,979 | 4 | 4 | def criar_vetor_b(n):
b = []
for i in range(n):
b.append(0)
return b
def printar_vetor(x,n):
'''
:param x: Vetor que será printado
:param n: tamanho do vetor
:return: None
'''
print("")
for i in range(n):
print("{:5}".format(x[i]))
print("")
return... |
c35a402c15bf99f960d004e332360461240d40c6 | cepedarod/adventofcode2020 | /challenge_8.py | 3,282 | 3.90625 | 4 | #!/usr/bin/python3
#-----------------------------------------------------
# Class that contains details about each instruction
class instruction(object):
def __init__(self, name, value):
self.name = name
self.value = value
self.excecuted = False
def flip(self):
if self.n... |
17d88c317da34cba963ec3c26bafafd50fe3d283 | emansuetti/Python-Challenge | /PyBank/main.py | 2,630 | 3.71875 | 4 | #importing the code modules
import os
import csv
#setting libraries and variables for place holders
profit_loss = []
month_name = []
changes = []
month_change = []
counter = 0
#opening the files needed for specific data
bank_data = os.path.join('.', 'Resources', 'budget_data.csv')
with open(bank_data, 'r') as csv... |
b6fbdb241183edb8de233c966e7484a3b22757c7 | Cameron-Cmmns/CP1404practicals | /prac_03/password_check.py | 566 | 4.125 | 4 | """
CP1401 - Prac_03
Password Check
"""
def main():
get_password()
def get_password():
password_input = input("Enter a password: ")
if check_password_length(password_input):
display_password(password_input)
else:
print("The password is too short")
def check_password_length(user_in... |
8f2a06fb0c83e1ba4c4b53b50644ab2e79a6cf10 | Cameron-Cmmns/CP1404practicals | /prac_05/emails.py | 843 | 3.890625 | 4 | """CP1404 - Practicals - prac_05
Emails
"""
def main():
email_to_name = {}
email = input("Email: ")
is_valid = True
while email != "":
name = get_name_from_email(email)
confirmation = input("Is this your name {}? (Y/n)".format(name)).lower()
# This if looks a little bad,... |
bda358136649bddd16e44b6e3122e8f97aff14d8 | hudaquresh/pythonDSRune | /sortingAndSearching/hashing/listing_1.py | 857 | 4.375 | 4 | '''We write a function called hash that takes a string and a table size and
returns the hash value in the range from 0 to tablesize - 1.'''
import unittest
def hash(aString, tableSize):
# Determines the sum of the ordinals of the string
# Returns the remainder of the ordinal value sum divided by tablesize
su... |
aea62d3118f59bb5af251f35721827348f349b61 | srireddy27/basics_Graph | /dfs.py | 738 | 3.734375 | 4 | from collections import defaultdict
class Graph:
dict1=defaultdict(list)
def addedge(self,u,v):
Graph.dict1[u].append(v)
def print(self):
return "Adjacency List for given is {}".format(list(Graph.dict1.items()))
def dfs(self,s):
visited=[0]*(len(Graph.dict1))
sel... |
ad45a54149e43b65fa4649888aafec4f627ed860 | AP-MI-2021/lab-3-emiliaimbrescu | /main.py | 5,710 | 4.03125 | 4 | # problema 10
def is_even(n: int) -> bool:
"""
Verifica daca numarul e par.
:param n: int, numarul verificat
:return: bool
"""
if n % 2 == 0:
return True
else:
return False
def get_longest_all_even(lst: list[int]) -> list[int]:
"""
Se afla secventa ce... |
3f03bf5ea99bde23ab796911c7f98d73cd4735b6 | arleybri18/holbertonschool-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 788 | 3.9375 | 4 | #!/usr/bin/python3
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
'''Class Rectangle inherit from BaseGeometry'''
def __init__(self, width, height):
'''init method
arg width (int): width of the rectangle
arg height (int): height of the rectangl... |
690382641232f0a674f253284634b5150517a935 | arleybri18/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 359 | 3.875 | 4 | #!/usr/bin/python3
class MyInt(int):
'''class MyInt inherit from int'''
def __init__(self, num):
'''init method'''
self.num = num
def __eq__(self, other):
'''overwrite eq method'''
return (self.num != other.num)
def __ne__(self, other):
'''overwrite ne method'''... |
449595b15bad36a65aee4c5751843a479bd732f8 | arleybri18/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,276 | 4.4375 | 4 | #!/usr/bin/python3
class Square:
"""Class with a instance private attribute, with optional value 0
validate type and value > to 0, send a message Error using raised
and define a method to calculate area of square
"""
def __init__(self, size=0, position=(0, 0)):
"""init method
... |
a64ad2f57ab0bd1bced210f6b3597fcec1c6c0b4 | offbr/Python | /pybasic/pack2/func7.py | 276 | 3.671875 | 4 | '''
Created on 2016. 10. 25.
재귀함수 : 함수가 자신을 호출 - 반복처리
'''
def Countdown(n):
if n == 0:
print('처리완료')
else:
print(n, end= ' ')
Countdown(n - 1) #이게 재귀
Countdown(5)
print()
print('다음 작업') |
a02698c97d287ca0ca8ffe78a7902b1af9a5d3d7 | austinpray/algorithms-reference | /knapsack/knapsack.py | 938 | 3.78125 | 4 | class Item:
def __init__(self, name, value, weight):
self.name = name
self.value = value
self.weight = weight
def density(self):
return self.value/self.weight
def __str__(self) -> str:
return '{}: value: {} weight: {}'.format(self.name, self.value, self.weight)
... |
d1f2e4c9fbcb510421987bfc05dc5f8524cfded6 | REAL-Pipetting/REinforced-Automaton-Learning-REAL-Pipetting | /examples/Beers_law/physics_models.py | 1,907 | 3.65625 | 4 | import numpy as np
def beers_law(solution, path_length, coeffs, min_wavelength, max_wavelength):
"""
Applys Beers-Lampert Law to get the total absorbtion
of a solution.
Inputs:
solution: Dictionary of the form Name->Concentration
path_length: float
coeffs: pd dataframe with column 'Waveleng... |
15dcac5383d05cea959eb887d2a2774caf31aaa5 | lastiz/alien_game | /settings.py | 1,174 | 3.75 | 4 | class Settings(object):
"""Класс для хранения всех настроек alien ware"""
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (1, 1, 1)
self.speed_ship = 3.5
self.bullet_speed_factor = 3
self.bullet_width = 3
se... |
ade51f4ef7c8d8d21023519b374c2eb5498b24a6 | HaosUtopia/e.on.a | /e.on.a/sleep_management/sleep_behavior.py | 532 | 3.546875 | 4 | import numpy as np
class Behavior:
'''
This class uses sensor data to train a marcov chain with deep learning, which
can represant humans behavior. The observed behavior can identify people and
give suggestion accordingly
'''
def __init__(self):
self.behavior = []#behavior mode... |
477ea4c0ef2493ad1e583a58eb2a9bfa1b7e396b | lucasklawrence/machine_learning | /classifiers/bayesian.py | 5,271 | 4.03125 | 4 | import numpy as np
class Bayesian:
"""
Algorithm from Introduction to Machine Learning (2nd edition) by Miroslav Kubat
Classification with Naive-Bayes Principle
Example to be described by x = (x1, ... , xn)
1. For each xi and for each class cj, calculate the condition probability P(xi | cj)
... |
fce01e358f14bf9cfb92191e5d08b0bf78c82a43 | kneth/FunStuff | /Misc/birthday.py | 165 | 3.53125 | 4 | import datetime
freq = []
for i in range(0, 7):
freq += [0]
for i in range(0, 100):
d = datetime.date(1969+i, 3, 12)
freq[d.weekday()] += 1
print(freq)
|
d3fb561480991456538cd4637bea004d23f5a4dc | ns408/practice_python | /book_python crash course/example_random.py | 615 | 3.6875 | 4 | #!/usr/bin/env python3
"""
Items which didn't fit anywhere else go in here.
"""
"""
\n - newline
\t - tab
"""
var = "myname\n\tFirstname\n\tLastname\nyourname"
print(var)
"""
rstrip()
lstrip()
strip()
"""
var_l = " string_with_space_on_left"
print(var_l)
print(var_l.lstrip())
var_r = "string_with_space_on_right "
pr... |
b38039e1aba097d6a6288d0b43009380d4d5afa4 | ns408/practice_python | /book_python crash course/02_lists.py | 2,090 | 4.65625 | 5 | #!/usr/bin/env python3
"""
Working with Python Lists
"""
summary = """
###### Summary ######
- lists usually contain more than one element so better name them plural. Eg: names, addresses
"""
print(summary)
alist = ["this", "that", "whatever", "whereever"]
print(f"Display the list: {alist}")
print(f"Display a single... |
20dfbc74a78196d86f51aee3e7905426eb1eb609 | ns408/practice_python | /book_python crash course/car.py | 1,469 | 4.46875 | 4 | #!/usr/bin/env python3
class Car:
"""Represent a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer = 0
def get_descriptive_name(self):
"""return a formatted name."""
long_name = f"{self.make} ... |
1c3558e408c9e5e00440365bbf1bd22b297abb50 | ns408/practice_python | /book_python crash course/11_testing_your_code/test_employee.py | 626 | 3.734375 | 4 | #!/usr/bin/env python
from employee import Employee
import unittest
class TestEmployee(unittest.TestCase):
"""Class to test methods within Employee Class"""
def setUp(self):
"""Define objects once for the test methods"""
self.an_employee = Employee('Jane', 'Doe', 5000)
def test_give_defa... |
2735ec8f7fa439e5e4de1964895857690e7b5e3d | Lyd1995/Python1 | /NearestPoints.py | 471 | 3.65625 | 4 | def distance(x1,y1,x2,y2):
return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)
def nearestPoints(points):
p1,p2=0,1
min_distance=distance(points[p1][0],points[p1][1],points[p2][0],points[p2][1])
for i in range(len(points)):
for j in range (i+1,len(points)):
d = distance(points[i][0], points[i][1... |
ccf8ee1cc85eb926cbad9143502bf29750a54017 | Lyd1995/Python1 | /ConvertColortoGrey.py | 3,696 | 3.890625 | 4 | # 将彩色图片转换为灰度图片
from graphics import *
def main():
# 创建彩色图片窗口
win = GraphWin("Color Image", 1500, 800)
win.setCoords(0.0, 0.0, 10.0, 10.0)
# 设置提示语
Text(Point(1, 9.5), "Enter name of image : ").draw(win)
inputText = Entry(Point(2, 9.5), 10) # 实体,可以接受键盘的输入
inputText.draw(win)
... |
27ede59a4240ea65507b9a4b132c01249efbbe19 | NicVG/curso1-miniproyecto2 | /miniproyecto2.py | 3,262 | 3.890625 | 4 | nombres=input("Ingrese los nombres de los jugadores de la siguiente manera:(nombre1) (nombre2)\n")
nombres_lista=nombres.split()
nombre1=nombres_lista[0][0:3].upper()
nombre2=nombres_lista[1][0:3].upper()
if nombre1==nombre2:
nombre2+="2"
print("\n")
print(nombre1+" 501")
print(nombre2+" 501\n")
... |
45247ef69547b1f1f7e94efb699f5158d510ebd3 | axelkennedal/kexjobbet | /playground/machine_learning/kNN/breast_cancer.py | 1,160 | 3.5625 | 4 | import numpy as np
from sklearn import preprocessing, neighbors
from sklearn.model_selection import train_test_split
import pandas as pd
def test_knn_cancer():
df = pd.read_csv("../test_data/breast-cancer-wisconsin.data")
# handle missing data in the dataset
df.replace('?', -99999, inplace=True)
# ig... |
ce7b5ebba8f345ab34b00bd6e6b2efdda8c8974a | calista95/Carelinx | /assignment1/assignment1.py | 2,973 | 3.890625 | 4 | import sys
#input: list of integer coin denominations and value desired
#output:
# if there is a solution, return a list of coins that make up the solution
# else, return an empty list
def amountToCoins(amount, denoms):
table = [[] for _ in range(amount+1)] #hash table to store the solution sets
... |
2f4c5bca8fdb67a8ea269039386c445e3c8c1135 | EUD-curso-python/control_de_flujo-Salvar3z | /control_de_flujo.py | 5,562 | 4.15625 | 4 |
"""Guarde en lista `naturales` los primeros 100 números naturales (desde el 1)
usando el bucle while
"""
naturales = []
a=1
while a < 101:
#print(a)
naturales.append(a)
a += 1
#print (naturales)
"""Guarde en `acumulado` una lista con el siguiente patrón:
['1','1 2','1 2 3','1 2 3 4','1 2 3 4 5',...,'...47 4... |
e6bc4d5bc963dd88a0151e0424d88d09719a7621 | pelonpelonete/PythonColaborativoV2 | /src/AntonioGzz90/clases_orientado_objeto.py | 1,044 | 3.734375 | 4 | #PRIMER CLASE
class Saludo():
def __init__ (self,persona,saludo):
self.persona = persona
self.saludo = saludo
def imprimirSaludo(self):
print(f"Hola {self.persona}, {self.saludo}")
#SEGUNDA CLASE
class Preferencia():
def __init__(self,primera,segunda,tercera):
self.pri... |
4bf9ba50026857e5f021525fe718774670034ec0 | pelonpelonete/PythonColaborativoV2 | /src/TheOmarNajera/clases.py | 1,052 | 3.6875 | 4 | class Cancion():
def __init__(self, nombre, cancion, duracion):
self.nombre = nombre
self.cancion = cancion
self.duracion = duracion
def imprimirinfo(self):
print(f"Nombre del artista: {self.nombre} \nNombre de la canción: {self.cancion} \nDuración: {self.duracion} min")
cl... |
cf84642d95a279de83cb0d8efd9eaea36494d1d9 | pelonpelonete/PythonColaborativoV2 | /src/Andres-Delgado0/clases.py | 940 | 3.953125 | 4 | class Humano():
def __init__(self, raza, nombre, estatura, edad):
self.raza = raza
self.nombre = nombre
self.estatura = estatura
self.edad = edad
def imprimirinfo(self):
print(f"Raza: {self.raza} Nombre: {self.nombre} Estatura: {self.estatura}cm Edad: {self.edad}años... |
b6c619039dc851a5748ea168f854dcdbb9a9f5be | Alexanderoneol/Lesson-1 | /Урок 1 задание 5.py | 1,006 | 4.0625 | 4 | revenue = float(input("Введите показатели выручки (рубли) - "))
cost_price = float(input("Введите показатели себестоимости (рубли) - "))
result = revenue - cost_price
if result > 0:
print(f"Отличный результат! Ваш бизнес принес прибыль {result} рублей!")
print(f"Рентабельность реализации составила {result / r... |
e288da15617a2fc2ca5fcebb4c577b52acf6c528 | Alexanderoneol/Lesson-1 | /Урок 2 задание 5.py | 344 | 3.75 | 4 | my_list = [9, 8, 7, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1]
new_number = int(input("Введите новый элемент для построения рейтинга при условии, что это натуральное число: "))
i = 0
for n in my_list:
if new_number <= n:
i += 1
my_list.insert(i, new_number)
print(my_list)
|
7ff58519873865a619bbaa579122ed4ff0ecda18 | Conor12345/Euler | /euler_1-40/venv/problem_19.py | 820 | 4.03125 | 4 | count = 0
# day 0 == monday, 6 == sunday
day = 5
date = 29
month = 12
year = 1900
while year < 2001:
# increment
day = (day + 1) % 7
date += 1
if month in [9,4,6,11] and date == 31: # 30 days
date = 1
month += 1
elif month == 2 and date > 27: # 29, 28 on leap years
# leap... |
9908a26f28642139642e6439a031cfa7290dbeff | Conor12345/Euler | /euler_1-40/venv/problem_38.py | 345 | 3.984375 | 4 | from functiones import *
largest = 0
num = 1
pan = ""
while True:
multiple = 2
pan = ""
pan += str(num)
while len(pan) < 9:
pan += str(num * multiple)
multiple += 1
num += 1
if len(pan) == 9 and isPandigital(pan,9):
if int(pan) > largest:
largest = int(pan)... |
7207f0334283b5f8345db45b287872d9947fb818 | Conor12345/Euler | /euler_1-40/venv/problem_7.py | 351 | 3.5 | 4 | import primefactors
def isPrimeNo(num1):
if len(primefactors.factorize(num1)) == 1:
return True
else:
return False
primeNo = 0
currentNum = 1
while True:
if isPrimeNo(currentNum):
primeNo += 1
print(primeNo, currentNum)
if primeNo == 10001:
print(currentNum)
... |
5e31d28480c1cda31915b49614207eb6ab8a0575 | Conor12345/Euler | /euler_1-40/venv/problem_9.py | 241 | 3.6875 | 4 | def pythag(a,b):
return (((a ** 2) + (b ** 2)) ** 0.5)
a = 2
b = 2
while True:
c = pythag(a,b)
if a + b + c == 1000 and c % 1 == 0:
print(a,b,c)
break
a += 1
if a == 999:
a = 2
b += 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.