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 |
|---|---|---|---|---|---|---|
a81e683fbbf4e7c108e0931b6fa608c84de56932 | FlowerFlowers/Leetcode | /src/Tree/637AverageOfLevelsInBinaryTree.py | 1,268 | 3.640625 | 4 | '''
leetcode题号:637
按顺序输出个二叉树每层节点的平均值
eg:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
思路:深度优先遍历每一个节点,然后一个info记录这层节点的节点数和值的总和作为结果的输出,比如对上面的例子,最终
info = [[3,1],[29,2],[2... |
76c410aec4b6c4e53aa435b5f074a4bb2b444b75 | FlowerFlowers/Leetcode | /src/Graph/997FindTheTownJudge.py | 1,026 | 3.546875 | 4 | '''
leetcode题号99
一个小镇有N个人,可能有1个法官或没有,要求:
1.法官不信任任何人
2.其他人都信任法官
如果有法官,请找出法官,没有返回-1
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Exam... |
a884945c120869b71d372617e292bf643ca60a87 | jackedison/Sudoku_Solver | /UI.py | 14,090 | 3.546875 | 4 | # Implement a sudoku UI using pygame
import pygame # wrapper for the SDL library
import time
import copy
import json # to read json sudoku from file
import solver
class Grid():
def __init__(self, window, rows=9, columns=9):
assert rows == columns # For now game requires but could adapt
self.... |
d54ff75a76d041fe913d0588725073d9fead3017 | MaureenFromuth/Election_Analysis | /Python_Practice.py | 938 | 3.578125 | 4 | #Add our dependencies.
import csv
import os
#Assign a variable to load a file from a path.
polling_data = os.path.join("election_results.csv")
#Assign a variable to save the file to a path.
saved_polling_data = os.path.join("analysis","election_analysis.txt")
#Initialize the total vote counter.
total_votes = 0
#Decl... |
38bcf67d9f81434e38f8c35efc84591a0fda6842 | araf-rahman/QA_Project_PerScholas | /Prime number.py | 226 | 3.828125 | 4 | def is_prime(n):
i = 2
while i < n:
if n%i == 0:
return False
i += 1
return True
p = 2
while p <= 100:
if is_prime(p):
print (p,"is prime number"),
p=p+1
print ("Done") |
fbc8e5cc713bb88c84767ae31767e01a43ce5ffe | dzbrozek/testris | /main.py | 7,181 | 3.6875 | 4 | import copy
import random
from typing import List
BOARD_WIDTH = 20
BOARD_HEIGHT = 20
blocks = [
[
[1, 1, 1, 1]
],
[
[1, 0],
[1, 0],
[1, 1]
],
[
[0, 1],
[0, 1],
[1, 1]
],
[
[0, 1],
[1, 1],
[1, 0]
],
[
... |
a342a3fd0834fc418850ca779b5e85ce5634c722 | FermiD/schoolworkk | /count letter frequencies.py | 362 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#%%
firstw = input("first word : ")
secondw = input("second word : ")
anag1 = sum([ord(x) for x in firstw])
anag2 = sum([ord(y) for y in secondw])
if (anag1 == anag2):
print("They are anagrams of each other")
else:
p... |
447bbacdf7bbd74304bdcf3e87995551c385ee49 | ownnow/Python3_Base | /src/BaseTest/Day2/1.py | 1,313 | 3.609375 | 4 | #coding:utf-8
'''
Created on 2016年3月20日
@author: yusha
'''
#一个字典就是一个键对应一个单值的映射。
#如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中,
# 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典
# d = {
# 'a':[1,2,3],
# 'b':[4,5]
# }
# e = {
# 'a':{1,2,3},
# 'b':{4,5}
# }
from collections import defaultdict
d = defau... |
3d04a6518785a52aa84fd898fef0911ab448fb46 | ownnow/Python3_Base | /src/Program_Design_Ideas/calendar.py | 1,624 | 3.828125 | 4 | def getYear():
print('This program prints the calendar of a given year.')
year = int(input('Please enter a year (after 1900):'))
return year
def firstDay(year):
k = leapyears(year)
n = (year - 1900)*365 + k
return (n+1)%7
def leapyears(year):
count = 0
for y in range(1900,y... |
949ad88034807cf3b28eea4ce730de298aa0bfae | Jugal112/Pentago | /GameBoard.py | 11,334 | 3.65625 | 4 | '''
Created on May 11, 2015
@author: Jugal112
'''
from Player import Player
import re
import copy
import sys
import random;
class GameBoard:
player1 = Player("player1","B")
player2 = Player("player2","W")
#computer = False means to turn the AI off. when it's True,
#then player 1 can play the c... |
6d38861b7a91b3fe49953ac7cb619a98cc415c2f | marksibrahim/sen_gen | /action7.py | 3,146 | 3.5 | 4 | import random
class Action7():
"""
generates Action 7, which is comprised of p17
"""
def __init__(self, our_story):
self.story = our_story
# p17 s1
if self.story.season['action7'] == "fall":
self.location = "on an island off the coast of Maine"
elif self.st... |
e5c6db189fcb2d0b3bc277d1695f1491119ad4bb | marksibrahim/sen_gen | /tools/story_pieces.py | 5,333 | 3.84375 | 4 | import random
"""
SEASONS: randomly generates a dictionary of seasons-by-plot-section for story 1
"""
def gen_seasons():
plot_order = ['action1', 'action2', 'action3', 'action4', 'action5', 'action6',
'action7', 'action8', 'action9']
opening_season = ('summer', 'fall', 'winter', 'spring')
... |
ed5bc0f83330c0aa412b71816c2e99f84c46fbc6 | hanneskuettner/advent-of-code | /2021/12/part2.py | 776 | 3.5625 | 4 | import networkx as nx
input = open('input.txt', 'r').read().strip()
cave = nx.Graph()
for line in input.splitlines():
cave.add_edge(*line.split('-'))
queue = [("start", set(["start"]), False)]
path_count = 0
while queue:
current, visited, double = queue.pop()
new_paths = []
if current == "end":
path_c... |
c664ec60323841dc3e3ad74658e15dc9ad0b65a9 | 30nt/IntroPython_09_06_21 | /lesson9_2_f.py | 532 | 3.625 | 4 | import random
def create_point(min_limit, max_limit):
point = {"x": random.randint(min_limit, max_limit),
"y": random.randint(min_limit, max_limit)}
return point
def create_triangle(points_name_str, min_limit, max_limit):
return {key: create_point(min_limit, max_limit) for key in points_nam... |
d761e36ff3db8724b77a83d79537ee72db4e9129 | shirishavalluri/Python | /Objects & Classes.py | 2,574 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Import the library
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[12]:
class Circle(object):
#Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius;
self.color = color;
... |
0e8d0496a488fa9e6c029bc2fcd97211533b8895 | jrkoval/tests | /math.py | 460 | 3.875 | 4 | #!/usr/bin/python
# added a comment
def mean(x):
sum=0
for num in x:
sum = sum + num
return(sum)/len(x)
def median(x):
x.sort()
if len(x)%2 == 0:
print(x[int(len(x)/2)])
print("minus 1" )
print(x[int(len(x)/2) -1])
res = ((x[int(len(x)/2)] + x[int(len(x)/2)... |
60cba51005949e2dcc2456a06c354716804b14f5 | c4rlos-vieira/exercicios-python | /Exercicio005.py | 198 | 4.0625 | 4 | n = float(input('Digite um número qualquer: '))
print('O número que você colocou foi {} \n O seu dobro é {} \n O seu triplo é {} \n Sua raiz quadrada é {}'. format(n, n*2, n*3, (n**(1/2))))
|
51c846a474c2efdb431369dc175f0d7413e553bc | c4rlos-vieira/exercicios-python | /Exercicio042.py | 654 | 4.03125 | 4 | from math import fabs
a = float(input('Digite a medida da primeira reta: '))
b = float(input('Digite a medida da segunda reta: '))
c = float(input('Digite a medida da terceira reta: '))
if fabs(b - c) < a < (b + c) and fabs(a - c) < b < (a + c) and fabs(a - b) < c < (a + b):
print('Você pode montar um triâng... |
8a163819da9e8eddc2c74438233b618c45f3c2a9 | c4rlos-vieira/exercicios-python | /Exercicio004.py | 160 | 4.0625 | 4 | n = int(input('Coloque um número qualquer: '))
print('O número que você escolheu foi o {}, \no seu antecessor é {} \nseu sucessor é {}'.format(n,n-1,n+1)) |
13a6be57fb45f71f115df4e0514a9c14dc8368c8 | c4rlos-vieira/exercicios-python | /Exercicio022.py | 325 | 3.875 | 4 | nome = str(input('Digite seu nome completo: '))
cespaço = int(len(nome))
sespaço = int(nome.count(' '))
primeiron = nome.split()
print(nome.upper())
print(nome.lower())
print('Esta string tem {} sem contar o espaços'.format((cespaço - sespaço)))
print('O primeiro nome tem {} letras.'.format(len(primeiron[0])))
|
e2de6927aa582c8cbfdfe37d44fc5da6abd5232f | c4rlos-vieira/exercicios-python | /Exercicio018.py | 300 | 4 | 4 | import math
a = math.radians(float(input('Digite um ângulo qualquer entre 0 e 360: ')))
print('-' * 20)
print('Estas são as medidas do angulo {:.2f}º: \n- Seno: {:.2f} \n- Cosseno: {:.2f} \n- Tangente: {:.2f}'.format(math.degrees(a), math.sin(a), math.cos(a), math.tan(a)))
print('-' * 20)
|
90a312cc4a77829922cafd4df5f7a1ff819f9c88 | sebcampos/Coursera_Projects | /Google_Python_IT_automation/python_scripts/capitalize.py | 212 | 3.8125 | 4 | #!/usr/bin/env python3
#this script uses the sys module to take stdin output and return it capatalized ie cat haiku.txt | capitalize.py
import sys
for line in sys.stdin:
print(line.strip().capitalize())
|
e9e3fc72670fa6728538f75ceec93659f309de51 | marcvifi10/Curso-Python | /Python 1/3 - Colecciones/29 - Conjuntos (parte 2)/Conjuntos.py | 1,132 | 3.828125 | 4 | # Conjuntos
# Creamos dos conjuntos con elementos
a = {1,2,3}
b = {3,4,5}
# Si los dos conjuntos tienen los mismos elementos, aunque esten desordenados, los dos son iguales
print(a == b)
# Para saber el numero de valores que tiene el conjunto
print(len(a))
# Unir dos conjuntos
c = a | b
print(c)
# Interseccion de ... |
1b39071c2140b24131741542defa41211e78b360 | marcvifi10/Curso-Python | /Python 1/3 - Colecciones/35 - Ejercicio 2 – Operaciones de conjuntos con listas/Ejercicio 2.py | 391 | 4.1875 | 4 | # Ejercicio 2
lista1 = [1,2,3,4,5,4,3,2,2,1,5]
lista2 = [4,5,6,7,8,4,5,6,7,7,8]
# Elimine los elementos repetidos de las dos listas
a = set(lista1)
b = set(lista2)
union = list(a | b)
soloA = list(a - b)
soloB = list(b - a)
interseccion = list(a & b)
print(f"Union: {union}")
print(f"Solo elementos A: {soloA}")
prin... |
986f005e3adbfd77d03c7a097b7506d30269dc40 | marcvifi10/Curso-Python | /Python 2/1 - Sintaxis Básica/8 - Sintaxis Básica VI. Las tuplas. Vídeo 8.py | 391 | 4.09375 | 4 | lista = [1,2,3,1]
# Convertimos una lista en una tupla
tupla = tuple(lista)
# Verificamos si el valor 1 esta dentro de la tupla
print(1 in tupla)
# Contamos cuantas veces se repite el valor 1 en la tupla
print(tupla.count(1))
# Contamos cuantos elementos tiene la tupla
print(len(tupla))
mitupla = ("Juan",1,12,1996... |
d63725f883990874809cbf3aced894c834fd2c9f | marcvifi10/Curso-Python | /Python 2/4 - Generadores/20 - Generadores II. Vídeo 20.py | 781 | 4 | 4 | def devuelve_ciudades(*ciudades): # Con el *, podemos pasarle los elementos que queramos
for elemento in ciudades:
for subElemento in elemento:
# Devolver el elemento
yield subElemento
ciudades_devueltas = devuelve_ciudades("Madrid","Barcelona","Valencia","Girona")
# Mostramos la primera letra del primer val... |
386525ce0b00e19ab86ef73ec516d298d859e071 | marcvifi10/Curso-Python | /Python 2/1 - Sintaxis Básica/7 - Sintaxis Básica V. Las listas. Vídeo 7.py | 614 | 4.15625 | 4 | lista = ["Marc","Alex","Juan"]
print(lista[:])
print(lista[:2])
print(lista[1:2])
print(lista[1:3])
# Añadimos un nuevo valor a la lista
lista.append("Marina")
# Devuelve la posición del valor
print(lista.index("Marc"))
# Muestra si el valor esta dentr de la lista
print("Alex" in lista)
# Añadimos más valores a... |
fdbf889e7283cbef1169dc66ef73a055555ae9eb | marcvifi10/Curso-Python | /Python 1/3 - Colecciones/32 - Pilas (con listas)/Pilas.py | 233 | 4 | 4 | # Pilas
# Creamos una pila
pila = [1,2,3]
# Agregando elementos por el final
pila.append(4)
pila.append(5)
print(pila)
# Eliminando elementos de una pila, por el final
n = pila.pop()
print("Sacando el elemento:",n)
print(pila)
|
a86660148259bd9388bd13a26d0a2944841fdc1b | marcvifi10/Curso-Python | /Python 1/1 - Introducion/17 - Ejercicio 5 – Descuento del 15% en una tienda/Ejercicio5.py | 180 | 3.640625 | 4 | # Ejercicio 5
precio = float(input("Entra el precio: "))
descuento = precio * 0.15
precio_final = precio - descuento
print(f"El precio final del producto es de ${precio_final}") |
7bc2fe1ce9a7b6d6a898f452bdecfa1522b0d212 | marcvifi10/Curso-Python | /Python 2/2 - Condicionales/13 - Condicionales IV. Vídeo 13.py | 463 | 3.953125 | 4 | print("Programa de becas Año 2017")
distancia_escuela = int(input("Introduce la distancia: "))
print(distancia_escuela)
numero_hermanos = int(input("Introduce el numero de hermanos: "))
print(numero_hermanos)
salario_familiar = int(input("Introduce el salario familiar: "))
print(salario_familiar)
if distancia_escue... |
6d3a83e1f6d40b2a9e97eb6035de1ea5a12adf7f | marcvifi10/Curso-Python | /Python 1/1 - Introducion/11 - Entrada de datos/Entrada_de_datos.py | 164 | 3.828125 | 4 | # Entrada de datos
nombre = input("Entra tu nombre: ") # Guardar un string
edad = int(input("Entra un numero: "))
print(f"Hola {nombre}")
print(f"Numero: {edad}") |
6eb19142f4b6642deb142d30cbbebaad41a7939c | marcvifi10/Curso-Python | /Python 1/1 - Introducion/4 - Asignación de valores/venv/Asignacion_valores.py | 280 | 3.84375 | 4 | numero = 10
numero2 = 10.56
suma = numero + numero2
print(numero)
print(type(numero))
print("Resultado: ",suma)
print()
print(numero2)
print(type(numero2))
print()
cadena = "Hola que tal"
print(cadena)
print(type(cadena))
print()
boleano = True
print(boleano)
print(type(boleano)) |
4c29dfe7db345d8ef19bf8a31177289a5116d3a6 | marcvifi10/Curso-Python | /Python 1/2 - Condicionales/23 - Ejercicio 4 - Calculadora aritmética/Ejercicio4.py | 592 | 3.90625 | 4 | # Ejercicio 4
num1 = float(input("Entra un numero: "))
num2 = float(input("Entra otro numero: "))
op = input("\nEntra la operacion a realizar: ")
op = op.lower()
if op == 's':
resultado = num1 + num2
print(f"El resultado de la suma es: {resultado}.")
elif op == 'r':
resultado = num1 - num2
print(f"E... |
b96d30b5f1d3dd4a0c52917ff587895390e1f0ca | dkurchigin/gb_algorythm | /lesson2/task1.py | 2,236 | 3.984375 | 4 | # 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем. После выполнения вычисления программа не завершается, а запрашивает
# новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака оп... |
7350e2b6288296a457d3791d5e2cebdc01baace3 | dkurchigin/gb_algorythm | /task7.py | 1,187 | 4.375 | 4 | # По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков.
# Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним
a = int(input("Введите длинну первого отрезка\n\n"))
b = int(inpu... |
83323c1163bd366d418957a6542e97e0ccaa72a8 | dkurchigin/gb_algorythm | /lesson2/task5.py | 684 | 4.125 | 4 | # 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
# Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
FIRST_SYMBOL = 32
LAST_SYMBOL = 127
letter_code = FIRST_SYMBOL
result_string = ''
while letter_code <= LAST_SYMBOL:
... |
187fb52a3a9f96c6c7023f200b80645b592f151c | deeaarbee/Intern-Tasks | /first.py | 1,911 | 3.734375 | 4 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
@staticmethod
def print_yes_or_no(node):
if node == 3 or node == 4 or node == 1:
... |
d68c6a29cd6db5c1df22918fdf1d3ddb31a088e4 | samaeen/django_data_visualization | /api/wordCounter.py | 197 | 3.625 | 4 | import re
def wordCounter(text):
words=re.split(r'[.,?\s]+', text)
wordCounter={}
for i in words:
if i not in wordCounter:
wordCounter[i]=1
else:
wordCounter[i]+=1
return wordCounter |
cfa20cc0ce19e7f0a0ea13a8e52ccc365814b5e5 | renzon/Estrutura_Dados | /bubble.py | 1,825 | 4.15625 | 4 | '''
***Adicionei teste de lista ordenada e o teste de lista
desordenada com vinte elementos;
***Havia dois testes com o nome def teste_lista_binaria(self),
mudei um deles para def teste_lista_desordenada;
>>Complexidade:
O bubbleSort roda em o de n ao quadrado em tempo de execução
no pior caso e o(1) em memória, Mas no... |
10b9dd3126aa2367f0fda1c75fa4cbaa23565bda | Demo-z/python_learn | /python-env/scrapingEnv/scrapetest.py | 560 | 3.515625 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")# urllib.request模块的urlopen()获取页面 <http.client.HTTPResponse object at 0x7f8c297a4940>
bsObj = BeautifulSoup(html.read(),"html.parser")#从网页中提取的 <h1> 标签被嵌在 BeautifulSoup 对象 bsObj 结构的第二层(html → ... |
687e8141335fe7d529dc850585f29ad5e50c4cbb | spacecoffin/OOPproj2 | /buildDict.py | 1,677 | 4.1875 | 4 | # Assignment does not specify that this program should use classes.
# This program is meant to be used in the __init__ method of the
# "Dictionary" class in the "spellCheck" program.
import re
def main():
# The program buildDict should begin by asking the user for a
# list of text files to read ... |
3d1648029bedbdee826fc82a2c85d7d0ddf99223 | dhjygit/python_code | /exercise_three.py | 218 | 3.53125 | 4 | from math import pi
from datetime import datetime
dt = datetime.now()
print(f"时间:{dt.year}年{dt.month}月{dt.day}日 {dt.hour}:{dt.minute}:{dt.second}")
print(dt.strftime("%Y年%m月%d日 %H时%M分%S秒 %A"))
|
d9574b010b6cfed5b3ef98f2256f593cae831be0 | donutdespair/metadata-torture-visibility | /aclu_pull_docs_data_into_csv.py | 3,533 | 3.609375 | 4 | # Before any next steps, backup the folder of your original ACLU data grabs just in case
# This python script looks through the folder of individual JSON files representing ACLU Torture FOIA Database data
# It loops through them to find only the ones that are from data/node type = "document"
# From those JSON files of... |
29228e1441c59c5262cee4ef4304739d35d3b8be | zhangbailong945/pythonStudy | /day25/jsondemo.py | 352 | 3.765625 | 4 | import json
#将字典转换为json
data={
'name':'zhangsan',
'sex':'男',
'url':'zhangbailong.com'
}
json_str=json.dumps(data)
print("python原始数据:",repr(data))
print("json对象:",json_str)
#将json对象转换为python字典
data2=json.loads(json_str)
print("data2['name']",data2['name'])
print("data2['url']",data2['url']) |
df7335b8093ec1f14b79075e9798fb8c0f2e2774 | zhangbailong945/pythonStudy | /day10/itertest.py | 152 | 3.859375 | 4 | list=['2',1,'zhangsan','666']
it=iter(list)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
for x in iter(list):
print(x,end='\n')
|
7a7ab6085f25abdc688ab65ebe6373cdc9e05530 | Anonsurfer/Simple_Word_List_Creator | /Word_List_Creator.py | 835 | 4.28125 | 4 | # This simple script allows you to create a wordlist and automatically saves it as .txt
# if the final value of wordlist is 100 - it will create the wordlist from 0,1,2,3,4.... so on to 100.
import os # Importing the Os Module
keys_ = open("keys.txt",'w') # Creating a new txt file
keys_range = int(input("Enter the fin... |
7f12c500ecd0bac47473615ddf95185f7bc23993 | josterpi/python | /python1.py | 2,734 | 4.21875 | 4 | #!/usr/bin/env python
# initialized at 1, I have two actions I can do on the number
# line. I can jump forward and jump backwards.
# The jump forward is 2*current position + 1
# The jump back is the current position - 3
# Can you hit all of the integers?
# If not, what can't you hit? What can you? Any patterns?
# When... |
e5d08e706a5ba084c4300770e044e6cd2e05e6e8 | rosstherock/ProjectEuler | /Primes.py | 4,111 | 3.546875 | 4 | # A library of custom functions relating to prime numbers.
#
# Author: Ross Atkins
# Date Created: September 2015
#
# These functions were used to solve various Project Euler Problems
# Project Euler Problems can be found at https://projecteuler.net/archives
def getPrimes(N):
"""
Calculates and returns a sorte... |
332cc425ae86c05788fb94b362521c28fa571e7d | salitr/pdsnd_github | /Project.py | 9,156 | 4.28125 | 4 | import time
import pandas as pd
import numpy as np
data = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
name = input('Enter your name: ')
print('Hello {},\n\nWelcome to the US bikeshare Data. \
\nNow, let\'s explore some of the data, Enjoy!'.f... |
8099f76f23600e482d6477259f9176d04973bad9 | gmartin1603/Python_Tic_Tac_Toe | /Tic_Tac_Toe.py | 3,986 | 3.90625 | 4 | #########Global Veriables##########
#board
board = ['-', '-', '-',
'-', '-', '-',
'-', '-', '-',]
game_still_going = True
winner = None
current_player = 'X'
#display the board
def display_board():
print(board[0] + ' | ' + board[1] + ' | ' + board[2])
print(board[3] + ' | ' + b... |
88ed76b4eadc71e3c40996da01f84dade6299e9a | Bishal16/Codeforces_C | /1370C.py | 531 | 3.84375 | 4 | def isPrime(n):
for i in range(2,int(n**.5)+1):
if n%i==0:
return False
return True
for t in range(int(input())):
n=int(input())
if n==1 :
print("FastestFinger")
elif n==2 :
print("Ashishgup")
elif n%2==1:
print("Ashishgup")
else:
if n&(n-... |
b8a3835a058968b89ff79edd1419b04f2001e048 | eric2wuk/pythonUtil | /my_inner_mudule/my_OrderedDict.py | 227 | 3.578125 | 4 | from collections import OrderedDict
ddd = dict([('a',1), ('b',2), ('c',3)])
print(ddd)
od = OrderedDict([('a',1),('b',2), ('c',3)])
# 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
print(od) |
45cd33ca7ad399c202a74c36d8a48c6c88eb8003 | eric2wuk/pythonUtil | /my_datetime/my_datetime_timezoo.py | 166 | 3.546875 | 4 | from datetime import datetime, timedelta, timezone
tz_utc_8 = timezone(timedelta(hours=8))
now = datetime.now()
print(now)
dt = now.replace(tzinfo=tz_utc_8)
print(dt) |
576df8b44c0259258cf04085a35bf727d9fca2c6 | agincel/SIT | /2 - Sophomore Year/Spring/CS370/FCTRL.py | 194 | 3.59375 | 4 |
def getZeroes(x):
exp = 1
fact = 5
zeroes = 0
while fact <= x:
zeroes += int(x / fact)
exp += 1
fact = pow(5, exp)
return zeroes
print(getZeroes(50))
print(getZeroes(8735373)) |
897837c68e5a6739dd37b64c6a7b787d396f81fb | noamm19-meet/y2s18-python_review | /exercises/conditionals.py | 91 | 3.546875 | 4 | # Write your solution for 1.2 here!
a=0
for x in range(101):
a+=x
if a%2==0:
print(a)
|
3c585b77ea74d4553dd7ec35eac9714377edcc69 | skepticshivam/Python | /exercise-39/exec39.py | 131 | 4.03125 | 4 | numbers={
'one' : 'ONE',
'two' : 'TWO',
'three' : 'THREE'
}
print "word to numbers"
for i,j in numbers.items():
print i,":",j
|
8789ae9f88ccd5a9931e586b7fd87bfeac3529ef | skepticshivam/Python | /exercise-21/exec21.py | 188 | 3.765625 | 4 | def add(a,b):
return (a+b)
def sub(a,b):
return(a-b)
def div(a,b):
return (a/b)
def mul(a,b):
return(a*b)
a=30
b=15
a1=add(a,b)
a2=sub(a,b)
a3= mul(a,b)
a4=div(a,b)
print a1,a2,a3,a4
|
6eaa87f3b56284f624fc6d292e3dfe02bc52dd67 | lussierc/nhlEfficiencyEvaluator | /src/scraper.py | 1,442 | 3.703125 | 4 | """Scrapes and saves play-by-play NHL data from the NHL API."""
import requests
import pickle
def run_scraper():
"""Get user scraping settings."""
print("ENTER SCRAPING INFO:")
# Set up the API call variables:
year = input("* Enter year: ")
print("Season types: 01 = Preseason, 02 = Reg Season, ... |
a9cc2ffc28ec15381aab9e4026b05337ee8deb8e | code-guide/python | /_5_data_structure/c_dict.py | 448 | 4.15625 | 4 | #!/usr/bin/env python3.5
''' 字典 '''
# 声明 name = {key: value}
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 修改 name[key] = value
result = dic['a']
dic['a'] = 2
# dic['asdas'] 访问不存在的key会报错
# 判断key是否存在
result = 'c' in dic
result = dic.get('q', 'empty return value')
# 删除
del dic['b']
dic.pop('c')
# del dic
# ... |
832dbe1f104c792489c9d9b295016e59878cf0b5 | HarrisonHelms/helms | /randomRoll/todo.py | 232 | 3.640625 | 4 | prompt = "\nList things that need to be done "
prompt += "\nEnter 'done' when you are finished: "
list = []
while True:
note = input(prompt)
if note == "done":
break
else:
list.append(note)
print(list) |
2b8a5961e68d32283401892eec11dbfade6c80d2 | HarrisonHelms/helms | /randomRoll/roll2.py | 350 | 4.25 | 4 | from random import random
R = random()
sides = input("Enter the number of sides on the die: ")
'''
rolled = (sides - 1) * R
rolled = round(rolled)
rolled += 1
'''
def roll(sides):
rolled = (sides - 1) * R
rolled = round(rolled)
rolled += 1
return rolled
num = roll(int(sides))
num = str(num)
print("Y... |
5a4968a2d9c9df538eda1c2e64901ae13177ec5a | MarkUmsTang/Python | /funcDef.py | 1,049 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(ang... |
8bb7e4bba2670b91d844bb9acd90ab63d43f0ea6 | lvjiawen/ichw | /pyassign3/wcount.py | 2,062 | 3.515625 | 4 |
# coding: utf-8
# In[3]:
"""wcount.py: count words from an Internet file.
__author__ = "Lvjiawen"
__pkuid__ = "1600012173"
__email__ = "1600012173@pku.edu.cn"
"""
import sys
import urllib.request
from urllib.request import urlopen
def wcount(lines, topn=10):
"""count words from lines of text string, the... |
152ae6653d542180bd838bb3372f77c93baae859 | MaciejChoromanski/design-patterns-python | /design_patterns_python/prototype.py | 1,353 | 4.03125 | 4 | # Example of 'Prototype' design pattern
from __future__ import annotations
from typing import List, Dict
import copy
class DataPrototype:
"""Prototype"""
def __init__(self, data: List[int, List[int]] = None) -> None:
self.data = data
def __copy__(self) -> DataPrototype:
new = self.__cl... |
9bde11c0b7143723c94181a470409ccffa27a43e | TiarahD18/cssi-1 | /week3/test.py | 1,133 | 4.09375 | 4 | #!/usr/bin/env python
#print("Hello CSSI")
#user_input = raw_input("Enter anything: ")
#print("You entered a ", type(user_input))
#print(user_input)
#print("int(raw_input) gives us int")
#num1 = int(raw_input("Enter number #1: "))
#num2 = int(raw_input("Enter number #2: "))
#print(num1 + num2)
#print(type(num1+ num2... |
f475b47945d0b2bae15e32fef9f41871cc5dab55 | allnicevivi/python_class | /H24076029_midterm/midterm_8.py | 311 | 3.65625 | 4 | j=9 # j為後面的數
while j>=1:
i=9 # i為前面的數
while i>=1: # print出每一列的樣子
print(i,"x",j,"=",i*(j),end="\t")
print(i,"x",j-1,"=",i*(j-1),end="\t")
print(i,"x",j-2,"=",i*(j-2),end="\n")
i=i-1
print() # 空白列
j=j-3 # i為9個一循環,每一個循環結束使j-3 |
eaa125329a51499b0e93e914f38f87935e44e2a7 | allnicevivi/python_class | /H24076029_quiz2/H24076029_quiz2_p1.py | 2,134 | 3.671875 | 4 | ### (a)+(b)
t=1
while True:
sn=str(input("(a)+(b): Enter a positive integer with square-number length: "))
while t**2<len(sn):
if len(sn)==t**2:
break
t=t+1
if len(sn)==t**2: # 若確定字數為平方數就繼續
break
else:
print("Not square-number length. Try again!") # 若字數不為平方數就重來一次
### (c) 把數字變成list
prin... |
20c70173e1040e3429db142a8d87de07a7bbe095 | Invalid-coder/Python2018 | /Sea_battle/Ship.py | 2,867 | 3.828125 | 4 | class Ship:
'''Клас корабель, який прив'язано до клітинки поля.
'''
def __init__(self, type, number, parent, xstart, ystart, xend, yend, row, col,c,outl='red',fill='blue',dx=30,dy=30):
self.type = type
self.decks = type
self.number = number
self.cells = {}
self.par... |
53078cf38a6d16976a0ccb250efb13078a9a7ee1 | pavan2004it/mathhack | /trihack.py | 560 | 3.78125 | 4 | # for i in range(1, int(input())):
# for j in range(1, i):
# print(j)
# for x in range(1, 5):
# print(x)
# for y in range(x):
# print(x,end='')
# print("\r")
# for i in range(1, int(input())):
# print(i*(10 ** i) + i)
# num1 = 100
# num2 = 10
#
# digits = len(str(num2))
#
# # add z... |
ae3af1c2f88403140d3b8d2ae5def7e060a15da5 | dmlviejo/Patrones-de-dise-o | /Patrones de diseño/Memento.py | 1,478 | 3.59375 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
class Guerrero:
pass
class Inicio():
_state = None
def __init__(self, state: str) -> None:
self._state = state
print(f"Estado inicial: {self._state}")
def fusionar(self) -> None:
print("Aho... |
21969bc2dc99439448b9195433df14b6bf4dd312 | briansu2004/monad | /monad/types/either.py | 3,260 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Philip Xu <pyx@xrefactor.com>
# License: BSD New, see LICENSE for details.
"""monad.types.either - The Either Monad."""
from . import Monad, Monadic
from ..mixins import ContextManager, Ord
class Either(Monad, ContextManager, Ord):
"""The Either Monad.
Repr... |
ca8ea004001f696ab22e73a3e70bcdd2e2d6c675 | srushti-712/ML-Basics | /Assignment2_Prob2-Inheritance_of_Member_class.py | 1,281 | 4.09375 | 4 | #assignment 2 - Problem 2
#implementation of 3 classes viz Member, Employee and Manager
class Member:
def __init__(self,name,age,pnum,add,sal):
self.name = name
self.age = age
self.pnum = pnum
self.add = add
self.sal = sal
def printSalary(self):
p... |
a8154be3b8000acb284ac3d8760f56f0bc782675 | malcolmmathew-zz/algo-practice | /trees/is_binary_tree_bst.py | 2,412 | 3.921875 | 4 | # Check if a binary tree is a binary search tree
class Node:
def __init__(self , key):
self.data = key
self.left = None
self.right = None
# Brute Force
def check_node(root):
# for each node, make sure its entire right subtree is greater, and its entire left subtree is less
if root is N... |
1c7cc0bd6e5cf11f905c51734540a9bd135b434e | malcolmmathew-zz/algo-practice | /trees/maximum_path_sum.py | 748 | 3.84375 | 4 | class Node:
def __init__(self , key):
self.data = key
self.left = None
self.right = None
def max_path_sum(cur_node):
if cur_node is None:
return 0
left_max = max_path_sum(cur_node.left)
right_max = max_path_sum(cur_node.right)
one_max = max(cur_node.data+left_max, c... |
16ba8b8b4379baef24d3a82a63502f54f156e378 | MatheusRBarbosa/ifes-ia | /a-estrela/main.py | 1,330 | 3.53125 | 4 | import sys
from tools import *
from star import *
def main():
if len(sys.argv) >= 2:
print_arrow_style = False;
map = read_text_file(sys.argv[1])
if len(sys.argv) == 6 or len(sys.argv) == 7:
initial_node = tuple([int(sys.argv[2]), int(sys.argv[3])])
final_node = tu... |
bb2b46885c612fd557962995cb28228fc5b648fc | see3dee/selenium-page-object | /die_for.py | 1,846 | 3.953125 | 4 | import random
# min = 1
# max = 6
stats = {"tot_ones": 0, "tot_twos": 0, "tot_threes": 0, "tot_fours": 0,
"tot_fives": 0, "tot_sixs": 0, "tot_num_rolls": 0, "min": 1, "max": 6}
all_rolls = []
how_many_rolls = int(input("How many times shall we roll the die? Please enter an integer."))
for i in range(how_man... |
6bd181c11704be6c49f1a2c326d6ea5bfe422fcd | see3dee/selenium-page-object | /lists.py | 525 | 3.765625 | 4 | lst = [1, 2, 3, 4, 5.3, 6, 7, 8, 9, 0]
evens = []
odds = []
for char in lst:
if char % 2 == 1:
odds.append(char)
elif char % 2 == 0:
evens.append(char)
else:
print(f"{char} must be a decimal.")
odds.append(11)
evens.append(12)
print(f"Here are the new lists: Evens: {evens} and odds:... |
e65a5f10e66f1d3405e1af1f40f492303cef0aee | jaclynrich/nyc-comedy-db | /get_comedian_list.py | 1,382 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 18:51:36 2017
@author: Jackie
"""
import pandas as pd
import csv
def main():
# Import manually assembled comedian list
xlsx = pd.ExcelFile('manual_comedian_list.xlsx')
df = pd.read_excel(xlsx, 'Sheet1', header=None, names=['comedian... |
c2baa303094582869887e81d30606377f0afdc99 | rjw57/psephology | /test-data/to_results.py | 1,714 | 3.578125 | 4 | #!/usr/bin/env python3
"""
Parse GE2017 result into a results file suitable for passing to psephology.
Usage:
to_results.py <input> <output>
Options:
-h --help Show a usage summary
<input> Input CSV file
<output> Output results file
"""
from collections import namedtuple
import ... |
b820c79f57cdf821a995c227ee41bdf2cd290fa6 | kqdtran/pyreduce | /friend_count.py | 702 | 3.53125 | 4 | import MapReduce
import sys
"""
Social Network dataset with friends counting in the Simple Python MapReduce Framework
Test Input: friends.json
Test Output: friend_count.json
"""
mr = MapReduce.MapReduce()
def mapper(record):
# key: person A
# value: just a single count indicating record[1] is a friend with ... |
b21dd30e0133a0c40c958ca465b348007bb94d1f | NickHlzv/Python | /Lesson6.Homework/task2.py | 295 | 3.625 | 4 | class Road:
def __init__(self, length, width):
self._weight, self._gauge, self._length, self._width = (10, 5, length, width)
def mass(self):
return float(self._weight) * float(self._gauge) * float(self._length) * float(self._width)
r1 = Road(250, 10)
print(r1.mass())
|
3b981fc86e0437291e2e5f6325cbed269dd5ebba | NickHlzv/Python | /Lesson6.Homework/task5.py | 696 | 3.578125 | 4 | class Stationery:
def __init__(self, title):
self.title = title
def draw(self):
print(f'{self.title} рисует')
class Pen(Stationery):
def draw(self):
print(f'Ручка: "{self.title}" рисует')
class Pencil(Stationery):
def draw(self):
print(f'Карандаш: "{self.title}" рису... |
b10932c5e6af34b8a962420a59ca54a7bb362045 | NickHlzv/Python | /Lesson1.Homework/task4.py | 558 | 3.828125 | 4 | user_number = input('Введите целое положительное число')
maximum = 0
if not user_number.isdigit():
print('Вы издеваетесь? Число должно быть целым и положительным')
elif int(user_number) > 0:
list_user_number = list(user_number)
for number in list_user_number:
if maximum < int(number):
ma... |
b3da8d8b2103d1787b67a8528f906e8c4cfefa5b | FuzzWool/hivemind2 | /_.py | 143 | 3.859375 | 4 | #Remove objects in a list.
lst = [True, True, False]
def false_list(arg):
for l in arg:
if l != True: yield l
print list(false_list(lst)) |
433a49288efd82cb0412084504f60720310711de | MGao535/python-challenge | /PyPoll/Election_Results.py | 1,471 | 3.5 | 4 |
# coding: utf-8
# In[102]:
import pandas as pd
# In[103]:
file = "election_data.csv"
# In[104]:
df = pd.read_csv(file, encoding="ISO-8859-1")
# In[105]:
df.head()
# In[106]:
df.count()
# In[107]:
cols = ["Voter ID", "Candidate"]
ext_df = df[cols]
ext_df.head()
# In[108]:
candidates = ext_df.... |
0f53779b7b072e3f47dc6dc86a6f206b8b950857 | lenaecs/advent_of_code_2018 | /Day_7.py | 4,248 | 3.640625 | 4 | advent = open("Input/input_day_7.txt")
test = ['Step C must be finished before step A can begin.',
'Step C must be finished before step F can begin.',
'Step A must be finished before step B can begin.',
'Step A must be finished before step D can begin.',
'Step B must be finished before ... |
74b40ffc131358fd8b4a57c1a27bbc4fd6d8674f | am-ansari/Hackerrank-challenges | /skipping_ones.py | 1,132 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Problem: Given an array containing only [0,1]; calculate the maximum number of
jumps to reach the end of array with the following conditions:
1) Always skip 1
2) Jump can be made in the increments of 1 or 2 only
Assumptions:
1) Array always starts with 0
2) Minimum ... |
6053d953f8b806b8623e5cb2f41a76654007d388 | ilae4e/RPI | /Distributed Imgur Search/Distributed/__init__.py | 1,265 | 3.640625 | 4 | import base64
Base = 5
Mod = 23
a = 6
b = 15
alice = (Base**a) % Mod
bob = Base ** b % Mod
alice_answer = bob ** a % Mod
bob_answer = alice ** b % Mod
#
# print alice_answer
# print bob_answer
#
# print base64.b64encode("".join(str(bob_answer)))
# print base64.b64encode("".join(str(alice_answer)))
... |
6d5c6e7f71cfb0e02582fe9ace5323b839d13e79 | materialsvirtuallab/megnet | /megnet/utils/preprocessing.py | 4,978 | 3.546875 | 4 | """
Preprocessing codes
"""
from typing import List
import numpy as np
from monty.json import MSONable
from .typing import StructureOrMolecule, VectorLike
class Scaler(MSONable):
"""
Base Scaler class. It implements transform and
inverse_transform. Both methods will take number
of atom as the secon... |
1d3b8c0502397f907e965adfd6535b58765c8c7a | shuhailshuvo/Learning-Python | /15.Date.py | 727 | 4.1875 | 4 | from datetime import datetime, date, time
from time import sleep
now = datetime.now()
print("Current Datetime", now)
today = date.today()
print("Current Date", today)
print("Current Day", today.day)
print("Current Month", today.month)
print("Current Year", today.year)
# difference between two dates
t1 = date(1971, 1... |
a2cf5e5ae6e085e95c4baa05e7e42867f8084d07 | edukyumin/TIL-Today_I_Learn | /0402_Queue/Queue_강의.py | 189 | 3.703125 | 4 | #1, 2, 3을 넣는 Queue 코드
def enq(n):
global rear
if rear == len(q)-1:
print('Full')
else:
rear += 1
q[rear] = n
q = [0]*3
front = -1
rear = -1
|
f6c4fe2324c3721a87d4cb379872b5df28e75911 | K59360501/Stock-Prediction | /Stock_AMD.py | 2,824 | 3.5 | 4 | import sklearn
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
#ดึง Dataset เฉพาะ 5 แถวแรก
url = "https://gitlab.com/59362345/softengineering/blob/master/AMD.csv"
df = pd.read_csv("AMD.csv... |
9d7c472ecf324e6200984b81439934faba900fd1 | wangchao1230/hello-aml-modules | /additional-includes/calculator/simple.py | 384 | 3.875 | 4 | __all__ = ['add', 'minus', 'multiply', 'devide']
def add(left, right):
return left + right
def minus(left, right):
return left - right
def multiply(left, right):
return left * right
def devide(numerator, denominator):
if denominator == 0:
print ("Invalid denominator, current value is 0")
... |
af519178c9be5b3af9ff881cd2159ae6ff259261 | fatisar/guitar-gyro | /src/utils/NoteMap.py | 1,692 | 3.734375 | 4 | import FrettedNote
# NoteMap encodes a mapping from notes to string-fret 2-tuples
class NoteMap:
# NOTE: The notes on a guitar range from E, to D#''
postfix = (",","","'","''")
letters = ("E","F","F#","G","G#","A","A#","B","C","C#","D","D#")
octave = 0
oct_cnt = 16 # a count to determi... |
e4a71284092ec0a1cc7a9e2a29eaf719e51a6ca4 | denglert/python-sandbox | /corey_schafer/sorting/sort.py | 2,775 | 4.4375 | 4 | # - Original list
lst = [9,1,8,2,7,3,6,4,5]
print('Original list:\t', lst )
# - Sort list with sorted() function
s_lst = sorted(lst)
print('Sorted list: {0}'.format(s_lst) )
# - Sort lits Using subfunction .sort()
lst.sort()
print('Sorted list:\t', lst )
# - Sort list in reverse order with sorted() function
s_l... |
9ea2900cf2d7cbcd21bce855b89b31ab746b96aa | denglert/python-sandbox | /corey_schafer/OOP_tutorial/Tutorial_3_regular_class_static_methods/regular_class_static_methods.py | 3,867 | 4.21875 | 4 | #!/usr/bin/env python
# - Concepts introduced:
# * regular instance method
# * classmethod
# * staticmethod
# * alternative constructor
# * self
# * cls
class Employee:
num_of_emps = 0 # - This is a class variable
raise_amount = 1.04 # - This is a class variable
def __init__(self, first, last, pay... |
a2a51c76c4d63aba6c2bd2db53b10c8038c80f80 | denglert/python-sandbox | /corey_schafer/OOP_tutorial/Tutorial_5_Special_Methods/magic_methods.py | 6,078 | 4.21875 | 4 | ##############################################
### --- Special (Magic/Dunder) methods --- ###
##############################################
# - Concepts introduced:
# * special methods
# * operator overloading
# * __*__ = dunder
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay): # __... |
3dbfd602383d5791f2f5a4bcfc4c5e54b07e9ce7 | denglert/python-sandbox | /corey_schafer/namedtuples/namedtuples.py | 932 | 4.40625 | 4 | ############################
### --- Named tuples --- ###
############################
from collections import namedtuple
### --- Tuple --- ###
# Advantage:
# - Immutable, can't change the values
color_tuple = (55, 155, 255)
print( color_tuple[0] )
### --- Dictionaries --- ###
# Disadvantage:
# - Requires more ty... |
6edf89e362112f2d59024c916e392dc1254d8858 | jniehues-kit/SLT.KIT | /scripts/ctc/create_unit_dict.py | 919 | 3.59375 | 4 | #!/usr/bin/env python
import argparse
import json
def create_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'--text',
help="text file containing units"
)
parser.add_argument(
'--output',
... |
ff535b57f3ca3b37ce4c631a797efe9f1508ae54 | reivb/XACO-EPSEVG-2019 | /Chat Multicanal/Entrega2/TCPClient.py | 1,006 | 4.09375 | 4 | # Example TCP socket client that connects to a server that upper cases text
import sys
from socket import *
# Default to running on localhost, port 12000
serverName = 'localhost'
serverPort = 12000
# Optional server name argument
if (len(sys.argv) > 1):
serverName = sys.argv[1]
# Optional server port number
if (len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.