blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
126fac3aba52940e7c6d68b6469b33a3687ec2fb | aaron-lee/mathmodule | /from math import constant.py | 257 | 4.15625 | 4 | from math import pi #importing only the pi constant from the module
def circumference(radius):
circum = 2*pi*radius #circumference formula
return circum
print("The circumference of circle with radius 20 is %f" % circumference(20))
|
2994075d9c7f2c3ec23c78dba932454f0a158f2f | Vachana1992/Python--Basic--Programs | /swapping.py | 121 | 3.90625 | 4 | a=int(input("enter a number"))
b=int(input("enter another number"))
print('unswapped=',a,b)
s=a
a=b
b=s
print (a,b) |
923f764e4486751490d26b8fc9e298d37fc99a96 | aafmj/TicTacToe_Alpha-Beta-Pruning | /TicTacToe.py | 4,979 | 3.78125 | 4 | class TicTocToe:
def __init__(self):
self.x_win = "X_WIN"
self.o_win = "O_WIN"
self.tie = "TIE"
self.board = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
self.player_turn = 'X'
def play(self):
while True:
... |
d94f6abbca81ab6e4a71372df4a0f4ab720a100a | nderkach/algorithmic-challenges | /max_profit.py | 433 | 3.734375 | 4 | def get_max_profit(a):
least_price = a[0]
max_profit = a[1] - a[0]
for cur_time, cur_price in enumerate(a[1:]):
max_profit = max(cur_price-least_price, max_profit)
least_price = min(cur_price, least_price)
return max_profit
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
stock_prices_yest... |
4fe23b91402689d50c3ef66efa208e8ecaedc8b0 | nderkach/algorithmic-challenges | /get_max_number.py | 435 | 3.59375 | 4 | def get_max_number(a):
print(a)
l = [a[0]]
for i in range(1, len(a)):
new_row = []
for el in l:
new_row.append(el + a[i])
new_row.append(el - a[i])
new_row.append(el * a[i])
if a[i] != 0:
new_row.append(el / a[i])
l = [m... |
e65362da9842fad8b898de770c5f2079e7ec21ef | nderkach/algorithmic-challenges | /find_parenthesis.py | 488 | 3.875 | 4 | def find_parenthesis(string, first):
count_opening = 0
for i, char in enumerate(string[first+1:]):
print(char, i)
if char == '(':
count_opening += 1
elif char == ')':
if count_opening == 0:
return i
else:
count_opening -... |
321d410f3cc0b433f27fb2aa41db17039aa320b5 | nderkach/algorithmic-challenges | /add_without_plus.py | 284 | 3.96875 | 4 | def add_without_plus(a, b):
add_without_carry = a ^ b
while a or b:
ca = a if a else 0
cb = b if b else 0
if (ca & 1) & (cb & 1):
carry = 1
else:
carry = 0
a >>= 1
b >>= 1
print(add_without_plus(3, 5)) |
084ae25866dbeaed7904de54f9da2e02a4efc3e6 | nderkach/algorithmic-challenges | /cakes.py | 562 | 3.53125 | 4 | def max_value(cake_tuples, capacity):
max_value = 0
cake_tuples = [c for c in cake_tuples if c[0] != 0]
cake_tuples.sort(key=lambda x: -x[1]/x[0])
current_capacity = 0
print(cake_tuples)
for t in cake_tuples:
while current_capacity + t[0] <= capacity:
max_value += t[1]
... |
f3029f13363729a0c038482798dd1a006701347f | nderkach/algorithmic-challenges | /min_tree.py | 499 | 3.65625 | 4 | class Node(object):
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def dfs(node):
if not node:
return
print(node.value, end=" ")
dfs(node.left)
dfs(node.right)
def bst_create(a, s, f):
if s >= f:
return None
p = (f +... |
5d6fd2e041c865c5eb1b27632bcf9aa6ffcf3d92 | nderkach/algorithmic-challenges | /drones.py | 304 | 3.53125 | 4 | from collections import Counter
# def find_unique(a):
# c = Counter(a)
# for key in c:
# if c[key] == 1:
# return key
# return None
def find_unique(a):
x = 0
for e in a:
x ^= e
return x
a = [15, 13, 19, 15, 21, 5, 5, 13, 21]
print(find_unique(a))
|
a564bccdddb5c58d4516e913abebb273567a3755 | nderkach/algorithmic-challenges | /linked_list_remove_middle.py | 650 | 3.984375 | 4 | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
def print_list(node):
while node.next:
print(node, end=" ")
node = node.next
print(node)
def remove_node(node):
prev = node
... |
2deade13cb79dd9964113a188396bebbb6f64b49 | nderkach/algorithmic-challenges | /square_areas.py | 1,149 | 3.53125 | 4 | class Solution(object):
def __init__(self):
self.max_size = 0
def get_square(self, matrix, srow, scolumn, size):
if srow > len(matrix) - size or scolumn > len(matrix[0]) - size:
return
for row in range(srow, srow+size):
for column in range(s... |
42f874a69acf79412e86b02b19d8aba5b402a8aa | nderkach/algorithmic-challenges | /graph.py | 1,389 | 3.734375 | 4 | from collections import deque
class Graph(object):
def __init__(self, nodes):
self.nodes = None
class Node(object):
def __init__ (self, name, children=[]):
self.name = name
self.children = children
self.visited = False
n1 = Node("A")
n2 = Node("B")
n3 = Node("C")
n4 = Node("D... |
7e70cce33783dbb35512e3a12528f32ebb296758 | nderkach/algorithmic-challenges | /most_distinct_path.py | 730 | 3.671875 | 4 | max_l = 1
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
n1 = Node(4)
n1.left = Node(5)
n1.left.left = Node(4)
n1.left.left.left = Node(7)
n1.right = Node(6)
n1.right.left = Node(1)
n1.right.right = Node(6)
d... |
120c416325481cb0828d720ada9d2a7b179cc77e | nderkach/algorithmic-challenges | /invert_tree.py | 692 | 3.8125 | 4 | from collections import deque
class Node(object):
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def __str__(self):
return str(self.val)
n1 = Node(4)
n1.left = Node(2)
n1.left.left = Node(1)
n1.left.right = Node(3)
n1.right = Node(7)
n1.right.l... |
3428f8b3c26a701d390038b3c4e9da2dd5bc287b | programmerpawn/SimpleTimer | /TotalTimer.py | 453 | 4 | 4 | import time
seconds = 0
minutes = 0
hours = 0
timeStart = input("Start timer? y/n ")
while timeStart != "n":
seconds += 1
time.sleep(1)
print(str(hours) + " Hrs " + str(minutes) + " min " + str(seconds) + " Sec ")
if seconds == 60:
seconds = 0
minutes += 1
#pri... |
4b18890c47bc8cd703b066c779594081436bdbf6 | teamneem/pythonclass | /Projects/proj09.py | 11,128 | 4.3125 | 4 | #/****************************************************************************
# Section 10
# Computer Project #9
#****************************************************************************/
#
#This is a program that is blackjack solitaire. It creates a tableau where
#the user can put dealt cards. After... |
1eba38a72a5777e42e51f82ad189db3764ca7689 | teamneem/pythonclass | /Projects/proj02.py | 2,144 | 4.65625 | 5 | #/****************************************************************************
# Section ?
# Computer Project #2
#****************************************************************************/
#Program to draw a pentagon
import turtle
import math
print 'This program will draw a congruent pentagon. Th... |
e12e3a63bb7af416d78dbe8d28f46b2f84c39e43 | 000DarkX/Examples | /json_example.py | 378 | 3.515625 | 4 | import json
weapons =[ {"name": "Sword", "attack": 5}, {"name": "hammer", "attack":7}]
print(weapons)
# saves weapons array into weapons.json
with open("weapons.json", "w") as f:
data = json.dumps(weapons)
f.write(data)
weapons = []
# loads weapons.json into weapons
with open("weapons.json") as f:
data... |
9abba75d1f7abcad0b1d4770e77b422f78d2a005 | civility0/tabula_recta | /tabula_recta.py | 1,235 | 4.09375 | 4 | import string
var=string.ascii_lowercase
list=[char for char in var]
ml="".join(list)
print("")
print(" tabula recta")
print("")
for i in range(0,26):
print(' '.join(ml[+i:]+ml[:+i]))
print("")
print("")
print("Spaces will be stripped from input")
print("Case will be converted to ... |
f54e5e1e9e61ea21a1642dc422f64d9656f43545 | stackSg/Nakatsu_TS | /DP_Nakatsu.py | 638 | 3.6875 | 4 | '''
i must be larger than s , i.e. i >= s
i < s is impossible
'''
str1 = "bcdabab"
str2 = "cbacbaaba"
def d(i, s):
if s == 0:
return 0
elif i < s or d(i - 1, s - 1) >=len(str2) :
return float('inf')
j = d(i - 1, s - 1) # lower bound
while str1[i - 1] != str2[j] and j < le... |
2f1ee905b39ea12a6175ec9404e31d4d3e4cface | anna1901/PythonCourses | /squaredraw.py | 934 | 3.859375 | 4 | import turtle
def customize_turtle(some_turtle, shape, color, speed):
some_turtle.shape(shape)
some_turtle.color(color)
some_turtle.speed(speed)
def draw_square(some_turtle):
for i in range(4):
some_turtle.forward(100)
some_turtle.right(90)
def draw_rectangle(some_turtle):
some_t... |
22cbf9e1eeeea93b5551fd38c52a436954e39047 | gabri3l0/ai-course | /vector-operations.py | 2,877 | 3.96875 | 4 | """ ia1.py
Este trabajo mostrara como con numpy puedes sumar,
restar, hacer traspuesta, multiplicar y sacar la
longitud de un vector por medio de numpy
Author: Gabriel Aldahir Lopez Soto
Email: gabriel.lopez@gmail.com
Institution: Universidad de Monterrey
First created: Thu 06 Feb, 2020
"... |
9efa93da2f4c0b385de6fe4261c3df1436763f14 | AnnetKabuye/Challenge-2-week-2 | /vowel_counter.py | 460 | 3.953125 | 4 |
def vowel_counter():
mystr = input("input a string of your choice")
mystr = mystr.casefold()
mystr_list= list(mystr)
vowels=['a','e','i','o', 'u']
count = 0
mystrVowel =[]
for j in mystr_list:
if j in vowels and j not in mystrVowel:
mystrVowel.append(j)
duplica... |
66ef82b509b7322690199ee2d8269fdb8ee25023 | SeleneGRdz/Actividad_4 | /mate.py | 1,657 | 3.984375 | 4 | from math import pi
import math
class Mate:
def cuadrado(self, x:int):
print("El area del cuadrado es: " +str(x * x))
def triangulo(self, x:int, y:int):
print("El area del triángulo es: "+str((x * y) / 2))
def circulo(self, x:int):
print("El area del círculo es: "+str(pi * x ** 2)... |
b4f42e587a09e5fff974fc00f645468a4d7ce5fb | sotdjin/PicFood | /web_dev/FP_user.py | 531 | 3.546875 | 4 | class PFUser:
username = ""
password = ""
food_ratings = {}
def __init__(self, username, password):
self.username = username
self.password = password
def display_user(self):
print "username:", self.username, " password:", self.password
def add_ratin... |
709c844400d5c0f182f20814c9b0b1727144f61a | nicolasferrari/Data-Analyst-Projects | /Working with Data Downloads/expulsions.py | 935 | 3.5625 | 4 | import pandas as pd
data = pd.read_csv("data/CRDC2013_14.csv",encoding="Latin-1")
#print(data["SCH_DISCWODIS_EXPWOE_HI_F"].sum())
#print(data["TOT_DISCWODIS_EXPZT_F"].sum())
expulsions = ["SCH_DISCWODIS_EXPWOE_HI_M",
"SCH_DISCWODIS_EXPWOE_HI_F","SCH_DISCWODIS_EXPWOE_AM_M",
"SCH_DISCWODIS_EXPWOE_AM_F","SCH_DISCWODIS_... |
28b56e2bde9637b6b3f230dc0532aa2420086923 | alioguzhanal/Homework | /HW-2.py | 394 | 3.9375 | 4 | import datetime
firstName = input("Adınızı giriniz: ")
lastName = input("Soyadınızı giriniz: ")
age = int(input("Yaşınızı giriniz: "))
dateOfBirth= input("Doğduğunuz yılı giriniz: ")
liste = [firstName, lastName, age, dateOfBirth]
print(liste)
if liste[2] <= 18 :
print("You can not go out because ... |
4a2dd635b536f0ce1f7be2cac11ed6b07c25ff87 | Giovanni-Venegas/Curso-python | /6. Colecciones en Python/7.1 05-Ejercicio-set.py | 724 | 4.25 | 4 | #set es una colección sin orden y sin índices, no permite elementos repetidos
#y los elementos no se pueden modificar, pero si agregar nuevos o eliminar
planetas = {"Marte", "Júpiter", "Venus"}
print(planetas)
#largo
print(len(planetas))
#revisar si un elemento está presente
print( "Marte" in planetas)
#agregar
planeta... |
4d73d78eac344d193b97874aba6547fa6cec7c80 | quodt/wunderpy | /wunderpy/cli/storage.py | 1,524 | 3.625 | 4 | '''Utility for storing a wunderlist token.'''
import json
import getpass
import os.path
from wunderpy import Wunderlist
try:
input = raw_input # python2.x
except NameError:
pass
def setup():
'''Prompt the user for a wunderlist login, authenticate
and save the token.
'''
def prompt_login()... |
28c58705dcb82a688e2e5b438687b8bbc1dd92b6 | ashalaby711/obds_training | /python_scripts/exercise1.py | 408 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
x = 1
string = "string example"
5>2
print(5>2)
print(x)
print(string)
while x < 11:
print(x)
x +=1
i = -1
while i > -11:
print(i)
i += -1
guess = int(input("Enter a number: "))
j = 0
for i in range(0, guess+1):
... |
cdc390af2912c1a0cb94d92ca084778c017692e2 | CoAxLab/azad | /azad/local_gym/wythoff.py | 6,450 | 3.546875 | 4 | from copy import deepcopy
from scipy.constants import golden
import numpy as np
import gym
def create_board(i, j, m, n):
"""Create a binary board, with position (i, j) marked."""
board = np.zeros((m, n))
board[i, j] = 1.0
return board
def create_cold_board(m, n, default=0.0, cold_value=1):
"""... |
97c275023ea49de56d1eaa92d368e32bc4499f01 | YoonHan/Algorithm | /python/Programmers/다리를 지나는 트럭/solution.py | 549 | 3.734375 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
answer = 0
waiting = deque(truck_weights)
passing = deque([0] * bridge_length)
weight_on_bridge = 0
while len(waiting) != 0:
answer += 1
weight_on_bridge -= passing.popleft()
if weight_on_bri... |
f5f513b868d66f57aad3158121a7146b9c5d4ff6 | YoonHan/Algorithm | /python/Programmers/소수찾기/solution.py | 663 | 3.671875 | 4 | from itertools import permutations
def prime_check(number):
if number == 0 or number == 1:
return False
is_prime = True
i = 2
while i**2 <= number:
if number % i == 0:
is_prime = False
break
i += 1
return is_prime
def solution(numbers):
answer ... |
5cd7f40d31bba4f51125bfac53b8694fc352e341 | nitr0313/euler_problem | /problem_4/main.py | 1,075 | 3.734375 | 4 |
def is_palindrome(st):
return st == st[::-1]
def main(dig):
x = y = int('1'+'0'*(dig-1))
stop = int('9'+'9'*(dig-1))
tmp = 0
results = 0
gg = []
for i in range(x,stop+1):
for j in range(y,stop+1):
tmp = i*j
if is_palindrome(str(tmp)):
gg.a... |
cf8c696818f4fc7a3262f22208aef8dd144400c1 | nitr0313/euler_problem | /problem_17/main.py | 2,747 | 3.5 | 4 |
DEBAG = False
TBL = {
0:"",
1:"one",
2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine",
10:"ten",
11:"eleven",
12:"twelve",
13:"thirteen",
14:"fourteen",
15:"fifteen",
16:"sixteen",
17:"seventeen",
18:"eighteen",
19:"nineteen",
20:"twenty",
30:"thirty",
40:"forty",
50:"fifty",
60:"sixty... |
fdbace294bc7f486cbe1d899501a8489d2dcf5d9 | NameZhangRan/Udacity | /Machine_Learning_Primary/03Linear_regresson/ppprint_python.py | 263 | 3.546875 | 4 | #-*-coding:utf-8-*-
def shape(M):
i = len(M)
j = len(M[0])
return i,j
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
import pprint
pp = pprint.PrettyPrinter(indent=1, width=20)
print '测试1.2 返回矩阵的行和列'
pp.pprint(B)
print(shape(B)) |
ad819aed136bc68e6dc0a5a1cb422a8b9e81dfbd | NameZhangRan/Udacity | /Machine_Learning_Primary/02Code/media.py | 631 | 3.96875 | 4 |
class Movie():
"""
Initialize the Movie class, and data points
title/storyline/poster_image/trailer
should be remember.
"""
def __init__(self, movie_title, movie_storyline,
poster_image, trailer_youtube):
"""
define the function init, initialize pieces of inform... |
a92ea01a4b55823a1cc6382dc96faa097c38ac62 | ca-sousa/py-guanabara | /exercicio/ex049.py | 137 | 4.0625 | 4 | num = int(input('Digite um numero para ver sua tabuada: '))
for n in range(1, 11):
print('{} x {:2} = {}'.format(num, n, (num * n))) |
d96e3e55822ba098149386e76b6c33e3acf9bc7b | ca-sousa/py-guanabara | /exercicio/ex034.py | 347 | 3.796875 | 4 | salario = float(input('Qual e o salario do Funcionario? R$ '))
if salario > 1250.00:
novo = salario + (salario * 0.10)
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora!'.format(salario, novo))
else:
novo = salario + (salario * 0.15)
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora... |
0ee0d9062b808f9eb210a09cfc4135d487a7cb1f | ca-sousa/py-guanabara | /exercicio/ex004.py | 353 | 3.828125 | 4 | var1 = input('Digite algo:')
print('O tipo e?', type(var1))
print('So tem espacos?', var1.isspace())
print('E um numero?', var1.isnumeric())
print('E alfabetico?', var1.isalpha())
print('E alfanumerico?', var1.isalnum())
print('Esta em maiuscula?', var1.isupper())
print('Esta em minuscula?', var1.islower())
print('Est... |
bb433f82a9722876ebf6656cd9021a1122951e14 | ca-sousa/py-guanabara | /exercicio/ex083.py | 333 | 3.75 | 4 | exp = input('Digite a expressao: ')
lista = []
for simb in exp:
if simb == '(':
lista.append('(')
elif simb == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
if len(lista) == 0:
print('Sua expressao esta valida!')
else:
print('Sua expressao e... |
d5eb7146faacc1648e98bde85c666a4f39531325 | ca-sousa/py-guanabara | /exercicio/ex050.py | 256 | 4.09375 | 4 | soma = 0
for n in range(0, 6):
num = int(input('Digite um numero inteiro: '))
if num % 2 == 0 :
soma += num
if soma == 0:
print('Nao foram escritos numeros pares')
else:
print('A soma dos numeros pares e igual a {}'.format(soma)) |
ba14a0d816d549d9a98baf888e0a0d2df9d6376c | ca-sousa/py-guanabara | /exercicio/ex025.py | 101 | 3.671875 | 4 | nome = input('Digite o seu nome completo: ')
print('Seu nome tem Silva? {}'.format('Silva' in nome)) |
719f5278dfc8d52c58d60c22ea58ca218598cbe6 | ca-sousa/py-guanabara | /exercicio/ex008.py | 250 | 3.859375 | 4 | dis = float(input('Uma distancia em metros:'))
km = dis / 1000
hm = dis / 100
dam = dis / 10
dm = dis * 10
cm = dis * 100
mm = dis * 1000
print('A medida de {} correspone a \n{}km\n{}hm\n{}dam\n{}dm\n{}cm\n{}mm'.format(dis, km, hm, dam, dm, cm, mm)) |
0ecfd83cbab8b4e7d931145b4683a50f6fc6cc95 | ca-sousa/py-guanabara | /exercicio/ex017.py | 193 | 3.59375 | 4 | import math
co = float(input('Qual o tamanho do cateto oposto: '))
ca = float(input('Qual o tamanho do cateto adjacente: '))
print('O hipotenusa vai medir {:.2f}'.format(math.hypot(ca, co))) |
f8a6d3f75253251c747a1187f62d5052460ca6b7 | ca-sousa/py-guanabara | /exercicio/ex069.py | 598 | 3.78125 | 4 | cont_id = cont_h = cont_m = 0
while True:
nome = input('Digite o nome: ')
idade = int(input('Digite a idade: '))
sexo = input('Digite o sexo: [M/F]').upper()
if idade > 18:
cont_id += 1
if sexo == 'M':
cont_h += 1
if sexo == 'F' and idade < 20:
cont_m += 1
res... |
3bf75989e878437e6cbaa2d238630d6d1e48ea78 | Lunatc/Desafio_Capgemini | /system.py | 1,764 | 3.75 | 4 | from datetime import datetime
import struct
def search(lista, nome):
for i in range(len(lista)):
if list[i] == nome:
return i
return -1
def new():
nome = input('Nome do anúncio:')
cliente = input('Escreva o nome do cliente:')
dia = input('Dia de início do anúncio:')
mes = input(... |
695e3b3d1563244e141461334ef8f54ce6561a47 | sandmgg/Portfolio | /hash map concordance table/concordance.py | 6,487 | 3.71875 | 4 | from hash_quad import *
import string
import os
class Concordance:
def __init__(self):
self.stop_table = None # hash table for stop words
self.concordance_table = None # hash table for concordance
def load_stop_table(self, filename):
""" Read stop words from inpu... |
7e5ddb61f59ede25bde1dead4937a2608e425536 | nonlinearcontrol/Machine-Learning | /A*/guess_maze_path_stop_if_blocked.py | 5,315 | 4.46875 | 4 | ########## guess_maze_path.py ##########
'''
- This script implements a path finding algorithm that takes its next step based on a minimized cost. End the path if the next step results in a higher cost
'''
#########
# imports
#########
from random import choice
from math import sqrt
###############... |
b6303509d11405e5e3a1533792300ac7133f36b7 | abnerrf/cursoPython3 | /2.pythonBasico/aula26/aula26.py | 159 | 3.640625 | 4 | '''
DESEMPACOTAMENTO DE LISTAS EM PYTHON
'''
lista = ['Luiz', 'João', 'Maria',1,2,3,4,5,6,7,8,9,100]
n1, n2, *outra_lista = lista
print(n1, n2, outra_lista) |
c7da80846085a4e3e54e4e949e67fbf3b366bfd4 | abnerrf/cursoPython3 | /2.pythonBasico/aula23/aula23.py | 328 | 3.875 | 4 | '''
LISTAS EM PYTHON
append, insert, pop, del, clear, extend, +
min, max
range
'''
# indice
# 0 1 2 3 4 5
lista = ['A', 'B', 'C', 'D', 'E', 10.5]
# -6 -5 -4 -3 -2 -1
lista[5] = 'Qualquer outra coisa.'
string = 'ABCDE'
print(lista[5])
print(string[1])
print(lista[1:4])
print(lis... |
df364a633145e4742ed9117caf8e5fd035e0b4a1 | abnerrf/cursoPython3 | /3.pythonIntermediario/aula9/aula9.py | 613 | 4.125 | 4 | '''
SETS EM PYTHON (CONJUNTOS)
add (adiciona), update (atualiza), clear, discard
union | (une)
intersection & (todos os elementos presentes nos dois sets)
difference - (elementos apenas no set da esquerda)
symmetric_difference ^ (elementos que estão nos dois sets, mas não em ambos)
'''
s1 = set()
s1.add(1)
s1.add(2)
s... |
bcb3c1ebb082c2dfea8e70a718f15b41f407cb6d | abnerrf/cursoPython3 | /2.pythonBasico/aula4/aula4.py | 499 | 3.65625 | 4 | '''
Tipos de dados
str - string - textos 'Assim' "Assim"
int - inteiro - 123456 0 -10 -20 -50 -60 -1500 1500
float - real/ponto flutuante - 10.50 1.5 -10.10 -50.93 0.0
bool - booleano/lógico - True or False - apenas 2 valores - 10 == 10 True?
'''
print('Abner', type('Abner'))
print(10, type(10))
print(25.23, type(25.23... |
11c11c814c2f833503bbea3fd4bcd90951af5a65 | iarzeno/MyFirstRepo | /list_ia.py | 792 | 4.125 | 4 | name = "Isa"
subjects = ["Math","French","English","Science"]
print("My name is " + name)
#print(subjects)
for i in subjects:
print("One of my classes is " + i)
tvshows = ["Gilmore Girls", "Friends", "How I met your mother"]
for i in tvshows:
if i == "Gilmore Girls":
print(i + " is th... |
0dc08dab87449d13edf34bb8a6a9537491985909 | singhamandeep-kgp/Hackerrank | /Counting_sort_2.py | 302 | 3.71875 | 4 | def countingSort(arr):
my_dict = {}
for i in range(0,100):
my_dict[i] = 0
for i in arr:
my_dict[i] += 1
final = []
for i in my_dict:
j = 0
while j < my_dict[i]:
final.append(i)
j += 1
return final
|
5d88faa8306146450a306976ce89b540d106754e | kosmokato/python-4-infosec | /snippets/files.py | 2,417 | 4.125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
PoC: Operaciones con ficheros
"""
# Abrir un fichero
f = open('filename', 'r') # asignamos un puntero al fichero a la variable f, abierto para LEER (r)
data = f.read()
f.close() # CIERRA LOS FICHEROS SIEMPRE
g = open('filename2', 'w') # asignamos fichero2 a 'g', para... |
99c3e82a14d1eb3a0fa1419a10d07812937784a0 | caiopetreanu/PythonMachineLearningForTradingCourseCodes | /_py/01-01_to_01-03/14_numpy_arrays_random_values.py | 1,172 | 4.125 | 4 | """ Generating random numbers. """
import numpy
import numpy as np
def run():
# generate an array full of random numbers, uniformly sampled from [0.0, 1.0)
print("pass in a size tuple", np.random.random((5, 4))) # pass in a size tuple
print("function arguments (not a tuple)", np.random.rand(5, 4)) # func... |
2381211739433a694f8c0020271610dc3aaf6e60 | caiopetreanu/PythonMachineLearningForTradingCourseCodes | /_py/01-08/03_minimizing_polynomials.py | 2,980 | 3.96875 | 4 | ''' Fit a polynomial to a given set of data points using optimization. '''
import pandas as pd
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as spo
from utils.util import p
def fit_poly(data, error_func, degree):
""" Fit a polynomial to given data, using supplied error fun... |
85142bef9db59050d92b353a2e7b1298e0f95663 | AdrianM20/Lab_2-4__Apartments-Expenses-FP- | /src/apartments/util/common.py | 897 | 3.5 | 4 | '''
Created on 19 oct. 2016
@author: adiM
'''
from apartments.domain.apartment import get_apartment_id
def string_contains(s, t):
'''
Check if the string s contains the string t.
'''
return t in s
def check_digits(s):
'''
Checks if a string contains only digits
'''
return s.i... |
5d5c3697399958ed3fcdbb2320b622a24659ba5d | kirtymeena/DSA | /9.Stack/evalution_of_postfix.py | 1,193 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 15:44:15 2020
@author: kirty
"""
class Stack:
def __init__(self):
self.stack = []
self.output = []
self.precedence = {"+":1,"-":1,"/":2,"*":2,"^":3}
def IsEmpty(self):
if self.stack ==[]:
retur... |
10e7adaeec98a5a5244a865e3324081b04f9ab9f | kirtymeena/DSA | /Linked List/1.Singly LinkedList - creation,printing,insertion,deletion.py | 13,056 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 12:24:56 2020
@author: Kirty
"""
"""
todo questions:
# deleting complete linked list
# detecting loop
#count the number of loops
# remove dup from unsorted list
"""
# creating nodes
class Node:
def __init__(self,data):
self.data = ... |
897f368f159aebad9f40a8c687b11064d4f961d8 | kirtymeena/DSA | /9.Stack/2.stack_using_linked_list.py | 962 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 13:29:44 2020
@author: kirty
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
class stack:
def __init__(self):
self.top = None
def push(self,data):
node = Node(data)
if self.top i... |
5bd2745faa9e6ce6fddd5b85b85f543096e88b3c | kirtymeena/DSA | /BInary Tree/BinaryTree.py | 1,541 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 13:24:31 2020
@author: Kirty
"""
class Node:
def __init__(self,value):
self.value = value
self.right = None
self.left = None
class BinaryTree(object):
def __init__(self,root):
self.root = Node(root)
... |
82913913594d25c23958b0462dcef6c91972c85a | kirtymeena/DSA | /6.Sorting/8.partition_of_array(for quick sort)--Navie.py | 564 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 18:25:42 2020
@author: kirty
"""
arr =[3,8,6,12,10,7]
def partition(arr,p=5):
i=0
j=len(arr)-1
temp=[]
for i in range(len(arr)):
if arr[i]<=arr[p]:
temp.append(arr[i])
i
for j in range(len(arr)):
if arr[j]>arr... |
efd62847567e102a1a00e0a9bd5245fe4e3c974e | kirtymeena/DSA | /3.hashing/count unique ele(using set).py | 261 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 21:16:58 2020
@author: Kirty
"""
def distinct(arr):
s = set([])
for i in arr:
s.add(i)
return len(s)
print(distinct([10,20,30,20,30,40]))
# time complexity = O(n)
# aux space - O(n) |
8390d0bdb0311cde387a6582ca43bb3e4ea7e1d6 | kirtymeena/DSA | /stack/2.Implimenting_queue_using_2stacks.py | 1,253 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 08:39:04 2020
@author: Kirty
"""
class Stack:
def __init__(self):
self.s1 = []
self.s2 =[]
# implementing queue using stacks --- Enqueue opr costly
# s1=[1,2] s2=[]
def enQ(self,data):
# O(N)
while len(self.s1)!... |
16899ea6ab685bcad9f4ba70a770f4a0e14f3d24 | gio2396ch/Wikipedia-Search | /scraper.py | 293 | 3.640625 | 4 | from bs4 import BeautifulSoup
import requests
con = str(input("What are you looking for? "))
def site(con):
url = requests.get("http://wikipedia.org/wiki/"+con).text
bsObj = BeautifulSoup(url, "html.parser")
res = bsObj.findAll('p')
print(res)
site(con)
|
6e04fa1b088f24a9508dc852f8d57e5d187e64cf | uswdnh47/608-mod3 | /custom-object.py | 637 | 3.71875 | 4 | class Purchase(object):
def __init__(self, amount):
self.amount = amount
def calculateTax(self, taxPercent):
return self.amount * taxPercent/100.0
def calculateTip(self, tipPercent):
return self.amount * tipPercent/100.0
def calculateTotal(self, taxPercent, tipPercent):
... |
2925d2a5bf59ef4946aed71db199120ed643ccd6 | dongruibin/MachineLearning | /comAlgorithm/KNN/KNN.py | 3,137 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#文件里面含有两个函数,一个用于生成小数据库,一个实现KNN分类算法
#####################################################
##KNN K Nearest Neighbors
# Input newInput: vector to compare to existing dataset(1xN)
# dataset: size m data set of know vector(NxM)
# labels: data set labels
# k: ... |
46a20ffe8aa8547852f632bac3bb8a6cd2f0086f | Raghav1806/Social-Networks | /NetworkX basics/roadNetwork.py | 909 | 3.6875 | 4 | # modelling a road network
import networkx as nx
import matplotlib as plt
import random
G = nx.Graph() # undirected graph
# for directed graphs, use: G = nx.DiGraph()
city_set = ['Delhi', 'Bangalore', 'Hyderabad', 'Ahmedabad', 'Chennai', 'Kolkata', 'Surat', 'Pune', 'Jaipur']
for each in city_set:
G.add_node(each)
... |
be1b553e2bd22c53f25cea785f7214ce5bab3531 | Geraldine2079744/S3.EDysP-Evidencia2 | /11_5DiferenciasArrayNumpyVsLista.py | 1,275 | 4.09375 | 4 | import numpy as np
import random
SEPARADOR = ('*' * 20) + "\n"
#Comprobacion de que un array de numpy y una lista no poseen el mismo comportamiento:
#Una lista puede contener elementos de diferentes tipos de datos
# en un array de numpy todos los elementos son del mismo tipo de dato
lista = [10, 'abc', 20]
print(list... |
28f8579ffbdba2c0b7da7bc60e6a023eac622383 | chav-aniket/cs1531 | /labs/20T1-cs1531-lab02/tax.py | 458 | 3.953125 | 4 | import locale
locale.setlocale(locale.LC_ALL, "")
income = float(input("Enter your income: "))
tax = 0
if income > 180000:
tax = 54232+0.45*(income-180000)
elif income>87000:
tax = 19822+0.37*(income-87000)
elif income>37000:
tax = 3572+0.325*(income-37000)
elif income>18200:
tax = 0.19*(in... |
0a2806ffd4ca293ddfe8a63c5255acea3ed5d881 | chav-aniket/cs1531 | /labs/20T1-cs1531-lab06/weather.py | 2,227 | 4.09375 | 4 | '''
Lab06 Exercise 4
'''
import sys
import csv
import datetime
from math import fabs
if len(sys.argv) != 3:
print("Invalid Input")
exit()
elif not isinstance(sys.argv[1], str) or not isinstance(sys.argv[2], str):
print("Invalid Input")
exit()
DATE = sys.argv[1]
LOCATION = sys.argv[2]
... |
30a0265bbf8333253f87f6f8e3bb732379b01efb | chav-aniket/cs1531 | /labs/20T1-cs1531-lab06/reduce_test.py | 680 | 3.84375 | 4 | from reduce import reduce
def test_one():
'''
Testing for non-lists
'''
reduce(lambda x, y: x + y, 'iufydt') == 'iufydt'
def test_two():
'''
Testing with empty list
'''
reduce(lambda x, y: x + y, []) == None
def test_three():
'''
Testing with valid input and ad... |
7c8cb97e1b50b85c8a7d5ec746a2b6c58bfee416 | chav-aniket/cs1531 | /labs/20T1-cs1531-lab05/encapsulate.py | 695 | 4.5 | 4 | '''
Lab05 Exercise 7
'''
import datetime
class Student:
'''
Creates a student object with name, birth year
and class age method
'''
def __init__(self, firstName, lastName, birth_year):
self.name = firstName + " " + lastName
self.birth_year = birth_year
def age(self):
''... |
ca2d90dbd0215e9c4db4c3f15a6f4fe0060d7384 | chav-aniket/cs1531 | /labs/20T1-cs1531-lab02/guess.py | 573 | 3.859375 | 4 | def guess(lo, hi):
prev = round((hi+lo)/2)
print(f"My guess is {prev}")
ans = input("Is my guess too low (L), too high (H), or correct (C)?\n")
if ans == 'C':
print("Got it!")
return
elif ans == 'L':
guess(prev, hi)
elif ans == 'H':
guess(lo, prev)
... |
a5d0765a8e62bbd467367d9a23faf13b00b75c8c | mightestDuck/divacon | /main.py | 3,321 | 3.9375 | 4 | import sys
import timeit
import numpy as np
import matplotlib.pyplot as plt
from typing import Callable
def binary_search(search_space: list, target: int, ordered: bool = False) -> (int, int, list):
if not ordered:
search_space = mergesort(list(search_space))
i_low = 0
i_high = len(search_space) ... |
0cba87264808a3510e30b8d9cf98eac6e8f8a586 | mascomen4/pycharm-projects | /python_classes/TextUtil.py | 2,646 | 3.953125 | 4 | #!/usr/bin/env python3
# Copyright (c) 2018 Podmogilniy Ivan
'''
Модуль дает несколько функций для форматирования строк
The Module provides a couple of functions to procedure strings.
>>> is_balanced('(Python (is (not (lisp))))')
True
>>> shorten("The Crossing road", 10)
'The Cro...'
>>> simplify(' some text with spuri... |
e1196cbd756ac669c9ed686bf706b212755565d0 | dannycerongarcia/simple-P2P-project | /fileIO.py | 694 | 3.953125 | 4 | # this file take care of writting file to the machine
import os
PATH_TO_FILE = "/read_file.txt"
PATH_TO_NEWFILE = "/new_file.txt"
cwd = os.getcwd()
path_to_file = cwd + PATH_TO_FILE
path_to_newFile = cwd + PATH_TO_NEWFILE
def convert_to_bytes(path_to_file=path_to_file):
data=None
with open(path_to... |
6192149e39b54573f0f7b762e070c5f910dd4af3 | mklopot/roadside_wumpus | /amulet.py | 970 | 3.5 | 4 | import item
class Amulet(item.Item):
def __init__(self,from_room,to_room):
self.name = "gray metallic bracelet"
self.weight = 1
self.from_room = from_room
self.to_room = to_room
self.value = 50000
self.description = "A lot heavier than it looks, with very precise curvature, the gray metal see... |
fd4585d4a1e33b280a9de688ddc616a36d00ec63 | abbasegbeyemi/outfield | /psolv_ch_2.py | 806 | 4.09375 | 4 | # Two python functions to find the minumum number in a list
from random import randint
import time
def non_linear(number_list):
smallest = number_list[0]
for n in number_list:
for c in number_list:
if c < n and c < smallest:
smallest = c
return smallest
def linear(nu... |
8fcda1b10eebda946124e3654c56e5176782e20f | abbasegbeyemi/outfield | /psolv_ch_4/psolv_ch_4_ADT.py | 1,327 | 4.4375 | 4 | class Stack:
"""The stack class which is an abstract data type that appends to and removes from the end of a list"""
def __init__(self):
"""Constructor for Stack"""
self._stack_list = []
def push(self, item):
self._stack_list.append(item)
def pop(self):
return self._st... |
3db83a5bfbe3eafff9f14e06654b9f2315e20834 | sadimauro/projecteuler | /euler010_v1.py | 387 | 3.984375 | 4 | #!/usr/bin/python3
import time
tStart = time.time()
import math
def isPrime(a):
for i in range(3, math.floor(math.sqrt(a))+1, 2):
if a % i == 0:
return False
return True
sum = 2
for i in range(3,2000000,2):
if isPrime(i):
sum += i
print(__file__ + ": answer: " + str(sum))
pri... |
8a10b7d365aca5537c5a8f0aefb6f8713be1d024 | sadimauro/projecteuler | /euler014_v2.py | 634 | 4 | 4 | #!/usr/bin/python3
import time
tStart = time.time()
def collatzLen(n):
""" Input: n, Output: list of the collatz sequence starting at n"""
newListLen = 1
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
newListLen += 1
return newListLen
longes... |
86ae39425cc9aa134aacd70408c98e20e0a39a75 | sadimauro/projecteuler | /euler047_v1.py | 1,060 | 3.671875 | 4 | #!/usr/bin/python3
import time
tStart = time.time()
import stevepe
import itertools
n = 2
firstInt = 0
primesToTry = [2]
while True:
# get additional primes to try, between max in the primes list and n
additionalPrimes = stevepe.getPrimesBetween(primesToTry[-1], n)
if len(additionalPrimes) > 0:
l... |
0337fb937ec4f8eabfebaeb93b7a716f765fe271 | sadimauro/projecteuler | /euler005_v2.py | 451 | 3.9375 | 4 | #!/usr/bin/python3
import time
tStart = time.time()
def gcd(a,b):
"""Compute the greatest common divisor of a and b"""
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
"""Compute the lowest common multiple of a and b"""
return a * b // gcd(a, b)
ans = 1
fo... |
830bdd23777c3c5b3f724a441814e38e5240fc79 | sadimauro/projecteuler | /euler024_v1.py | 391 | 3.515625 | 4 | #!/usr/bin/python3
import time
tStart = time.time()
import itertools
def nth(iterable, n, default=None):
"""Returns the nth item or a default value"""
return next(itertools.islice(iterable, n, None), default)
perms = itertools.permutations(range(10))
print(__file__ + ": answer: " + str(nth(perms, 999999)))... |
8a9b0ac75224c9a620caed1c7d6074ff1b4b8d5c | TMazenge/Introduction-to-Python | /Database Search/main.py | 5,291 | 4.3125 | 4 | import database
def find_movies_by_genre(movies, genre):
"""Finds all movies of the given genre.
Args:
movies: All the movie records in the database.
genre: The genre to search for.
Returns:
A list of all the movie titles of movies that
belong to the given genre.
"""
resul... |
3d37f0a460f46635166c3d0041fe589f143b23f0 | TahinDani/edX_exercises | /edX_isIn.py | 507 | 4.0625 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if aStr == '' or len(aStr) == 1:
return False
half_point = int((len(aStr))/2)
test_char = aStr[half_point]
if char == test_char:
... |
f1d102e541ddc8597d78a53a5ffd377295a6fd0a | TahinDani/edX_exercises | /Problem Set 2/edX_bisectionFixedMonthlyPayment.py | 1,747 | 3.875 | 4 | # Write a program that uses these bounds and bisection search to find the smallest monthly payment to the cent
# (no more multiples of $10) such that we can pay off the debt within a year.
# Monthly payment lower bound = Balance / 12
# Monthly payment upper bound = (Balance x (1 + Monthly interest rate)**12) / 12.0
d... |
785bd67c0c45ceeeb9a54ed6e93c79e46ae90503 | pythoncanarias/eoi | /05-libs/docs/external/fire/canvas.py | 1,129 | 3.546875 | 4 | import fire
class BinaryCanvas(object):
"""A canvas with which to make binary art, one bit at a time."""
def __init__(self, size=10):
self.pixels = [[0] * size for _ in range(size)]
self._size = size
self._row = 0 # The row of the cursor.
self._col = 0 # The column o... |
dd972508d621747c2828816f2deb7e2d3c24d719 | pythoncanarias/eoi | /01-environment/scripts/2-convert-hours-into-seconds.py | 196 | 3.59375 | 4 | seconds = 12345
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
result = f"{hour}:{minutes}:{seconds}"
print(result)
|
3b0b7031a8ae0f61d2ad945f82afd5762ac843e1 | pythoncanarias/eoi | /02-core/05-loops/solutions/hamming.py | 162 | 3.5625 | 4 | str1 = '0001010011101'
str2 = '0000110010001'
distance = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
distance += 1
print(distance)
|
bd194a762bb7029be06e18a15eae9d6a5b58d5ef | zeeshanalam39/dip-opencv-python | /9 morphological operations/morphological_opening.py | 2,693 | 3.546875 | 4 | import cv2 as cv # Import packages
import numpy as np
import math
IMAGE = cv.imread('D:\@Semester 06\Digital Image Processing\Lab\Manuals\Figures\lab9\_img2.tif', 0) # Read img
cv.imshow('Original Image', IMAGE) # Show img
cv.waitKey(0)
cv.destroyAllWindows()
def convert_to_binary(img, val): # Function to... |
65afde48f386051a43ed3c050af141ed73b2406f | laura-chen/interviewprep | /hashtable.py | 1,284 | 3.90625 | 4 | # A simple hash table implementation. Handles collisions by overwriting original
# value at location in the hash table. (Chaining and linear probing are
# better methods.)
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
self.table = [None]*self.capacity
self.size = ... |
b1775a415f954f9f7c89537059c4ab872dcd3f40 | danisebastian9/Ciclo1MinTIC | /Semana4/while4.py | 345 | 4.0625 | 4 | n = int(input('Digite limite inferior: '))
m = int(input('Digite limite superior: '))
while n > m:
print('El limite inferior debe ser menor que el superior, vuelva a ingresarlos')
n = int(input('Digite limite inferior: '))
m = int(input('Digite limite superior: '))
while n <= m:
if n % 2 == 0:
... |
528087ceda21a8cf8a5c9f5af728566ae1aaad3d | danisebastian9/Ciclo1MinTIC | /Semana3/Salario.py | 666 | 3.921875 | 4 | horasTrabajadas = float(input('Digite las horas trabajadas por semana '))
if horasTrabajadas > 0 and horasTrabajadas <= 80:
if horasTrabajadas > 40 :
horasExtras = horasTrabajadas - 40
print('Sus horas extras son: ', horasExtras)
valorExtras = horasExtras * 2000
print("El valor de la... |
75e6a02370732abacb18641686be5a5babcfd942 | danisebastian9/Ciclo1MinTIC | /Semana3/Exercise7FinalWeek.py | 982 | 3.765625 | 4 | edad = int(input('Edad: '))
puntaje = int(input('Puntaje: '))
ingreso = float(input('Ingreso: '))
if edad >= 15 and edad <= 18:
descuentoEdad = 25
elif edad >= 19 and edad <= 21:
descuentoEdad = 15
elif edad >= 22 and edad <= 25:
descuentoEdad = 10
else:
descuentoEdad = 0
if ingreso <= 1:
descu... |
16a20b34e6cad77af3a382254f049d3558bce321 | danisebastian9/Ciclo1MinTIC | /Semana6/exerArrays01.py | 508 | 3.96875 | 4 | '''
Realicen en Python un programa que lea 10 números por teclado,
los almacene en un arreglo y muestre la suma,
resta, multiplicación y división de todos.
'''
import numpy as np
def numList():
longLista = 10
numList = np.zeros(longLista, dtype=int)
for i in range(longLista):
numList[i] = int(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.