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 |
|---|---|---|---|---|---|---|
cefe128d5308652f4d34d798336ef8e9219b273d | zekeriyaolke/phyton-introduction | /HomeWork/Final.py | 2,050 | 4.15625 | 4 | class RecipeItem:
def __init__(self, name, quantity):
self.name = name
self.quantity = quantity
class Recipe:
def __init__(self, name, items):
self.name = name
self.items = items
def cook(self):
recipeItems = [f"{i.name}({i.quantity})" for i in self.ite... |
9b70291e8bc2d7e8ef2da22a853f2d75266ad1cb | Gupta-sparsh/tkinter | /Input Fields.py | 420 | 4.0625 | 4 | #in this program we are using text fields to handle the inputs
from tkinter import *
root = Tk()
inp = Entry(root, width = 50)
inp.pack()
inp.insert(0,"Enter your year of brith : ")
def click():
out = "You are " + str(2020-int(inp.get())) + " years old."
label = Label(root,text=out)
label.pack()
myButton = Butt... |
8c8e9e603bb0158caba4f71ed1938b4d2d5767a8 | apopma/stats | /stats.py | 3,190 | 3.90625 | 4 | from math import sqrt
__author__ = 'Adam'
# Stats for Python 3.4.2
class Stats(object):
# Syntax: Stats([foo, bar, ...]).function()
def __init__(self, numbers):
self.numbers = numbers
self.sanity_check = True
# Some basic sanity t... |
c107c5ac3413f415b6b22106d1050c95ad8ba614 | amrsharaf/PAL | /src/preprocess.py | 1,114 | 3.5 | 4 | import argparse
# Parse command line flags
def parse_arguments():
ap = argparse.ArgumentParser()
ap.add_argument('--input', '-i', help='file name', required=True)
ap.add_argument('--output', '-o', help='output file', required=True)
return ap.parse_args()
def cleanup_line(line):
splits = line.strip... |
edff0ca72ec4f39965a19d30c1b438abb97ee38e | 42jpryor/projectEuler | /projectEuler/projects11-20/project19/app.py | 1,616 | 3.953125 | 4 | # coding=utf-8
# https://projecteuler.net/problem=19
# Counting Sundays
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which h... |
c1b6ca6583d5a75b56c23477b47c399465392371 | zerayh/Zeray | /geom_formulae.py | 8,492 | 4.28125 | 4 | __author__ = 'hagos'
from numpy import *
from numbers import Number
def area_circle(radius: Number) -> Number:
"""
Calculate area of a circle.
@param radius: the radius of circle
@return: the area (square units of radius)
>>>area_circle(3)
28.274333882308138
"""
return pi*radius**2
d... |
765e67c4dc7ddecc442ecdc69e67af694a139826 | lcabral37/masks | /imageProcessor.py | 6,433 | 3.640625 | 4 |
from PIL import Image, ImageDraw
import numpy
import face_recognition
class ImageProcessor:
"Contains sevelral methods to processes into finding faces within"
def __init__(self, image=None, nparray=None, filename=None, processing=1024):
"""class constructor
The constructor requires either the ... |
025cef1c313522611076b64b01a8019796f04029 | killernye/cs61a | /lectures/21.py | 4,549 | 3.703125 | 4 | class Tree:
def __init__(self, root, branches=[]):
self.root = root
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)
def __repr__(self):
if self.branches:
branch_str = ', ' + repr(self.branches)
else:
... |
25f7935ea41928b74a758d81f0fa91126df15a8b | killernye/cs61a | /lectures/07.py | 1,002 | 3.890625 | 4 | def cascade0(n):
print(n)
if (n >= 10):
cascade(n // 10)
print(n)
def cascade1(n):
"""Another form of cascade. This one will be longer but more clear."""
if n < 10:
print(n)
else:
print(n)
cascade(n//10)
print(n)
def inverse_cascade(n):
grow(n)
... |
e91ec89907074a03385082a1110441dd21b9d763 | sweta-chauhan/tic-tac-toe-game | /ai.py | 3,083 | 3.953125 | 4 | DIMENSION = 3
HUMAN = 'X'
COMPUTER = 'O'
def Is_board_Empty(board):
for i in range(DIMENSION):
for j in range(DIMENSION):
if(board[i][j]=='_'):
return True
return False
def check_board(board):
for row in range(DIMENSION):
if(board[row][0]==board[row][1] and board... |
c690de4fab1038c0f6ea95857716261ea0220fc2 | deyh2020/QAOA-MaxClique | /test.py | 172 | 3.953125 | 4 | myList= [1,5,5,5,5,1]
max1 = myList[0]
indexOfMax = 0
for i in range(1, len(myList)):
if myList[i] > max1:
max1 = myList[i]
indexOfMax = i
print(max1) |
4b2b49930bcdfaa9c4857829ace1117172c2224a | lagacemichel/RaspberryPiSpeaksArduino | /MorseCodeGenerator.py | 2,489 | 3.859375 | 4 | # Morse Code Generator Python Program that translates a
# text string to Morse Code and outputs it to a GPIO pin.
# This program is used as part of a demonstration to show
# connectivity between a Raspberry Pi and an Arduino UNO.
# It is associated with the Raspberry Pi Speaks Arduino
# blog post on https://lagace... |
ea796343109b21475bf13847eeabcba2f2eebe7d | suttidaiam/Assignment | /Assignment#2/Assignment2.py | 181 | 4 | 4 | # -*- coding: cp1252 -*-
#Assessment 2 (String Manipulation)
def FirstReverse(str):
rev_str = str[::-1]
return rev_str
str = raw_input("Input:")
print FirstReverse(str)
|
58319dd94fb7d331486e3416bc451f19b4e7a294 | balamurugan1999v/playerlevel | /swift3.py | 156 | 3.84375 | 4 | a=input()
for i in a:
o=ord(i)
if (o>=65 and o<88) or (o>=97 and o<120):
o=o+3
print(chr(o),end="")
else:
o=o-23
print(chr(o),end="")
|
f6b6c58ea3054982e5c90db92b72ba5a54b9d788 | padminibai/training | /python/new.py | 181 | 4.15625 | 4 | for word in 'apricots':
print('the word is :',word)
B=input("enter the char:")
if(B=='b'):
print("Blueberries")
elif(B=='c'):
print("Cherries")
else:
print("pls enter b or c:")
|
a277e4d579882e802e151ad8492c322f82ca12be | padminibai/training | /python/for.py | 155 | 3.984375 | 4 | days=['mon','tues','wednes','thurs','fri','satur','sun']
print(days[0:3])
print(days[3:])
print(days[4:6])
for days in days:
print('week days:',days)
|
f969dfec70b4d6a0fcdd0eb24ec00c6acec10e49 | padminibai/training | /python/dic.py | 101 | 3.640625 | 4 | dict={'name':'mahal','age':56,'class':'first'}
print("name:",dict['name'])
print("age:",dict['age'])
|
0d68551843d403dfe1ba8f923220c70937532eb0 | paradoxal/3.-linkedlist | /linkedlist MALLI.py | 2,810 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:File: linkedlist.py
:Author: <Your email>
:Date: <The date>
"""
class LinkedList:
"""
A doubly linked list object class.
The implementation makes use of a `ListNode` class that is used to
store the references from each node to its predecessor and follower
... |
60884b484bab43f5da46de6555db97edb50b0b3a | ICS3U-Programming-LiamC/Assign-03-Python | /bonus_salary.py | 2,638 | 3.953125 | 4 | #!/usr/bin/env python3
# Created by: Liam Csiffary
# Created on: May 11, 2021
# This program determines whether the number the user inputed was
# positive, negative, or 0
# this is the fucntion that does everything
def bonuses():
salary = (input("What is your salary: "))
years_worked = (input("How many years... |
d0e9ab7fa54ea487e8c6e487aa1cbb53ba6aebcf | Void137/test-python | /main.py | 107 | 3.796875 | 4 | a = 2
b = 3
s = a + b
print(f"результат {s}") # Результат 5
print("Hello world!")
|
f5b993a8beb2c44bc6072ef07d6a5eb96b38ea1e | samarth-singh-thakur/rc_car_Raspberry_Pi | /m.py | 1,835 | 3.609375 | 4 | # Python Script
# https://www.electronicshub.org/raspberry-pi-l298n-interface-tutorial-control-dc-motor-l298n-raspberry-pi/
import RPi.GPIO as GPIO
from time import sleep
in1 = 24
in2 = 23
in3 = 22
in0 = 25
temp1=1
GPIO.setmode(GPIO.BCM)
GPIO.setup(in1,GPIO.OUT)
GPIO.setup(in2,GPIO.OUT)
GPIO.setup(in3,GPIO... |
a95e837fad822e30f618e76db527a7081bace018 | ruslanchistov/My-site | /media/calculator.pyw | 10,082 | 3.953125 | 4 | """" Калькулятор """
import tkinter as tk
"""функция вывода на экран цифр"""
def add_digit(digit):
value = calc.get() # считываем данные с экрана калькулятора.
if value[0] == '0' and len(value) == 1 and digit != '.': # для удаления нуля перед вводом цифр.
va... |
81fe36735b80677a69cd5f1b229ba777cb0dcdf9 | santosh-srm/srm-pylearn | /28_max_of_three_numbers.py | 917 | 4.40625 | 4 | """28_max_of_three_numbers.py"""
print("----Finding max of 3 numbers----")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
if (num1 > num2):
if (num1 > num3):
print(f'The max number is {num1}')
else:
pr... |
ea71feb2281ff84f4af0461d38d8c236000aa1fb | santosh-srm/srm-pylearn | /24_conditional_operators.py | 736 | 4.03125 | 4 | """
24_conditional_operators.py.
== Equal to Operator
!= Not equal to Operator
< less than Operator
<= less than or equal to Operator
> greater than Operator
>= greater than or equal to Operator
"""
print('20 > 35', 20 > 35)
print('20 > 15', 20 > 15)
print('24 >= 24', 24>=24)
print('49 >= 55', 49>=55)
print('85 <= 99'... |
4d8aeca0237647aca35162c05d841e915175bde8 | santosh-srm/srm-pylearn | /7_arithmetic_operations.py | 727 | 3.71875 | 4 | """07 - Arithmetic_operations"""
a = 15
b = 2
sum = a + b
difference = a - b
product = a * b
division = a / b
remainder = a % b
a = 10
b = 5
sum = a + b
diff = a - b
product = a * b
div = a / b
mod = a%b
print (f'Sum of {a} and {b} ({a} + {b}) is = {sum}') # 10+5 = 15
print (f'Diff of {a} and {b} ({a} - {b}) is = {d... |
485638e90767c3729c2e58115078a84fba15158a | santosh-srm/srm-pylearn | /W03D01/32_multiplicationtable.py | 708 | 4.3125 | 4 | """Print a multiplication table."""
def main():
"""Printing Multiplication Table"""
print_table(2)
print_table(7)
print_table(13)
def print_table(n):
"""Print nth Multiplication Table"""
print(f"Table {n}")
for i in range(1, 11):
print(f'{n} * {i} = {n*i}')
print("\n")
main()
... |
fc999a6149bd663387a2080a931f62b06daff0f1 | santosh-srm/srm-pylearn | /18_compoundinterestpgm.py | 579 | 3.984375 | 4 | """18_compound_interest.py."""
p=int(input("Enter the principal amount: "))
r=float(input("Enter the rate of interst: "))
n=int(input("Enter the duration for which interest is applied per time period: "))
#t=int(input("Enter the number of time period elapsed: "))
rate=(1+r)**n
fv=p * rate
print(f"the compound intere... |
9fbcce04fb901867bc6073f89aa535e4f6536cbb | ljsmallwood/Module-4 | /module4a.py | 286 | 3.59375 | 4 | def hallsensor(input) #read from sensor
power = 16 #GPIO pin
while True
if input == GPIO.HIGH #if we get an 'on' reading
GPIO.output(power,GPIO.HIGH) #takes power pin and sets on
elif input == GPIO.LOW
GPIO.output(power,GPIO.LOW) #takes power pin and sets off
|
ce136243527956b696d20ee238fffe7d9bad7122 | alxpck/lpthw | /ex19.py | 931 | 3.84375 | 4 | # Define the cheese_and_crackers function
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
# Call the function with straight numbers as arg... |
023abc0ab1139fb0b66e8046cf2cd299d2a65a72 | alxpck/lpthw | /ex20.py | 1,019 | 4.0625 | 4 | # Import the sys module and the argv module
from sys import argv
# Set the args for argv
script, input_file = argv
# Define the print_all function
def print_all(f):
print f.read()
# Define the rewind function
def rewind(f):
# seek() moves around the file in bytes
f.seek(0) # seek(0) moves to the 0th byte
# Def... |
c1b3fb60f4bd7f38b72f262330e47fff87793d94 | santiagotoapanta6/DEBER_EJER10 | /ejer10.py | 2,585 | 3.65625 | 4 | from tkinter import *
import random
import time
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(10, 10, 60, 60, fill='blue')
self.canvas.move(self.id, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
... |
d0ac30ca59efefea381c1e40ccec1874e5da50ec | marcyheld/SI506 | /hangman.py | 2,691 | 4.09375 | 4 | def blanked(word, guesses):
returnString = ""
for char in word:
if char in guesses:
returnString += char
else:
returnString += "_"
return returnString
def health_prompt(currentHealth, maxHealth):
returnString = ""
if currentHealth == ... |
96d3e73073624cfbd006ef9c24b6e16f3634d7e2 | kudoo-cloud/timeseries-prediction | /generate/warehouse.py | 2,296 | 3.6875 | 4 | #!/usr/bin/python
# This script populates the WareHouse table with
# simulated data.
import os
import random
import requests
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
from zipfile import ZipFile
from dotenv import load_dotenv
import database
class WareHouse:
"""
This ... |
3321c945984e49408705fb32e5c11726d958ee4d | pelizaldeiv/python | /automate/hello_world.py | 317 | 4.0625 | 4 | #This program says hellow and asks for my name
print('Hello')
print('What is your name?')
myName=input()
print('Hello' + myName)
length=len(myName)
print('The length of your name is: ' + str(length) + ' characters')
print('What is your age?')
myAge=input()
print('You will be ' + str(int(myAge) + 1) + ' in a year')
|
76eb0249b1a88019a1a5036f28eec7bfb4b8620a | dlenwell/interview-prep-notes | /code-samples/python/linked_lists/quicksort.py | 2,182 | 4.09375 | 4 | """
Quick sort
this is a classic recursive quicksort method that uses recursion
basically it uses the last number in the sequence as a "pivot" and sorts
items that are less than the pivot in one group and more in another.
then concats sub calls of the two sides together. in the end you end up
with a sorted list.
"""... |
7c55973288c8e4ee84d4f8a3eef0718275273273 | dlenwell/interview-prep-notes | /code-samples/python/binary_search/binary_search_tree.py | 9,047 | 4.28125 | 4 | """
Binary Search Tree
"""
from ansimarkup import ansiprint as print
class Node():
"""
node object consists of three parts; value and, left and right children
"""
def __init__(self, value, parent=None):
"""
"""
self.value = value
self.left = None
self.right =... |
3c09976cfb901f5b38551a5e35a298019b3fad2a | dlenwell/interview-prep-notes | /code-samples/python/linked_lists/mergesort.py | 2,489 | 4.0625 | 4 | """
Merge Sort o(n*log^n)
uses 4 funcitons:
sort <- initial call kicks off the sort with the objects head
merge_sort <- recursive function that splits > sorts > merges
middle <- helper function to find the middle of the list
merge <- helper function to merge two lists in order
"""
import time
from base import Lin... |
8a8b90655fc27a1434364c3581fdb48792f07658 | dlenwell/interview-prep-notes | /code-samples/python/inverting_trees/invert.py | 1,913 | 4.25 | 4 | """
Tree inversion:
"""
from tree import Node, Tree
from collections import deque
class InvertTree(Tree):
"""
InvertTree Tree class extends the base Tree class and just adds the invert
functions.
This class includes a recursive and an iterative version of the function.
"""
def invert_aux(s... |
36971ab6b8c60ebcc14bb7e80e02aed12da59be3 | PoseTracking/PoseSimulator | /poseModel/Node.py | 1,186 | 3.515625 | 4 | class Node:
x = 0
y = 0
confidence = 0.0
id = -1
name = ""
nameList = ["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder", "LElbow", "LWrist", "RHip", "RKnee",
"RAnkle", "LHip", "LKnee", "LAnkle", "REye", "LEye", "REar", "LEar", "Background"]
def __init__(self, id):... |
c91a76b812699229b8a648cec8c278e8a5a1d802 | jorgejmt94/DFS_BFS_HillClimbing | /DFS-BFS-HillClimbing_n-ari.py | 5,273 | 3.921875 | 4 | import sys
import datetime
#
# BFS Algorithm
#
def BFS(root):
nodes = []
stack = [root] #ponemos el root en la cola
#el primer nodo sera el maximo y el minimo a la vez
min_node = stack[0]
max_node = stack[0]
while stack:
cur_node = stack[0]
print "Visiting node",str(... |
3648169455cc7807af0ca0333c64a103e1cdf0b8 | stephica/macchanger-1 | /macchanger.py | 1,143 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import random
import time
if os.geteuid() != 0:
print "You must be root to change the MAC address\n"
sys.exit(1)
def macchanger():
'''Returns a random MAC'''
# first byte must be even
chars = '0123456789ABCDEF'
MAC = random.c... |
7077f3af00c752930ee1da5d899b10daf0a79ca4 | chuc4/PokerBot-1 | /Poker/evalhand.py | 26,520 | 3.984375 | 4 | """
EvaluateHand
"""
class EvaluateHand:
"""
This is the EvaluateHand class. This class's sole purpose is to
evaluate the given hand. It runs an algorithm that checks to see
what is the best combination for the hand. Such combinations are
a Royal Flush, Two Pair, Straight Flush, Four of a Kind, etc... |
5d0a68a80a4c40d32d9733b51153813a8c5088c9 | madvn/TFSearch | /examples/MNIST/main.py | 2,974 | 3.5 | 4 | """
Another slightly more complex example involving the benchmark MNIST dataset
The goal here is to evolve the weights and biases for MNIST
This main script uses Network to convert genotype-phenotype and to evaluate
fitness
Author: Madhavun Candadai
Date Created: Sep 18, 2017
"""
import numpy as np
import tensorflow a... |
f5b3ba94a075adaa9e503183df5af9e4df687c29 | gaqzi/frankenstein | /mod/Guessing.py | 968 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
__author__ = 'Bjrn Andersson <gaqzi@sanitarium.se>'
__version__ = '1.0'
__copyright__ = 'Copyright (c) 2004, Bjrn Andersson'
__license__ = 'GNU GPL'
from re import search
class Guessing:
def __init__ (self, main_module):
self.main = main_module
self.load... |
d4943bbba8e666d8ef341fcd0ee503b585d8b426 | jtlai0921/MP31819_examples | /範例檔/ch08ok/prime.py | 305 | 3.78125 | 4 | import math
def is_prime(n):
i=2
while i<=math.sqrt(n):
if n % i == 0: # 如果整除,i是n的因數,回傳False
return False
i=i+1
return True
n = int(input('請輸入一個數字: '))
if is_prime(n):
print(n,'是質數')
else:
print(n,'不是質數')
|
8eb84820df10d6add7d890b6b751c60f5c711529 | lucassouzaspc/calculadora_trabalhista | /menu.py | 2,820 | 3.859375 | 4 | import inss as inss
import irpf as irpf
import ferias as ferias
import plr as plr
import salario_liquido as sl
def calculadora():
while True:
print(""" \n====== Menu de Opções: =======\n
0. Calcular desconto INSS
1. Calcular desconto IRPF
... |
a70d9adf9c41dcea63cb3ee9288549265421536b | KeiitiAle/Metodos-Numericos | /3/10.py | 1,803 | 3.5625 | 4 | # -*- coding: utf-8 -*-
'''
@file: 9.py
@date: 17th September 2017
@author: Carlos Adir (carlos.adir.leite@gmail.com)
@description: Algoritmo de Spline Cubico
'''
import sys
import aux
import numpy as np
import sympy as sp
def Separavel(sp, x):
if type(x) == np.ndarray:
n = len(x)
y = np.zeros(... |
5b92d5b97a3f0d81a13339d271312b7af2394321 | KeiitiAle/Metodos-Numericos | /4/geogebra/Interpolador.py | 1,362 | 3.71875 | 4 | '''
Como usar
Este é um algoritmo para calcular as funcoes interpoladoras para o geogebra
Se eu quero o 1_1.ggb, então eu coloco o = 0
Se eu quero o 2_1.ggb, então eu coloco o = 1
...
Se eu quero o 5_1.ggb, então eu coloco o = 4
'''
n = 3
a = 0
b = 1
o = 4
oldo = o
#f = sqrt(1+cos(x)^2)
if not o > 0:
o = 1
prin... |
0d7b1296151c16ff927bbd9d9265ae3424a845d5 | KeiitiAle/Metodos-Numericos | /2/4.py | 1,515 | 3.765625 | 4 | # -*- coding: utf-8 -*-
'''
@file: 4-Secant_method.py
@date: 17th July 2018
@author: Carlos Adir (carlos.adir.leite@gmail.com)
@description: Método da Secante
Este algoritmo descreve o método da secante.
Esee metodo da secante consiste em uma adaptação do método de Newton mas que aproxima a d... |
da9d235d2c26db945093380dd6a6b496c277aef4 | ajerit/python-projects | /laboratory1/Lab4/Lab04Ejercicio1.py | 1,190 | 3.890625 | 4 | #
# Adolfo Jeritson. 12-10523
#
# Descripcion: Dados los coeficientes de un polinomio, lo construye y
# muestra el grado del mismo
#
# 5/05/2015
#
# Variables
# coef : array(0,M] of int
# c: int
# M: int
# polinom: array[0, len(coef)+1) of str
# grado: int
# i: int
# Valores Iniciales
M = int(input("Introduza el val... |
4ea39cb7ac1c5285bff945eb40694885931c37b6 | ajerit/python-projects | /laboratory1/Lab6/Lab6Ejercicio1.py | 1,298 | 3.890625 | 4 | #
# Adolfo Jeritson. 12-10523
# 19/05/2015
#
# Descripcion: Chequear si una secuencia esta ordenada.
#
# Analisis descendente
def entradaSec(n: int) -> [int]:
# PRECONDICION: N > 1
# POSCONDICION: True
# var a:array[0,n) of int
# cota n - x
a = []
for x in range(n):
a.append(int(input("Ingrese elemento #"+str... |
d755ee086dd0b32b0b2c8c0a886136fe8044ba48 | ajerit/python-projects | /scripts/sumafactacotada.py | 697 | 3.953125 | 4 | # SUMA DE FACTORIALES
# ACOTADO DESDE UN I HASTA UN N DADOS
# USANDO ANALISIS DESCENDENTE
#
import math
N = int(input("Tope: "))
i = int(input("Inicio: "))
print("---")
def SumaFact(N, i):
def fact(x):
assert(x>=0)
x1 = x
num = 1
while x >= 1:
num = num*x
x = x - 1
assert(num == m... |
3b6a27260b1b2486e2cdd5bd1a4c84162a65981b | ajerit/python-projects | /sorting/project/sorts.py | 7,368 | 3.640625 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# Autores:
# Mathias San Miguel 13-11310
# Adolfo Jeritson 12-10523
limite = 15 #tamano (dado) minimo de subarreglo para ordenar con otro algoritmo diferente a insertionsort
############
#
# HeapSort
#
############
# Parametros: seq: Arreglo que representa un cuasi-heap... |
db9b1bc2388ac6a9645d929098e299ca9bd30cc9 | ajerit/python-projects | /laboratory1/Lab4/quiz-1210523.py | 785 | 3.96875 | 4 | # Adolfo Jeritson. 12-10523
#
# Descripcion: Calcular la aproximacion del logaritmo natural de un numero real
#
# 5/05/2015
#
# Variables
# N: real
# it: int
# suma: real
# aprox: real
# produc: real
# Valores Iniciales
print("CALCULO DEL VALOR APROXIMADO DE ln x")
N = float(input("Diga el numero x al que desea calcu... |
719ec4586871f33b5aa9e2fbb28f44d0b0a66b26 | ajerit/python-projects | /scripts/got_game.py | 12,374 | 3.90625 | 4 | #
# Adolfo Jeritson
# Example of a adventure-type game with game of thrones
# 2015
#
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 __ini... |
3110b65f4b971f4a2c2967f250e3a22afd73e8f0 | ajerit/python-projects | /sorting/binary.py | 451 | 4.15625 | 4 | #
# Adolfo Jeritson
# Binary search implementation
# 2016
#
# inputs: A: Array of elements
# x: Target element
# returns None if the element is not found
# the position in the array if the element is found
def binarySearch(A, x):
start = 0
end = len(A)
while start < end:
mid = end + (start-end) ... |
8cccea64eff990dbda89bc32a04997116bcf00f4 | ajerit/python-projects | /adt/queue.py | 2,167 | 3.984375 | 4 | #!/usr/bin/env python
#
# Descripcion: Implementacion del TAD Cola usando
# listas enlazadas
#
# Autor: Federico Flaviani
# Autor: Adolfo Jeritson
#
from linkedList import ListNode, ListIterator
# Descripcion: Clase que implementa una cola usando listas enlazadas
# Atributos: _qhead: atributo privado q... |
ea30d850e5f06ac21da9ef24a9f1e4d6cade3401 | Anupama-Regi/python_lab | /24-color1_not_in_color2.py | 235 | 4.1875 | 4 | print("Program that prints out all colors from color-list1 not contained in color-list2")
l=input("Enter list1 of colors : ")
l2=input("Enter list2 of colors : ")
a=l.split()
b=l2.split()
l3=[i for i in a if i not in b]
print(l3) |
674392160a40f2309d6542271f2325d25bd5abc8 | Anupama-Regi/python_lab | /28-remove_even_numbers.py | 315 | 4.21875 | 4 | print("*Program to create a list removing even numbers from a list of integers.*")
n=input("Enter the list of integers : ")
l=list(map(int,n.split()))
print("List of numbers : ",l)
#l2=[i for i in l if i%2!=0]
#print(l2)
for i in l:
if(i%2==0):
l.remove(i)
print("List after removing even numbers : ",l) |
02cfdf0ea51f84c61af9f5fab573f94e0e440937 | Anupama-Regi/python_lab | /Cycle_4-python-Anupama_Regi/bank_account.py | 1,250 | 4.03125 | 4 | class bank:
def __init__(self,n,acno,t,a):
self.name=n
self.ac=acno
self.type=t
self.amount=a
def display(self):
print("\nDETAILS :\n\nName : ",self.name,"\nAccount no. : ",self.ac,"\nAccount type : ",self.type,"\nAmount : ",self.amount)
def deposit(self,am):
self.am=am
print("Total amount : ... |
7f902eb622852e3435c85d96ab00338b215a3f1e | Anupama-Regi/python_lab | /Cycle_3-python-Anupama_Regi/15-factorial_using_function.py | 209 | 4.4375 | 4 | print("Program to find factorial using function")
def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
print("Factorial is ",f)
n=int(input("Enter the number to find factorial : "))
factorial(n)
|
fc4856ae2c16f50139ecec552062b52c8a480ce3 | silverstar03/nuguseyo | /Student.py | 1,190 | 3.625 | 4 | import datetime
class Student:
def __init__(self):
self.date=datetime.datetime.now().strftime('%Y-%m-%d')
self.name=''
self.number=0
self.student={}
self.today_count=0
def select(self, number):
self.file()
for v in self.student.keys():
if num... |
89acada2d332b59dea7dd433764aee87d9bc1796 | lponcec94/lab-data-vikings | /viking_clases.py | 1,991 | 3.59375 | 4 | import random
class Soldier:
def __init__(self, health, strength):
self.health = health
self.strength = strength
def attack(self):
return self.strength
def receive_damage(self, damage):
self.health -= damage
class Viking(Soldier):
def __init__(self, name, healt... |
e6cd95b4afa8919cfd20b371b6207b7bf62638c3 | sshwu/advent-of-code | /advent-of-code/AdapterArray.py | 2,010 | 3.6875 | 4 | import re
def quicksort (arr, left, right):
index = partition(arr, left, right)
if left < index - 1:
arr = quicksort(arr, left, index - 1)
if index < right:
arr = quicksort(arr, index, right)
return arr
def partition (arr, left, right):
pivot = arr[int((left+right)/2)]
while le... |
9c68bc27ba23b85a5a400da91ac481f778f0d3f4 | carlosefr/bpstat-api-scripts | /src/single_series_gdp.py | 3,652 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Plot a lone series from Bank of Portugal's statistics API.
#
# Note: This code is meant as an example and, in order to
# maximize readability, lacks proper error handling.
#
# Carlos Rodrigues <cefrodrigues@gmail.com>
#
import time
import requests
import pandas
... |
33213c025b71e3a6c350f781f8495794a9cccd80 | shahad-mahmud/problem_solving | /hackerrank/New_Keyboard.py | 803 | 3.59375 | 4 | st = input()
res = ''
HOME = 0
END = 1
BACK_SPACE = 2
HOME_CON = 3
index = 0
NUM_LOCK_ON = True
flag = END
for char in st:
if char == '<':
flag = HOME
index = 0
continue
if char == '>':
flag = END
continue
if char == '*':
res = res[:-1]
continue... |
48ae08491555336fd989828451207c2044544719 | 471644/Arrays_Strings_Math_CP | /Longest Substring Without Repeating Characters.py | 1,550 | 3.984375 | 4 | '''Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answe... |
d7a0b63e88fee2ce131db2a6335876a8d02655d1 | PacktPublishing/Mastering-IPython-4 | /Chapter 3/prog1.py | 610 | 3.6875 | 4 | import queue
import threading
def f(n, q):
curr = n
tmp = 1
while curr != 1:
tmp = tmp + 1
if curr % 2 == 1:
curr = 3 * curr + 1
else:
curr = curr/2
q.put(tmp)
def main( ):
sum = 0
q = Queue.Queue()
threads = []
for i in range(100):
... |
15525aac3f46226708568e3bed0416f553e5fd87 | borkarfaiz/python | /Python Tutorial/tp/tp_url_beautifulsoup.py | 846 | 3.578125 | 4 | import urllib.request
from bs4 import BeautifulSoup
#a = urllib.request.urlopen('https://www.w3.org/Style/Examples/011/firstcss.en.html')
#c = (a.read())
#print(c)
#print('\n\n\n\n\n\n\n\n\n\n\n\n\n')
b = html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's st... |
a933fcbbb78cfc63e0f02e520319c350d3d68713 | borkarfaiz/python | /Python Tutorial/fibo.py | 306 | 3.8125 | 4 | # fibonance numbers module
def fib(n):
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n):
a, b = 0, 1
rslt = []
while b < n:
rslt.append(b)
a, b = b, a + b
return rslt
if __name__ == '__main__':
import sys
fib(int(sys.argv[1]))
print(fib2(int(sys.argv[2])))
|
9c84952e67080dbb61e1bc8c19de869129090a67 | borkarfaiz/python | /Searching/binary.py | 367 | 3.78125 | 4 | def binarySearch(alist, item):
if len(alist) == 0:
return False
else:
midpoint = len(alist) // 2
if alist[midpoint] == item:
return midpoint
elif item < alist[midpoint]:
return binarySearch(alist[:midpoint],item)
else:
return binarySearch(alist[midpoint+1:], item)
a = [1, 4, 6, 12, 15, 17, 21, 25,... |
10c8ddc131128cc08d98033c80d062d4a09e1484 | inventionzhang/TensorFlowApplication | /tensorFlowApp/test/ReloadFunction2.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 定义在类的内部
class time:
# 构造函数
def __init__(self, hour=0, minutes=0, seconds=0):
self.hour = hour
self.minutes = minutes
self.seconds = seconds
# 函数的第一个参数是self,如果没有第二个参数,具体就用self.hour
def printTime(self, t):
print str(t.hour) + ":" + \
... |
be8eba674362698c834cd23fabd5b3b7ea8dfc41 | RumanAhmed/Projects | /Python/name, age function.py | 339 | 4.03125 | 4 | def printinfo( name,age ): # the function this code will perform
days=age*365 # the calculation it will perfrom to workout how many days i have been alive for
print ("Name: ", name)
print ("Age ", age)
print ('days ', days)
return;
printinfo( 'shuayb',20 )# this will print the variable which i... |
e59eb509420d978c7b8a8dcefb0c02e74cfda29e | Aqiil/enigma-machine | /enigma-machine.py | 40,180 | 3.765625 | 4 |
import time
import datetime
import sqlite3
from sqlite3 import Error
import os
import random
import re
import collections
class rotor:
def __init__(self, alphabet, notch, turnover, position, ringSetting):
"""Create new rotor"""
self._charAlphabet = alphabet #Initialises alphabet as tuple csv
... |
e0d9f160bddd7e0b3623e757be9c2757ba6725eb | cat-in-the-box/alysha-de-silva | /3_personality_quiz.py | 1,421 | 4.0625 | 4 | name = input("Hi! What's your name? ")
print ("Hello, "+name,"!")
age = input("How old are you? ")
print("\nYou're "+age,"""! That's awesome! Are you ready to get started? Let's find out whether you have more
introverted or extroverted tendencies!""")
total = 0
q1 = str.lower(input("Do you hate to go to big parties? Y... |
5905c3b2f9094ca85031b3df74dc45f77822853b | ereeshika/basicPython | /hype.py | 954 | 3.984375 | 4 | # select a random number from 1 to 10
# from random import seed
from random import randint
# seed random number generator
# seed(1)
# generate random number
n = randint(1, 10)
if n == 1:
print("Only you can change your life. No one else can do it for you")
elif n == 2:
print("Don't watch the clock; do what it ... |
59810bff4f65a4c6afc95e9f3416d8e8fe19919b | Razor00/random | /classic/misc/scripts/permutation.py | 152 | 3.5625 | 4 | #!/usr/bin/python
import itertools
N = int(raw_input())
for n in range(1, N+1):
for i in (itertools.product(['Y','N'], repeat=n)):
print "".join(i)
|
f10fba8484f40d395e19fae764216304d733db07 | nsaenzz/Rock-Paper-Scissors | /rock_paper_scissors.py | 2,266 | 3.71875 | 4 | import game
import random
import time
import humanPlayer
import randomPlayer
import cyclePlayer
import reflectPlayer
import rockPlayer
import oppositePlayer
"""This program plays a game of Rock, Paper,
Scissors between two selected Players (User or computer),
and reports both Player's scores each round."""
def selec... |
0d2b750d304eb5070e69b76e5215bffce500f5fa | Jazmein85/Python2 | /ejemplosqlite3.py | 1,147 | 3.59375 | 4 | from os import curdir
import sqlite3
import click
from click.termui import prompt
def crear_tabla(con, cursor):
try:
cursor.execute('CREATE TABLE employees(id integer PRIMARY KEY, nombre TEXT, apellido TEXT, salario REAL)')
con.commit()
except:
print('La tabla fue creada')
@c... |
761c7402b14ea4b389bd3a87c4b502404a5f2a71 | albusdunble1/Leetcode | /leet_code/easy/leet_isomorphic.py | 764 | 3.59375 | 4 | class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic1 = {}
dic2 = {}
if not(len(s) == len(t) and len(set(s)) == len(set(t))):
return False
for i in range... |
e170b209a42be410718977f4979a1d822403c196 | albusdunble1/Leetcode | /leet_code/easy/leet_sister.py | 676 | 3.78125 | 4 | class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
unique = set(candies)
if len(unique) >= len(candies) / 2:
return len(candies) / 2
else:
return len(unique)
... |
7c8ebeaf759a75f0b84971c89dd493d73db2afc8 | albusdunble1/Leetcode | /leet_code/easy/leet_flip.py | 749 | 3.5 | 4 | class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for img in A:
img.reverse()
for i in range(len(img)):
if img[i]:
img[i] = 0
... |
0040894ed7c4aa17def9b39fca839a78751ac0c5 | albusdunble1/Leetcode | /leet_code/easy/leet_days.py | 769 | 3.671875 | 4 | class Solution(object):
def dayOfYear(self, date):
"""
:type date: str
:rtype: int
"""
small = [4,6,9,11]
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:10])
output = 0
if year % 4 != 0:
... |
53541e942bec775a87d02e9c17b3ba877c2d0978 | albusdunble1/Leetcode | /emoji.py | 89 | 3.625 | 4 | for x in range(1,10):
print("v" * x)
x = 1
while x < 10:
print("x" * x)
x+=1 |
c66a96426fd1b25444cc77052d3f796227c95159 | albusdunble1/Leetcode | /leet_code/easy/leet_rotatestrings.py | 658 | 3.75 | 4 | class Solution(object):
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if not A and not B:
return True
elif not A or not B:
return False
indices =[]
letter = B[0]
... |
057a47ab1a8eaf165bcc6da7869f3ad71dbd21b2 | albusdunble1/Leetcode | /leet_code/easy/leet_reverseint.py | 827 | 3.53125 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if not x:
return 0
str_x = str(x)
prefix = ''
if str_x[0] == '-':
prefix = str_x[0]
str_x = str_x.replace(pref... |
2474322649710c15c26e0ce397f0794097c45d78 | albusdunble1/Leetcode | /rps_basic.py | 1,599 | 4.09375 | 4 | import random
print("...rock...")
print("...paper...")
print("...scissors...")
p1_score = 0
p2_score = 0
while True:
print(f"\nPlayer 1 Score: {p1_score} | Player 2 Score: {p2_score}\n")
player1 = input("(enter Player 1's choice): ").lower()
# player2 = input("(enter Player 2's choice): ")
player2 ... |
9e0509096d515ad3f9287fd34f2969d69a8a91d9 | albusdunble1/Leetcode | /bouncer.py | 273 | 3.984375 | 4 | print("How old are you?")
age = input()
if not age:
print("You trollin bro?")
else:
age = int(age)
if age >= 18 and age < 21:
print("Wristband")
elif age >= 21:
print("Drink, normal entry")
else:
print("Too young, sorry...")
|
bfea2f5b5643683d8505662896f21b40482d13f7 | dev7knight/phone-locator- | /phone_locator.py | 545 | 3.5625 | 4 | import phonenumbers
from phonenumbers import geocoder
from phonenumbers import carrier
from phonenumbers import timezone
while True:
number = input("please enter phone number with country code ")
ch_number = phonenumbers.parse(number, "CH")
print(geocoder.description_for_number(ch_number, "en... |
3d874770a147ceda0b3d62c380385d5292009d00 | ulissesg/oficina2018 | /exercicios1/exercicios1.py | 6,940 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
'''Importe outras bibliotecas abaixo'''
''' EXERCÍCIOS
Obrigatorio UTILIZAR RECEITA DE PROJETO!!!
Todos os testes devem ser feitos dentro da classe Tests no final do arquivo.
Faca os testes antes do codigo, conforme a receita de projeto e a tecnica TDD.
... |
c913f698e3470c87e7e67b0fec3bb2e4baaab8f0 | ulissesg/oficina2018 | /exercicios3/editor_de_texto.py | 2,448 | 3.703125 | 4 | '''
PROBLEMA:
Projete um programa de editor de texto simples (de uma linha).
O programa deve permitir que o usuário digite com o teclado, dando feedback imediato na tela.
Deve permitir, também, que o usuário conserte seu texto por meio da tecla 'backspace' (tecla de apagar texto).
DICA1: Muita atenção na análise de d... |
54c1bc7e8f9d226fb869cd0da58026cfb5b08d24 | Jazmany23/Codigos | /ciclos.py | 917 | 4.125 | 4 | # ciclos
class Ciclos:
def __init__(self,num1=0,num2=1):
self.numero1=num1
def usoWhile(self):
# ciclo reetitivo que se ejecuta por verdadero y sale por falso
car = input("Ingrese vocal: ")
car = car.lower()
while car not in('a','e','i','o','u'):
car = inpu... |
71c6c990cb067a053461d52af67c6a7f6bfa3c21 | crystalDf/Automate-the-Boring-Stuff-with-Python-Chapter-10-Debugging | /traceback_format.py | 262 | 3.65625 | 4 | import traceback
try:
raise Exception('This is the error message.')
except:
error_file = open('errorInfo.txt', 'w')
print(error_file.write(traceback.format_exc()))
error_file.close()
print('The traceback info was written to errorInfo.txt.')
|
3bf050700ee59e70d6fa1b5f41b4829a1b033df9 | horia94ro/python_fdm_26februarie | /day_2_part_1.py | 1,981 | 4.25 | 4 | print(7 >= 10)
print(10 != 12)
print(15 > 10)
a = 32
if (a >= 25 and a <= 30):
print("Number in the interval")
else:
if (a < 25):
print("Number is smaller than 25")
else:
print("Number is bigger than 30")
if a >= 25 and a <= 30:
print("Number in the interval")
elif a < 25:
print... |
29301b611a86cba01b722a78064de2c139139a7c | horia94ro/python_fdm_26februarie | /day_3_part_1.py | 3,030 | 4 | 4 | # my_list = [123, "some string", 15.7, True, "cat"]
# print(my_list[3]) #True
# print(my_list[2:])
#
#
# my_list[0] = "modified value"
# print(my_list)
# # print(my_list[99]) #IndexError since index 99 doesn't exist in my_list
# my_list.append("new value") #adding individual new values
# my_list.append(False)
#
# my_l... |
ffe5d18808d02effa7c6f953a25ea7ed7b023e4f | Woodforfood/learn_how_to_code | /Codewars/8kyu/Square(n)_Sum.py | 226 | 3.90625 | 4 | # Complete the squareSum/square_sum/SquareSum method so that
# it squares each number passed into it and then sums the results together.
def square_sum(numbers):
numbers = [i**2 for i in numbers]
return sum(numbers)
|
ac3ef1b204dc2e5be36f08d323737db025865c55 | Woodforfood/learn_how_to_code | /Codewars/7kyu/Find_the_capitals.py | 260 | 4.125 | 4 | # Write a function that takes a single string (word) as argument.
# The function must return an ordered list containing the indexes of all capital letters in the string.
def capitals(word):
return [i for i, letter in enumerate(word) if letter.isupper()]
|
cc0454ed477bc4f645dc1ba3bfee41ba44fcb42a | CarolineBmn/advanced-data-journalism | /assignments/scraping/scrapeassign.py | 1,839 | 3.671875 | 4 | #scraping assignment Caroline Bauman
import urllib2, csv
import mechanize
from bs4 import BeautifulSoup
#Get output file ready
output = open('output.csv', 'w')
writer = csv.writer(output)
br = mechanize.Browser()
br.open('http://enr.sos.mo.gov/EnrNet/CountyResults.aspx')
# Fill out the form
br.select_form(nr=0)
br.... |
1b5d4f9c9e03e13d181a634a91de20993bc8986a | saurabhpatel021/Sdemo | /python/py_basic all.py | 766 | 4.03125 | 4 | a=input("num of a=") #take input from user
b=input("num of b=") #take input from user
c=input("num of c=") #take input from user
d=input("num of d=") #take input from user
a=float(a) #convert into float
b=float(b) ... |
3478f44be1468ad83f9843cccc644fcf6c76c355 | mserce2/multiple-linear-regression | /multipleLinear.py | 636 | 3.515625 | 4 | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
df=pd.read_csv("multipleLinear.csv",sep=";")
x=df.iloc[:,[0,2]].values
y=df.maas.values.reshape(-1,1)
multiple_linear=LinearRegression()
multiple_linear.fit(x,y)
print("b0:",multiple_linear.intercept_)
print("b1,b2:",multiple_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.