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
a5aa9d1003ff2a25340a7e491e08b7edf1d211cb
bawate/recipe-app-api
/app/app/calc.py
168
4.09375
4
def add(x, y): """Add the two numbers together""" return x + y def subtract(x, y): """Subtract the two numbers and return the output""" return x - y
784b7b523480ccf7e5f6f0199b77f936031817a1
CristiReyes/Assignment-9
/classBattleship.py
1,563
4.09375
4
from random import randrange board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print(' '.join(row)) shipX = randrange(5) shipY = randrange(5) counter = 0 print("Let's play battleship!\nTry and sink my battleship in 4 tries!\n") ...
c58baaecc2fe4213097c80ec74bfdca41d2b99ad
xdronmanx/a3200-2015-algs
/lab4/Gogolev/Zadacha4.py
932
3.71875
4
from sys import stdin first_line = stdin.readline() list = [int(p) for p in first_line.split(' ')] k = 10 def INSERTION_SORT(list): for j in range(1, len(list)): key = list[j] i = j - 1 while (i >= 0) and (list[i] > key): list[i+1] = list[i] i = i - 1 list[...
fa611914011816c11f5d5dd6151440c3d283b2b0
JayBhakhar/maths-project
/python files/task2.py
242
3.5
4
## TASK 6.9.14 ## import itertools lst = [] num = int(input("input number for permutations :- ")) for n in range(num): n = n + 1 lst.append(n) for p in itertools.permutations(lst): print(''.join(str(x) for x in p))
7c9e4ac3c13a544af61ae090df839bc6cc64073a
LorchZachery/satlabeling
/dev/hotkeys/hotkeys.py
1,199
3.859375
4
from pynput import keyboard # the key combination to look for COMBINATIONS = [ {keyboard.Key.shift, keyboard.KeyCode(vk=65)} ] def execute(): """function to execute when a combination is pressed""" print("do something") # The currently pressed key (initially empty) pressed_vks = set() def get_vk(key):...
dea7be93bb9263fb2a4d9b34211ec58944b1a130
dwg920302/python_customs
/darkspace/kakao2.py
1,152
3.578125
4
# 0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요. # # 예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다. # # 0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요. # # 제한 사항 # numbers의 길이는 1 이상 100,000 이하입니다. # number...
3bf49a56937907bf9e6dac455d92ededc5dc91b0
dwg920302/python_customs
/darkspace/practice_questions/pr4to2.py
410
3.5
4
class AllAvg(object): def __init__(self): pass @staticmethod def main(): res = 0 ls = [] while 1: num = input('더할 수를 입력 (0 입력 시 종료) ->') if num == '0': break else: ls.append(num) for i in ls: ...
c45411686f718da72193c21419c52e94ab639716
cloudwiki/learnPython
/class_generator_8_queens.py
1,347
3.625
4
__metaclass__ = type def conflict(state, nextX): nextY = len(state) for i in range(nextY): #Every element in state and its index represent the position in the table. #e.g. state(0)=1, means the queue's position is at cell(1,0). index is for Y axis, value is for X axis #the expression r...
d352e9025b496ce99ba87a9e8b66916464230442
dodomorandi/hatspil
/hatspil/reports/report_table.py
7,207
3.53125
4
"""An abstraction layer to handle tables in a report. Reports need some HTML, therefore an abstraction layer is extremely useful to create and customize a table before the HTML code is generated. This module contains some classes that ease the process. """ from collections import OrderedDict from enum import Enum fro...
93228a077666cb8189480f29a59d84c2c4876b18
gmayank32/SklearnTutorialWorkspace
/skeletons/exercise_02_sentiment.py
3,551
3.53125
4
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a ...
3e5e11a8ca59974cce5523a2ba0ad5b714e1c4dc
EduardoCastro15/Compiladores
/Practicas/PracticaOpcional/Final.py
8,996
3.890625
4
from Automata import * import Thompson #función para crea tuplas que guardan las transiciones del archivo def tres(transiciones): Aux = [] #Lista auxiliar anterior = 0 #Badera auxiliar for i in range(0,int(len(transiciones)/3)): #Ciclo del numero de transacciones entre 3 siguiente = (i+1)*3 #Calculamos el valor d...
68fcee641d98c5364551e28cb08b4adbcc3eb772
waallf/bishi_
/1/5.py
821
3.5625
4
line = input() # line = "1-8/3+1" fuhao = ("+","-","*","/") def yunsuan(a,b,c): if c == "+": return a+b if c == "-": return b-a if c == "*": return a*b if c == "/": return b/a fuzhan = ["#"] shuzhan = [] all = int(line[0]) for i in line: if i in fuhao: if ((i ...
43eb8cab392f0af1963cb32b5736d64a5c45ef8f
jjgecon/Personal_coding_projects
/MATLAB Intro/Sollow.py
2,319
3.671875
4
# Code by Javier Gonzalez on December 2019 # For any questions please contact javierj.g18@gmail.com # Simple Sollow Model with graphs import numpy as np import matplotlib.pyplot as plt # Set time period and grid space T,n = 1, 100 # Capital Grid k = np.linspace(0,T,n) # Set the functions def production(k, alpha = 0...
79fda46293cd0e4507776b9a56fdbee2181acfc7
goodwjsphone/WilliamG-Yr12
/pygmae/balls.py
2,030
3.984375
4
#Import libaries import pygame import math import random # Difine colours RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) WHITE = (0,0,0) #initialise pygame pygame.init() # set the height and width of the screen screen_width = 700 screen_height = 400 screen = pygame.display.set_mode([screen_width,screen_height]) #us...
fd73641925aa29814156330883df9d132dbcb802
goodwjsphone/WilliamG-Yr12
/ACS Prog Tasks/04-Comparision of two.py
296
4.21875
4
#write a program which takes two numbers and output them with the greatest first. num1 = int(input("Input first number ")) num2 = int(input("Input second number ")) if num1 > num2: print (num1) else: print(num2) ## ACS - You need a comment to show where the end of the if statement is.
82d97c5675e99633b6b63b7d525822bbd3882bb0
zarkaltair/Learn-python
/Tasks by MFTI/tasks to module #3.py
279
3.5
4
def min(x, y): if x <= y: return x else: return y def sum(x): res = 0 for i in range(x): res += i return res def print_nums(x): for i in range(x): print(i) return print_nums(10) def func(x): res = 0 for i in range(x): res += i return res print(func(4))
40e1eaceaa0f5cb8111b5ace4ac79664026c1a32
zarkaltair/Learn-python
/Lessons by HoudyHo/lesson (31).py
1,571
4.03125
4
# Модуль itertools стандартная библиотека, один тип функций в этой библиотеке это бесконечные итераторы from itertools import count # count выводит все элементы в соответствии с заданными параметрами for i in count(3): print(i) if i >= 11: break from itertools import accumulate, takewhile n...
72d30c71a2db05c7d7bc10a83c3c5dc644d2a83b
zarkaltair/Learn-python
/Lessons by HoudyHo/lesson (18).py
1,230
3.765625
4
test = None if(test == None): print(test) foo = print() if foo == None: print(1) else: print(2) # Dictionary - Словарь test = { 'ключ1':'значение1', 'ключ2':'значение2', } try: print(test['тестовый_ключ']) except KeyError: print('Такого ключа не существует!') test = { 'ключ1':'значение1', 125:'сто двадцать ...
640ca5a2d92ab891850b77b0ca823a67875827af
zarkaltair/Learn-python
/Lessons by HoudyHo/lesson (16).py
771
4
4
def exc(text): assert text!='' print(str(text)+'!') exc('Hi') def test(number): assert number>0, 'Number should be bigger than 0.' print(str(number)) test(10) file=open('test.txt','r') print(file.read()) file.close() filename = input('Укажите файл?: ') file = open(filename,'r') print('В данном файле '+str(len(f...
4074745536d1e72f684c66b59a50d73e06c192c1
zarkaltair/Learn-python
/Lessons by HoudyHo/lesson (9).py
126
3.828125
4
number = 0 while number <= 10: number +=1 if (number % 2) != 0: continue; print('Четное число ' + str(number))
cd1a1d0e5e8a812f8807e38617b0209b439526ba
zarkaltair/Learn-python
/Lessons by HoudyHo/lesson (4).py
828
3.953125
4
a = input('Введите первое число : ') b = input('Введите второе число : ') print(int(a) + int(b)) print(str(1) + '2' + str(3) + '4') name = input('Enter your name: ') count = input('How many?: ') print(name*int(count)) pogoda = 'Зима' time = 'День' print( 'Программа запущена.' ) if pogoda == 'Зима': print( 'Сейчас х...
ae0d80dd8205cf6e4e2a4e8fe376fcb73a85ec10
olcplif/python-hw
/#15_Argument_parser/Task_1.py
1,444
3.75
4
# 1. Написати програму яка буде зберігати username і email в файл json. # При наявності користувачів перед тим як додати юзера програма повинна перевірити чи не існує на данний момент # користувача з таким username і email, якщо існує вивести помилку. import argparse import json class ParsErrorUsername(Exception): ...
a504de158456b0ed73810de157595638f3bb6236
olcplif/python-hw
/hw#11_Testing/calc_unitests/calc.py
3,692
3.859375
4
class Calc: @staticmethod def sum(a: int, b: int) -> int: """ Шукає суму двох чисел >>> Calc.sum(4, 5) 9 Використовуючи формулу a + b :param a: перший доданок, може бути int або float :param b: другий доданок, може бути int або float :return: сума додан...
547d80458ccdd2ae094da776e14344e26b9e8a59
Cooler5339/homework_alevel
/lesson 3 (ATM V2).py
296
3.75
4
money = int(input('Withdrawal amount:')) banknotes = [50,100,200,500,1000] for i in banknotes: if money >= 0: change = money // i money -= change * i if change != 0: print ('Get your money!:'+str(change)+'*'+str(i)+'$') else: print ('GoodBye! See later!')
662d78c93d5033e86f181c7d1bd1d4ad59fc2814
Cooler5339/homework_alevel
/Lesson 6(Students_Grades).py
470
3.78125
4
std = {'Alex': 51, 'Bob': 66, 'Jango': 87, 'James': 87} n = std.keys() n = len(n) point = sum(std.values()) avrg_grades = point / n print("Средний балл студентов: " + str(int(avrg_grades))) print('Студенты с баллом выше среднего: ') for i in std: if std[i] > avrg_grades: print(i) print("Студенты с баллом н...
22f107c9e4ce076b6c85487a69afddf89078e389
rahmatmaftuh/numpytutorial
/5manipulasimatrix.py
620
4.0625
4
import numpy as np a = np.array(([1,2,3], [4,5,6], [7,8,9])) print("matriks a dengan ukuran", a.shape) #cara 1 print("matriks a dengan ukuran", np.shape(a)) #cara 2 #transpose matrix = perubahan baris jadi kolom dan sebaliknya print("transpose matrix a") #cara 1 print(np.transpose(a)) #cara ...
f5f9f5d2efbb9b2e1d94f0dc69462e599cb354cc
michaelmiranda1/python
/Michael Miranda Midterm.py
6,511
3.703125
4
# coding: utf-8 # ''' # PART TWO: # # Students choice! # # Create a new Jupyter notebook. # In that notebook, I would like for you to choose a plotting library (matplotlib, bokeh, holoviews, or seaborn) # and either a data set from the example data sets included with that library or another data set you may find # ...
0081d5aee1547ad94975bbc294a419c9dff3287e
pavel-stoykov/python_advanced
/Lab_04/03.even_matrix.py
258
3.640625
4
row_counter = int(input()) matrix = [[int(num) for num in input().split(', ')] for row in range(row_counter)] even_matrix = [[matrix[row][col] for col in range(len(matrix[row])) if matrix[row][col] % 2== 0]for row in range(len(matrix))] print(even_matrix)
330f50a9f2ce32dbdd10580fb4f3588c8a649bf8
pavel-stoykov/python_advanced
/Exercise_05/03.min_max_sum.py
251
4
4
numbers = [int(x) for x in input().split()] min_num = min(numbers) max_num = max(numbers) sum_of_numbers = sum(numbers) print(f'The minimum number is {min_num}') print(f'The maximum number is {max_num}') print(f'The sum number is: {sum_of_numbers}')
34f204200e558447243cff4744db849206990a37
pavel-stoykov/python_advanced
/Lab_02/02.average_student_grade.py
474
4.0625
4
number_of_students = int(input()) student_record = {} for _ in range(number_of_students): token = input().split() name = token[0] grade = float(token[1]) if name not in student_record: student_record[name] = [grade] else: student_record[name].append(grade) for name, marks in stude...
2b9acbe4f5531d940d6ace3940d6f62a37716237
pavel-stoykov/python_advanced
/EXAM(OLD PROBLEMS)/01.santa_present_factory.py
1,740
3.5625
4
from collections import deque DOLL = 150 WOODEN_TRAIN = 250 TEDDY_BEAR = 300 BICYCLE = 400 materials = deque(int(x) for x in input().split()) magic_level = deque(int(x) for x in input().split()) gifts = { 'Doll': 0, 'Wooden train': 0, 'Teddy bear': 0, 'Bicycle': 0 } while materials and magic_level: ...
b90d53eecb97b29b7ed1216789795c4e93cf97ff
NiyazHellYeah/Test
/2.1.py
572
4.09375
4
#Создать список и заполнить его элементами различных типов данных. #Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. #Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. list = [2, 'text', 456, 45.3, None, True] for i in list: p...
f97d622ce56e91169df1810f16702072542cbf8b
paulscottrobson/mz-virtual-machine
/documents/comparison_check.py
185
3.578125
4
def check(b,a): if b <= a: print("FFFF") else: print("0000") check(3,2) check(2,2) check(2,3) print("") check(-3,-2) check(-2,-2) check(-2,-3) print("") check(2,-2) check(-2,2)
a7b9758e30b5b2ef0ae6a43a68671ce37f709c9a
joao-pedro-serenini/recursion_backtracking
/fibonacci_problem.py
678
4.1875
4
def fibonacci_recursion(n): if n == 0: return 1 if n == 1: return 1 return fibonacci_recursion(n-1) + fibonacci_recursion(n-2) # top-down approach def fibonacci_memoization(n, table): if n not in table: table[n] = fibonacci_memoization(n-1, table) + fibonacci_memoiz...
523b8d740409e168ec71a85de5ca4b0461f1afa7
Jinwon777777/Baekjoon-Algorithm
/1920 수 정렬.py
435
3.75
4
def binary_search(a, x): start = 0 end = len(a)-1 while start <= end: mid = (start+end)//2 if x == a[mid]: return 1 elif x > a[mid]: start = mid + 1 else: end = mid - 1 return 0 n = int(input()) a = list(map(int, input().split())) m = ...
a606701ff19aeb87aa7747cd39d40feb826ccb29
PhyzXeno/python_pro
/transfer_to_x.py
991
4.25
4
# this piece of code will convert strings like "8D4C2404" into "\x8D\x4C\x24\x04" # which will then be disassembled by capstone and print the machine code import sys from capstone import * # print("the hex string is " + sys.argv[1]) the_str = sys.argv[1] def x_encode(str): the_str_len = len(str) count = 0 the_x...
03eb76f8d1e0ed2cc8a90a690bcf2362dd6e2ff8
makkolli31/DeepLearning
/rnn_raw.py
8,770
4.03125
4
#An attempt at a batched RNNs # #I don't think this is an LSTM. What is the difference, exactly? I want to #know the more complicated functional forms, how to backprop them, and what #the advantage is. import numpy as np import matplotlib.pyplot as plt class RNNlayer(object): def __init__(self, x_size, h_size, y_...
65b2fa8b9512bf5becb5cb06ede5c8419f179426
balcanuc/playground
/serve.py
275
3.65625
4
#!/usr/bin/env python print('Content-type: text/html\n') print('<title>Hello World</title>') for num in range(2, 5000): prime = True for i in range(2,num): if (num%i == 0): prime = False if prime: print(num) # comment added by ccsyi06
55afd5b5bd7c9e281bbf5a37dfe588e8f0456661
panzerox123/Intro-to-CV-and-DL
/linear_regression_formula.py
805
3.828125
4
import numpy import matplotlib.pyplot as plt import pandas as pd #from sklearn.linear_model import LinearRegression dataset = pd.read_csv("data.csv") X = dataset['sqft_living'] Y = dataset['price'] #print(X) #print(Y) len_x = len(X) len_y = len(Y) x_sum = 0 y_sum = 0 for i in range(0,len_x): x_sum = x_sum + X[...
3a4b122d8d066cee75d23e342ae79fe6e098e305
PotatoTaco/Programming-Crappy-Solutions
/Machine Learning/Algorithms from Scratch/Genetic Algorithm.py
2,198
3.515625
4
import random # Finds the number 10 from a range of 0 to 100 class GeneticAlgorithm: def __init__(self, debug=False): self.population = [] self.debug = debug ### These 4 functions can be altered depending on what is being searched def randomInit(self): self.population = [ra...
faa8d2c01c7ee9411c16d86ac35291dddaa3ea07
PotatoTaco/Programming-Crappy-Solutions
/Frameworks Testing/Discord Bot/Python/basic.py
2,579
3.71875
4
#https://realpython.com/how-to-make-a-discord-bot-python/ import discord from discord.ext import commands TOKEN = input("Enter discord token: ") bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.event async def on_message(message): #...
f48a8232fb0645e5a3e96f406a019552080d6020
shmuli9/rolling_averages_data_challenge
/rolling_averages.py
2,710
3.625
4
import csv import time from datetime import datetime import matplotlib.pyplot as plt import numpy as np import pandas as pd ''' example.csv contains the values for the system. The thing to note about the file is that the sampling periods are not every 1 second. So there might be a value at t = 0s of 200, and...
7664385455f917000232e15bd520625c5e6966d6
marshallwicker/AITournament
/maroon.py
14,887
3.640625
4
from isolation import * import random X = True def congruent_mod(x, y, n): return (x - y) % n == 0 class PlayerAgent(Player): mid_tiles = {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31} def __init__(self, name, token): """ Initialize a new instance :param name:...
e44ce2e63d37ea010cb07d82b35dec3a5f129612
lky1020/OpenCV
/OpencvPython/Chapter4.py
517
3.71875
4
#Chapter 4 - Shapes & Texts import cv2 import numpy as np img = np.zeros((512, 512, 3), np.uint8) #print(img.shape) #img[:]= 255, 0, 0 #blue, green, red #shapes cv2.line(img, (0, 0), (img.shape[1], img.shape[0]), (0, 255, 0), 3) #shape[1] = width, shape[0] = height cv2.rectangle(img, (0, 0), (250, 250),...
44435a2014b6a639d8da89bd5a59ed297360f46e
sky332060679/python_exercises
/列表.py
258
3.75
4
number = [1,2,1,3,1,4,1,5] number.remove(number[1]) number[1]="sky" number[3]="star" print(number) num = [1,2,3] num.extend([4,"k",8]) num[1] = 5 print(num) loc1 = num.index(1) print(loc1) number.pop() print(number) number.pop(1) print(number) dir(list)
9579ff167d38ede721ad4a9526fc140406285322
ramonvoges/wordcloud
/goethecloud.py
1,005
3.8125
4
"""A short script to create wordclouds from a given text and with a """ from PIL import Image from wordcloud import WordCloud # import wordcloud # from nltk.corpus import stopwords from stop_words import get_stop_words import random import numpy as np import matplotlib.pyplot as plt with open("Goethe_Sammler.t...
47626d69623bdd02a17afa26135ba68fd9d59ad3
deilsonamaral1/checkerboard-turtle
/checkerboard.py
2,748
3.890625
4
# Checkerboard by Deilson Amaral and Amanda Tavares import turtle as t t.penup() # Set position to better draw the Checkerboard t.setpos(-258,-258) t.pendown() t.speed(0) square_len = 66 pattern1_distance = -7 pattern2_distance = -9 square_num = 8 # The black squares with space to draw other def square(): t.colo...
d5c87c28e1f6505f198d33629b1049f254df8857
dilawarm/crypto-tools
/vigenere-cipher.py
791
4
4
import string import operator ALPHABET = string.ascii_uppercase + "ÆØÅ" def vigenere(plaintext, key, algo): op = operator.add if algo.lower() == "encrypt" else operator.sub return "".join( ALPHABET[ ( op( ALPHABET.index(plaintext[i].upper()), ...
bf6f04f7153f61fa4b46fc99f71116374d9230d4
AgustinParmisano/tecnicatura_analisis_sistemas
/trabajos_entregas/parcial/mariano/and_or_OP.py
993
3.859375
4
#1) #a)Realice una funcion que dado los numeros pasados por parametro retorne si A=1 y B=1 Res=1, Res=0 en cualquier otro caso. A = input("Ingrese un numero: ") B = input("Ingrese otro numero: ") def andfun(A,B): if A == 1 and B == 1: return 1 else: return 0 print(andfun(A,B)) #b)Realice una funcion que simul...
7bc36647921f253c1ed133c6593de0c35104d261
AgustinParmisano/tecnicatura_analisis_sistemas
/ingreso/maxmin.py
592
4.3125
4
#!/usr/bin/python # coding=utf-8 ''' Realizar un programa que lea dos números enteros desde teclado e informe en pantalla cuál de los dos números es el mayor. Si son iguales debe informar en pantalla lo siguiente: “Los números leídos son iguales”. ''' num1 = int(raw_input('Ingrese un número: ')) num2 ...
0d354df29e4cb1c53cb6e2c5f5dbe2237bd3b179
AgustinParmisano/tecnicatura_analisis_sistemas
/programacion1/practica4/practicaruben.py
565
3.640625
4
#!/usr/bin/python cuenta = {} p1 = raw_input ("ingrese su nombre: ") p2 = raw_input ("ingrese su apellido: ") p3 = input ("ingrese su dni: ") p4 = (p1 + p2) len (p4) clave = (len(p4)*p3) cuenta = {"nombre":p1,"apellido":p2,"dni":p3,"clave":(clave)} print (cuenta) key = raw_input ("ingrese campo que quiere modificar: ...
57e9dfdc906e74b737efbe5372dbf0dc2b2d5dcf
AgustinParmisano/tecnicatura_analisis_sistemas
/programacion1/practica3/examples/while_example_dict.py
459
3.90625
4
#while con diccionarios salir = False lista_personas = [] while not salir: persona = {} persona["nombre"] = raw_input("Ingrese nombre: ") persona["apellido"] = raw_input("Ingrese apellido: ") persona["edad"] = input("Ingrese nombre: ") lista_personas.append(persona) print("Persona Agregada") ...
79a66e49efd1a09bbab6be1c2762e67536c3316e
AgustinParmisano/tecnicatura_analisis_sistemas
/programacion1/practica2/pract2_punt2_B.py
121
3.9375
4
#!/usr/bin/python char = raw_input("Ingrese un caracter: ") if char == "A": print("65") if char == "a": print("91")
c3d0f6d7b3313771078a67651c4bf0502b8bbe77
cpe202spring2019/lab1-eddiekaung
/lab1_test_cases.py
8,505
3.578125
4
import unittest from lab1 import * # A few test cases. Add more!!! class TestLab1(unittest.TestCase): def test_max_list_iter_none(self): """test case for when int_list in None""" tlist = None with self.assertRaises(ValueError): # used to check for exception max_list_iter(tli...
cb98d945347ea48f38f8aca0eba2629615b09cb8
ShenYuCN/WorkspacePython
/common/time/time_clock.py
436
3.65625
4
import time import random originalTime = time.time() # temp = originalTime + 30 * 60 + random.randint(1,10*60) # temp = originalTime + 10 * index + random.randint(5,10) temp = originalTime + random.randint(5,10) print('temp:',int(temp),'originalTime:',int(originalTime)) while True: if time.time() > temp: print(...
ba9f1fd6c7c56f7673b760b605b0fc17d14e0556
mylgcs/python
/训练营day02/01_函数.py
851
4.15625
4
# 将一个常用的功能封装为一个单独的代码片段,用一个单词来表示,通过这个单词,只需极简结的代码,即可实现这个功能, # 这样的代码片段,称为"函数"! # 比如print 和 input就是函数 # 函数 def print_poetry(): print("春眠不觉晓,处处蚊子咬,夜来嗡嗡声,叮的包不少。") # 函数调用 print_poetry() # 函数的参数与返回值 # 通过参数将数据传递给函数,通过返回值将运算的结果回传 def add(a, b): return a + b # 运算结果可以赋值给另一个变量,也可以直接使用 c = add(1, 2) print(c) # 调用函数的...
5159bf2cc3aa09a0c788414dd11d11a86323e415
pansilup/demo-on-homomorphic-encryption
/3DGHV_FHE_add_mul_comp.py
7,936
3.9375
4
# -*- coding: utf-8 -*- """ ---------------------------------------------------------- Program : Demonstrates DGHV fully homomorphic encryption scheme and examples for Addition, Subtraction, Multiplication & Comparison Author : Pansilu Pitigalaarachchi Created : on Mon Sep 14 11:54:36 2020 Based...
1ccb06e849cbfddb4d6b6944c5ced71f63c927f9
ravikailash/CtCI-6th-Edition-Python
/Chapter16/6_Smallest_Difference.py
1,524
4.03125
4
''' Exercise: 16.6 Smallest Difference Find the pair with the least difference (one from each array) Example: Input : [1, 3, 15, 11, 2], [23, 127, 235, 19, 8] Output: 3, (11, 8) ''' import sys # Function to sort the arrays in O(nlog(n)) def merge_sort(arr): # function to create the partitions def make_partition(a...
312a2e85b4ccda00f60582c622cef45399f840ff
aayushidwivedi01/puzzles-uninformed-search
/test_hw2.py
4,160
3.59375
4
import homework2 as hw # this imports our code in example.py, assuming it is in the same directory import unittest class TestProblem1(unittest.TestCase): def test_num_placements_all(self): print "PROD:{}".format(hw.num_placements_all(3)) def test_num_placements_one_per_row(self): self.assert...
df7821e9150c8313a38474711a7219b5e62817b0
chibby0ne/data_science_book
/statistics.py
6,056
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import Counter from matplotlib import pyplot as plt from linear_algebra import sum_of_squares, dot import math num_friends = [100, 49, 41, 40, 25 ] daily_minutes = [20, 10, 5, 4, 15 ] friend_counts = Counter(num_friends) xs = range(101) ys = [friend_co...
eeb00931ba248bbd9bf559f1d9b00182afbb0667
FraugDib/algorithms
/money_change.py
4,602
4.1875
4
import time def find_change(results, current_decomposition, n, denominations): """Find changes Arguments results -- accumulate result in an array. Each item is also an array current_decomposition -- decomposition of n in denominations n -- numbe...
71e3cde9c72a32fbe851556cd631bf4197683cec
hellosheng1989/Tree-Regression-etc
/decision boundary plot learning.py
1,399
3.640625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 20:41:46 2015 @author: SSL """ # # Example code that shows how to plot the function value and a decision # boundary for a simple logistic regression model using python # # Author: Nathan Jacobs (with some initial code by Hampton Young) # import numpy as...
b4a12f6745de0c32fcbcccaef64c8417b1c8db50
Limmen/Distributed_ML
/lab2/fashon_mnist_tf/task2/task2.py
8,610
3.734375
4
# Task 2 - Feed-Forward NN with 4 layers # 1. See results in stats.txt, A bit more overfitting in this task since the model is more powerful. # We got better accuracy with ReLU, they had about the same overfitting but ReLU was just higher accuracy overall. # 2. ReLU gives faster convergence than sigmoid. # Reasons: sig...
eddbfcdcac00ce56bd2b01f0b860544ce2ebfe8b
jhonCenaDito/ML
/distance.py
485
3.734375
4
import numpy as np size1 = int(input("Size of first array:")) a = np.empty(size1) for i in range(len(a)): x = float(input("Element:")) a[i]=x print(np.floor(a)) size2 = int(input("Size of second array:")) b = np.empty(size2) for i in range(len(b)): x = float(input("Element:")) b[i]=x print(np.floor...
dc78fb5c530654bfe6b5bf2c81618e681ba98135
richjeet/restaurant
/ScatterPlot.py
778
3.71875
4
# SCATTER PLOT # Import the necessary modules import pandas as pd import matplotlib.pyplot as plt plt.style.use('seaborn') # Initialize the lists for X and Y sp = pd.read_csv('ScatterPlot.csv') print(sp.head()) Food= sp['MonthlyExpenseFood'] Grocery= sp['MonthlyExpenseGrocery'] ratio = sp['Ratio'] # Plot the data usi...
de62d877172215f9cbb0b30b24e8009b3485bf47
cpkoywk/IST664_Natural_Language_Processing
/Lab 1/assignment1.py
1,148
4.21875
4
''' Steps: get the text with nltk.corpus.gutenberg.raw() get the tokens with nltk.word_tokenize() get the words by using w.lower() to lowercase the tokens make the frequency distribution with FreqDist get the 30 top frequency words with most_common(30) and print the word, frequency pairs ''' #Import required modules im...
3dc68ef09e9d9603205971449f3c33aa0ccadb8b
HarshadMahajan/Python
/ImpPrograms/JumpCheck.py
570
3.84375
4
def checkJump(list2): list3=[] jump=0 for i in range(0,len(list2)): if list2[i]==0: list3.append(i) print(list3) for j in range(0,len(list3)-1): if list3[j+1]-list3[j]==1: print("here") pass else: print("there") ...
d15ec60b357e0fa12ca61ab6de77dd4e47b39af5
HarshadMahajan/Python
/challange-Coderbyte/map-and-lambda-expression/map-and-lambda-expression.py
237
3.625
4
#!/usr/bin/env python N = int(raw_input()) if N == 0: fibs = [] elif N == 1: fibs = [0] else: fibs = [0, 1] while N > len(fibs): fibs.append(fibs[-1] + fibs[-2]) assert len(fibs) == N print map(lambda x: x**3, fibs)
f6b1e488b4e9ffe777ebf095f8b0f6f971a46869
HarshadMahajan/Python
/Data Types/1-python-lists.py
644
4.09375
4
#!/usr/bin/python t = int(raw_input()) nums = [] for i in range(0, t): orgs = raw_input().split(' ') if orgs[0] == "insert": nums.insert(int(orgs[1]), int(orgs[2])) elif orgs[0] == "append": nums.append(int(orgs[1])) elif orgs[0] == "remove": nums.remove(int(orgs[1])) elif...
e6d41b36bad86757c9ddf5f06950d5d85d284580
HarshadMahajan/Python
/challange-Coderbyte/find-angle/find-angle.py
211
3.8125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import division import math ab = int(raw_input()) bc = int(raw_input()) c = math.degrees(math.atan(ab / bc)) c = int(round(c)) print str(c) + '°'
75878426bcd9e85977798a77469e77306fe37543
HarshadMahajan/Python
/Classes/2-class-2-find-the-torsional-angle.py
1,016
3.609375
4
import math class Points(): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __sub__(self, O): x = self.x - O.x y = self.y - O.y z = self.z - O.z return Points(x, y, z) def dot(self, O): x = self.x * O.x y = self....
2b41cfa7994ec770f4f9fcb3a0bcf1cf989eda61
HarshadMahajan/Python
/challange-Coderbyte/validate-list-of-email-address-with-filter/validate-list-of-email-address-with-filter.py
344
3.78125
4
#!/usr/bin/env python import re def isValidAddress(address): result = re.match(r'[a-zA-z0-9\-_]+@[a-zA-Z0-9]+\..{1,3}$', address) return True if result else False N = int(raw_input()) addresses = [] for i in range(N): addresses.append(raw_input()) addresses = filter(isValidAddress, addresses) addresses...
c1560c6661b5e85e379782cc32e4a02df3886530
HarshadMahajan/Python
/Regex and Parsing/9-validating-named-email-addresses.py
240
3.84375
4
import re EMAIL_REGEX = re.compile(r'^[a-zA-Z]{1}[\w\-\.]+@[a-zA-Z]+\.[a-zA-Z]{1,3}$') for _ in range(int(raw_input())): name, email = raw_input().strip().split() if (re.match(EMAIL_REGEX, email[1:-1])): print name, email
9690a88dd1eef02c7e87d615b303e9910a2c3e66
Mukul-Singh-github/Python-Programs-Games-
/BlackJack.py
4,787
3.953125
4
#This is Black Jack Game #HOW TO PLAY THE GAME #There is a dealer and a player they will both have two random cards from the deck of 52 #the player's always plays first. #the goal is to have total value of our cards close to 21 aur 21. #if player's total of two card is suppose 15 player can say hit and he/she will be...
15a79024657a7564d79b63195c64e1b75e56f5b7
niall-oc/things
/codility/fish.py
4,904
3.78125
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/ You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are number...
1a50b33e46332742fb6a5beb00dee504f4560a8f
niall-oc/things
/puzzles/grid8/grid8.py
3,303
4.09375
4
""" ### FILL IN THE GRID PUZZLE Objective: Arange the numbers 1 through 8 in the grid below. +---+---+ | | | +---+---+---+---+ | | | | | +---+---+---+---+ | | | +---+---+ RULES: No consecutive numbers may appear next to each other either vertically, hor...
eb9d5ad1a3bb38c87c64f435c2eabd429405ddc3
niall-oc/things
/codility/odd_occurrences_in_array.py
2,360
4.28125
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the sam...
57994eee0033581a355200e38514b5504652fca3
niall-oc/things
/codility/max_double_slice_sum.py
2,808
4.03125
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ A non-empty array A consisting of N integers is given. A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice. The sum of double slice (X, Y, Z) is the...
203ae511e881868303be870501531fb41c688fea
niall-oc/things
/codility/dis_analysis.py
840
4.125
4
def factorial(n): # recursive if not n: return 1 else: return n * factorial(n-1) def factorial_for(n): if not n: return 1 else: r = 1 for i in range(1, n+1): r = i*r return r def factorial_while(n): if not n: return 1 else...
a523273dc9d1ad99757b69d934be11c74f4dd009
niall-oc/things
/codility/stone_wall.py
2,995
3.828125
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. ...
db239ae5d7cc670f71e8af8d99bc441f4af2503a
niall-oc/things
/puzzles/movies/movies.py
2,571
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Given the following list in a string seperated by \n characters. Jaws (1975) Starwars 1977 2001 A Space Odyssey ( 1968 ) Back to the future 1985. Raiders of the lost ark 1981 . jurassic park 1993 The Matrix 1999 A fist full of Dollars 10,...
e6ea4c49d3012708cededb29a1f79f575561c82f
niall-oc/things
/codility/frog_jmp.py
2,058
4.15625
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a f...
c19bf205d5b5c6727b416e0eb658a7e6c6336f74
niall-oc/things
/codility/frog_river_one.py
3,224
4.09375
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/ A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Lea...
74c545021bb4322872287accaf68765b46d44c8f
zsediqyar/CIS61
/COVID19-weeks/lab_9.py
1,955
3.9375
4
# IMPORTED FUNCTIONS AND CLASSES # for question two class Link: empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest # for question three class Tree: def __init__(self, entry, child=[]): ...
575320ec01e71aeb6179a71f2fe231e83e1cb3fa
zsediqyar/CIS61
/week_2/lab_2.py
1,656
4.0625
4
from operator import add, sub # QUESTION 1 def both_positive(x, y): return x > 0 and y > 0 print(both_positive(1, 6)) # QUESTION 2 def a_plus_abs_b(a, b): if b < 0: f = sub else: f = add return f(a, b) print(a_plus_abs_b(1, -5)) # QUESTION 3 def two_of_three(a, b, c): return...
e95be775f63568c96ab74027cc5128e40a2ecb4a
junaidnz97/Competitive-Programming
/SPOJ/GCD2 - GCD2.py
237
3.703125
4
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) test=int(input()) for i in range(0,test): inp=input() inp=inp.split() a=int(inp[0]) b=int(inp[1]) c=gcd(a,b) print(c)
7d8dbd2a9a0f07a80037438ff3bfd84d4bac0fb9
jason870518/JerryHW
/0326/sources/calculator.py
217
3.890625
4
def calculator(x ,y , operator): if(operator=='+'): return (x + y) if(operator=='-'): return (x - y) if(operator=='*'): return (x * y) if(operator=='/'): return (x / y)
c956a8bade22ace7bbd5dbdcb1d99ceeb81df9c2
turab45/Travel-Python-to-Ml-Bootcamp
/Day 1/prime-in-range.py
332
3.71875
4
# Author: Muhammad Turab factor = 0 for i in range(0, 100): if (i == 1): continue factor = 1 for j in range(2, i // 2 + 1): if (i % j == 0): factor = 0 break # factor = 1 means i is prime # and factor = 0 means i is not prime if (factor == 1): ...
782ec079574fb356dc83ca93db09cd62cd33356c
turab45/Travel-Python-to-Ml-Bootcamp
/Day 2/Q1.py
293
3.953125
4
# Author : Muhammad Turab def add_into_list(number, list): list_len = len(list) for i in range(list_len): list[i] = list[i] + number return list list1 = [1, 2, 3, 12, 19, 2] print("Before adding 3: ", list1) list1 = add_into_list(3, list1) print("After adding 3: ", list1)
e7cc7acf58fb03f5052a257eb4211f44f9ebe8e0
hoangtunglamm/hoangtunglam-session3-c4e13
/list/testtiep.py
352
3.75
4
menu = ['com ga', "com rang", "banh trang","nem"] for index, item in enumerate(menu): #emumerate la liet ke print(index + 1,". ", item,sep="") a = int(input("vi tri chu muon thay doi: ")) b = input("sua thanh? ") index = a - 1 menu[index] = b for index, item in enumerate(menu): #emumerate la liet ke pri...
5e636ab79bdcbef2f6ffdc5e51868ba3ea9e5286
hoangtunglamm/hoangtunglam-session3-c4e13
/homework/shop.py
836
4.03125
4
menu = ['T-Shirt', 'Sweater'] while True: YourAnswer = input("Welcome to our shop,what do you want (C,R,U,D)? ") if YourAnswer.upper() == 'C': MyAdd = input("Enter New Item: ") menu.append(MyAdd) print("Our Item",end = ":",sep = "") print(*menu,sep=",") elif YourAnswer.upper...
6d9f114137d797356159757b9fbe33d3205f9860
ababaug/AUGUSTINE-ABAH-CIPHER
/cipher.py
1,705
3.765625
4
import unicodedata # coding: utf-8 def cipher(lineNumber): alpha_dict = {} with open("files/input.txt", "r") as instr: line = instr.readlines()[lineNumber] r_line = line.rstrip() # removes space beneath instr_list = r_line.split(":") count = int(instr_list[0]) enc_dec = ...
a1aeb5483a52e6fd8d49394a428ab11fea0cf483
LiZimo/gensearch_wknockoff
/gen_search2/gen_search.py
10,648
3.65625
4
#!/usr/bin/env python ''' Search for patterns using the learn/predict functions provided by scikit-learn library. There are 3 files involved in every run: 1) A csv input file, which has samples as rows, and variables as columns. 2) A csv labels files, has the same samples as in the input file and, the class (0/1) ...
daa741e39e9e1b51c0c08a4cb97ad51e97b29aab
SarthakGirotra/Chess_python
/chess/game.py
2,087
3.59375
4
import pygame from .board import Board from .constants import WHITE, BLACK, BLUE, SQUARE_SIZE class Game: def __init__(self, win): self.win = win self._init() def _init(self): self.board = Board(self.win) self.turn = WHITE self.valid_moves = [] self.selected = ...
fdec6fee3a57a11783c40eafcb9125b11e174f51
Anshu-Singh1998/python-tutorial
/fourty.py
289
4.28125
4
# let us c # Write a function to calculate the factorial value of any integer enyered # through the keyboard. def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = int(input("Input a number to compute the factorial : ")) print(factorial(n))
85e5854450a443a1ee79a1364a98a27c24516681
Anshu-Singh1998/python-tutorial
/seven.py
488
3.8125
4
# let us c # Input cost price and sales price of an item through keyboard. # wap to determine whether the seller made profit or loss # and also determine profit or loss he made. cp = int(input("Enter cost price:")) sp = int(input("Enter selling price:")) loss = 0 profit = 0 if cp > sp: loss = cp - sp print("bus...
5ca65e5362eca7bf9cfeda1021564e6c20ccb4a5
Anshu-Singh1998/python-tutorial
/eight.py
228
4.25
4
# let us c # input a integer through keyboard and find out whether it is even or odd. a = int(input("Enter a number to find out even or odd:")) if a % 2 == 0: print("the number is even") else: print("the number is odd")
4516d98fd3db1d9c9049bb6cb3d1fe18e9e7914b
Anshu-Singh1998/python-tutorial
/nineteen.py
268
4.15625
4
# From internet # Write a program to remove an element from an existing array. from array import * num = list("i", [4, 7, 2, 0, 8, 6]) print("This is the list before it was removed:"+str(num)) print("Lets remove it") num.remove(2) print("Removing performed:"+str(num))
edf8f4a595688a90b7b816a09cfaf75a73cb621e
Anshu-Singh1998/python-tutorial
/second.py
388
3.9375
4
# let us c # Input a distance through keyboard where distance between two cities are (in km) . # convert and print this distance # in meters , feet, inches and centimeters. kilometers = int(input("Enter a distance:")) meter = kilometers*1000 feet = kilometers*3280.84 centimeter = kilometers*100000 inch = kilometers*...
72dcbbca43b43701f50195a9767c6de6a20bda8b
wcphkust/sling
/python/avl_insert.py
3,025
3.515625
4
import random import pprint class node: def __init__(self, key = 0, height = 0, left = None, right = None): self.key = key self.height = height self.left = left self.right = right ################## # accessory func # ################## def get_height(x): if x is None: return -1 else: return x.height ...