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 |
|---|---|---|---|---|---|---|
b45c396e6b80a33845f27583f96a22f385f7250d | jmishra01/Google_foobar_Challenge | /5/5_1 Expanding Nebula.py | 5,858 | 3.515625 | 4 | # Expanding Nebula
# ================
# You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! -
# one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You start monitoring the nebula,
# but unfortunately, just a mome... |
d5d2ac28e6e566984101db96010427dc702f18f5 | jmishra01/Google_foobar_Challenge | /3/3_5 Find_the_Access_Codes.py | 2,567 | 3.8125 | 4 | # Find the Access Codes
# =====================
# In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured
# with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that i... |
6e59bbbea25aca648e640db7e36bcde89272d4a4 | ArielGz08/unaj-2021-s2-unidad3-com16 | /reuso_codigo_fuente.py | 1,266 | 3.859375 | 4 | # Vamos a ver como a través del uso de funciones podemos evitar tener código fuente repetido
# Código fuente aportado por Walter Grachot (tiene unos 34 sentencias originalmente)
def carga_producto_y_calcula_subtotal():
producto= input("Ingrese nombre del producto comprado: ")
valor= float(input("Ingrese su valo... |
6ba4b5dedebb3eeca01e63654515cfbd086881aa | xiaojieluo/yygame | /game/calculator.py | 7,110 | 4.34375 | 4 | #!/usr/bin/env python
# coding=utf-8
# copy from http://blog.chriscabin.com/coding-life/python/python-in-real-world/1101.html
# Thanks
class Stack(object):
"""
The structure of a Stack.
The user don't have to know the definition.
"""
def __init__(self):
self.__container = list()
def __i... |
aee33d9d32071f96b20643094deb1c6fc6158768 | EwertonLuan/Curso_em_video | /56_cadastro_de_pessoas.py | 881 | 3.703125 | 4 | ida = 0 # idade dos dois somados
h_velho = 0 # idade do homem mais velho
h_vn = '' # Nome do homem mais velho
m_20 = 0 # mulheres com 20 anos
for i in range(1, 5):
nome = str(input('Digite o nome {}ª pessoa: '.format(i)))
idade = int(input('Dite idade {}ª pessoa: '.format(i)))
ida += idade
... |
c966acf1bedce7a5d9ff29d21a4e9db069c70141 | EwertonLuan/Curso_em_video | /41_categoria_atleta.py | 714 | 3.8125 | 4 | from datetime import date
print('\033[1;32m##\033[m' * 20+'\nPrograma para ver a categoria dos atletas\n'+'\033[1;32m##\033[m'*20)
ida = date.today().year - int(input('Qual a idade do atleta: '))
if ida <= 9:
print('Atleta esta com {} anos, sua categoria é \033[1;33mMIRIM\033[m'.format(ida))
elif ida <= 14:
pr... |
0fa3b0ba1cc789068b001406df17eba6a53c8628 | changzhai/project_euler | /project_euler/src/pe23.py | 1,726 | 4.0625 | 4 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
instructions = """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of... |
a0c074a2bca1cb02d862c7f5ce267ee28785adc4 | kbethany/LPTHW | /ex19_drill.py | 754 | 3.53125 | 4 | #create new function, cheese_and_crackers, which has two variables
def pets(cat_count, dog_count):
#the function has four things inside it contains, 4 print statements
print "You have %d cat!" % cat_count
print "You have %d dog!" % dog_count
print "Man, those are hungry pets!"
print "Give them a boost!\... |
feb27cb841884e8a2460cbe7cc645bb2ba7ae2fb | kbethany/LPTHW | /ex15.py | 912 | 3.765625 | 4 | #sys is a package, argv says to import only the vars listed
#when you call up the program (ex15.py filename), where argv is any
#module i want retrieved from that package.
from sys import argv
#argv is the arguments vector which contains the arguments passed
#to the program.
script, filename = argv
#opens the filnemae ... |
a9d1ca7beb482a72282d801a27858350ff365c7a | migeller/thinkful | /pip_001/fizz_buzz/fizz_buzz.py | 642 | 3.828125 | 4 | #!/usr/bin/env python
import sys
def modulo(x, y):
""" Determines if we can divide x from y evenly. """
return x % y == 0
def stepper(limit = 100):
""" Steps through from 1 to limit and prints out a fizzbuzz sequence. """
print "Our Upper Limit is %d! Let's go!" % limit
for n in xrange(1, limit + 1):
if modul... |
3b78e75671e8048fe45e4dfa2319d6cbc7d3bfe1 | YoZe24/lingi2364-projects | /project1/src/apriori_prefix_vdb.py | 3,406 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def apriori(filepath, minFrequency, verbose=True):
"""Runs the apriori algorithm on the specified file with the given minimum frequency.
This version has:
- intelligent candidate generation using prefixes (implemented using lists);
- fr... |
a6f2c1f7a0acbdf5f1685ebd3456be49aeb01aed | peter0703257153/School-project | /school_directory.py | 3,555 | 3.78125 | 4 | __author__ = 'pedro'
class School_directory(object):
def __init__(self):
self.schools = []
def add(self, school_name):
self.schools.append(school_name)
def find(self, name):
for school in self.schools:
if school.school_name == name:
return... |
381d4fa43d359440ffc3198333987812e06308c7 | aishwariya-7/apple | /main.py | 324 | 3.703125 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
Str ="I LOVE BEEZ LAB";
count =0;
for(i in range(0.len(Str))):
if(Str[i]!=' '):
count=count+1;
print... |
ff73cf14435050af2da53a669de66c9aa5de32aa | bruyneron/python_ds | /algo/bubble_sort.py | 625 | 3.859375 | 4 | # TC - O(n^2)
def ascending_sort(a):
n = len(a)
for i in range(0, n):
for j in range(0, n-1-i):
# (n-1)-i => n-1 becuase we are doing a[j] & a[j+1]. We don't want to go over the limit of j and get index out of range error.
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1... |
83dfa83903466ca2eca35f96a9351f76d7dc9adb | bruyneron/python_ds | /ds/queue.py | 4,221 | 3.78125 | 4 | '''
1) List
enqueue() | q.append()
dequeue() | q.pop(0) 1st element is 0
size() | len(q)
is_empty() | len(q)==0
2) SLL/DLL
(Have to use DLL. Reason: With SLL deletion takes O(n), Queue is supposed to take O(1) for deletion) <--- This is dumb
why??
SLL with head and tail.
Insertion ... |
751fab2eb3a2da8e335dff8b2ae2da160df1872f | lx881219/webley-puzzle | /webley.py | 3,392 | 3.78125 | 4 | import csv
import sys
import pathlib
class Solution:
def __init__(self):
self.result = []
self.target_price = None
self.menu = []
def handle_file_error(self):
print('Please provide a valid csv file in the following format. (python webley.py example.csv)')
print("""
... |
96265a429106573491aed434cec6d734534eea5a | backcover7/Algorithm | /15. 3Sum.py | 3,174 | 3.515625 | 4 | import bisect
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums)<3: return res
length = len(nums)
listsort = sorted(nums)
for start in range(length-2)... |
d4eec8ca65674a001474dcd2574fcbfea7d9df70 | backcover7/Algorithm | /70. Climbing Stairs.py | 1,148 | 3.59375 | 4 | class Solution(object):
def climbStairs_recurse(self, n):
"""
:type n: int
:rtype: int
"""
# recurse but time limit exceeded
# Time complexity: O(2^n)
if n <= 1: return 1
return self.climbStairs_recurse(n-1) + self.climbStairs_recurse(n-2)
... |
65da66866a817543e61627a73d2eed4cc2e6abb2 | backcover7/Algorithm | /513. Find Bottom Left Tree Value.py | 714 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
... |
ac51f8eefc234d49caf3a6a2eaee68f88f018e38 | backcover7/Algorithm | /29. Divide Two Integers.py | 862 | 3.640625 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
# https://www.youtube.com/watch?v=htX69j1jf5U
sig = (dividend < 0) == (divisor < 0)
a, b, res = abs(dividend), abs(divisor)... |
1451fa9c04e5ce8636d023001c663fb6a988b0bf | wajishagul/wajiba | /Task4.py | 884 | 4.375 | 4 | print("*****Task 4- Variables and Datatype*****")
print("Excercise")
print("1. Create three variables (a,b,c) to same value of any integer & do the following")
a=b=c=100
print("i.Divide a by 10")
print(a,"/",10,"=",a/10)
print("ii.Multiply b by 50")
print(b,"*",50,"=",b*50)
print("iii.Add c by 60")
print(c,"+",50,"=",b... |
ac8beccafc68748818a0de9915cfc0cec1c81cb7 | Reynbra/Portfolio | /python/TurtleFrogger/scoreboard.py | 1,993 | 3.921875 | 4 | from turtle import Turtle
FONT = ("Courier", 20, "normal")
SCORE_COLOR = "white"
ROAD_LINE_COLOR = "white"
SCORE_ALIGNMENT = "left"
LIVES_ALIGNMENT = "right"
GAME_OVER_ALIGNMENT = "center"
LEVEL_TEXT = "Level"
LIVES_TEXT = "Lives"
GAME_OVER = "GAME OVER"
class Scoreboard(Turtle):
def __init__(self):
supe... |
fc7353b01d945e9bbbaebd7aa6a6dd8f59ed8d2a | LucindaDavies/codeclan_caraoke | /tests/room_test.py | 1,236 | 3.671875 | 4 | import unittest
from classes.room import Room
from classes.guest import Guest
from classes.song import Song
class TestRoom(unittest.TestCase):
def setUp(self):
self.song1 = Song("Help", "The Beatles")
self.song2 = Song("Saturday Night", "Sam Cooke")
self.songs = [self.song1, self... |
302f242cb6fc42a6350e476cc19a5460bd56361f | 50Leha/automation_tests | /rospartner/utils.py | 390 | 4.0625 | 4 | """
Module with utility functions
"""
from random import choice
import string
def generate_email_name():
"""
utility to generate random name and email
:return: tuple(email, name)
"""
name = [choice(string.ascii_letters) for _ in range(5)]
email_tail = '@foo.bar'
# join to string
name ... |
c6f8241e148b4e503af3f3709885ee964e931838 | x-jeff/Tensorflow_Code_Demo | /Demo3/3.1.MNIST_classification_simple_version.py | 1,542 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
#该语句会自动创建名为MNIST_data的文件夹,并下载MNIST数据集
#如果已存在,则直接读取数据集
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
#mini-batch size
batch_size=100
#训练集的数目
#print(mnist.train.num_examples)#55000
#一个epoch内包含的mini-batch个数
n_batch=mn... |
340e077ad8099cd7baca8c3b057c004ea81f827e | vspatil/Python3-HandsOn | /Chapter_4_IF_stmts/exercise_5.1.py | 863 | 3.796875 | 4 | car ='golf'
car == 'olf'
##print(car)
"""
car = 'Golf'
print("Is car == 'Golf'? , I predict True.")
print(car == 'Golf')
print("\nIs car == 'Audi'? , I predict False.")
print(car == 'Audi')
deserts = 'Kheer'
print("Is desrt == 'Kheer'? , I predict True.")
print(deserts == 'Kheer')
print("Is desert == 'Ice Cream'? ,... |
209d0d207a72810d04216d15b8bafdbea0c50c36 | vspatil/Python3-HandsOn | /Chapter_8_Classes_Methods/Exercise_9.13.py | 675 | 3.890625 | 4 | #9.13
"""
from collections import OrderedDict
favourite_languages = OrderedDict()
favourite_languages['Brad'] = 'SQL'
favourite_languages['Adam'] = 'ERP'
favourite_languages['Mike'] = 'Python'
favourite_languages['Chris'] = 'JAVA'
for name , language in favourite_languages.items():
print( name.title() + " 's fav... |
e4849cacfa472b48f1fdb666339c05655b491ffa | vspatil/Python3-HandsOn | /Chapter_6_UserInputs_whileLoops/Exercise_7.5.py | 1,580 | 4.15625 | 4 | """prompt = "Enter a series of toppings : "
message = ""
while message != 'quit':
message = input(prompt)
if message == 'quit':
break
else:
print("We will add " + message + " to the pizza!")"""
"""
age=''
while age != 'quit':
age = input("Enter your age : ")
if age == 'quit':
... |
9badd15b93c998b8ae1eae271cbb7062d96aa860 | duxinn/data_structures_algorithms | /算法和数据结构的应用/顺序表相关/search.py | 1,168 | 3.953125 | 4 | # 搜索是在一个项目集合中找到一个特定项目的算法过程。搜索通常的答案是真的或假的,因为该项目是否存在。
# 当然可以按照具体需求,返回值可以设为要查找的元素的下标,不存在返回-1
# 搜索的几种常见方法:顺序查找、二分法查找、二叉树查找、哈希查找
# 本文只是基于顺序表实现的查找算法,二叉树,哈希以后在介绍
def find(L, item):
'''顺序查找,对排序的顺序表没有要求
最优:O(1)
最差:O(n)
'''
for i in L:
if i == item:
return True
return False
def binary_search(L, item):
'''二分查找,也叫折半... |
fd54b8243950b9f4fa2a96387dae8962fc2aa9d1 | duxinn/data_structures_algorithms | /数据结构/栈和队列/queue.py | 597 | 4 | 4 |
class Queue(object):
'''队列的实现,通过list存储数据'''
def __init__(self):
self.__queue = []
def enqueue(self, item):
'''入队操作'''
self.__queue.append(item)
def dequeue(self):
'''出队操作'''
return self.__queue.pop(0)
def is_empty(self):
'''判断是否为空'''
return not self.__queue
def size(self):
'''返回队列的长度'''
re... |
26248c4900a2793b3fa9d03434f62af8cffacbc9 | mihail-serafim/Pytest_Doxygen_Flake8 | /src/CircleT.py | 1,887 | 3.65625 | 4 | ## @file CircleT.py
# @author Mihail Serafimovski
# @brief Defines a circle ADT
# @date Jan. 10, 2021
from Shape import Shape
## @brief Defines a circle ADT. Assumption: Assume all inputs
# provided to methods are of the correct type
# @details Extends the Shape interface
class CircleT(Shape):
## @b... |
a3824f6e28c7cc6f87bca06600ee9f162c03f1f7 | AliMorty/B.SC.-Project | /Code/Queen.py | 3,023 | 3.703125 | 4 | from random import randint
from ProblemFile import ProblemClass
gameSize = 8
class QueenProblem(ProblemClass):
def get_initial_state(self):
arr = []
for i in range( 0 , gameSize):
arr.append(i)
# for i in range (0 , gameSize):
# print(arr[i])
return QueenSta... |
45dfca16469965060a325a60de88582be64df8ce | gousiosg/attic | /coding-puzzles/graph.py | 2,340 | 3.828125 | 4 | #!/usr/bin/env python3
import queue as q
from typing import List
class Node():
def __init__(self, value):
self.visited = False
self.neighbours: List[Node] = []
self.value = value
def __repr__(self):
return str(self.value)
class Graph():
def __init__(self, nodes):
... |
e1c3c0e94463b139ac244a685556d19698fd0e5c | grigil/Useless_functions | /sortByHeight/sortByHeight.py | 204 | 3.625 | 4 | def sortByHeight(a):
b=0
k=0
while k < len(a):
i=0
while i < len(a):
if a[i]!=-1:
if a[k]!=-1:
if a[k]<a[i]:
b=a[i]
a[i]=a[k]
a[k]=b
i=i+1
k=k+1
return a
a
|
8386925eadcb21fba3a504222cac6fadbc610e37 | ashwani-rathee/DIC_AI_PROGRAM | /8-andgate.py | 3,269 | 3.5 | 4 | # create a proper neural network to classify 00,01,10,11
# importing numpy library
import numpy as np
from numpy import linspace
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from scipy import signal
# sigmoid function
def sigmoid(x):
return 1/(1+np.exp(-x))
x1 = 0
x2 = 1... |
04859558d6e5f72cfb55f04050eb86543567c754 | JonathanGrimmSD/projecteuler | /031-040.py | 8,156 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
__author__ = "Jonathan Grimm"
__date__ = "07.02.18"
import math
# 031: Coin sums:
def count(S, m, n):
if n == 0:
return 1
if n < 0:
return 0
if m <= 0 and n >= 1:
return 0
return count(S, m - 1, n) + cou... |
4291e627f6dee78285a3d018a8ea6c9fc7a8ffd9 | Jackroll/aprendendopython | /exercicios_udemy/Programacao_Procedural/perguntas_respostas_57.py | 1,548 | 3.765625 | 4 | #sistema de perguntas e respostas usando dicionário
#criado dicionário Perguntas que contem chave pergunta, e o valor da che é outro dicionário
#com perguntas e respostas
perguntas = {
#{pk} : {pv}
'pergunta 1' : {
#{pv[pergunta]}
'pergunta': 'Quanto é 2 + 2 ?',
#{rk} : ... |
fc70c57920b9e56aae696754aa6ff347e7971aba | Jackroll/aprendendopython | /exercicios_udemy/desafio_contadores_41.py | 375 | 4.3125 | 4 | """fazer uma iteração para gerar a seguinte saída:
0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
"""
# método 01 - usando while
i = 0
j = 10
while i <= 8:
print(i, j)
i = i+1
j = j-1
print('------------------')
# método 02 - usando for com enumerate e range
for r, i in enumerate(range(10,1, -1)): #enumerate cont... |
88cce404c8ad3f07c9e4f09b09d80a8ffc660acb | Jackroll/aprendendopython | /exercicios_udemy/Orientacao_Objetos/desafio_poo/banco.py | 879 | 3.921875 | 4 |
# Classe Banco, possui cadastro com agencias, clientes e contas
class Banco:
def __init__(self):
self.agencia = [111, 222, 333]
self.clientes = []
self.contas = []
#método para cadastrar clientes no banco
def cadastrar_cliente(self, cliente):
self.clientes.append(cliente)
... |
972a883e10eda7523b400da701755868927938e8 | Jackroll/aprendendopython | /agregacao/classes.py | 982 | 4.3125 | 4 | """ Agregação é quando uma classe pode existir sozinha, no entanto ela depende de outra classe para funcionar corretamente
por exemplo: A Classe 'Carrinho de compras' pode existir sózinha, mas depende da classe 'Produtos' para pode funcionar corretamente
pois seus métodos dependem da classe produto.
E classe Produtos p... |
0c1622a3e7497ab2ef4a8274bf3cae27492824df | Jackroll/aprendendopython | /exercicios/PythonBrasilWiki/exe003_decisao.py | 490 | 4.1875 | 4 | #Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
letra = str(input('Digite F ou M :'))
letra_upper = letra.upper() #transforma a string para Uppercase para não haver erro em caso de digitação da letra em minusculo
if l... |
55dace0617bee83c0abef6e191326eb87f464c6a | Jackroll/aprendendopython | /exercicios_udemy/Programacao_Procedural/arquivos/arquivo_aula_83.py | 1,867 | 4.125 | 4 |
file = open('abc.txt', 'w+') #cria o arquivo 'abc.txt' em modo de escrita w+ apaga tudo que ta no arquivo antes de iniciar a escrita
file.write('linha 1\n') #escreve varias linhas no arquivo
file.write('linha 2\n')
file.write('linha 3\n')
file.write('linha 4\n')
print('-=' * 50) ... |
5a335fbe510d1f1f212e5f14d7658c5419433237 | Jackroll/aprendendopython | /exercicios_udemy/Orientacao_Objetos/composicao/main.py | 681 | 3.90625 | 4 | """Composição:
Uma classe é dona de objetos de outra classe
Se a classe principal for apagada todas as classes que foram usadas pela classe principal serão apgadas com ela
"""
#Por conta da composição, não houve a necessidad de importação da classe endereço, já que ela compoe a classe Cliente
from classes import Clie... |
d5e351dc79c6ce6ef0e4eff3683a8640af0adfdf | Jackroll/aprendendopython | /exercicios_udemy/Orientacao_Objetos/composicao/classes.py | 931 | 3.765625 | 4 |
#classe cliente que recebe uma instancia da classe endereço para atualizar sua lista de endereços
class Cliente:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.enderecos = []
def insere_endereco(self, cidade, estado):
self.enderecos.append(Endereco(ci... |
14aaf8a634e733d0cc8b08e69615b924fc9274ef | Jackroll/aprendendopython | /exercicios_udemy/poo/aula90_classes/pessoas.py | 1,555 | 4.03125 | 4 | from datetime import datetime
class Pessoa:
ano_atual = int(datetime.strftime(datetime.now(), '%Y')) #atributo de classe
def __init__(self, nome, idade, comendo = False, falando=False): #atributo do objeto, o de método
self.nome = nome
self.idade = idade
self.come... |
e76d821bf83cad07252a52fd9184058abff76da9 | Jackroll/aprendendopython | /exercicios_udemy/Orientacao_Objetos/context_manager/context_manager_lib.py | 839 | 3.890625 | 4 | #método 02 de criar gerenciador de contexto - usando contextmanager, atraves da criação de uma função.
from contextlib import contextmanager
# é criado uma função normal, só que decorada com @contextmanager para virar gerenciador de contexto
@contextmanager
def abrir(arquivo, modo):
try:
print('Abrindo o ... |
2f18dce6db44f8cbde41683bccd3f16611aace20 | Jackroll/aprendendopython | /exercicios_udemy/Modulos_uteis/Json/json_main.py | 978 | 4.34375 | 4 | """
trabalhando com json
Documentação : https://docs.python.org/3/library/json.html
json -> python = loads / load
python -> json = dumps / dump
"""
from aprendendopython.exercicios_udemy.Modulos_uteis.Json.dados import *
import json
# convertendo dicionário para json
dados_json = json.dumps(clientes_dicionario, inden... |
1b139816100f6157c1492c44eb552c096fb8b32f | verma-rahul/CodingPractice | /Medium/InOrderTraversalWithoutRecursion.py | 2,064 | 4.25 | 4 | # Q : Given a Tree, print it in order without Traversal
# Example: 1
# / \
# 2 3 => 4 2 5 1 3
# / \
# 4 5
import sys
import random
# To set static Seed
random.seed(1)
class Node():
"""
Node Struct
"""
def __init__(self,val=None):
self.val=val
... |
ffb8dd75a8a0fc099a0bdcdebf42df80831ef9ff | tistaharahap/woods.py | /woods.py | 11,344 | 3.515625 | 4 | import sys
class OutOfTheWoods(object):
def __init__(self):
print chr(27) + "[2J"
self.name = "John Doe"
self.fragileObjectInFrontOfTree = ""
self.fragileObjectCondition = ""
self.wildAnimalSeen = ""
self.takeTheWildAnimalWithMe = False
self.stayWithGranny = False
self.torchCarried = 0
self.jum... |
72e74e7dfbb1bc401f524e41e649fd8fc74da6dd | search-94/Genetic_algorithm | /inventario de carne.py | 9,057 | 3.625 | 4 | #ALGORITMO GENETICO INVENTARIO OPTIMO DE ALMACEN DE CARNE
import random
class algoritmoGenetico:
def __init__(self): #creacion de variables
self.poblacion = []
self.genotipo = []
self.bondad = []
self.cc = []
self.fprobabilidad = []
self.eliteq = []
self.eli... |
14dc9c14dabdbc50f0924f6695e343c5832b4a4c | brunoatos/Aprendendo-programar-Python | /exercicio 16 com função del student pen test.py | 368 | 3.9375 | 4 | lista=['virus','notebook','desktop','S.O','Memoria']
print (lista)
remover_lista=lista.pop()
print (lista)
print (remover_lista)
#é simples, criei uma nova variavel e adicionei uma função pop() nela. depois printei a variavel lista depois de usar a função pop() e por ultimo printei a variavel que removi da lista.a funç... |
2d3c4ff762249c691d6f3d6ac5831727a8b10856 | brunoatos/Aprendendo-programar-Python | /exercicio 8 student pen test.py | 248 | 4.03125 | 4 | list=['maça','banana','pêra']
print (list[0])
'''nesse caso para imprimir uma lista de string , ela começa da esquerda para a direita com primeiro ordem 0 , tudo que está entre conchetes chama-se lista e cada string ou seja nomes com aspas .''' |
9796ce266ad609f77291d57651f921f20800e65d | beenlyons/Ex_python | /Ex_collections/order_dict_test.py | 264 | 3.515625 | 4 | from collections import OrderedDict
user_dict = OrderedDict()
user_dict["asd"] = 0
user_dict["b"] = "2"
user_dict["c"] = "3"
user_dict["a"] = "1"
# 删除第一个
print(user_dict.popitem(last=False))
# 移动到最后
user_dict.move_to_end("b")
print(user_dict) |
3ea969feb1deb687f7dd9e573bdb0c18d4a6bef1 | maweefeng/baidubaikespider | /test/html_parse.py | 1,309 | 3.609375 | 4 |
from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">E... |
f6011e9bc0bbb8a46e698b872d66dce993462449 | JarredAllen/EncryptionCracker---APCSP-Create-Task | /encryptions/dictionary.py | 4,396 | 4.1875 | 4 | '''
The dictionary class, which handles verifying if something is a word, as well as how common the word is
@author: Jarred
'''
#from encryptions.base_class import base_class
supported_languages=['english', 'french']
list_of_english_words=[]
def build_list_of_english_words():
if list_of_english_words:
r... |
b9b33ab2d004d734e4c27fa5c53e2233dceb0589 | agaevusal/base-of-python | /MyIterator.py | 589 | 3.6875 | 4 | class MyIterator:
def __init__(self, lst):
self.lst = lst
self.i = 0
self.k = len(self.lst) - 1
def __next__(self):
while True:
if self.i <= self.k:
if self.lst[self.i] % 2 != 0:
self.i += 1
return se... |
78d23605c09e0aff64a21f8fb8b8adc26ccd48ec | Fedor-Pomidor/primeri | /primer3.py | 437 | 3.9375 | 4 | import math
x = float(input("Введите значение 'x'"))
y = float(input("Введите значение 'y'"))
z = float(input("Введите значение 'z'")) #вводите не меньше 4.4
if z >= 4.4:
def primer1 (x, y, z):
chislitel = math.sqrt(25 * ((x * y * math.sqrt(z - 4.4)) ** 2 + 5))
znamenatel = 8 + y
... |
b036a5e8f32b0b4921be8bd523a5ab5be07ed0f4 | RyanTucker1/Tkinter | /playground.py | 464 | 4.0625 | 4 | from Tkinter import * #gives us access to everything in the Tkinter class
root = Tk() #gives us a blank canvas object to work with
root.title("Here Comes the Dong")
button1 = Button(root, text="Button 1")
button1.grid(row=1, column=1)
entry1 = Entry(root)
entry1.grid(row=1, column=0)
label1 = Label(root, text="Owen... |
da2230aea01a610ec306f52b65855d0fcc48d558 | BenjaminSchubert/SysAdmin-scripts-for-linux | /pyDuplicate/filehandler.py | 2,155 | 3.859375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
This file contains functions to handle files, list, order, and removing some
"""
from os import walk
from os.path import join, isfile, getsize, isdir
import logger
import const
def tree_walk_with_size(_dir):
"""
Takes a directory and returns a list of file wit... |
110e743b74b52c326956398c48bdcc4d5ef10902 | kotsky/py-libs | /algorithms/merge/array_merge_algorithms.py | 3,960 | 3.96875 | 4 | """Array Merge functions
- merge_sorted_arrays(arrays) - to merge sorted arrays into one sorted
"""
# O(N*log(K) + K) Time / O(N + K) S
# where N - total number of elements
# K - number of subarrays
def merge_sorted_arrays(arrays):
if not len(arrays):
return arrays
# O(K) Time & Space
def ... |
c806d61916dedef457259a49a3a71b8a3d88479a | kotsky/py-libs | /data_structures/heaps/heaps_tree_implementation.py | 4,503 | 4.0625 | 4 | """Min-Heap tree structure
Thin Min-Heap implementation is based on pure binary tree structure
with certain balancing optimisation by using additional attribute
direction.
Min-Heap methods:
- class MinHeap() - Build Min-Heap from an any array with
integers with a complexity O(N) Time / O(N) Space
- peek() - check... |
a9aac54689126f3e08fe3fe9c1c751934a2704c5 | kotsky/py-libs | /algorithms/sort/array_sort_algorithms.py | 6,548 | 4.03125 | 4 | """
In this sheet, sorted algorithms are implemented in the most
optimal way.
The following list:
Merge Sort
Heap Sort
Quick Sort
Selection Sort
Insertion Sort
Bubble Sort
"""
# Avg: Time O(N*log(N)) / Space O(N)
# Worst: Time O(N*log(N)) / Space O(N)
# Idea:
# Create auxiliary array, where yo... |
6c9fc9c03b1d6ab243793f33bc481c57fae9b639 | cardboardcode/pycrypt | /src/parserlib.py | 4,209 | 3.9375 | 4 | import sys
import os
def encryptFile(st, text):
for letter in text:
if (letter == 'a'):
st+=str('1')
if (letter == 'b'):
st+=str('2')
if (letter == 'c'):
st+=str('3')
if (letter == 'd'):
st+=str('4')
if (letter == 'e'):
st+=str('5')
if (letter == 'f'):
st+=str('6')
if (letter == 'g')... |
745d6348846a729ba22f518714f39d8f0deb861d | Vrndavana/Sprint-Challenge--Intro-Python | /src/cityreader/cityreader.py | 872 | 3.859375 | 4 | import csv
cities = []
class City:
def __init__(self, name,lat,lon):
self.name = name
self.lat = lat
self.lon = lon
def cityreader(cities=[]):
with open("cities.csv") as p:
city_parser = csv.DictReader(p, delimiter= ",", quotechar = "|")
for row in city_parser:
city = City(row["city"],... |
be5a272602da6854598512c0b5a9b34d80c39a7c | nicovandenhooff/project-euler | /solutions/p22.py | 3,229 | 3.59375 | 4 | # Project Euler: Problem 22
# Names scores
# Author: Nico Van den Hooff
# Github: https://github.com/nicovandenhooff/project-euler
# Problem: https://projecteuler.net/problem=22
# Note: I implement a vectorized implementation with NumPy for this problem.
# Specifically, I first create a vector for each name, whe... |
f9fa0a430f651302cd9cce0092eaa8fadb18930e | nicovandenhooff/project-euler | /solutions/p48.py | 1,016 | 3.703125 | 4 | # Project Euler: Problem 48
# Self powers
# Author: Nico Van den Hooff
# Github: https://github.com/nicovandenhooff/project-euler
# Problem: https://projecteuler.net/problem=48
DIGITS = 10
def self_powers_sum(start, stop):
"""Calculates the sum of a series of self powers.
Parameters
----------
start... |
0a5c041eb9e714cdda7ffc9df287233452add307 | caiorss/OSlash | /oslash/applicative.py | 1,383 | 3.96875 | 4 | from abc import ABCMeta, abstractmethod
class Applicative(metaclass=ABCMeta):
"""Applicative functors are functors with some extra properties.
Most importantly, they allow you to apply functions inside the
functor (hence the name).
"""
@abstractmethod
def apply(self, something: "Applicative")... |
3169664c0f8cd32d7389d4dbb2a907fb916be13e | bogdanf555/randomNumberGuessingGame | /bin/functionalities.py | 8,134 | 3.875 | 4 | import ast
# difficulty levels for the game
difficultyPool = ("easy", "normal", "hard", "impossible")
# dictionary that associates a level of difficulty to
# the proper range of guess, the number of attempts and
# the maximum value that a secret number can get
# format of dictionary : difficulty - range, attempts, m... |
237e8e64ed9f6967042daee49a8b0f72c64e63a0 | moses4real/python | /Conditionals/For Loop.py | 109 | 3.515625 | 4 | Emails = ['Adewarasalavtion56@gmail.com','Oluwadamilare.m@yhaoo.com','Oluwadamilaremoses56@gmail.com']
for item in Emails:
if 'gmail' in item:
print(item)
|
3c1956e8a1f44ea31ff37e0a78e965bd4ae05b28 | Menelaos92/Library-Management-System | /frontend.py | 6,418 | 3.921875 | 4 | from tkinter import *
import backend
def view_command():
list1.delete(0,END) # Deleting everything from start to end.
for count, row in enumerate(backend.view_all()):
list1.insert(END,(count+1,row)) # The first argument sets the position where its going to get settled the incoming string inside... |
7c5abeb358b5790cff1bdfbf801c5093fa286443 | SavinKumar/Python_lib | /Original files/Library.py | 34,819 | 3.734375 | 4 | from tkinter import *
import sqlite3
import getpass
from functools import partial
from datetime import date
conn = sqlite3.connect('orgdb.sqlite')
cur = conn.cursor()
def passw():
pa=getpass.getpass()
passwo='seKde7sSG'
print('Entered password is of ',len(pa),' characters, To continue press Ente... |
b0670e3cdb4f9647102f477224de46ad97ff78d3 | nsc1114/comp110-21f-workspace | /exercises/ex02/repeat_beat.py | 378 | 3.96875 | 4 | """Repeating a beat in a loop."""
__author__ = "730394272"
beat: str = input("What beat do you want to repeat?")
num: str = input("How many times do you want to repeat it?")
total: str = beat
if int(num) <= 0:
print("No beat...")
else:
runtime: int = int(num)
while runtime > 1:
total = total + ... |
8b859bf457f2da415c393ea7f56d62495e778835 | MarynaNogtieva/mipt | /practice1/spider.py | 280 | 3.609375 | 4 | import turtle
import math
t = turtle.Turtle()
t.shape('turtle')
legs_angle = 360 / 12
for i in range(12):
t.forward(100)
t.stamp()
t.left(180) # turn to face center on the way back
t.forward(100)
t.right(180) # turn to face border on the way forward
t.right(legs_angle)
|
d9d7f6302c0c7c3721bd63c6b2866c6f111ee243 | MarynaNogtieva/mipt | /practice1/10_indended_sqares.py | 373 | 4.09375 | 4 | import turtle
import math
t = turtle.Turtle()
t.shape('turtle')
side_size = 50
def draw_square(t, side_size):
for i in range(4):
t.forward(side_size)
t.left(90)
for i in range(10):
draw_square(t,side_size)
# t.forward(side_size)
side_size += 20
t.penup() # lift turtle
# move turtle outside
t.backward(10)
... |
81eba7d41e0f8962458519751b02c21dc52c88a5 | Sreenidhi220/IOT_Class | /CE8OOPndPOP.py | 1,466 | 4.46875 | 4 | #Aum Amriteshwaryai Namah
#Class Exercise no. 8: OOP and POP illustration
# Suppose we want to model a bank account with support for 'deposit' and 'withdraw' operations.
# One way to do that is by Procedural Programming
# balance = 0
# def deposit(amount):
# global balance
# balance += amount
# ... |
85b42725e82771c0e8e6e04f84e2c5e1fbec0606 | sisinflab/Perceptual-Rec-Mutation-of-Adv-VRs | /src/utils/__init__.py | 904 | 3.515625 | 4 | import sys
import os
import socket
def cpu_count():
"""
Returns the number of CPUs in the system
"""
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif 'bsd' in sys.platform or sys.platfo... |
cd6b3802242956ea0c86e3ca72e844c80484ccc6 | arcann/mstr_python_api | /microstrategy_api/task_proc/bit_set.py | 262 | 3.515625 | 4 | from enum import Enum
class BitSet(set):
def combine(self):
result = 0
for entry in self:
if isinstance(entry, Enum):
result |= entry.value
else:
result |= entry
return result
|
c79f3df4eb01631e73363cd6e5e6546e15380b30 | edran/ProjectsForTeaching | /Classic Algorithms/sorting.py | 2,073 | 4.28125 | 4 | """
Implement two types of sorting algorithms: Merge sort
and bubble sort.
"""
def mergeMS(left, right):
"""
Merge two sorted lists in a sorted list
"""
llen = len(left)
rlen = len(right)
sumlist = []
while left != [] and right != []:
lstack = left[0]
while right... |
4b41489f518c4cbca1923440c3416cdfef345f88 | edran/ProjectsForTeaching | /Numbers/factprime.py | 657 | 4.28125 | 4 | """
Have the user enter a number and find all Prime Factors (if there
are any) and display them.
"""
import math
import sys
def isPrime(n):
for i in range(2,int(math.sqrt(n)) + 1): # premature optimization? AH!
if n % i == 0:
return False
return True
def primeFacts(n):
l = []
fo... |
05acb3ccc06473b83b430816bd688b410a97871f | edran/ProjectsForTeaching | /Numbers/alarm.py | 2,457 | 3.671875 | 4 | """
A simple clock where it plays a sound after X number of
minutes/seconds or at a particular time.
"""
import time
import pyglet
def passedTime(t, typetime):
"""
Returns time passed since t (seconds)
typetime can be <m> or <s> to specify
the returning type (minutes or seconds)
"""
try:
... |
9f7f047dbb43adc3798df7b33e7de4554a64c0ac | DanielWillim/AoC2019 | /day1.py | 354 | 3.609375 | 4 | def fuel_cost(mass):
mass_fuel = (mass // 3) - 2
if mass_fuel <= 0:
return 0
return mass_fuel + fuel_cost(mass_fuel)
inp = open('inp_day1', "r")
lines = inp.readlines()
total_cost = 0
print(fuel_cost(14))
print(fuel_cost(100756))
for line in lines:
total_cost += fuel_cost(int(line... |
bafd57196a0350f468390680e923c9fe9541e77a | keyman9848/bncgit | /xmjc_analysis/dataDeal/dataCollection/txtCollection.py | 609 | 3.515625 | 4 |
import pymysql
# 打开数据库连接
db = pymysql.connect(host='172.16.143.66',port = 3306,user='kjt', passwd='kjt$',db ='kjt',charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
sql = "SELECT VERSION()"
sql1= "select * from users"
cursor.execute(sql1)
# 获取所有记录列表
results = cursor.fe... |
d0659e52a363d340934df53c5ae71b1e9fd16209 | ClayMav/BPlus-Tree | /bplustree/bplustree.py | 8,164 | 3.890625 | 4 | """
This is a group project, to be worked on and completed in collaboration with
the group to which you were assigned in class.
One final report is due per group.
A number of groups, selected randomly, will be asked to demonstrate the
correctness of your program for any input data.
Your task is to develop and test a... |
2b7c6bb7e8405efe52a594d97bc7c7ac1584417c | kujaku11/mt_metadata | /mt_metadata/utils/list_dict.py | 7,082 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 16 11:08:25 2022
@author: jpeacock
"""
# =============================================================================
# Imports
# =============================================================================
from collections import OrderedDict
# ========================... |
dc4e1a66e05f8db95dda9efbdc9c4dfc3748b791 | IDSF21/assignment-2-samarthgowda | /main.py | 4,335 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
@st.cache
def load_songs():
df = pd.read_csv("./data.csv")
df = df.drop_duplicates(["id", "name"], keep="last")
df = df.dropna(how="any")
df["year"] = df["year"].astype(int)
return... |
1ab87bc5c2863c90dea96185241b0869f2259f30 | sonusbeat/intro_algorithms | /Recursion/group_exercise2.py | 489 | 4.375 | 4 | """ Group Exercise Triple steps """
def triple_steps(n):
"""
A child is running up a staircase with n steps and can hop
either 1 step, 2 steps, or 3 steps at a time.
Count how many possible ways the child can run up the stairs.
:param n: the number of stairs
:return: The number of possible way... |
916e2aa4bc23a717c6ba3d196b26cb44a02e6c78 | sonusbeat/intro_algorithms | /7.Loops/01.exercise.py | 469 | 4.21875 | 4 | # Exercises
# 1. Write a loop to print all even numbers from 0 to 100
# for num in range(101):
# if num % 2 == 0:
# print(num)
# list comprehension
# [print(i) for i in range(101) if i % 2 == 0]
# 2. Write a loop to print all even numbers from 0 to 100
# for i in range(0, 101):
# if i % 2 == 1:
# ... |
ec45e6109ddd2f2f3b9984404f015b828f0ca4f1 | sonusbeat/intro_algorithms | /SearchingAlgorithms/2.binary_search.py | 1,037 | 4.28125 | 4 | """
Binary Search
- how you look up a word in a dictionary or a contact in phone book.
* Items have to be sorted!
"""
alist = [
"Australia", "Brazil", "Canada", "Denmark",
"Ecuador", "France", "Germany", "Honduras",
"Iran", "Japan", "Korea", "Latvia",
"Mexico", "Netherlands", "Oman", "Philippines",
... |
07f7fc0b352b9919350390eab9eba036b89fba66 | sonusbeat/intro_algorithms | /Labs/Lab0.py | 492 | 3.84375 | 4 | import turtle
screen = turtle.Screen()
screen.bgcolor("#90ee90")
t = turtle.Turtle()
t.pensize(5)
t.shape('turtle')
t.color("blue")
t.stamp()
for _ in range(12):
t.penup()
t.forward(100)
t.pendown()
t.forward(10)
t.penup()
t.forward(20)
t.pendown()
t.stamp()
t.penup()
t.backwar... |
d7d7dddc18064c4b24885e0caa07872f3fcde5d3 | CavHack/Manhattanite- | /EM-GMM/k_clustering.py | 2,969 | 3.9375 | 4 | ##############################################################################################################
# Author: Karl Whitford
#
# Manhattanite- Multi-disciplinary Machine Learning/A.I Toolkit with Python
#
# Extracted from project description:
# WHAT YOUR PROGRAM OUTPUTS
#
# You should write your K-means and E... |
42a61c3c43eaa30894aeb3bd7980dfc679b34475 | the-economancer/Project-Euler | /Problem003.py | 789 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 15:53:11 2016
Functions to compute largest prime factor of a given number
@author: michael
"""
import math
import time
def isPrime(x):
for y in range(2,int(math.sqrt(x))+1):
if x % y == 0:
return False
return True
def factors(x):
... |
e4c980515428ad2e3bb23d9cf104d9ebf30a2780 | molweave532/IntroToProg-Python-Mod07 | /HW07-Error-Handling/Assignment07-error-handling-MW.py | 1,010 | 4.03125 | 4 | # ------------------------------------------------- #
# Title: HW07 - error handling
# Description: A brief description of error handling
# ChangeLog: (Who, When, What)
# Molly Weaver, 02/27/21, Created Script
# ------------------------------------------------- #
try:
# write a test case here
intOne =... |
8738e0b40f3dd5bd03454d4190fd660bbab6bd43 | jameskowalski97/plotting-library | /assignment_4.py | 1,273 | 3.609375 | 4 | #!/bin/python
# Import the libraries we are using. It is good practice to import all necessary
# libraries in the first lines of a file.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#test comment
# Create an array (a multi-dimensional table) out of our data file, full of text
all_data = np.... |
795353bbba095affade0e5933b63a0e3fbec7a6e | low101043/final-year-13-project | /final_Game_File.py | 3,848 | 3.703125 | 4 | # Main Game
from tkinter import * #This means I can use tkinter
#import gamePrototype4
###################################################################################################################################################################################################################################... |
80582061e8c52501b90a818218215639ef8cbdcb | Lackman-coder/collection | /argsandkwargs.py | 661 | 3.5625 | 4 | # *args methods:
def name(*args):
name(a)
print("denser","anitha","lackman","drikas","rakshana" "\n")
def animal(*bets):
animal(b)
print("cat","dog","parrot","fish" "\n")
def item(*home):
for items in home:
print(items)
item("tv","fridge","ac","electronics" "\n")
#if u not using *args then u cannot give mo... |
5c70c82b051ae0d488a4562748e5fd235202534c | corinnelhh/data-structures | /Graph/graph_directional.py | 3,337 | 3.75 | 4 | class Node(object):
def __init__(self, data):
self._data = data
self._visited = False
class Graph(object):
def __init__(self, *data):
self._edges = {}
self._nodes = []
for node in data:
self._nodes.append(Node(node))
def add_node(self, data):
... |
1cc74b32a7fc70815377e099434dc908ee962da7 | corinnelhh/data-structures | /Queue/queue.py | 935 | 4 | 4 | class Node(object):
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
self.last = None
class Queue(object):
def __init__(self, data=None):
self.head = None
self.tail = None
self.size = 0
if data:
for val in data... |
0ea7ceffc8365b8d61d10608a240a6c59a05247e | corinnelhh/data-structures | /Heap/binary_heap.py | 1,959 | 3.859375 | 4 | #!/usr/bin/env python
#import math, random
class BinaryHeap(object):
def __init__(self, max_heap="max", *data):
self._list = []
self._size = 0
self.max_heap = True
if max_heap == "min":
self.max_heap = False
elif max_heap != "max" and max_heap is not None:
... |
6954f9970b9f32aa4de9e42e0964ca73a1b1cf88 | corinnelhh/data-structures | /Stack/stack.py | 542 | 3.71875 | 4 | class Node(object):
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
class Stack(object):
def __init__(self, data=None):
self.head = None
if data:
for val in data:
self.push(val)
def push(self, data):
self... |
2d5ff47ae292ccb66d00aeea9471839310bae822 | vamsikrishna6668/python | /class8.py | 827 | 3.859375 | 4 | class Employee:
emp_desgination=input("Enter a Employee Desgination:")
emp_work_loaction=input("Enter a Employee Work Location:")
def fun1(self):
print("Iam a function1")
def assign(self,idno,name,sal):
print("The idno of the Employee:",idno)
print("The Name of the Employe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.