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
208d49cd7ecd45749340ca31fb872ced765fe2bf
kluitel/codehome
/src/advance-topic.py
908
3.546875
4
#! /usr/bin/python # To change this template, choose Tools | Templates # and open the template in the editor. __author__="kluitel" __date__ ="$Sep 23, 2013 11:48:31 PM$" if __name__ == "__main__": print "Hello World"; ''' advance topic 1. Generators . accelarates the function execution . resumable ...
9253bfa6d2eab7f2651462ed0544938cabbc052e
trando46/Projects
/Python/bdo_hw6.py
2,160
3.515625
4
# Bao Tran Do # 05/23/2021 import numpy as np import sys, subprocess import pydot import pygraphviz as pgv def matrix(file): contents = open(file).read().strip() return [item.split() for item in contents.split('\n')[:]] def adjacencyMatrix(A, name): rows = len(A) columns = len(A[0]) G = pg...
6ea2bddc10f5de63209bca6fc6a6d4398fa7121f
geetha79/pythonprograms
/grade.py
235
3.953125
4
g=int(input("enter ur grade:")) if g>100: print("grade shoude be less than 101...pLz try again!!!") elif g>= 90: print("A") elif g>=80: print("B") elif g>=70: print("C") elif g>=60: print("D") else: print("F")
db5aecaac502e13576b83af91e3fe4acdf25e798
geetha79/pythonprograms
/t1.py
220
3.59375
4
divisorList=[1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200] for j in divisorList: if j>1: for i in range(2,j): if (j%i)==0: break else: print(j)
d6e6c932bfb74c138e8a65d35f88718b04ce4636
Louis874/python-natural-language-processing--cookbook
/ch1/lemmatization.py
494
3.71875
4
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() def lemmatize(words): lemmatized_words = [lemmatizer.lemmatize(word) for word in words] return lemmatized_words def main(): words = ['leaf', 'leaves', 'booking', 'writing', 'completed', 'stemming'] lem_words = lemmatize(words) ...
4ac2865306ca76bc66cf775e6acffe0aa520875d
paulipotter/BCI-Scholar
/Contacts.py
634
3.515625
4
class Contacts: def __init__(self): # int, int, list self.contact_buddy = 0 #this number adds up all the items in the list below self.total_seconds = 0 # each index represents a day and the number at that index is the amount of # contacts between those two calves during tha...
cf3b6ca9cc9121c247da32d938e971e8447ea377
pnumaster/bugs_music_crawler
/weather_crawler/busan_weather.py
2,345
3.671875
4
# https://www.weather.go.kr # 테마날씨 -> 세계 날씨 -> 아시아 -> 대한민국 -> 부산 import matplotlib.pyplot as plt import matplotlib from urllib.request import urlopen from bs4 import BeautifulSoup #html=urlopen("https://worldweather.wmo.int/kr/city.html?cityId=336") html=urlopen("https://www.weather.go.kr/w/theme/world-weather.do?con...
8464eb1b27fe118c4c544a517ad8c72f9c360c73
charm-dev-pro/Squadron-Roster
/RemoveCadet.py
1,668
3.609375
4
# Import os to remove and rename the files import os # Function that removes a cadet from the roster def remove(): found = False # Search for the cadet search = input('Enter the first name of the cadet you want to remove: ').upper() search2 = input('Enter the last name of the cadet you want to remove: ').u...
fe10e568f35ab1f490b99af0c4741cfe2530775a
aviadud/intro2cs-ex11-backtrack
/ex11_sudoku.py
3,202
4.40625
4
################################################################ # FILE : ex11_sudoku.py # WRITER : Aviad Dudkewitz # EXERCISE : intro2cs ex11 2017-2018 # DESCRIPTION: This program solve a Sudoku boards # using the principle of backtracking. ################################################################ from ex11_ba...
73ee7521b193c38c3357293c4dc494b29f439b57
Anamikaswt/list-files
/square.py
103
3.640625
4
list1=[1,2,3,4,5,6,7] s=[] i=0 while i<len(list1): m=list1[i]**2 s.append(m) i=i+1 print(s)
2f7d114879e8a763f2950f345cf568d06ebd61d5
ebin0402/Local-Machine
/Scripts/WIN or LOSE_Techgig challenge.py
1,218
3.859375
4
#WIN or LOSE '''T=int(input("Enter the trials: ")) N=int(input("Participants: ")) def Fight(): villain=[] player=[] for item in range(N): v=input("Enter Villains: ") villain.append(v) for item in range(N): p=input("Enter Players: ") player.append(p) for ...
c84032aef80f7d334618e47b9d23c668bb6ecacf
ebin0402/Local-Machine
/Scripts/Second lowest Grade.py
321
3.78125
4
''' Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line ''' ...
0011346898e4e2b1a3e24d9211ae3bf42db0376c
debiprasadmishra50/Python-Learning
/Python-Introduction/.Py Files/While Loop.py
574
4.03125
4
#!/usr/bin/env python # coding: utf-8 # ## While Loop # In[4]: num = 5 # In[5]: while (num > 0): print(num) num-=1 # In[6]: num = [1,2,3,4,5] # In[7]: num.pop() # In[8]: num # In[9]: num.append(5) # In[10]: num # while 3 in num: # print("3 is in the list") # num.pop() # In...
c2b3ea6b62942a014d886bb95dc9339d4e3c5210
debiprasadmishra50/Python-Learning
/Python-Introduction/.Py Files/Dictionaries.py
1,273
3.9375
4
#!/usr/bin/env python # coding: utf-8 # ## Dictionary # #### Mutable and denoted by {key, value} # #### Key Value Pair : Use {} : Mutable : Can Store Duplicate Values # In[1]: dictionary = {"key":"value"} # In[2]: dictionary # In[3]: dictionary["key"] # #### Creating a fitness list # # In[4]: fitnes...
0a08293e35d0d181b03ef54814b13f75e8748f6f
chrihill/COM170-Python-Programming
/Program1.py
590
4.21875
4
# Christian Hill #Program Assignment 1 #COMS-170-01 #Display basic information about a favorite book #Variabels: strName - my name, strBookName - stores book name, strBookAuthor - author name, strDate - copy right date, strPage - number of pages strName = 'Christian Hill' strBookName = 'The Fall of Reach' strB...
e871afeb489027ea96b4f7e4c84253cc72c4b83e
chrihill/COM170-Python-Programming
/Project2.py
613
3.90625
4
#Christian Hill #Prgram Assignment number #COMS-170-OE01 #This application calculates the totsl bill at a resturant #Variables: intSubtotal as the subtotal input, ftTip as the 18% tip, ftTax as the 6% tax, ftGrandtotal as the total input of all the variables intSubtotal = int(input('Enter subtotal of Bill: ')) ...
54f3d116b7d7208d6c63f981e52be65a55c05901
jmo927/vue-portfolio
/playtime.py
153
3.609375
4
animals = ['cow', 'duck', 'cat'] for thing in animals: print thing def printStuff (): newString = 'Sup Fresh' print newString printStuff()
ef967ce3f6c95469d800c1081f5a7c73cd1c7cd0
PhungXuanAnh/python-note
/thread_sample/threading_check_is_alive.py
598
3.671875
4
import threading import time def print_time(threadName, delay, counter): while counter: time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 f2 = threading.Thread(target=print_time, args=["22222", 1, 5]) f2.setName("ccccccccccccccccccccccccccc") f2.start...
14093e80907c72aef0c4e56bf90b648a5e2030d5
PhungXuanAnh/python-note
/pymongo_sample/pymongo_array_query.py
5,759
3.65625
4
""" https://docs.mongodb.com/manual/tutorial/query-arrays/ """ import json import pymongo from utils import ObjectIdEncoder from url import AUTHEN_URL client = pymongo.MongoClient('localhost', 27017) # client = pymongo.MongoClient(AUTHEN_URL) db = client.test_database collection = db.test_collection # match an arra...
829b0a16ec63189f502037b1c97df9563008a69f
PhungXuanAnh/python-note
/pickle_usage/pickle_module_load.py
438
3.734375
4
''' Created on Mar 1, 2017 @author: xuananh this modules use to save an python object ''' import pickle from pickle_usage.pickle_module_save import Company with open('pickle_company_data.pkl', 'rb') as input_data: company = pickle.load(input_data) print(company.name) # -> banana print(company.value) ...
e45f9ca7deaca521285aa0886350deff1da8860d
PhungXuanAnh/python-note
/dictionary_sample/merge_and_sum.py
2,954
3.578125
4
origin_dict = {"first": {"all_rows": {"pass": "dog", "number": "1"}}} update_dict = {"first": {"all_rows": {"fail": "cat", "number": "5"}}} updated_dict = {"first": {"all_rows": {"fail": "cat", "number": "5", "pass": "dog"}}} def merge(update, origin): for key, value in update.items(): if isinstance(value...
07555a1a5ab61b04c03ed8ee1d1ee82173ffdaa7
PhungXuanAnh/python-note
/recursively_dump_obj.py
415
3.5
4
import types def dump_obj(obj, level=0): for key, value in obj.__dict__.items(): if not isinstance(value, types.InstanceType): print(" " * level + "%s -> %s" % (key, value)) else: dump_obj(value, level + 2) class B: def __init__ (self): self.txt = 'bye' class A...
a52d8ff1174f0d446d3026764c38656635b500c7
PhungXuanAnh/python-note
/pymongo_sample/pymongo_delete.py
1,536
3.578125
4
""" https://docs.mongodb.com/manual/tutorial/query-arrays/ """ import json import pymongo import random from utils import ObjectIdEncoder from url import AUTHEN_URL client = pymongo.MongoClient('localhost', 27017) # client = pymongo.MongoClient(AUTHEN_URL) db = client.test_database collection = db.test_collection ...
7dc235cc47b99f28ab730e8f0a61d9e2a8d6bc83
PhungXuanAnh/python-note
/list_sample/list_sample.py
4,630
3.96875
4
list1 = [1, 2, 3] for val in list1: print(val) if isinstance(list1, list): print("That is list") mylist = [0, 1, 2, 3, 4, 5] # -6 -5 -4 -3 -2 -1 # chi so duong thi duyet tu phai sang trai, phan tu dau tien co chi 0, duyet cung chieu kim dong ho # chi so am thi duyet tu trai sang phai, phan tu dau tieng...
8d9cf33139cfed49eaf6430074b80e7ba9e5b0f0
PhungXuanAnh/python-note
/others.py
711
4.4375
4
def add(x): return x + 1 def sample_map(): """ map() func allows us to map an iterable to a function. """ print(list(map(add, [1, 2, 3]))) def sample_map_lambda(): """ map() func allows us to map an iterable to a function. using lambda for avoid define a func """ p...
66925ba819178b10091e3559af358044a69c4f02
erxiao211/Python
/Google_News.py
751
3.59375
4
import bs4 import lxml #xml parser from bs4 import BeautifulSoup as soup from urllib.request import urlopen def news(xml_news_url): Client=urlopen(xml_news_url) xml_page=Client.read() Client.close() soup_page=soup(xml_page,"xml") news_list=soup_page.findAll("item") for news in news_list: #test ...
3f0e956f104f788afb6b6906ae5db2a592cab5e5
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios2/ex080.py
518
3.96875
4
lista = [] for c in range(0,5): valor = int(input('Digite um valor: ')) if c == 0 or valor > lista[-1]: lista.append(valor) print('Adicionado ao final da lista') #elif valor > lista[len(lista)-1]: #ou lista[-1] # lista.append(valor) else: pos = 0 while pos < len(l...
bf10ff9510a7274223d8764192a1f36366636bb7
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex037.py
486
4.15625
4
numero = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para a conversão [1] converter para binário [2] converter para octal [3] converter para hexadecimal''') opcao = int(input('Sua opção: ')) if opcao == 1: print(f'{numero} em binário é igual a {bin(numero)}') elif opcao == 2: print(f...
9d5be47af2dc98844eaa9fe46c409e61e532dbab
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios2/ex081.py
429
3.984375
4
lista = [] while True: numeros = int(input('Diga um valor: ')) continuar = str(input('Quer continuar: ')).upper().strip()[0] lista.append(numeros) if continuar == 'N': break print(f'Você digitou {len(lista)} elementos') lista.sort(reverse = True) print(f'A lista em ordem decrescente fica: {lista...
fa39ccee70c48eb3074e2510f21ef8ede32e379c
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex006.py
167
3.875
4
x = int(input('Digite um número x ')) print(f'O dobro desse número é {x*2},\nO triplo desse número é {x*3},\nA raiz quadrada desse número é {x**(1/2):.2f}')
a11f57d50681d1880f3cafd9b18fbfde70163f38
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex051.py
279
3.953125
4
print('---'*10) print(' 10 TERMOS DE UM PA ') print('---'*10) primeiro = int(input('Primeiro termo: ')) razao = int(input('Diga a razão: ')) decimo = primeiro + ( 10-1 ) * razao for c in range(primeiro, decimo + razao ,razao): print(c, end=' > ') print('ACABOU!')
d22fbdaed94fc08a9d6b81e59f19f13a0cf23fa2
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex048.py
258
3.78125
4
soma = 0 cont = 0 for conta in range(1, 501, 2): if conta % 3 == 0: cont += 1 #números que foram somados ou 'cont = cont + 1' soma = soma + conta #numeros somados print(f'A soma de {cont} valores impares e divididos por 3 é: {soma}')
8bc27db57bff2d9de4fbdf21e8aebe60bd12173d
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex042.py
409
3.96875
4
n1 = float(input('Diga o primeiro segmento: ')) n2 = float(input('Diga o segundo segmento: ')) n3 = float(input('Diga o terceiro segmento: ')) if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n2 + n1: print('Forma triângulo') if n1 == n2 == n3: print('EQUILÁTERO') elif n1 != n2 != n3 != n1: print('...
f7c62d23b653fb0898963027dd2c91f61c8cb160
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios/ex063.py
270
3.96875
4
print('Sequência de fribonacci!') termos = int(input('Quantos termos vocÊ quer mostrar? ')) t1 = 0 t2 = 1 print(f'{t1} > {t2} ', end='') cont = 3 while cont <= termos: t3 = t1 + t2 print(f'> {t3} ', end='') t1 = t2 t2 = t3 cont += 1 print('FIM! ')
daaaccb80a903e850a50ece0c18cb4e727999019
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/Aulas/Aula7.py
327
3.71875
4
#nome = str(input('qual é o seu nome?')) #print(f'prazer em te conhecer {nome:=^20}!') n1 = int(input('escolha um valor: ')) n2 = int(input('escolha outro valor: ')) print(f'A soma vale {n1+n2} ', end= '') print(f'A divisão é {n1/n2:.3f} ', end= '') print(f'O produto é {n1*n2},\n A divisão inteira é {n1//n2}') ...
b70134465177acc973f1e9776625ca4ef5a9c991
FernandaSlomp/Resumo_Tecnologias_Introdutorias
/Curso_Python_MEGAREVISAO/aprendendo/exercicios2/ex090.py
315
3.671875
4
tentando = [] dados = {'nome': 'x', 'media': 'y'} nome = str(input('Nome: ')) media = int(input(f'A média de {nome}: ')) dados['x'] = nome dados['y'] = media print(f'O nome é igual a {nome}') print(f'A média é igual a {media}') if media >= 7: print('Situação é aprovado!') else: print('DESAPROVADO!')
0769cd43344c09b50f5f6e3d3f31b15d554f3ad8
nashvent/compiladores-ucsp
/practica-0/ejercicio-1/validator_stack.py
1,590
3.609375
4
from collections import deque class Validator: valid_chars = { "{": {"required": None}, "}": {"required": "{"}, "[": {"required": None}, "]": {"required": "["}, "(": {"required": None}, ")": {"required": "("} } def __init__(self, str): self.counter ...
cc6b9847227b72713e41b6b3caddb6f1a0fcb00b
xuvf/fc
/part3/part3.py
6,842
4.25
4
""" This module represents some classes for a simple word game. There are a number of incomplete methods in the which you must implement to make fully functional. About the game board! The board's tiles are indexed from 1 to N, and the first square (1,1) is in the top left. A tile may be replaced by another tile, hen...
a19f33e47c0d0914d93af7a9f0bb2f776c1002cc
ietsy/WISB256
/Opdracht4/bisection.py
478
3.765625
4
import sys import math def findRoot(f, a, b, epsilon): # Calculate the midpoint m = (a + b) / 2 # Terminate if the endpiont is the root if f(m) == 0: return m # Check if the half is larger than epsilon else return midpoint elif math.fabs(m-a) <= epsilon: return m # See what ...
cfcc3e256dc182b34139ef8df06054073b438b9a
d3v3l0/pedl-examples
/external/mnist_pytorch/model_def.py
3,115
4
4
""" This example shows how to interact with the pedl PyTorch interface to build a basic MNIST network. The method `build_model` returns the model to be trained, in this case an instance of `nn.Sequential`. This model is single-input and single-output. For an example of a multi-output model, see the `build_model` metho...
1bbef9302d7541e1985107433a0fbfb42db95cd6
Bjarkis/TileTraveler2
/tiletraveler.py
3,657
3.953125
4
import random # Constants NORTH = 'n' EAST = 'e' SOUTH = 's' WEST = 'w' YES = 'y' NO = 'n' levers = [(1,2), (2,2), (2,3), (3,2)] def move(direction, col, row): ''' Returns updated col, row given the direction ''' if direction == NORTH: row += 1 elif direction == SOUTH: row -= 1...
35b5a413e426b3428d1fde116f2e9b02cf096b1b
MFMorrell/scikits.bvp_solver
/scikits/bvp_solver/ProblemDefinition.py
27,986
3.9375
4
import numpy import tools import pickle class ProblemDefinition: """Defines a boundary value problem. """ def __init__(self, num_ODE, num_parameters, num_left_boundary_conditions, boundary_points, function, ...
050d7f7d3cb896b98ee9745c806ccd585ef3a16f
cjim8889/Algorithms
/LinkedList/singleLinkedList.py
1,464
3.5625
4
class Node: def __init__(self, value = None, nextNode = None): self.value = value self.nextNode = nextNode def __repr__(self): return self.value class SingleLinkedList: def __init__(self): self.head = None self.tail = self.head ...
3ea0003beea89266866ca00c7ae40d08a3634a4d
tchka/python2
/task_1.py
585
4.1875
4
# https://drive.google.com/file/d/18aEzzMoVyhGi9VjPBf_--2t-aVXVIvkW/view?usp=sharing # Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. number = int(input('Введите целое трехзначное число: ')) number = abs(number) n0 = number % 10 print(n0) number = number // 10 n1 = number % 10 print(...
86d65327fb31f18bc6cea2166a080dc98ad213b9
Cesar0106/JogoCraps_CesarAdes_JonathanSutton
/JogoCraps.py
4,149
4
4
import random quant_fichas = 20 print ("Bem vindo ao jogo de Craps! Neste jogo, você poderá escolher entre 4 modalidades de apostas, sendo elas: Field, Twelve, Any Craps e Pass Line Bet. Você começará o jogo com 20 fichas, e se chegar no zero será eliminado do jogo. Você poderá sair da partida ao digitar 'sair do jogo'...
e29aa4e712ea51fdc730f1a935d4d3e3323ef155
ternado/toto_analysis
/toto_analysis/csv_analysis.py
1,794
4.0625
4
#! /usr/bin/python # -*- coding: utf-8 -*- # author : lyushuen@gmail.com import csv class Csv(object): """ 用来处理csv 文件,三个函数的作用: rowdicts: csv文件的第一行中的每一个单元格作为key,对每一行都会产生多个 key: value对的 dictionary columdicts:以csv文件的第一行中的每一个单元格作为key, 每一列会产生一个字典 keydicts: 根据用户输入的key的关键字, 此函数会产生基于此关键字的针对每一行的字典 """ def __i...
3d29ffea6c2741fa46cd5425620a0c5f72aa92b7
mwenz27/python_misc
/SumNumbersBetween.py
160
3.84375
4
a = int(input("Select numbers ")) b = int(input("Select number ")) total = 0 print(list(range(a,b+1))) for i in range(a,b+1): total += i print(total)
3be67f96c253b5738481fd7fe5ed02fe4cf3a55c
uriophir/WeatherPatterns
/plot.py
7,618
3.59375
4
# coding: utf-8 # # Assignment 2 # # Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize your...
335684024724e8a85709e04144449037d244bcd5
melbing1/7x24
/simulator/GraphGenerator/GraphGenerator.py
2,566
3.875
4
# Library: Why it was imported: import sys # System (used to take arguments) import numpy as np # Poisson Distribution import matplotlib.pyplot as plt # Show the plot import DataGenLib as DataGen # Misc Functions # Source ...
8f66de70e5f5cf09af62f71a4b94f455f4cf4dbd
MXYLR/Full-Speed-Python-Exercises-Answer
/协程学习和练习/LearnGenerator.py
712
3.75
4
def create_num(all_num): a, b = 0, 1 current_num = 0 while current_num < all_num: ret = yield a#如果第一次用next,那么这个a就是next前面变量的结果 print(">>>ret>>>", ret) a, b = b, a+b current_num += 1 obj = create_num(10) #obj.send(None) #send一般不会用来放到第一次启动生成器,如果非要这么做,那么传递None r...
dbf9bd4e33d038c1c5849ea0e3414bbd60ae5777
zufishantaj/competitiveprogramming
/chefandop.py
343
3.859375
4
if __name__ == '__main__': test = int(input()) for i in range(test): inputString = input() numList = inputString.split(' ') num1 = int(numList[0]) num2 = int(numList[1]) if num1 > num2: print(">") elif num1 < num2: print("<") else: ...
a25c3917dfc3fd580e9bcb107df8a50c0e9719ff
alliequintano/triangle
/main.py
1,412
4.1875
4
import unittest # Function: triangle # # Given the lengths of three sides of a triangle, classify it # by returning one of the following strings: # # "equ" - The triangle is equilateral, i.e. all sides are equal # "iso" - The triangle is isoscelese, i.e. only two sides are equal # "sca" - The triangle is scal...
187c84f5194be8077edccd8c4a7c0b58de4b5298
rkoblents/python-text-adventure-api
/textadventure/customgame.py
4,298
3.515625
4
from abc import ABC, abstractmethod from typing import List from textadventure.actions import EntityActionToEntityManager from textadventure.battling.commands import AttackCommandHandler from textadventure.battling.managing import DamageActionManager, BattleManager, HostileEntityManager from textadventure.commands.com...
2b9af2abd62ebfcc7ca16936e275856ede230b17
rkoblents/python-text-adventure-api
/textprint/textutil.py
1,023
3.8125
4
from pyparsing import Literal, nums, Word, delimitedList, Optional, alphas, oneOf, Combine, Suppress # note this imports a class called Optional. If we, in the future, import typing.Optional, this will conflict ESC = Literal("\x1b") integer = Word(nums) escapeSeq = Combine(ESC + '[' + Optional(delimitedList(integer,...
9d5ed7ba5c2fde36c91effd5965afeffe1ff3feb
rkoblents/python-text-adventure-api
/textprint/input.py
13,453
3.5
4
import warnings from typing import TYPE_CHECKING from textprint.line import Line try: import curses except ImportError: curses = None warnings.warn("module curses not installed. textprint module won't be fully operational") if TYPE_CHECKING: from textprint.textprinter import TextPrinter class Edita...
c04cd357aa9cb9982ca98ada57d4f62f3a5553a7
rkoblents/python-text-adventure-api
/textadventure/sending/message.py
10,018
3.9375
4
import warnings from enum import Enum from typing import List from textadventure.utils import join_list from textprint.colors import Color class MessageType(Enum): """ An enum that represents how the message will be printed out and how it will be shown """ IMMEDIATE = 1 """The message will be pr...
779f0b708669ff515d08fba2e71ca52fc1797810
rkoblents/python-text-adventure-api
/textadventure/item/holder.py
1,127
4
4
from typing import TYPE_CHECKING if TYPE_CHECKING: from textadventure.item.item import Item class Holder: # kind of like an interface """ This is a simple class that represents something that holds items Item picking up/dropping is handled by the weapon that is being dropped/picked up using change_...
678e8fb7c3db7d2030132845d46d7670d55341ca
gautam-b/games
/soduku_solver/Soduku.py
1,684
3.6875
4
""" Solve Soduku Puzzle thorough backtracking and recurssion """ import time import puzzle from soduku_img import draw_soduku from utils import print_sudoku backtracks = 0 def find_cell_to_fill(sudoku): for i in range(9): for j in range(9): if sudoku[i][j] == 0: return (i, j...
bb7dcad752dae71271ae21e4c21bee34efeb9cdd
bbugyi200/old_dotfiles
/.task/hooks/utils/dates.py
1,370
3.734375
4
"""Functions Relating to Dates and Times""" import datetime as dt date_fmt = '%Y%m%dT%H%M%SZ' def get_tomorrow(): """Returns Formated Datetime for Tomorrow (at 6AM)""" tomorrow = _style_dt(dt.datetime.today() + dt.timedelta(hours=18)) return tomorrow.strftime(date_fmt) def get_today_dt(): """Retur...
232b21b4bd8c523d2dfb3e9fc72084168121d563
trdvangraft/evoalg
/src/algorithms/optimizer.py
1,359
3.640625
4
"""Super class for all swarm based optimizers """ from __future__ import annotations import abc from src.problems.problem import Problem from src.utils.logger import Logger class Optimizer(metaclass=abc.ABCMeta): def __init__(self, number_of_iterations: int, population_size: int) -> None: self.n...
e5572061f74d7ece9347f62239a8b88969edd9af
ambujpawar/advent_of_code_2020
/day_6.py
1,279
3.5
4
def ReadInputData(file_path): input_data = open(file_path, "r") input_strings = input_data.readlines() lines_list = [line.strip('\n\n') for line in input_strings] return lines_list def GroupAnswersPerGroup(input_data): group_answers = [] final_data = [] for data in input_data: if d...
92b2f41ce0a2607bf8f16d530d3826492bba4fe6
LuanCantalice/JogoAdivinhacao
/Parte1.py
972
4.09375
4
def JogoAdvinha(): import random numAleatorio = random.randint(1, 100) tentativas = 3 print("Você tem 3 tentativas!") while(tentativas > 0): print("---TENTATIVAS RESTANTES--->", tentativas) tentativas = tentativas - 1 palpite = eval(input("Digite o seu palpite: ")) if...
c972f1a19b48e7c1a1068b78e2475b17e11852bf
Wilfred/difftastic
/vendored_parsers/tree-sitter-python/test/highlight/pattern_matching.py
1,297
3.5
4
match command.split(): # ^ keyword case ["quit"]: # ^ keyword print("Goodbye!") quit_game() case ["look"]: # ^ keyword current_room.describe() case ["get", obj]: # ^ keyword character.get(obj, current_room) case ["go", direction]: # ^ keyword curre...
c903469c5987fbd24b41baa770bcc83622333c0c
Tometoyou1983/Python
/Automate boring stuff/RockPaperScissors.py
1,900
4.03125
4
import random, sys print ("Lets play Rock, Scissors, Paper") wins = 0 losses = 0 ties = 0 while True: print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties)) while True: playerMove = input("Enter a move: (r)ock, (s)cissors, (p)aper, (q)uit: ") if playerMove == "q": sys.exit() ...
3fadb55e9a4967095f0085c03276d0a716851c80
Tometoyou1983/Python
/Automate boring stuff/commacode.py
424
3.84375
4
import os, sys os.system("clear") spam = [] while True: name = input("Enter a string: ") spam.append(name) moreDataFlag = input("Would you like to enter more? (Yes/No)") if moreDataFlag != "Yes": break accumString = "" for i in range(len(spam)-1): accumString = accumString + spam[i] + " ,"...
0acc03cdc92969207312994c2e7e357f2818cca6
Tometoyou1983/Python
/Python web programs/seleniumWebBrowser.py
687
3.65625
4
# ! python3 # Selenium controlled web browser. # Author suggested using firefox. trying to use chrome. #to use chrome, we need chrome driver copied on the machine and the path provided. import os, sys, bs4, requests from selenium import webdriver os.system('cls') driver_path = "C:/Users/NagaVenkataSuryaNare/Documents...
808e12eef51c92d2ef004a9b39a638b1e5334fd4
Tometoyou1983/Python
/Automate boring stuff/collatz.py
2,119
4.1875
4
''' import os, sys os.system("clear") print("Lets introduce you to collatz sequence or problem") print("its an algorithm that starts with an integer and with multiple sequences reaches at 1") numTries = 0 accumlatedNum = "" newNumber = 0 def collatz(number): if number % 2 == 0: newNumber = number // 2 ...
42308e549e899e178a4008bf979c26d2334fa4d0
Tometoyou1983/Python
/Automate boring stuff/threadDemo.py
387
3.90625
4
# python 3 # demo of multi threading in python import os, threading, time os.system('cls') print('Start of the program') def takeANAP(): time.sleep(5) print('Wake Up!') threadObj = threading.Thread(target=takeANAP) threadObj.start() threadObj = threading.Thread(target=print, args=['cats', 'Dogs', 'Frogs'],...
8c5c77bfc74d306f009270795c5ffc647418e894
Leberwurscht/pcolormesh_preprocess
/pcolormesh_preprocess/functions.py
1,502
3.53125
4
import numpy as np def pcmp(*args, indexing="ij"): """ Preprocess data passed to pcolormesh so that axes are aligned to the centers of the corresponding rectangles, not their borders. You can either call it with three arguments (x axis, y axis, 2D data) or with only one argument (only 2D data, x and y are ge...
5be5bc3055fa7c49eb23047b4bbee11666ec8c34
pashk-ka/bikeshare
/bikeshare.py
9,320
4.21875
4
import time import pandas as pd import numpy as np from collections import Counter CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Retu...
75602031dd4135a86ffbf3a9f07745815430daa6
manishmadugula/Practice-Code
/Graph_algorithms/python/heap.py
955
3.578125
4
class MinHeapStructure(): def __init__(self,Array): self.heap=Array[:] self.minHeap(self.heap) def swap(self,m,n,arr): o=arr[m] arr[m]=arr[n] arr[n]=o def minHeapify(self,i,arr): if(i <= len(arr)/2-1): try: if(arr[2*i+1]>arr[2*i+2]): minVal=arr[2*i+2] minInd=2*i+2 else: m...
4daadec02e142fd54e1b26b86c0a0a87a7890022
GACAL2707/Clase4
/reto2.py
784
4.03125
4
''' ----------------------------- RETO N°2 Bucle for ----------------------------- ¿Sabías que agregar la palabra Mississippi a un número al contar los segundos en voz alta hace que suene más cercano al reloj? A menudo lo usan los niños que juegan al escondite para asegurarse de que el buscador haga un conteo honesto...
cb60959d9c5c4e92c92b62f494f27791bf8b5d2d
snowhork/hadou
/clock.py
631
3.515625
4
import os, time class Clock: def __init__(self, output_path=None, name=''): self.name = name self.output_path = output_path def __enter__(self): print(self.name) self.begin = time.clock() return self @property def current(self): return time.clock() - se...
df74088042f641804aff9a4b2f5da16b6f157fb2
Kennethowl/Practicas-Java-y-Python
/Python/cajeroAutomatico.py
966
4.03125
4
# Simulacion de un cajero automatico from os import system saldo = 2000 while True: system("cls") print("1 - Consultar") print("2 - Retiros") print("3 - Depositos") print("4 - Salir") opcion = int(input("Seleccione una opcion: ")) if opcion == 1: print(f"Saldo en tu cuenta es: {sa...
08fd2a87081a0ddc7d56c5c9a6c393ba669efa75
Kennethowl/Practicas-Java-y-Python
/Python/HelloWorld_Datatypes.py
694
4.25
4
# Comentarios print("Hola Mundo, como estan") # Datatypes # Maneras de imprimir string print("Hola Mundo, como estan") print("""Hola Mundo, como estan""") print('Hola Mundo, como estan') print('''Hola Mundo, como estan''') # Comando Type print(type(100)) # Concatenacion print("See you around" + " " + "World") # ...
74c121ffafebd7c1e22bbcb646002a8448fa9e24
mattseatondev/challenges
/PythonChallenges/factorial.py
186
4.125
4
def factorial(num): prod = num for i in reversed(range(1, num + 1)): print(f'{prod} TIMES {i} EQUALS {prod * i}') prod *= i return prod print(factorial(10))
3c456da9254bc36cec0c1bbd3f85eeb0847375d6
ken2190/Stock
/_API_Investpy.py
2,009
3.5625
4
import investpy """the question is, where is the csv file generated?""" def my_get_indices(country=None): return investpy.get_indices(country=country) def my_get_stocks(country=None): return investpy.get_stocks(country=country) def my_get_funds(country=None): return investpy.get_funds(country=country)...
d7cebd84b108409385559adcd3626a7edfd912d2
Wuzhibin05/python-course
/Course/Section-1/day14/1.复习.py
1,520
3.875
4
""" 迭代器和生成器 迭代器: 双下方法 : 很少直接调用的方法。一般情况下,是通过其他语法触发的 可迭代的 —— 可迭代协议 含有__iter__的方法('__iter__' in dir(数据)) 可迭代的一定可以被for循环 迭代器协议: 含有__iter__和__next__方法 迭代器一定可迭代,可迭代的通过调用iter()方法就能得到一个迭代器 迭代器的特点: 很方便使用,且只能取所有的数据取一次 节省内存空间 生成器 生成器的本质就是迭代器 生成器的表现形式 生成器函数 生成器表达式 生成器函数: 含有yield关键字的函数就是生成器函数 特点: 调用...
71db75a715c2446479379562808a271d7a1ff9a7
Wuzhibin05/python-course
/Course/Section-1/day1/t1.py
2,769
3.515625
4
#-*- encoding:utf-8 -*- #print('我爱中国') ''' x = 1+2+3+4 print(x) print(x*5) y = x*5 print(y+100-45+2) print('泰哥泰哥,我是小弟') print('泰哥泰哥,我是三弟小妹') t-t = 2 3t_t = 23 *r = 4 _ = 'fdsa' ___ = 4 %- = 'fdsa' 2w = 5 qwe-r = 'wer' kfdsdlafhsdakfhdsakdfjkhsdakf = '太白' print(名字) AgeOfOldboy = 56 NumberOfStudents = 80 #下划线 age_...
f76468fed3eeadeaccde1ff32efe89fab1aace67
joannacao/Bikeshare-data-analysis
/bikeshare-data.py
1,742
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 20 00:06:25 2018 @author: joann """ import numpy as np import pandas as pd from scipy import stats from datetime import datetime as dt #Display or graph 3 metrics or trends from the data set that are interesting to you. #Which start/stop stations are most popul...
aa1bd618908b34c1af864436281fa6da04140f81
artreven/fca
/fca/algorithms/patterns.py
6,092
3.828125
4
# -*- coding: utf-8 -*- """ Holds functions for processing patterns. For this purpose one holds 2 contexts: positive and negative. Patterns are combinations of attributes that only appear in positive context and do not appear in the negative context. Intuition: every pattern is a combination of attributes that is suffi...
7bd036236fb05c171afba7371570f7abab4fadaa
FYP-BE-E2/Fire-Dectection-Using-Python-and-Image-Processing
/ImageSubtraction.py
993
3.515625
4
#importing Open Cv2 library import cv2 #importing Numpy Library import numpy as np # storing video from primary camera in to variable vidcap = cv2.VideoCapture(0) #https://docs.opencv.org/3.0-beta/doc/tutorials/video/background_subtraction/background_subtraction.html #this method take first image and store into fgm var...
a9b0109936cb0e7cff27f71f27389f6d0a7bef82
elisabethvirak/python-challenge
/PyBank/main.py
2,390
3.75
4
# import modules needed import csv import os # create values profit_loss = 0 months = 0 monthly_profit_list = [] month_max_profit = ["", 0] month_max_loss = ["", 0] avg_profloss = 0 # create path to find csv file budget_csv = os.path.join("budget_data.csv") # create csvfile to write to output = os.path.join("budget...
1f646e7aaf750999ca1b60e39b3fc1deaa894786
rirwin/sandbox
/scratch/github-data-printer/github_json_print_json_per_line.py
1,064
3.515625
4
import json from pprint import pprint as pprint import sys if len(sys.argv) != 3: print "you need 2 arguments" print "First to be path to the file (full or relative)" print "Second to be the path for the output file" sys.exit(1) in_file_path = sys.argv[1] out_file_path = sys.argv[2] print "opening",...
02822058efc7642aa91e374dab6dcecf41100159
GT12ness/lectures
/examples/Ulohy_hodina4.py
1,997
4.15625
4
""" 1. napiste program v pythone - vypisete text: aka je vonku teplota? - zadate vstup (cislo) - vyhodnotite ak je teplota vyssie ako 25 tak vypiste: "zober si tricko. " ak nie vypiste: "Zobrer si aj sveter. " - na konci vypiste: "Mozes ist vonku" mozne riesenie: """ temperature = float(input('What ...
5bdcd8c247868d62876b0ffc7dcb5384b6487862
hyangit/gomoku
/game/game.py
583
3.65625
4
# 游戏 class Game: def __init__(self, board, display, player1, player2): self.board = board self.display = display self.player1 = player1 self.player2 = player2 self.player = self.player1 def mainloop(self): self.display.mainloop() def play(self): if s...
5eb1b26666be2f0691511c721d9803c9eddbaafa
op-secure/ML-Python-Scikit-Notes
/7_numpy_NaN-values.py
947
3.859375
4
# NaN Values import numpy as np a = np.array([np.nan, 0 ,1 ,2, np.nan]) print(a) # Note: Scikit-learn does NOT accept NaN values # - They will need to be filtered out as follows # Check for NaN values print(np.isnan(a)) # Filter out NaN values # - Negate the array and apply box brackets print(a[~np.isnan(a)]) # A...
7bbba16ef22f06a564aca9ae2b284df1faa60ed7
ohsean93/Data_Structure
/python/heap.py
2,368
3.578125
4
class Node: def __init__(self, data, p_node=None, l_node=None, r_node=None): self.data = data self.p_node = p_node self.l_node = l_node self.next_node = r_node def __repr__(self): return str(self.data) class Heap: def __init__(self): self.head = None ...
304f5e570b6810e9a79473cfa6b1fbda91a02a90
boop34/adventofcode-2020
/day_13/day_13.py
1,810
3.609375
4
#!/usr/bin/env python3 # fetch the input with open('input.txt', 'r') as f: # initialize the departure time d_time = int(f.readline().strip()) # get the bus information bus_ids = f.readline().strip().split(',') # include the 'x' for the second part of the puzzle bus_ids = list((int (i) if i != '...
858b08348957013008b64cadc2f46261f4d838d8
boop34/adventofcode-2020
/day_23/day_23.py
5,545
3.6875
4
#!/usr/bin/env python3 # 1 million MILLION = 1000000 # initialize the cups input cups = [5, 3, 8, 9, 1, 4, 7, 6, 2] # cups = [3, 8, 9, 1, 2, 5, 4, 6, 7] # initialize total moves to be done i.e 100 moves1 = 100 moves2 = 10000000 def solve(cups, moves, n): ''' this function takes the cups list and the number ...
d2cc673c4cf2e97e1e81612c5f7cbe3dee16443a
TabibitoDK/StudyApp
/data/Chemistry/main.py
1,589
3.9375
4
# define functions def data_parser(file_location, salt): f = open(file_location, "r") for x in f: result = x.split(" = ") salts = result[1].split(" ; ") for s in salts: if salt == s: return result[0] f = open(file_location, "r") for x in f: res...
b4b469aeb580da7bf9a83b6b1b3c64a967cd3dc8
Turhsus/coding_dojo
/python/bike.py
736
4.21875
4
class Bike(object): def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print "Price:", self.price, "Dollars; Max Speed:", self.max_speed, "MPH; Miles:", self.miles return self def ride(self): print "Riding" self.miles...
e32905d86c706641cd8d2f51e9a41dffd5bfaf0e
Turhsus/coding_dojo
/python/scores_grades.py
384
4.0625
4
print "Scores and Grades" def get_grade(score): if (score <= 69): return " Your grade is D" elif (score <= 79): return " Your grade is C" elif (score <= 89): return " Your grade is B" else: return " Your grade is A" for item in range (0, 10): print "Test Score?" score = input() print "Score: " + str(sc...
d4ad382c502ac892325624830275d229b1951113
Turhsus/coding_dojo
/python/car.py
624
3.859375
4
class Car(object): def __init__(self, price, speed, fuel, mileage, tax = 0.12): self.tax = tax self.price = price if(self.price > 10000): self.tax = .15 self.speed = speed self.fuel = fuel self.mileage = mileage self.display_all() def display_all(self): print "Price:", self.price print "Speed:", ...
a3b0981d930c5dfc9263c27c1e7197a2c304b01e
casteller/autoTestFile
/自动化测试学习/1、python学习/11、多线程/t1.py
418
3.5625
4
''' 炒菜的例子, 刚搬家的时候 ''' from time import ctime, sleep def chicken(): for i in range(2): print("我正在做宫保鸡丁~~~~~~~. %s" % ctime()) sleep(2) def fish(): for i in range(2): print("我正在炒鱼香肉丝~~~~~~~~ %s" % ctime()) sleep(3) if __name__ == '__main__': chicken() fish() p...
8585c6e5a44004277849fb411970f6005e0e2ae9
casteller/autoTestFile
/自动化测试学习/2、sele学习/autoUI_selenium/lesson01/simple2.py
934
3.5625
4
from selenium import webdriver # 指定是chrome 的驱动 # 执行到这里的时候Selenium会去到指定的路径将chrome driver 程序运行起来 driver = webdriver.Chrome(r"d:\tools\webdrivers\chromedriver.exe") # get 方法 打开指定网址 driver.get('http://www.baidu.com') # 查找到那个搜索输入栏网页元素,返回一个表示该元素的WebElement对象。 element_keyword = driver.find_element_by_id("...
5086cc33f668aca535c8bcd1a9bc3b66388f1284
mk2016a/LightNovels
/novels/tools/rename.py
1,328
3.828125
4
import re import os class RenameFiles: def __init__(self, folder): self.folder = folder def walk(self): for root, dirs, files in os.walk(self.folder): for dir in dirs: path = root + '/' + dir print(path) for file in files: ...
740de0cb3d6afbb7c3b28752d15a1e7bdb751a12
Breenori/Projects
/FH/SKS3/Units/urlParser/sqlite/sqlite.py
570
4.15625
4
import sqlite3 connection = sqlite3.connect('people.db') cursor = connection.cursor() cursor.execute("create table if not exists user(id integer primary key autoincrement, name text, age integer)") cursor.execute("insert into user values (NULL, 'sebastian pritz', 22)") #1 cursor.execute("select * from user") row =...
f5832a67aa4a7c76bba38c5e5d3cdd3869bec668
Breenori/Projects
/FH/ADS1/Learning/Learning/Learning.py
580
3.9375
4
import math a = int(input("Please enter a:")) b = int(input("Please enter b:")) c = int(input("Please enter c:")) if(a != 0): p = b / a q = c / a D = pow(p/2,2) - q if(D < 0): print("x1 = " + str(-p/2) + "+i" + str(math.sqrt(-D))) print("x2 = " + str(-p/2) + "-i" + str(math.sqrt(-D))) elif(D >= 0): x1 = -...
42cd3d0787a26a0396649801cae592e27a0d9b27
Breenori/Projects
/FH/SKS3/Units/logodesign.py
441
3.96875
4
import turtle ''' def rectangle(side): for i in [1,2]: turtle.forward(side) turtle.left(-90) turtle.forward(side/4) turtle.left(-90) for i in range(1,9): rectangle(100) turtle.left(-45) ''' wn = turtle.Screen() wn.bgcolor("black") t = turtle.Turtle() t.shape("turtle") t.col...