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
2cfd1f9d722212623cbf47bdeb06affade887485
adoxography/SPieL
/spiel/util.py
1,493
3.75
4
""" spiel.util Utility methods for SPieL """ import collections from itertools import zip_longest def flatten(lst): """ From https://stackoverflow.com/a/2158532 """ for elm in lst: if isinstance(elm, collections.Iterable) \ and not isinstance(elm, (str, bytes)): yi...
41ab824651ece0787b2d7ecf340531958e953d73
zooshgroup/bagelbot
/attendance_breakdown.py
853
3.78125
4
#!/usr/bin/env python """ Simple script for generating some simple meeting attendance statistics using history of past meetings. """ from utils import open_store store = open_store() everyone = store["everyone"] history = store["history"] store.close() attendance = {p: {"total": 0, "dates": []} for p in everyone} for...
f2b7a0d5b9d50c827fcc1afead13a413a1be0107
cthulhu1988/RandomPython
/crossfoot.py
681
3.734375
4
def check_digit(num): remnant = num # remnant = 61248 num = 61248 cross_foot = 0 # set at 0 while remnant > 0: #should cycle last_digit = (remnant % 10) # is 8 product = (last_digit*2) # is 16 last_dig_product = product % 10 # should be 6 first_dig_product = product // 10 # cut off 6 to show 1 cross_...
f7571d0f4ac74d14cd97c80b71a30b4e088d7ffc
cthulhu1988/RandomPython
/formatCLA.py
516
3.90625
4
# CLAxx BY Isaac Callison, CSCI 1170-007, Arthur # Program ID: ch2x11.py / break down ration of males to females based on user input # Remarks: This program accepts user input regarding the number of makes and # females in a class and displays a percentage breakdown of that percentage formatted as %. maleInput = float...
22f1c34f802e203b90f11ca33857336a02ecc081
cthulhu1988/RandomPython
/while.py
336
3.890625
4
def main(): keep_going = "y" while keep_going == "y": sales = float(input("Enter amount of sales: ")) com_rate = float(input("Enter commission rate: ")) commision = sales* com_rate print("the commision is",commision) keep_going = input("do you want another? y or n...
810cae98bb215d155ab7af94909263cab5d78202
cthulhu1988/RandomPython
/clearBeepers.py
1,805
3.578125
4
# OLA106 BY Isaac Callison, CSCI 1170-007, Due: 09/29/2016 # PROGRAM ID: clearpapers.py / Pick up papers along perimeter of house # AUTHOR: Isaac Callison # INSTALLATION: MTSU # REMARKS: Reeborg has been ill and unable to pick up the papers # around his home. He should pick...
6ddbbb7c8731cdd5594a56b70a15ffdd6dfd30cc
cthulhu1988/RandomPython
/final.py
1,745
3.875
4
# binary search def main20(): list1 =[2,7,5,4,6,7,8,9,7,45,3,2,4,455,6,67,8,9,0,43,56,78,55,44,33,22,33,44,567] list1.sort() print(list1) x = binary_search(45,list1) print(x) def binary_search(key,lst): low = 0 high = len(lst)-1 while high >= low: mid = (low + high)//2 ...
9525203170b602c2b0e819343c9d4a8009144e8e
iSaran/robamine
/robamine/utils/math.py
3,483
3.546875
4
#!/usr/bin/env python3 from math import exp import numpy as np import matplotlib.pyplot as plt def sigmoid(x, a=1, b=1, c=0, d=0): return a / (1 + exp(-b * x + c)) + d; def rescale_array(x, min=None, max=None, range=[0, 1], axis=None, reverse=False): assert range[1] > range[0] assert x.shape[0] > 1 r...
3ae9deb8c088aa03569c85cc6c73ac6753517075
joshua7linares/Tecnicas3-2
/JoshuaLinares/p31.py
662
3.921875
4
#recibe una matriz y la muestra print "Linares Alonso Joshua A." matriz1=[] res=0 def crear(matriz): for i in range (2): matriz.append([0]*2) def ingresar(matriz): for i in range(2): for j in range(2): print "fila: ", i+1, "coluumna: ", j+1 matriz[i][j]=input("ingresa valor: ") def most...
fb3ea9a899cefd93ebf5e57c7329e92346a08314
joshua7linares/Tecnicas3-2
/JoshuaLinares/p19.py
117
3.90625
4
print "tabla de multiplicar" n=input("ingresa un numero") for i in range(1,11): print n," ","x"," ",i,"=",n*i
bf6e9266e629ca3c2466e99f3dd5ad05a7c98c4b
joshua7linares/Tecnicas3-2
/JoshuaLinares/p22.py
282
3.609375
4
#determina si un nuemro es perfecto n=int(input("ingresa un valor:")) def div(n): suma=0 m=1 while m!=n: if n%m==0: suma=suma+m m=m+1 else: m=m+1 if suma==n: print n, "es un numero perfecto" else: print n, "no es un numero perfecto" div(n)
aafb57c9e700c8559e1dc797c50328d30a853fdc
joshua7linares/Tecnicas3-2
/JoshuaLinares/p12.py
577
3.609375
4
#distingue entre numeros primos y numeros no primos dentro de un intervalo print "Linares Alonso Joshua A." ni=int(input("limite inferior del intervalo: ")) ns=int(input("limite superior del intervalo: ")) m=int(2) band="true" def primo(ni,ns,m,band): for i in range(ni,ns+1): while band=="true" and m!=i: ...
1ba195d3c852eb34ab75dd289b4722f5c972507f
connietem/flask
/sdmt/8queens/8queens.py
558
3.59375
4
import json import os inf=open("8q.json") board=json.loads(inf.read()) board=board["matrix"] print(*board,sep="\n") print("\n\n") def issafe(row,col): for i in range(8): for j in range(8): if(board[i][j]==1): if row==i: return False if col==j: return False if abs(row-i)==abs(col-j): re...
a8d0ca20d70b6a9463d2de848ff2f97f9d3bb374
Velaqu3z/sem9-lab
/ejercicio5.py
324
3.984375
4
numeros = [] suma=0 for i in range(5): a=int(input("ingrese un valor: ")) numeros.append(a) for numero in numeros: suma += numero promedio=suma/len(numeros) print("el numero mayor es " , max(numeros)) print("el numero menor es " , min(numeros)) print("la suma es " , suma) print("el promedio es " , prome...
794c2aafc83080dfb5206b8824792a1e37bb997c
fromradio/hadoop_python
/reducer.py
916
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from operator import itemgetter import sys current_word = None # 当前的单词 current_count = 0 # 当前单词的个数 # 输入同样来自于标准输入 for line in sys.stdin: line = line.strip() parts = line.split('\t') # 注意刚刚我们的输出一行仅有两个项,一个为单词,一个为1 # 所以不满足条件则跳过 if len(parts) != 2: ...
d8847c5dda7b1470f38c7acf9ab1046a423da2e7
jrmaciel-zx/design_patterns
/command/command.py
966
3.796875
4
from abc import ABCMeta, abstractmethod class Order(metaclass = ABCMeta): @abstractmethod def execute(self): pass class BuyStockOrder(Order): def __init__(self, stock): self.stock = stock def execute(self): self.stock.buy() class SellStockOrder(Order): def __init__(self, ...
4693a753a7e8f36f6f7c8e7f051c3e1a345ca0cd
Moussaddak/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
317
4.3125
4
#!/usr/bin/python3 """ Method """ def append_write(filename="", text=""): """ appends a string at the end of a text file (UTF8) and returns the number of characters added: """ with open(filename, mode='a', encoding='utf-8') as file: nb_char = file.write(text) return nb_char
052e58db5eab96bbe66b975e0854102b97348b76
masonsbro/spring-2017-contests-solutions
/02-10/1/ac/cameron.py
85
3.59375
4
t = int(input()) for i in range(t): seat = int(input()[:-1]) print(seat * 6)
529d61781aae511b4ea76f5ca1ff12eb6c18e756
masonsbro/spring-2017-contests-solutions
/02-24/3/ac/rperce.py
430
3.890625
4
T = int(input()) for _ in range(0, T): line = input().split(' ') height = int(line[0]) depth = int(line[1]) width = 12 * int(line[2]) number = int(line[3]) # If there's, e.g., 5 steps, the total volume is (1 + 2 + 3 + 4 + 5) times that of a # single step (+1 makes it inclusive) step_u...
86e5e191208d4536242eae7f352f26a744e92d58
ghost-k2tl/devnet-lab01
/devnet-lab01.py
365
4.0625
4
student1 = {"Name": "Bui Dang Phong", "age": "30", "work": "TTKTKV1"} student2 = {"Name": "Bui Dang B", "age": "25", "work": "TTKTKV2"} student3 = {"Name": "Bui Dang C", "age": "20", "work": "TTKTKV3"} students = (student1, student2, student3) for a in students: print("-----------------") print("Ten: " + a["Name"]...
b6bba3b4b7c5d62db31d8cf73cb4a0e8a8b94384
FranVaquer92/Minimizing-costs-with-DRL
/dqn.py
1,711
3.640625
4
#!/usr/bin/env python # coding: utf-8 # # CASO PRÁCTICO 2 - MINIMIZACIÓN DE COSTES # ## DEEP Q-LEARNING # In[ ]: #Import libraries import numpy as np #Implement an algorithm of deep q-learning class DQN(object): #INTRODUCTION AND INITIALIZATION OF DQN PARAMETERS AND VARIABLES def __init__(self, max_memor...
990e1956b147a5641d1bb759ddcb99da0ba470fc
SvWer/MultimediaInteractionTechnologies
/05_Excercises03_12/02.py
637
4.3125
4
#Write a Python program to calculate number of days between two dates. Sample dates: (2019, 7, 2) (2019, 7, 11) from datetime import date from datetime import timedelta if __name__ == '__main__': date1 = input("What is the first date (dd.mm.jjjj)") print("Date 1: ", date1) day1, month1, year1 = map(int, date1.spli...
3012bc01e5cb5276a0b69aec668dd198b8e71332
IsaacPintoRamos/python-codes
/financiamento-casa.py
435
3.90625
4
valorCasa = float(input('Valor da casa: R$ ')) salario = float(input('Sálario do comprador: R$ ')) anosPagando = int(input('Anos de pagamento: ')) mensalidade = float(anosPagando * 12) mensal = float(valorCasa / mensalidade) print(f'Para pagar uma casa de R${valorCasa} em {anosPagando} anos a prestação será de R${men...
1e53f701603b4dd36c49263baacb32be7d45a46a
IsaacPintoRamos/python-codes
/alistamento.py
700
3.828125
4
nascimento = int(input('Ano de nascimento: ')) anoAtual = 2021 #ANO ATUAL idade = 2021 - nascimento idadeAlistamento = idade - 18 anoAlistamento = nascimento + 18 if idade == 18: print(f'''Quem nasceu em {nascimento} tem {idade} anos em {anoAtual}. Você tem que se alistar IMEDIATAMENTE. ''') elif idade > 18: ...
9fa41e058abc847525a06a787677bbe865be68cc
id4thomas/AlgoProbs
/Leetcode/72.py
3,580
3.75
4
# Minimum Edit (insert, delete, replace) # Levenshtein Dist # https://en.wikipedia.org/wiki/Wagner–Fischer_algorithm # Wagner-Fischer Algorithm class Solution: # Wrong Answer # Considered LCS and in between # def minDistance(self, word1,word2): # # print(self.lcs(word1,word2)) # ...
6f6fc3e93b01f4332a2cbd2127e40a1d5c31200c
taneesh28/Linear-search
/linear search.py
530
4.09375
4
#from numpy import * from array import * #import numpy as np n=int(input("enter the size on an array")) arr = ([]) for i in range(n): x=int(input("enter its elements")) arr.append(x) print(arr) val=int(input("enter the value you want to see into your input values")) #lsearch(arr,val) def lsearch(...
ef0d9d8743bb2d07de4db8ff8d75d25ee65bd7c6
samer-habash/WorldOfGames
/Score.py
844
3.625
4
from Utils import SCORES_FILE_NAME def write_score(difflevel): with open(SCORES_FILE_NAME, 'a+') as f: POINTS_OF_WINNING = (difflevel * 3) + 5 f.write(POINTS_OF_WINNING) def add_score(difficulty): #check if file is empty then it fails if os.path.exists(SCORES_FILE_NAME) and os.path.getsiz...
dd83df51388638dd0a07d0538d76c015f0b81e4a
d-tibbetts/Scribbler-S2
/Switch.py
3,904
4
4
from Myro import * import random init("COM5") def spin(): #bot spins around 360 degrees. for counter in range (0,4): turnBy(90) def robotPlaySong(): s=readSong("chariot.txt") playSong(s) # function that will make the robot beep if it is called and a line # is detected def beepLine()...
a710f22924ca68c3ae963df648513ca5d69f28d0
timothyshort/data_analysis
/03_data_analysis/wine_taste_case_study/15_conclusions_query.py
1,764
3.59375
4
# coding: utf-8 # # Drawing Conclusions Using Query # In[2]: # Load `winequality_edited.csv` import pandas as pd df = pd.read_csv('winequality_edited.csv') df.head() # ### Do wines with higher alcoholic content receive better ratings? # In[15]: # get the median amount of alcohol content alcohol_med = df['alc...
e431c3591e039077b2eaf965e297f854f314e3dd
elhamsyahrianputra/Pemrograman-Terstruktur
/Chapter 11/Chapter11_Pyhton Project_No.01.py
264
3.640625
4
from datetime import * listDate = [] def diffDate(x): listTgl = x.split("-") tgl1 = date.today() tgl2 = date(year = int(listTgl[0]), month = int(listTgl[1]), day = int(listTgl[2])) selisih = tgl2 - tgl1 return selisih.days print(diffDate("2021-03-14"))
e5bcd8ff40bd976fb01c7502cb189dffb712c403
elhamsyahrianputra/Pemrograman-Terstruktur
/Chapter 06/statistik.py
634
3.65625
4
# function untuk mencari jumlah data def sum(*Mydata): jumlah = 0 for bil in Mydata : jumlah += bil return jumlah # function untuk mencara rata-rata data def average(*Mydata): # gunakan function len() untuk mencari banyak data dari Mydata rata_rata = sum(*Mydata)/len(Mydata) return rata_rata # function untuk m...
c55fa8d98b3a689a9249bfbd085e302eda36d9a9
elhamsyahrianputra/Pemrograman-Terstruktur
/Chapter 07/Chapter07_Latihan No.3.py
395
3.71875
4
print("------------------------------") print("PROGRAM HITUNG RATA-RATA") print("------------------------------") bil = 0 n = 0 while True: try: bil = bil + int(input("Masukkan bilangan bulat: ")) n = n + 1 except ValueError: print("Bukan bilangan bulat") penutup = input("Lagi (y/n)? : ") if penutup == "n...
62c1e0937f4ec798bb1ecbe2de1ad10baacce2d6
777EROS777/-
/main.py
555
3.734375
4
# def f(n): # a = 0 # b = 1 # if n == 1: # print(a) # else: # print(a) # print(b) # for i in range(2, n): # c = a + b # a = b # b = c #цикл фибоначче < 100 a = 0 b = 1 fibo = [a, b] while b < 100: a, b = b, a + b fibo.append(b) print(fibo) #список четных чисел из списка фибоначче i = [] for it...
6ce09295f942446f6d10f7414323fc785ea8edf4
dagleaves/ASTAR
/astar.py
7,720
3.640625
4
from queue import PriorityQueue import pygame pygame.init() WIDTH = 800 HEIGHT = 800 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("A* Search Algorithm") RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) PURPLE = (128, 0, 128) GOLD = (255, 2...
939c3826a79bfc6d39d199a79260976f2387c187
datastreaming/tsfuse
/tsfuse/data/__init__.py
21,900
3.5
4
import os from enum import Enum import numpy as np from .tags import Tags, TagKey, HierarchicalTagKey from .units import units __all__ = [ 'Collection', 'Type', ] class Collection(object): """ Data structure for representing time series data and attribute-value data. Internally, collections st...
8d7af6662ea6c857d90e90046fcb45f7865160ad
Chillin-Examples/SearchAndDefuse
/PythonServer/app/helpers/logic/dls.py
1,280
3.65625
4
# -*- coding: utf-8 -*- # python imports from collections import deque # performs a Depth Limited Search def dls(world, start_position, max_depth, goal, valid_ecells=None): if not goal is None and goal.is_equal(start_position): return 0, [] positions = deque([start_position]) depths = deque([0])...
8b8565a1d9b82a6a9e7b61d491ba4184f5a1e524
Scavi/SnakeSqueeze
/src/snake_squeeze/Y2017/Day1InverseCaptcha.py
367
3.578125
4
class Day1InverseCaptcha: @staticmethod def solve(number, is_adjacent: bool = True): result = 0 split = 1 if not is_adjacent: split = int(len(number) / 2) for i, val in enumerate(number): if number[i] == number[(i + split) % len(number)]: ...
58b4ca15f45d8c5400b683b9a9ddbbddb159b816
pniewiejski/algorithms-playground
/data-structures/Stack/bracket_validation.py
955
4.21875
4
# Task: # You are given a string containing '(', ')', '{', '}', '[' and ']', # check if the input string is valid. # An input string is valid if: # * Open brackets are closed by the same type of brackets. # * Open brackets are closed in the correct order. from collections import deque OPENING_BR...
e6a3a6cd8ee7317bac53b7feff5aa6444d89cc6d
pniewiejski/algorithms-playground
/data-structures/Stack/find_max_in_stack.py
3,312
3.90625
4
# Task: # Implement a stack which has a max() method, which finds the max value on stack. # # This is a tricky task because stacks do not give us # this kind of operation straight out of the box. # We will have to somehow store the information about the max value. # We will have to _cache_ the max value....
bea427841ea9283504ac6ff8e0db93dbd1e118bc
pniewiejski/algorithms-playground
/dynamic-programming/knapsack.py
1,828
4.0625
4
# This is a simple solution to a discrete knapsack problem using dynamic programming from pprint import pprint ITEMS = [ { "name": "tablet", "price": 1500, "weight": 1}, { "name": "stereo", "price": 3000, "weight": 4}, { "name": "computer", "price": 2000, "weight": 3}, ] MAX_BACKPACK_WEIGHT = 4 # This i...
50e61b2fe9dad797b0ab2e3cfeffb89906326e29
AJgthb2002/Python-games
/Road_crossing_turtle_game/player.py
495
3.640625
4
from turtle import Turtle STARTING_POSITION = (-60, -270) MOVE_DISTANCE = 10 FINISH_LINE_Y = 280 class Player(Turtle): def __init__(self): super().__init__() self.shape("turtle") self.color("black") self.penup() self.start_pos() def start_pos(self): ...
37c45e5b078d4c958ba4934ba67de440d802a40a
aaronkrusniak/lucasbday
/gamedev/Inventory.py
984
3.75
4
import Item, Playsound """ An module for an Inventory. These are technically static methods, because they exist outside of a class. """ inventory = [] def addItem(item): inventory.append(item) def useItem(itemname): for item in inventory: if item.name is itemname: item.use() ...
71a8bda357dff676392fd8e5fa529464a2e66501
KinaD-D/Homework
/Урок 28.11.2020/Урок 28.11.2020/Урок 28.11.2020/Введите что зашифровать.py
537
3.5
4
count = 0 deleted = '' osnova = x = str(input('Введите что зашифровать, если количество символов нечетное, оставшеяся символ допишется в конце ')) y = int(len(x)) c = len(x) // 2 x = osnova[c: len(osnova)] y = osnova[0: c] while count < len(osnova) // 2: countx = x[count] county = y[count] deleted += cou...
4238ef5459c897e2dd8fff20c5f3045bbeceb15a
KinaD-D/Homework
/ДЗ 31.10.2020/Камень Ножницы Бумага.py
2,406
4.125
4
print('Добро пожаловать в камень ножницы бумага, сдесь вы будете играть с ботом.\nВ конце игры вам покажут статистику, если хотите что бы она была точнее играйте больше.') Game = int(input('Введите сколько игр играть будете ')) scissors = bumaga = kamen = raza = wins = 0 import random for i in range (Game): input...
025e4ee4a1a97e06bb58c77decda366ac37f653d
mathprog123/python-graphics
/lessons/5/lesson5homework.py
769
3.671875
4
from tkinter import * W = 600 H = 400 Win = Tk() c = Canvas(Win, width=W, height=H, bg="white") c.pack() R = 40 block = c.create_rectangle(50, 50, 50 + R, 50 + R, fill="blue", outline="blue") is_pressed = False def motion(event): global is_pressed x, y = event.x, event.y is_inside_block = c.coords(blo...
844bcf2ca023c0db43bd06b7ff2eaea8873f2587
drusepth/pyworld
/entity.py
523
3.53125
4
class Entity: def __init__(self): print('initing entity') self.token = DEFAULT_TOKEN self.age = 1 # todo overload == the real way def equals(self, other): return self.token == other.token and self.location.x == other.location.x and self.location.y == other.location.y def set_location...
bf117beb937c1d6ccec80d8268f633b4243650d1
YaroslavGavrilychev/Python_1594
/HW1.py
238
3.5625
4
sec = int(input('Пожалуйста, введите время в секундах: ')) min = sec // 60 hours = min // 60 day = hours // 24 print(f"%02d дн %02d час %02d мин %02d сек " % (day, hours % 24, min % 60, sec % 60))
d0bf885d49f2c82bd2d4a5b579151e6fb41468d0
KS2019775054/Python
/153-4.py
188
3.78125
4
a = int(input("몇 점 ?? ")) if a >=90: print("A") elif 80<=a<90: print("B") elif 70<=a<80: print("C") elif 60<=a<70: print("D") else: print("F")
0da8d98c1eeb6c1459b1549b3ec91c5fcac28b3e
KS2019775054/Python
/93p-6.py
295
3.640625
4
x1 = int(input("x1 :")) x2 = int(input("x2 :")) y1 = int(input("y1 :")) y2 = int(input("y2 :")) c = ((x1-x2)**2 + (y1-y2)**2)**0.5 print(c) import turtle t = turtle.Turtle() t.goto(x1,y1) t.goto(x2,y2) t.write("길이 " + str(((x1-x2)**2 + (y1-y2)**2)**0.5)) t.write("길이",c)
779031464bc7e79513e022f24567fd077a4b7325
jaydendrj/gnistudy
/从入门到实践/6字典/2字典初步.py
736
3.78125
4
information={'first_name':'c',"last_name":'m',"age":21,'city':'sh'} print(information['first_name']) print(information['last_name']) print(information["age"]) print(information['city']) favorite_numbers={ 'cm':2, 'dy':4, 'az':5, 'jz':21, 'ZX':45, } for name in favorite_numbers: print(name+'最...
f32c6c3e282fb5eedf4b48c55ceb3f68e6b92c52
jaydendrj/gnistudy
/从入门到实践/3_列表/3.2_列表元素删除插入添加.py
1,444
3.5625
4
invite_list=['a','xiaoming','3','dj'] busy_friend='3' l=busy_friend+'不能参加。' print(l) invite_list.remove(busy_friend) new_fiend='ne' invite_list.append(new_fiend) #没办法替换到原来的位置,怎么通过元素找到对应的索引值(虽然元素不唯一(可能重复出现)) message=invite_list[0]+",一起吃晚饭。" print(message) print('我找到了一个更大的餐桌。') invite_list.insert(0,'cm') invite_list ....
c22d81ea52a2223bfa06ce64c2e9d7f7c1a25e84
sramako/mouth_tracking
/s.py
1,164
3.9375
4
#Python 2.x program to transcribe an Audio file import speech_recognition as sr import cPickle import gzip def load(file_name): # load the model stream = gzip.open(file_name, "rb") model = cPickle.load(stream) stream.close() return model def save(file_name, model): # save the model stream...
700a7094a0a75386f168d9b276b1e894b9fe8560
Bellerofonty/palindrome_search
/palindrome_search.py
2,285
3.96875
4
""" Checks text from text.txt (utf-8) for palindrome sentences (containing more than one word) """ import re palindromes = [] punctuation_marks = ['?', '.', '!', '/', ';', ':', ',', '-', '–', '—', '\n', '"', "'", '«', '»', '*', '(', ')'] def line_to_sentences(line): """ Divides a line to senten...
05d77996fd2099c074ce4c0cf01cfea430c412c6
A-Dabek/Euler_reactivation
/p60s/p65.py
580
3.75
4
from fractions import Fraction def partial(ind): if ind % 3 == 2: return 2 * (ind//3 + 1) return 1 def bottom_to_top(frac, level): frac = 1 / frac if level == 0: return frac frac = (partial(level) + frac) return bottom_to_top(frac, level-1) def solve(): start = Fraction...
53d55675232a81b72eeda84b5357affd15290b7a
Rony20/Information-Security-Ciphers-and-Modular-Arithmetic
/AuyokeyCipher.py
1,289
3.53125
4
def affine(msg,key): result = "" for i in range(len(msg)): if i == 0: result += chr(((ord(msg[i]) - 64) + key) % 26 + 64) else: result += chr(((ord(msg[i]) - 64) + (ord(msg[i - 1]) - 64)) % 26 + 64) return result key = int(input("Enter key : ")) msg="THISISMYMESSAGE"...
2692fa6374464b2bd88aa123c69b60b73bd16464
stonedchess/engine
/stonedchess/game.py
3,842
3.53125
4
from typing import List, Optional, Union from .board import Board, Move from .movement import Movement from .player import Player from .position import Position class Game: """Game logic""" def __init__(self, board: Union[Board, Position]): self.board = board if isinstance(board, Board) else Board(b...
35989fef672a16308c2d919efd8aeb474f57de4e
OlgaBukharova/Python_projects
/черепашка 1/черепашка 4.py
103
3.71875
4
import turtle turtle.shape ('turtle') for x in range(360): turtle.forward (1) turtle.left(1)
e9c519040728ccf2b22ca6bda0c9c200840b68a8
OlgaBukharova/Python_projects
/черепашка 1/черепашка 10.py
276
4.375
4
import turtle from math import pi turtle.shape ('turtle') def circle (r): l=2*pi*r for i in range (360): turtle.forward (l/360) turtle.left (1) r=100 d=3 for i in range (d): circle (r) turtle.left (180) circle(r) turtle.left (180/d)
393cfd774cdd988ec4b1ee0c5c958decf64c7939
OlgaBukharova/Python_projects
/черепашка 1/черепашка 11.py
279
4.375
4
import turtle from math import pi turtle. shape ('turtle') def circle (r): l=2*pi*r for i in range (360): turtle.forward (l/360) turtle.left (1) for r in range (10,100,10): for i in range (2): circle (r) turtle.left (180)
6b05b506359cfa7cef92ca7e9705b187904c7d22
RiverHendriksen/cs-361
/assignment 1/testKwic1.py
1,821
3.9375
4
#River Hendriksen 2016 #CS-361 Assignment 1 #Kwic1test.py #The test will see if the various conditions applied will still allow to the program to work #this test runs under the assumption that we are not in a list of lists at this point #eg the example ("hello \n bucko that ") does prouduces ["hello" , "bucko", "that"...
bf8893db6c522f8e6d0f7e1470b0c11b3b887829
Alvarlegur/Isbilar_1.0
/models/car.py
1,317
3.65625
4
class car: #defining inital class instance def __init__(self,licensePlate, manufacturer, typeCar, manOrAuto, fuelType, priceGroup, manufYear,availability): self.__licensePlate = licensePlate self.__manufacturer = manufacturer self.__typeCar = typeCar self.__manOrAuto = manOrAuto ...
52ba768f53166b89cb616b91304c33867370bdd4
Earthaa/LeetCode
/Python/LeetCode142 Linked List Cycle II.py
681
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ tortoise = head hare = hea...
e790676a19952d2f11608aacfb96bce68f9bb140
Earthaa/LeetCode
/Python/LeetCode49 Group Anagrams.py
640
3.703125
4
class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ strdict = {} for each_str in strs: sorted = "".join((lambda s:(s.sort(),s)[1])(list(each_str))) if strdict.has_key(sorted): ...
58c82783c60044127883f0c2b05511f2c8e6abbd
Take-Take-gg/20460065-Ejercicios-Phyton-02
/Ejercicios-02/Condiciones-01/Condiciones-01.py
605
3.9375
4
# Condiciones 01 """ 1.- Escribe un programa que pida dos números enteros y que calcule su división, escribiendo si la división es exacta o no. """ """ 2.- Mejora el programa anterior haciendo que tenga en cuenta que no se puede dividir por cero. """ try: num=(float(input("Dame un primer numero: "))) num2=(flo...
c6d341b18c7cd5a8d56dfce347a1bd9e9bd94fcf
Take-Take-gg/20460065-Ejercicios-Phyton-02
/Ejercicios-02/Bucles-02/Bucles-02.py
561
3.8125
4
# Bucles 02 """ 2.- Escriba un programa que pida un número entero mayor que cero y que escriba sus divisores. """ try: num = int(input("Dame un numero mayor que 0 y te digo sus divisores: ")) if num <= 0: print("Que fue lo que te dije?") else: def prop(num): lista = [] ...
3d5ba11ea5e414633b2d196ea20056aedb57f003
Ulysses3/Pyto
/Pyto/Samples/SciPy/ndimage.py
345
3.71875
4
""" An example of rotating an image with SciPy. Taken from https://www.guru99.com/scipy-tutorial.html """ from scipy import ndimage, misc from matplotlib import pyplot as plt panda = misc.face() #rotatation function of scipy for image – image rotated 135 degree panda_rotate = ndimage.rotate(panda, 135) plt.imshow(pa...
bd7e7ea2d52530fb032f7e4fac2991d15e5cbbba
willgoshen/CTCI-with-Python
/1-2-permutations.py
275
3.984375
4
def permutations(s1, s2): sorted_s1 = sorted(s1) sorted_s2 = sorted(s2) if sorted_s1 == sorted_s2: return "'{}' is a permutation of '{}'".format(s1, s2) return "'{}' is not a permutation of '{}'".format(s1, s2) print(permutations("this", "histy"))
89f86900127409f212ca1237293456f3809d628d
jamesjose03/handcricketgame
/handcricket.py
5,617
3.875
4
#Hand Cricket Game import random,time list=["Hand","Cricket","Game!!!"] def bowl(): print ("The game starts now! You are bowling! All the best!") print("Enter the number of overs to play: ") over=int(input()) balls=over*6 comptotal=0 thrownballs=0 while ...
3c4465418f980be01250fa017db3031a6a69e33b
barenzimo/Basic-Python-Projects
/2-tipCalculator(2).py
410
4.28125
4
#A simple tip calculator to calculate your tips print("Welcome to the tip calculator \n") bill=float(input("What was the total bill paid? $")) tip_percent=float(input("What percentage of bill would you like to give? 10, 12 or 15? ")) people=int(input("How many people are splitting the bill? ")) total=float(bill+(bill*...
25aae8e1743f08bed875c22fb21ddb5679ae9710
felipovski/python-practice
/intro-data-science-python-coursera/curso1/semana7/opcional2_hipotenusas.py
169
3.515625
4
def soma_hipotenusas(): n = int(input("Digite um número positivo: ")) soma = 0 i = 1 hipotenusa = i^^2 + i^^2 return def é_hipotenusa():
036cb3fa6ce58f996455c615afc108d84768dfcd
felipovski/python-practice
/intro-data-science-python-coursera/curso1/semana4/exercicio1.py
169
4.15625
4
def fatorial(): n = int(input("Digite um número: ")) fatorial = i = 1 while i <= n: fatorial *= i i += 1 print(fatorial) fatorial()
8ec6d128c0824cc7d2193d0e98eed0b03ed2db43
felipovski/python-practice
/intro-data-science-python-coursera/curso1/semana6/exercicio1_nim.py
2,270
4.0625
4
def campeonato(): print("\nBem-vindo ao jogo do NIM! Escolha:\n") escolha = int(input("1 - para jogar uma partida isolada\n2 - para jogar um campeonato ")) if escolha == 2: print("\nVoce escolheu um campeonato!\n") print("**** Rodada 1 ****\n") partida() print("**** Rodada 2...
d6a6d3337d059143f199535475ecd958184ce1cf
felipovski/python-practice
/intro-data-science-python-coursera/curso2/semana2/ex1_maisculas.py
903
3.53125
4
import re def maiusculas(frase): maiusculas = "" frase_sem_espaco = re.sub(r'[.!?\s0-9\W]+', "", frase.rstrip()) #frase.replace(r'[.!?]+', "") for ch in frase_sem_espaco: if ch.upper() == ch: maiusculas += ch return maiusculas def testa_maiusculas(): if maiusculas('Programamos ...
0c719b3acb3a4af4425fa11a271a079af4fdfba6
felipovski/python-practice
/intro-data-science-python-coursera/curso1/semana3/ordemCrescente.py
346
4.125
4
def main(): numero1 = int(input("Digite o primeiro número inteiro: ")) numero2 = int(input("Digite o segundo número inteiro: ")) numero3 = int(input("Digite o terceiro número inteiro: ")) if numero2 >= numero1 and numero2 <= numero3: print("crescente") else: print("não está em orde...
c18acb2f58d57c188886a64d51a5ae7102fc0ee3
LeoGouchon/CsDevPendu
/versionUI/fPendu.py
3,490
3.828125
4
""" --------------------------- Créé le 27/11/2020 @author: leo.gouchon --------------------------- Explication : Fichier contenant toutes les fonctions utiles pour le programme pendu en version Tkinter Bug : def CheckLetter : le if ne sert à rien, il faut le changer pour obliger l'utilisateur à ré écrire une lettre ...
ec7377b4db81edd24b77fc10305bd6b293c766ca
iamnarendrasingh/Data-Camp-Learn
/Simple Linear Regression in Python From Scratch/main.py
640
4
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("E:\Self_GitKraken\Working_Repo_GitHub\Data-Camp-Learn\Simple Linear Regression in Python From Scratch\Salary_Data.csv") x = data['YearsExperience'] y = data['Salary'] print(data.head()) def linear_regression(x, y): ...
683a9bc344820c0f8bd5860fa94d79986c8a7e73
TazcDingo/python-learn-demo
/demo_str.py
1,553
3.875
4
'''this is a demo of string''' import sys import string class DemoStr: '''这是一个Demo Str类''' @staticmethod def learn_method(): '''this is a method''' # 构造函数有两种,直接字面化常量赋值和str()构造 # str.capitalize() string 首字母大写,其余全小写 example = "exAmple iS Example" example_cap = example...
64a0a295d0d4e9900f19407a3f515f88ffbe7b6a
lvanderlyn/VideoGame
/isContact_L1.py
10,243
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 7 16:53:22 2014 @author: koenigin """ # -*- coding: utf-8 -*- """ Created on Wed Mar 5 14:32:50 2014 @author: koenigin """ import pygame, sys, random from pygame.locals import * #working meh #by which i mean not working # i mean, it does some shit # just not the shit...
a6b5328e99375763052fb2d3daef2ce0a416ce2d
ExpressHermes/Coursera-Algorithmic-Toolbox
/Week 2/2_last_digit_of_fibonacci_number/fibonacci_last_digit.py
663
3.75
4
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_fib_fast(n): fib = [-1 for x in range(n+2)] fib[0] = 0 fib[1] = 1 ...
04734a3bf4de3e86dc53cbfe32ee53bd65fce137
pys6478/Algorithm
/Python/1924.py
225
3.515625
4
import sys a, b = input().split() a = int(a) b = int(b) month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = {0:'SUN', 1:'MON', 2:'TUE', 3:'WED', 4:'THU', 5:'FRI', 6:'SAT'} print(day[(sum(month[:(a)]) + b)%7])
f9557ef9c21bd019a264875fcd42649c5f4b0058
G0rocks/Python
/Threading/threadingTest.py
530
3.8125
4
# Testing the threading functionality of the threading module import threading from threading import Thread from time import sleep def sum(a: int, b: int): return (a+b) def doThing1(): """ Does the first thing """ sleep(3) print("Thread 1. The sum of 2 and 5 is {int}", sum(2,5)) def doThing2(): """ D...
892fd5944397d2898ddb951b7521b87ed60b92d3
juanpaluna1234/UVAS
/12347 Binary Search Tree.py
1,004
3.65625
4
from sys import stdin import math def main(): p = [] for line in stdin: if line == "\n": break line.strip() p.append(int(line)) i = 0 while(p[0] >= p[i]): i = i + 1 first_half = p[1:i] second_half = p[i:] binaryTreeSearch(p[0],first...
b49bfc359d47693f3279bea2025abcc20af36ba6
HadarShahar/zoom
/client/video/video_encoder.py
1,001
3.59375
4
""" Hadar Shahar VideoEncoder. """ import cv2 import numpy as np class VideoEncoder(object): """ Definition of the class VideoEncoder. """ # the quality of the image from 0 to 100 (the higher is the better) JPEG_QUALITY = 80 # default is 95 @staticmethod def encode_frame(frame: np.ndarr...
bc770215e2df7b775b85bb3c94f300088761bcf1
aemms/PythonAlgorithms
/fibonacci2.py
128
3.71875
4
def fibonacci2(n): i = 1 j = 0 for k in range(n): j = i + j i = j - i return j print fibonacci2(5) print fibonacci2(53)
e43ef94d6d8258887a0416dcdcbfdd74640615d1
thanhlankool1/Python-Baitap
/pyfml/exercises/ex4_8.py
577
3.65625
4
#!/usr/bin/env python3 def solve(): '''Trả về list N bộ integer (a, b, c) là độ dài 3 cạnh của tam giác vuông cạnh huyền `c` có chu vi 24 cm (perimeter), biết độ dài các cạnh <= 10cm. Yêu cầu dùng list comprehension. ''' li1 = [(a, b, c) for a in range(11) for b in range(11) for c in range(11)] ...
afb5d72453919d5fa092b00ac3ecab1f17ffb748
dolleye96/CSE368_assignment1
/slideproblem.py
5,703
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 14 11:03:51 2017 @author: Nils Napp Modified on Thu Sep 5 21:35:17 2019 @modified by: Jiwon Choi """ import numbers import random class State: """ State of sliding number puzzle Contains array of values called 'board' to indicate tile positions, and...
7ca2e9212bffc44c0c47458cc5b39a720b354643
yoagauthier/deep_learning_course
/TD2/mnist_CNN.py
6,551
3.578125
4
#!/usr/bin/python from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import tensorflow as tf # >>>> Loading MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_se...
299fd791e3ccea48bee18f80ab5be8ce83093d31
DaxelTH/AlgoritmosPython
/Order/mergesort.py
887
3.9375
4
def mergeSort(lista): if len(lista)>1: mid = len(lista)//2 mitadIzq = lista[:mid] mitadDer = lista[mid:] mergeSort(mitadIzq) mergeSort(mitadDer) i=0 j=0 k=0 while i < len(mitadIzq) and j < len(mitadDer): if int(mitadI...
7ae6081af87c673a2bb322031785bb7026f629ca
lulala66/python-practice
/03advFunc.py
3,064
3.890625
4
# -*- coding: utf-8 -*- # homemade list generator (map func) from math import cos, pi from functools import reduce # function as input # 'listGenerator' a implementation of 'map' function def listGen(f, list): result = [] for num in list: result.append(f(num)) return result print(listGen(cos, [p...
1670e11bc05d4b8105e0fd85a7681fb8ec38b8f1
lulala66/python-practice
/algorithm/validParentheses.py
4,055
3.90625
4
class Solution: """ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. """ def isValid(self, s): """ ...
9c12254de9187c1c7560dd89fd33a969b3d9d4ca
korosuke613/konishi_python_learn
/type_check.py
733
3.703125
4
def type_check(param): if isinstance(param, int): return "intです" elif isinstance(param, float): return "floatです" def another_convert_type(param): if '.' in param: param = float(param) else: param = int(param) return param def convert_type(param): try: ...
451669caf3401e89605fe1299fbd054be4ab04ca
korosuke613/konishi_python_learn
/repetition.py
597
4.0625
4
from condition import judge_plus_minus def sub(): # 0 1 2 for i in range(3): print(i) judge_plus_minus() while True: judge_plus_minus() def main(): is_correct = False while not is_correct: answer = input("パンはパンでも食べられないパンはなんだ?") if answer == "フライパン": ...
8c7aa3e146e9bb170b1fc57522fffbabcae77948
jeanjoubert10/Simple-bouncing-ball-with-python-3-and-pygame
/Bouncing ball with classes.py
1,619
3.8125
4
# Simply pong game using python 3 and pygame # Minimal without start and game over screen import pygame import random vec = pygame.math.Vector2 TITLE = 'Simple Pong with Python 3 and Pygame' WIDTH = 600 HEIGHT = 600 FPS = 120 FONT_NAME = 'arial' WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) class Ba...
1eb8d5a661dcf8233311273918b3ec488e6d93cd
nadeem-ninja/Backend-And-api
/venv/lib/python3.8/site-packages/random_timestamp/__init__.py
1,644
3.5625
4
__title__ = 'random_timestamp' __version__ = '1.1' __author__ = "FENG Hao" __license__ = 'GPL v3.0' from random import randint from datetime import timedelta as td, datetime as dt, date, time import calendar as cal # Function which generates random time object def generate_random_time(): hour = ran...
2d462e37e3aae358cb78b7bb43b980fe0b0be395
jc8702/Apex---Curso-Python
/apex-ensino-master/aula-12-08-2020/ex-08.py
405
4.21875
4
# Exercício 08 # Escreva um programa em Python que receba o nome e o sobrenome do usuário, em seguida os imprima em ordem reversa. Por exemplo: if __name__ == '__main__': nome = input("Digite um nome: ") sobrenome = input("Digite um sobrenome: ") print(f'{nome} {sobrenome} {3 * 3}') # Apex Ensino ...
032252889d48a51bff36a8118faf76ac83cd0df3
jc8702/Apex---Curso-Python
/apex-ensino-master/aula_17_08_2020/ex-04.py
1,112
4
4
# ex-04.py if __name__ == '__main__': banco_de_dados = [] comando = None menu = """ * adicionar: Adiciona um registro * excluir: Exclui um registro * diminuir: Exclui o último registro feito * mostrar: Mostra os dados * sair: Sai. """ print(menu) while comando != 'sair':...
30b7a0a95d92d3b3e7257b3d1a1f39ac6de5284e
jc8702/Apex---Curso-Python
/apex-ensino-master/aula-12-08-2020/ex-06.py
683
4.34375
4
# Exercício 06 # Escreva um programa Python que pedirá 3 números, informe qual deles é o menor. if __name__ == '__main__': numero1 = int(input("Digite o primeiro número: ")) numero2 = int(input("Digite o segundo número: ")) numero3 = int(input("Digite o terceiro número: ")) numeros = [numero1, numero2...
2896f442015040760fe81d6ba7cc8d1dfb091fd5
pranavarora1895/intermediate_python
/events.py
307
3.90625
4
import threading event = threading.Event() def myFunction(): print("Waiting for event to trigger!!") event.wait() print("Performing Action XYZ now...") t1 = threading.Thread(target=myFunction) t1.start() x = input("Do you want to trigger the event?? (y/n): ") if x == 'y': event.set()
cc7a99e42302c448bfd8d59d0e2c2b38670dbeae
linhuiyangcdns/leetcodepython
/两个数组的交集 II.py
982
4.5625
5
""" 给定两个数组,写一个方法来计算它们的交集。 例如: 给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]. 注意: 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。 我们可以不考虑输出结果的顺序。 跟进: 如果给定的数组已经排好序呢?你将如何优化你的算法? 如果 nums1 的大小比 nums2 小很多,哪种方法更优? 如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办? """ class Solution: def intersect(self, nums1, nums2): ...
625fe63c17b5d8fe88879be6568c357a0f7aedc7
linhuiyangcdns/leetcodepython
/移动零.py
847
3.984375
4
""" 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ ...