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
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...
4bb0736d12da8757a76839f242d902fb08afc461
vamsikrishna6668/python
/class2.py
559
4.3125
4
# w.a.p on class example by static method and static variables and take a local variable also print without a reference variable? class student: std_idno=101 std_name="ismail" @staticmethod def assign(b,c): a=1000 print("The Local variable value:",a) print("The static ...
2435e4af4414429c2bc3b66ee1475829799b01d6
seraht/AmazonScraper
/Scraping/laptop_features_class.py
2,267
3.546875
4
""" Define an OOP Features, with the corresponding attributes and functions for the features of the laptop Authors: Serah """ from Createdb import connect_to_db from datetime import datetime import config from Logging import logger import sys sys.path.append('../') DB_FILENAME = config.DB_FILENAME class Features: ...
8425d06717614c9e3d0a34e0c253cf1f6eebf8d3
svi-lab/general_programs
/slice_of_pie.py
3,391
3.53125
4
import numpy as np from warnings import warn def slice_of_pie(matrix, phi_1, phi_2, r_1=0, r_2=np.inf, center=False): """isolates the sclice of an image using polar coordinates Prerequisites: numpy Parameters: matrix:2D ndarray: input matrix as 2D numpy array (your input image) r_1:float: ...
3a5908b10e1eb651085ac4dee75e344b8bb9cc83
singzinc/PythonTut
/basic/tut2_string.py
785
4.3125
4
# ====================== concat example 1 =================== firstname = 'sing' lastname = 'zinc ' print(firstname + ' ' + lastname) print(firstname * 3) print('sing' in firstname) # ====================== concat example 2 =================== foo = "seven" print("She lives with " + foo + " small men") # ======...
57d256f05332980e76360dc99e3f2693905a8b60
giacomofi/DijkstraAlgorithmR
/heapdijkstra.py
2,818
3.515625
4
from graph import Graph from node import Node import time class HeapDijkstra: def __init__(self): pass nodeLinkAndCost = [] heaps = [] finalHeap = [] def createGraph(self): nodes = [] g = Graph(nodes) f = open("GeneratedGraph.txt", "r") lines = f.readlin...
9e59cf888a34263475acad0a8dd3543d5352a105
gbmhunter/AdventOfCode2017
/day12/day12.py
1,361
3.65625
4
connections = [] with open('input.txt', newline='') as file: for line in file: connPrograms = line[line.index('>') + 2:] connPrograms = [x.strip() for x in connPrograms.split(',')] connPrograms = list(map(int, connPrograms)) connections.append(connProgram...
bb3d93729ebf17b23e6af471a3165371da9715fc
gbmhunter/AdventOfCode2017
/day5/day5.py
973
3.640625
4
input = open('input.txt') inputLines = input.readlines() instrList = [] for line in inputLines: instrList.append(int(line)) canExit = False index = 0 steps = 0 while True: if index < 0 or index >= len(instrList): break instr = instrList[index] # print('instr = ' + str(instr)) # Increme...
cb8589722606e8fa69a9db8c49f7a55080f8a8cc
talhaibnaziz/projects
/pi3ddemos/CollisionBalls.py
1,902
3.65625
4
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals """ Example of using the loop control in the Display class with the behaviour included in the pi3d.sprites.Ball class """ import random import sys import math import demo import pi3d MAX_BALLS = 25 MI...
1a8b164a526e8a1cde7fc6617f1caf31f95c7cb3
antoniogi/HPC
/Python/TACC_HPC/3_matplotlib/bars_color.py
590
4.03125
4
#!/usr/bin/env python # # Creates and displays a bar plot. Changes the bar color depending on # the y value # # # agomez (at) tacc.utexas.edu # 30 Oct 2014 # # --------------------------------------------------------------------- import matplotlib.pyplot as plt import numpy as np x = np.arange(5) yvals = [-100, 200, ...
21edae2f34df0c3b13ec7a37bdbfcfce357fe524
jgramm/altfactsbot
/textToMarkov.py
5,144
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 11 15:35:37 2017 @author: James """ import re import random def textTo2GramMarkov(text, wordsTo=dict(), count=0): #text = re.sub(r'\W+', '', text) #words = text.split() words = "".join((char if char.isalpha() else " ") for char in text).split() ...
efc04c2b1660461fb8321fa29699e5d73ffd6285
oliviervos/python_workbook_174_Solution
/IntroductionToProgramming/E14.py
169
3.734375
4
height_us = map(float,raw_input("please input your height with feet and inches, sep by ,").split(',')) print "your height in cm is", 2.54*(height_us[0]*12+height_us[1])
79b4b968d475c29c3a99f4a85724ca9a3d05f4c9
oliviervos/python_workbook_174_Solution
/IntroductionToProgramming/E13.py
1,132
3.6875
4
# the solution in the book is optimal but too simple, here we give the optimal dynamic programming solution coins = input("input a number of cents in integer\n") pennies = 1 nickels = 6 #in order to make it harder, we make nickles to be 6 dimes = 10 quarters = 25 #limit the denominations to only 4 types from ...
590b4ee6898e35551b8059ef9256d307a8bcce59
markvakarchuk/ISAT-252
/Python/Rock, Paper, Scissors - Linear.py
1,891
4.1875
4
import time import random # defining all global variables win_streak = 0 # counts how many times the user won play_again = True # flag for if another round should be played game_states = ["rock", "paper", "scissors"] #printing the welcome message print("Welcome to Rock, Paper, Scissors, lets play!") time.slee...
b47c6a6383e857ea7ca8e93cc0c24f43a59c7516
piyushsharma161/Detect-and-count-differnet-products
/training/copy_dir.py
1,122
3.515625
4
import os, shutil import argparse ''' Creating the output directory if not already exists Doing the copy directory by recursively calling my own method. When we come to actually copying the file I check if the file is modified then only we should copy. ''' parser = argparse.ArgumentParser() def copy_dir(src, dst, s...
c07f63c3755581aca8eb2c7adf3024aaf422ea60
eclansky/scriptPlayground
/looping.py
301
3.9375
4
#looping #for loops #Make a for loop that prints out dictionary stuff #items returns list of dictionaries key:value pairs # dict.items format # Putting sep separator equal to empty string makes it delete the spaces between for name, price in menu_prices.items(): print(name, ':', price, sep='')
51d1da533af29e0a438cfa46ab22b85054e3eeb4
alexng96/ECE143Team6
/analysis_modules.py
3,095
4.40625
4
import pandas as pd def make_pandas(fname): """Makes a pandas dataset from the given csv file name. Changes data-types of numeric columns Arguments: fname {string} -- the csv files with CAPE data """ assert fname == 'engineering.txt' or 'humanities.txt' or 'socialSciences.txt' or 'ucsd.txt', "...
3a784950aad8f17238f9aa4ca346ae1491f77b92
rebondy/barbot
/algorithm.py
5,373
3.75
4
Margarita = ["Tequila", "Cointreau", "Lime Juice"] MintJulep = ["Wiskey", "Angostura Bitters", "Sugar Syrup"] PlantersPunch = ["White Rum", "Lime Juice", "Sugar Syrup", "Angostura Bitters"] Cosmopolitan = ["Vodka", "Cointreau", "Lime Juice", "Cranberry Juice"] Vodkatini = ["Vodka", "Vermouth"] Fitzgerald = ["Lemon Juic...
2f0f16f52d149b8420c44326c81b66f24be427e3
rudrut/developing-python-applications-2020
/Week7_tasks.py
4,921
3.65625
4
#---------------------------------------------------------------- #Task 1 #class Complex: # def __init__(self, real = 0, imaginary = 0): # self.real = real # self.imaginary = imaginary # # def getReal(self): # return self.real # # def getImaginary(self): # return se...
92d4b3e00f461d9582d502d56ae028f3297f6c90
arqcenick/SRMNIST
/contrib_homework.py
7,549
3.5
4
# CS 559 homework template # Instructor: Gokberk Cinbis # # Adapted from # https://www.tensorflow.org/get_started/mnist/pros # License: Apache 2.0 License # # Homework author: <Your name> ######################################################### # preparations (you may not need to make changes here) ##################...
cb8efd3255f3b5a4c19a93b4efb02de49c4c0a84
Clay190/Unit-5
/warmup13.py
265
3.640625
4
#Clay Kynor #11/16/17 #warmup13.py from random import randint words = [] for i in range(1,21): num = randint(1,100) words.append(num) words.sort() print(words) print("The maximum is", words[19]) print("The minimum is", words[0]) print("Sum", sum(words))