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 |
|---|---|---|---|---|---|---|
11c57367b1f26d98d8ccab7ab1fc44fedfe7ca42 | IceMints/Python | /blackrock_ctf_07/Fishing.py | 1,503 | 4.25 | 4 | # Python3 Program to find
# best buying and selling days
# This function finds the buy sell
# schedule for maximum profit
def max_profit(price, fee):
profit = 0
n = len(price)
# Prices must be given for at least two days
if (n == 1):
return
# Traverse through given price array
... |
9e78c589ae150f49d8d743ffabe3acfa3b85674a | smallflyingpig/leetcode | /the_sward_to_offer/29.py | 1,046 | 3.546875 | 4 | """
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
input1: [[1,2],[3,4]]
output1: [1,2,4,3]
"""
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
... |
8bbbe27826bc90773247fa63aa779423a92b00ad | smallflyingpig/leetcode | /the_sward_to_offer/41.2.py | 2,064 | 3.75 | 4 | # -*- coding:utf-8 -*-
"""
字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
后台会用以下方式调用Insert 和 FirstAppearingOnce 函数
string caseout = "";
1.读入测试用例字符串casein
2.如果对应语言有Init()函数的话,执行Init() 函数
3.循环遍历字符串里的每一个字符ch {
Insert(ch);
caseout += FirstAppearin... |
5b8a511d1b41dbecda8f5349c3a3fba7ae96ced2 | smallflyingpig/leetcode | /the_sward_to_offer/41.1.py | 2,279 | 4 | 4 | # -*- coding:utf-8 -*-
"""
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
"""
import heapq
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, va... |
5318a53949d7cf0e5c395602ac52d225b64f572d | GeoffBreemer/DLToolkit | /dltoolkit/preprocess/resize.py | 995 | 3.984375 | 4 | """Resize an image to a new height, width and interpolation method"""
import cv2
class ResizePreprocessor:
"""Resize an image to a new height, width and interpolation method
Attributes:
width: new width of the image
height: new height of the image
interp: resize interpolation method
... |
fbf0437b8e91ebb09b1b51296170487289735c66 | GeoffBreemer/DLToolkit | /dltoolkit/preprocess/resizewithaspectratio.py | 1,581 | 3.890625 | 4 | """Resize an image while maintaining its aspect ratio, cropping the image if/when required
Code is based on the excellent book "Deep Learning for Computer Vision" by PyImageSearch available on:
https://www.pyimagesearch.com/deep-learning-computer-vision-python-book/
"""
import cv2
import imutils
class ResizeWithAspe... |
9da1e536d9a360a4ced7217b0b8a338a7d2b2b25 | DivyaraniPhondekar/TrainingAssignments- | /Python/Assign5/Image.py | 787 | 3.71875 | 4 | from PIL import Image
size = 100, 100
class main():
while(1):
x=input("Plase Enter operation no. you want to execute: 1. RESIZE THE IMAGE 2. THUMBNAIL OF IMAGE 3.EXIT \n")
if x == 1:
try:
im = Image.open('panda.jpg')
im = im.resize(size, Image.ANTIALIAS)... |
0a9583f1a597607cbb0d764815bbc0444507b8b4 | Zhen001/Big-Data-Management-and-Analysis | /HDFS & MapReduce/WDreducer1.py | 1,500 | 3.8125 | 4 | #!/usr/bin/env python
'''
The script is for reducing phase
'''
import sys
current_word = word = None
current_count = line_count = word_count = unique_word = 0
words = []
# input comes from STDIN
for line in sys.stdin:
line = line.strip()
# parse the input we got from WDmapper.py
key, val = line.split('\t', 1)... |
dc9e8b7b79223b58c8f7c37728d86957306ed96e | JVuns/Driver-Log-Recorder---Final-Project | /New folder/New folder/Kvun/P04 NIM 02(2).py | 335 | 3.75 | 4 | input1 = int(input("Input N: "))
input2 = int(input("Input M: "))
matrix = []
input3 = str(input("Input string: "))
count = 0
for y in range(input1):
for i in range(input2):
a = []
a.append(input3[count::(input2)])
matrix.append(a)
count += 1
a = ""
for x in matrix:
for c in x:
... |
251caa642fd81d10abb2f3e7f8eeee6439325ffd | JVuns/Driver-Log-Recorder---Final-Project | /New folder/New folder/Kvun/P04 NIM 02.py | 244 | 3.921875 | 4 | input1 = str(input("Input the initial integer: "))
count = 0
while len(input1) != 1:
result = 1
for i in input1:
count += 1
result *= int(i)
input1 = str(result)
print (f"After {count} process: {result}")
|
245ab5b35314ca645807899f74f23c23d067a88b | cdacsanket1595/exam1 | /gcd.py | 95 | 3.890625 | 4 | a=(input("Enter no 1:-"))
b=(input("Enter no 2:-"))
if a > b:
print(a)
else:
print(b)
|
ca852b7e34604400fef625312f0d1c033dca39b0 | frankverrill/Py | /Test/cust_service_bot.py | 4,893 | 3.90625 | 4 | """ cust = customer/
selected = every function where there is an option to select/
"""
def cust_service_bot(): # Automated web customer support
print(
"The DNS Cable Company's Service Portal.",
"Are you a new or existing customer?",
"\n [1] New",
"\n [2] Existing")
selected = ... |
f938ced4e04b95f0d13048fcefe7c2e633edd2fc | bristy/HackYourself | /hackerearth/hacker_earth/college/practice/generate_prime.py | 603 | 3.65625 | 4 | # http://www.hackerearth.com/practice-contest-1-3/algorithm/generate-the-primes-2/
from sys import stdin
def getInt():
return map(int, stdin.readline().split())
# @param integer n
# list of primes below n
def sieve(n):
primes = list()
s = [True] * n
s[0] = s[1] = False
for i in xrange(2, n):
... |
a1514c507909bd3d00953f7a8c7dd09223779ead | VEGANATO/Organizing-Sales-Data-Code-Academy | /script.py | 651 | 4.53125 | 5 | # Len's Slice: I work at Len’s Slice, a new pizza joint in the neighborhood. I am going to use my knowledge of Python lists to organize some of the sales data.
print("Sales Data")
# To keep track of the kinds of pizzas sold, a list is created called toppings that holds different toppings.
toppings = ["pepperoni", "pine... |
f2c8fbab9bf7f8bc0e423d9a2b53896a95961b02 | AbhayF8/thinkpython.py | /1.py | 497 | 3.84375 | 4 | import turtle as t
def koch(t,n):
"""draws a koch curve with the given length n and t as turtle"""
if (n<3):
t.fd(n)
return n
else:
koch(t,n/3)
t.lt(60)
koch(t,n/3)
t.rt(120)
koch(t,n/3)
t.lt(60)
koch(t,n/3)
# to draw a snowflake with ... |
f21b2b2f20b59d677d6f2fbbed23ea46bd0ad713 | pharick/python-coursera | /week7/15-synonims.py | 160 | 3.640625 | 4 | n = int(input())
words = dict()
for _ in range(n):
word1, word2 = input().split()
words[word1] = word2
words[word2] = word1
print(words[input()])
|
c3fa671896b191e6f884c9e46fbe7361b5326dac | pharick/python-coursera | /week3/2-sum-of-row.py | 105 | 3.625 | 4 | n = int(input())
sum = 0
for i in range(1, n + 1):
sum += 1 / (i**2)
print("{0:.6f}".format(sum))
|
c05f73e0239c2ae34f6f9807765cc18635fa359e | pharick/python-coursera | /week7/9-polyglots.py | 431 | 3.703125 | 4 | n = int(input())
all_students = set()
one_student = set()
for i in range(n):
m = int(input())
student_langs = set()
for j in range(m):
student_langs.add(input())
if i == 0:
all_students = student_langs
else:
all_students &= student_langs
one_student |= student_langs
... |
d4d0831a7335cd636b06fa82f6eaf2bf6a02134d | pharick/python-coursera | /week2/45-max-near-equal.py | 276 | 3.578125 | 4 | n = int(input())
last = 0
if n != 0:
count = 1
else:
count = 0
max_count = count
while n != 0:
last = n
n = int(input())
if n == last:
count += 1
else:
count = 1
if count > max_count:
max_count = count
print(max_count)
|
fa097a4d517368a2cc341da7e94089ea82ec627e | pharick/python-coursera | /week4/14-gcd.py | 239 | 3.90625 | 4 | def gcd(a, b):
if a == 1 or b == 1:
return 1
if a == b:
return a
if a < b:
a, b = b, a
if a % b == 0:
return b
return gcd(b, a % b)
a = int(input())
b = int(input())
print(gcd(a, b))
|
23993e926a21e60e5527f7b11f2d8e718e44574d | pharick/python-coursera | /week2/14-even-odd.py | 228 | 3.796875 | 4 | a = int(input())
b = int(input())
c = int(input())
is_one_even = a % 2 == 0 or b % 2 == 0 or c % 2 == 0
is_one_odd = a % 2 == 1 or b % 2 == 1 or c % 2 == 1
if is_one_even and is_one_odd:
print("YES")
else:
print("NO")
|
7e2eb3ac9b86b13729fed53e427e0b5edab2b4ef | pharick/python-coursera | /week3/15-first-and-last.py | 179 | 3.65625 | 4 | string = input()
o1 = string.find("f")
o2 = string[::-1].find("f")
if o2 != -1:
o2 = len(string) - o2 - 1
if o2 == o1:
print(o1)
else:
print(o1, o2)
|
8a7d269f016f4d4511b3170780220892909b84e1 | pharick/python-coursera | /week7/7-guess-number.py | 288 | 3.71875 | 4 | n = int(input())
numbers = set(range(1, n + 1))
line = input()
while line != "HELP":
question = set(map(int, line.split()))
answer = input()
if answer == "YES":
numbers &= question
else:
numbers -= question
line = input()
print(*sorted(numbers))
|
f61e08ab356df988fdff02fd02f40935d059eabb | pharick/python-coursera | /week2/18-boxes.py | 1,473 | 3.5625 | 4 | a1 = int(input())
b1 = int(input())
c1 = int(input())
a2 = int(input())
b2 = int(input())
c2 = int(input())
case1 = (a1 == a2) and (b1 == b2) and (c1 == c2)
case2 = (a1 == b2) and (b1 == a2) and (c1 == c2)
case3 = (a1 == b2) and (b1 == c2) and (c1 == a2)
case4 = (a1 == a2) and (b1 == c2) and (c1 == b2)
case5 = (a1 == ... |
d46dd99e9bdbbabb35b9ea77ace0f6cc280ccc2a | pharick/python-coursera | /week2/7-chessboard.py | 357 | 3.8125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x_diff = x1 - x2
if x_diff < 0:
x_diff = x2 - x1
y_diff = y1 - y2
if y_diff < 0:
y_diff = y2 - y1
if x_diff % 2 == 0:
if y_diff % 2 == 0:
print("YES")
else:
print("NO")
else:
if y_diff % 2 == 0:
print(... |
dfd3b1f1adfba41eb01831fc03f550c4bb826f43 | pharick/python-coursera | /week7/12-phone-numbers.py | 458 | 3.9375 | 4 | def unify_number(number):
result = ""
for s in number:
if s != "(" and s != ")" and s != "-" and s != "+":
result += s
if len(result) == 7:
result = "8495" + result
elif result[0] == "7":
result = "8" + result[1:]
return result
new_number = unify_number(input(... |
03b4ce541905902ed5e04e0634319e05b91a805e | cohadar/learn-python-the-hard-way | /ex35.py | 1,550 | 3.84375 | 4 | import sys
def gold_room():
print "this room is full of gold, how much do you take?"
choice = raw_input('> ')
try:
how_much = int(choice)
except ValueError:
dead('learn to type a number')
if how_much < 50:
print "Nice, you are not greedy, you win"
sys.exit(0)
else:
dead("You greedy bastard")
def be... |
3678c826c8c66c2acfa14d167753cd1905a5a048 | LokIIE/AdventOfCode2020 | /Day3/firstStar.py | 288 | 3.515625 | 4 | inputFile = open("input.txt", "r")
grid = []
currColumn = 0
countTrees = 0
for line in inputFile:
if line[currColumn] == "#":
countTrees += 1
currColumn += 3
if currColumn >= (len(line) - 1):
currColumn = currColumn % (len(line) - 1)
print(countTrees) |
0f71ebbafc60d8f6974949e63fccbfc22ac011b3 | asirvex/andela-interview | /password_checker.py | 1,305 | 4 | 4 | from string import ascii_uppercase, ascii_lowercase, digits
passwords = list(input("Enter comma separated passwords: ").split(","))
def min_length(password):
return len(password) >= 6
def max_length(password):
return len(password) <= 12
def has_lower(password):
lower_count = 0
for letter in password:... |
b23339a3e5ef9ad71ba9b7cbf064fe1f262ae40b | altruistically-minded/euler | /problem_003/problem009.py | 2,541 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
=================================================================
Sieve of Eratosthenes
=================================================================
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.... |
d3315de4b268377b31cf00542f69fb9f8ea1190d | AlanSobenes/for_loop_basic1 | /for_loop_basic1.py | 576 | 3.609375 | 4 | # 1. Basic
for x in range(150):
print(x)
# 2. Multiples of Five
for x in range(5, 1000, 5):
print(x)
# 3. Counting the Dojo way
for x in range(1, 101):
if x % 10 == 0:
x = "Coding Dojo"
elif x % 5 == 0:
x = "Coding"
print(x)
# 4. Whoa. That sucker's Huge
sum = 0
for x in ran... |
1a8262e906cafab214943997574fa2106db0abdf | HenryAcevedo/canvas-scripts | /scripts/get-course-comments.py | 1,651 | 3.53125 | 4 | #
# Henry Acevedo
#
# Purpose: Get Comments from assignments for a course
import csv
from canvasapi import Canvas
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
MYURL = config.get('instance', 'test')
MYTOKEN = config.get('auth', 'token')
canvas = Canvas(MYURL, MYTOKEN)
def ... |
53aa99bf40211591483a7abce633ab307626820f | pveiga-abreu/design-patterns | /State/classes/desconto.py | 2,008 | 3.578125 | 4 | from abc import ABCMeta, abstractmethod
class Estado_Orcamento(object):
__metaclass__ = ABCMeta
@abstractmethod
def aplica_desconto(self, orcamento): pass
@abstractmethod
def aprova(self, orcamento): pass
@abstractmethod
def reprova(self, orcamento): pass
@abstractmethod
de... |
6d03e7955cb8adfb46904b66c2ba00bfab127d99 | sofieditmer/deep_learning | /src/lr-got.py | 12,832 | 3.796875 | 4 | #!/usr/bin/env python
"""
Info: This script creates a baseline logistic regression model and trains it on the dialogue of all Game of Thrones 8 seasons to predict which season a given line is from. This model can be used as a means of evaluating how a deep learning model performs.
Parameters:
(optional) input_fil... |
f75bd1438134ff227c897c69d72b3d002aeb7998 | t3miLo/web-caesar | /vigenere.py | 1,703 | 4 | 4 | from helpers import alphabet_position, rotate_character
def vigenere_encrypt(text, key):
checker = 'abcdefghijklmnopqrstuvwxyz'
key_number = []
new_message = ''
for each_letter in list(key):
key_number.append(alphabet_position(each_letter.lower()))
key = 0
for each_char in list(text... |
a82ebcde0450e32bd403f3f334e81976abec92b9 | brennomaia/CursoEmVideoPython | /ex007.py | 210 | 3.921875 | 4 | nota1 = float(input('Digite o valor da nota 1: '))
nota2 = float(input('Digite o balor da nota 2: '))
media = (nota1+nota2)/2
print('A média entre {} e {} é igual a: {:.1f}'.format((nota1), (nota2), (media))) |
a4b6a01b3a542cccebc03ecdc5b90bbb4c56b3e5 | brennomaia/CursoEmVideoPython | /ex049.py | 321 | 4.03125 | 4 | #Exercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
# EXERCICIO COM BASE DA AULA 13
t = int(input('Digite o valor da tabuada: '))
for c in range(1, 11): ## Contar de 1 a 10
s = t * c
print('{} x {} = {}'.format(t, c, s)) |
4c4dcc03d10adde7510c0f9e1c252050b23cad92 | brennomaia/CursoEmVideoPython | /ex039.py | 724 | 4.15625 | 4 | from datetime import date
aNasc = int(input('Digite o ano de nascimento: '))
aAtual = date.today().year
idade = aAtual - aNasc
# Menores de idade
if idade < 18:
calc = 18-idade
print('Quem nasceu em {} tem {} anos em {}.\nAinda faltam {} anos para o alistamento militar!\nO alistamento será em {}.'.format(aNas... |
ef9497e554f2959e53ee6cc4b1438806cfc9b619 | brennomaia/CursoEmVideoPython | /ex046.py | 462 | 3.953125 | 4 | ## Exercício Python 048: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
soma = 0 ### Acomulador de soma
cont = 0 #### acomulador de contagem
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1 ### Contagem de numero divise... |
4b08e3c064c59408afaf5783e9a15d29e59426cc | brennomaia/CursoEmVideoPython | /ex014.py | 162 | 3.890625 | 4 | cel = float(input('Digite a temperatura em graus celsius:'))
convfah = ((cel*9/5)+32)
print('A conversão de {:.2f}°C é igual a {:.2f}°F'.format(cel, convfah)) |
c97f9a652604ecfda8fa6906940f66ef6ad7083f | RealDense/school | /fun/helloWorld.py | 200 | 3.671875 | 4 | import random
#name = raw_input("please type name: ")
#if(name =="Camille"):
# print ("Camille is the freakin best!")
#else:
# print ("hello World")
num1 = random.randint(1,10)
print(num1)
|
b0f9cb6596d4f841f133ba1ec06378f536569eb1 | RealDense/school | /6600_IntelligentSystems/hw1/logical_perceptrons.py | 4,290 | 3.59375 | 4 | #!/usr/bin/python
####################################################
# CS 5600/6600/7890: Assignment 1: Problems 1 & 2
# Riley Densley
# A01227345
#####################################################
import numpy as np
import math
class and_perceptron:
def __init__(self):
# your code here
sel... |
4e7a0bda2e931e40f9f012cb524c295f44beeca5 | ouril/python-Homework | /ykxb.py | 878 | 3.78125 | 4 | # функция считывает строку и решает уравнение заданного вида
exp = input("Введите уравнение в виде y = kx + b, где k и b - числа:\n")
x = float(input("Введите x:\n"))
k = ''
b = ''
kcount = 0
# цикл читает выражение и находит k и b
for i in exp:
# пропускаем у = , пробелы и +
if i == 'y' or i == '=' or i == '... |
4f354744baf727b45cea6383918aa4cc0ac20c3e | danielmedinam03/Diplomado-Python2021 | /EjerciciosVarios/MenuFunciones.py | 10,437 | 3.8125 | 4 | i = 0
uLiquido = 0
volumenFinal=0
indice=0
def operacion(numero1, numero2, opcion):
if opcion == 1:
resultado = numero1+numero2
print("resultado: ", resultado)
elif opcion == 2:
resultado = numero1-numero2
print("resultado: ", resultado)
elif opcion == 3:
if nume... |
fbe096ded2a9ff3e5aab6aea8cb0bda8b85ee4a9 | zitaxcy/pythoncoursera | /6.3.py | 123 | 3.625 | 4 | def CT(strings,characters)
count = 0
for character in strings:
if character = characters:
count = count + 1
return count |
15a7a744d88f9c4a79360b3fa80daeb92a8e3131 | 0xred/DeleteDuplicate | /SimpleDuplicate.py | 1,132 | 4 | 4 | import os
###########################################
# function to remove duplicate emails
def remove_duplicate():
# opens emails.txt in r mode as one long string and assigns to var
emails = open(iii, 'r').read()
# .split() removes excess whitespaces from str, return str as list
emails = emails.split()... |
a0aa4a59a44339f86763d469e59d695ff2d508e7 | raspoli/Self-Organized-Criticality-on-Spreading-of-Cooperative-Diseases | /Python Functions/network.py | 586 | 3.578125 | 4 | import networkx as nx
def make_adjmat_dict(List):
import numpy as np
AdjList = dict()
l1 = int(np.sqrt(len(List)))
j = 0
for neigh in (List):
neighbors = []
for i in List[neigh]:
neighbors.append(l1 * i[0] + i[1])
AdjList[j] = neighbors
j += 1
... |
f0e01d3a40149e29c69709346fb7ba673de0a4b5 | houpaul0817/AE401-2021s-paul | /test0925.py | 403 | 3.53125 | 4 | # from mcpi.minecraft import Minecraft
# import time
# mc = Minecraft.create()
# while 1+1==2:
# mc.setBlock(-236,77,238,46)
# time.sleep(0.1)
score = int(input("score: "))
if score >= 90:
print('Grade is: A')
elif score >= 80:
print('Grade is: B')
elif score >= 70:
print('Grade is: ... |
7df64998ce5965ba3fabcbd54cedc6751ca413c8 | gustavovalverde/intro-programming-nano | /Python/Work Session 5/Loop 4.py | 2,343 | 4.46875 | 4 | # We now would like to summarize this data and make it more visually
# appealing.
# We want to go through count_list and print a table that shows
# the number and its corresponding count.
# The output should look like this neatly formatted table:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
... |
a9bed93ff1f778a466167b06cbc8afa902dabf9e | gustavovalverde/intro-programming-nano | /Python/Problem Solving/Calc_age_on_date.py | 2,173 | 4.21875 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
daysOfMonths = [31, 28, 31, 30, 31, 30, 31... |
8dc56aa55548dc8396efee8198999e9cb2be735f | Isaac-Gathere/basic-calculator-python | /calc2.py | 3,321 | 3.65625 | 4 | from tkinter import*
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_Input.set(operator)
def ClrButton():
global operator
operator =""
text_Input.set("")
def equals():
global operator
total = str(eval... |
b44302339187c200fa0fd172cfd3a21988353133 | jrvc/reSkilling | /nn_implementation/nn1.py | 3,829 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
FROM SCRATCH
Build a 3-layer neural network with 1 input layer, 1 hidden layer and 1 output layer.
The number of nodes in the input layer is 2; the dimensionality of our data.
The number of nodes in the output layer is 2; the number of classes we have.
The number of nodes in th... |
1018f2da0c71c59aa9491bf5ab74ab734accb09d | adirickyk/course-python | /try_catch.py | 302 | 4.3125 | 4 | #create new exception
try:
Value = int(input("Type a number between 1 and 10 : "))
except ValueError:
print("You must type a number between 1 and 10")
else:
if(Value > 0) and (Value <= 10):
print("You typed value : ", Value)
else:
print("The value type is incorrect !")
|
9dda20b3902f6af459be06794b77330670b0fc4c | WalkingLight/Expert-System | /or_op.py | 2,657 | 3.6875 | 4 | import operator
import sys
class OrOp:
__data = []
__n = ['=', '<', '>']
__change = 1
def __init__(self, var_list):
for line in var_list:
if '|' in line or ('^' not in line and '+' not in line):
self.__data.append(line)
@staticmethod
def check_facts(char, ... |
17b0b49f8b26d7ddf8f5e7543df2b457494e985e | younga7/leap_year | /alex_young_hw2.py | 550 | 4.1875 | 4 | # CS362 HW2
# Alex Young
# 1/26/2021
# Run this file using python3 alex_young_hw2.py
# This program checks if a year is a leap year with error handling
c = 0
while c == 0:
try:
n = int (input('Enter year: '))
c = 1
except:
print ('Error, input is not valid, try again!')
if n % 4 == 0:
... |
25a6b266cbcad69bc8428e4af1773d658e5b8e39 | arielmirra/python-sandbox | /src/sandbx.py | 2,037 | 3.953125 | 4 | # you will need to install matplotlib (pip install matplotlib)
import matplotlib.pyplot as plt
data = [['a', 1, 1], ['b', 3, 2]]
for item in data:
plt.plot(item, 'ro-')
plt.show()
from graph import Graph
def plot_graph(graph):
"""
graph has:
- Vertex list
- Edge list
"""
# [[0, 1], [1, 2... |
5a812ff48b2fa61605d10ebc0538feb11906d4c4 | burrizozo/aoc2020 | /day6.sln.py | 778 | 3.5625 | 4 | file1 = open('day6.input.txt', 'r')
lines = file1.readlines()
def part1():
ans = 0
questionset = set()
for line in lines:
if line != "\n":
for question in line.rstrip():
questionset.add(question)
else:
ans += len(questionset)
questionset = set()
ans += len(questionset)
print(ans)
... |
7d4785c275e7b8786a52fa8ceb1673399da57ac4 | Patroon-tab/QOG | /Assistance_Files/Image_Resizing.py | 241 | 3.515625 | 4 | from PIL import Image, ImageTk
def resize(input,output,x,y):
img = Image.open(input)
img = img.resize((x, y))
img.save(output)
def main():
resize("pic.png", "pic2.png", 208, 183)
if __name__ == "__main__":
main()
|
8507c80a2044c46f0789317abad550d142deaa35 | toanqz/ktpm2013 | /triangle/test.py | 4,256 | 3.5625 | 4 | import unittest
import math
import triangle
class test(unittest.TestCase):
#test tam giac deu
def test_triangleDeu1(self):
self.assertEquals(triangle.detect_triangle(1.0, 1.0, 1.0), "Tam giac deu")
def test_triangleDeu2(self):
self.assertEquals(triangle.detect_triangle(2**32.0-1, 2... |
e09986bf28f9a3da5e9156b14da0e624914afbd7 | yellingviv/practice_makes_perfect | /are_they_close.py | 840 | 3.71875 | 4 | # challenge: https://gist.github.com/seemaullal/eab0853325b70aa41d211cdf7259ddc9
def check_similarity(word1, word2):
"""check if word1 and word2 are only one character different"""
similar = False
counter = 0
range_len = 0
if len(word1) - len(word2) not in (-1, 1, 0):
return similar
e... |
e8368e5d17e8682b1f8d59ab9466995584747627 | castacu0/codewars_db | /15_7kyu_Jaden Casing Strings.py | 1,069 | 4.21875 | 4 | from string import capwords
"""
Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you... |
e8467f6d82e44b3c9d21456ec71255cbd64a3909 | JGracia98/python_game | /python_game.py | 5,505 | 4 | 4 | ## This is based off of Happy Death Day.
## You have to try and solve you're own death and find out who killed you.
## Goodluck
## Scene
from textwrap import dedent
from sys import exit
class Scene(object):
def enter(self):
exit(1)
class Bedroom(Scene):
def enter(self):
print(dedent("""
... |
3e942eb151c8963b5a79e62b66c52ea98ae60fc0 | bayuwira/KNN-Classification-from-scratch | /KNeighborsClassifier.py | 1,117 | 3.5625 | 4 | import numpy as np
#compute the euclidean distance between two point of data'
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
class KNeighborsClassifier:
def __init__(self, num_neighbors=7):
self.num_neighbors = num_neighbors
def fit(self, X, y):
self.X_train = X
... |
bdcf5f38df876124dac89805f4ac6b695dca3d14 | jeffreyziegler/PythonClass-2015 | /Class3-ErrorTesting/ordinalTest.py | 851 | 3.765625 | 4 | import unittest
import lab3
class ordinalTest(unittest.TestCase):
def test_one(self): #run test to distinguish between 1st and 11th
self.assertEqual('11th',lab3.ordinal(11))
self.assertEqual('1st',lab3.ordinal(1))
def test_teens(self): #run test to check ordinals of teens
self.assertEqual('13th',lab3.ordi... |
eea36189021cd2a623499e0b66692b637ddc61db | jeffreyziegler/PythonClass-2015 | /Class6-SortSearch/hw4/JZhw4.py | 609 | 4.03125 | 4 | # insertion sort
def insertion_sort(item_list):
for i in range(1, len(item_list)):
k = item_list[i]
j = i - 1
while (j >= 0) and (item_list[j] > k):
item_list[j+1] = item_list[j]
j = j - 1
item_list[j+1] = k
return insertion_sort
# selection sort
def selection_sort(item_list):
for spot in range(len... |
9940f02410122ddc6d0a9394479576fa0fb1a4fb | marizmelo/udacity | /CS262/lesson3/mapdef.py | 267 | 4.125 | 4 | def mysquare(x): return x * x
print map( mysquare, [1, 2, 3, 4, 5])
print map( lambda(x): x * x, [1, 2, 3, 4, 5]) # this use of lambda is sometimes called anonymous function
print [len(x) for x in ["hello", "my", "friends"]]
print [x * x for x in [1, 2, 3, 4, 5]] |
c287b5f834c313060f4ad2004de99619a66b123a | marizmelo/udacity | /CS262/lesson3/small_words.py | 157 | 4.1875 | 4 | def small_words(words):
for word in words:
if len(word) <= 3:
yield word
print [w for w in small_words(["The", "quick", "brown", "fox"])]
|
37857877fae4554279f5fe54ba39cbacc9d8e7a7 | jatingandhi32/Analysis-and-Design-of-Algorithms | /ADA/topologicalSort.py | 762 | 3.828125 | 4 | import numpy as np
def topological(adj,indegree,n):
"""for i in range(n):
for j in range(n):
indegree[i] +=adj[j][i]"""
length =n
while length:
for i in range(n):
if indegree[i]==0:
print(i+1,end=" ")
indegree[i]=-1
for j in range(n):
if adj[i][j]==1:
indegree[j]=indegree[j]-1
le... |
c02aeab828af37abdfbf341362fe2037ea58b382 | jatingandhi32/Analysis-and-Design-of-Algorithms | /ADA/Sudoku.py | 2,141 | 3.671875 | 4 | import numpy as np
def display(arr):
for i in range(9):
for j in range(9):
print (arr[i][j],end = " ")
print ()
def unassigned(arr,l):
for row in range(9):
for col in range(9):
if(arr[row][col]==0):
l[0]=row
... |
1f2dbc00c9e3b42288863fa939ccccc913bff71a | sacrrie/reviewPractices | /6515/fixedPoint.py | 504 | 3.765625 | 4 | #find the item value equals to index in log n time
#first let's implement the binary search algo
#done
def fixedPoint(arr):
#index=list(range(len(arr)))
i=0
while len(arr)>1:
j=len(arr)//2
i+=j
if arr[j]==i:
return(True)
elif arr[j]<i:
arr=arr[j:]
... |
cde62f98c13afd6ad02a93f7e13e40980d9a54c7 | sacrrie/reviewPractices | /CC150/Python solutions/5-0.py | 1,272 | 4.0625 | 4 | #bit manipulation practice file
#a simple bit manipulation function
'''
import bitstring
print(int('111001', 2))
def repeated_arithmetic_right_shift(base,time):
answer=base
for i in range(time):
answer=base>>1
return(answer)
a=repeated_arithmetic_right_shift(-75,1)
print(a)
def repeated_logical_ri... |
75bda027beb93483617dd1068f2a2e44dcb7e49b | mingcgg/mars | /com/bak/mnist_1.0_softmax.py | 5,811 | 3.515625 | 4 | import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data as mnist_data
from matplotlib import pyplot as plt
from matplotlib import animation
mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
#属于分类问题 全连接网络:每一个像素点(特征)都与标准值连接28*28... |
3d6870ba3a835e3ca8426695bf5762d934341486 | Shmuelnaaman/NYC_Subway_Rainy_days | /fix_turnstile_data.py | 1,860 | 3.828125 | 4 | import csv
def fix_turnstile_data(filenames):
'''
Filenames is a list of MTA Subway turnstile text files.
There are numerous data points included in each row of the
a MTA Subway turnstile text file.
Here I write a function that will update each row in the text
file so there is only one e... |
3f672028ddf03e5d74d21b000c8476a9df8f5c94 | cameronp98/python-brainfuck | /brainfuck/program.py | 2,515 | 3.96875 | 4 | """
Model the state of a brainfuck program and
act upon it using brainfuck operations.
"""
class ExecutionError(Exception):
"""
An error during program execution.
"""
pass
class Program:
"""Represents the execution state of a brainfuck program."""
def __init__(self, num_cells):
"""
... |
89a7a9009cea475f97fbe0daf1c5eb350aa4b014 | guoxiaowhu/lenstronomy | /lenstronomy/LensModel/Profiles/hernquist.py | 6,787 | 3.53125 | 4 | import numpy as np
class Hernquist(object):
"""
class to compute the Hernquist 1990 model
"""
_diff = 0.00000001
_s = 0.00001
param_names = ['sigma0', 'Rs', 'center_x', 'center_y']
lower_limit_default = {'sigma0': 0, 'Rs': 0, 'center_x': -100, 'center_y': -100}
upper_limit_default = {'... |
328d4465fe96b12b3d8d70be1898d8e97763d312 | SumireSakamoto/python-tutorial | /uranai.py | 858 | 3.625 | 4 | import random
def number_input(message):
result = input(message)
if(result.isdigit()):
result = int(result)
return result
else:
return 0
def judgement(omikuji):
rand = random.randint(1,9)
if (omikuji == rand):
print('大吉ですね')
elif(omikuji > rand):
print('... |
9743e67ea9188f1012825f5f6b6be4fb74ba7313 | DenVanvan/maze-BFS_alg | /maze_class.py | 3,251 | 3.71875 | 4 |
import os
from time import sleep
from collections import deque
class Maze:
# transforms .txt to list of lists
def __init__(self, file_path):
with open(file_path, 'r') as file:
self.content_initial = file.read().split('\n')
self.content_processed = [item for item in self.content_i... |
3710e775d29c95539cc626d2e47089372815ed56 | naga1992/python_projects | /inheritence.py | 895 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 18:46:05 2018
@author: DS00331004
"""
class Parent():
def __init__(self,last_name,eye_color):
print("Calling Parent Class Constructor")
self.last_name=last_name
self.eye_color=eye_color
def show_info(self):
print("last ... |
41b7bb5d872aee8f2458e1a9d5245f9a0d3d5eab | netstat-antp/netscripts | /test.py | 110 | 3.71875 | 4 | print "hello world!"
print "printing something else!"
for i in range (10):
print "Test number" + str(i)
|
d1a11902d5e502f95373da7a202e95409e576f44 | inwk6312winter2019/openbookfinal-sararasheed123 | /task1Asubtask1.py | 631 | 3.578125 | 4 | fin1 = open("Book1.txt",'r')
fin2 = open("Book2.txt",'r')
fin3 = open("Book3.txt",'r')
for line in fin1:
word1 = line.strip()
print(word1)
for line in fin2:
word2 = line.strip()
print(word2)
for line in fin3:
word3 = line.strip()
print(word3)
for item1 in word1:
if len(item1) == 50:
print(item1)
break
el... |
b45c396e6b80a33845f27583f96a22f385f7250d | jmishra01/Google_foobar_Challenge | /5/5_1 Expanding Nebula.py | 5,858 | 3.515625 | 4 | # Expanding Nebula
# ================
# You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! -
# one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You start monitoring the nebula,
# but unfortunately, just a mome... |
d5d2ac28e6e566984101db96010427dc702f18f5 | jmishra01/Google_foobar_Challenge | /3/3_5 Find_the_Access_Codes.py | 2,567 | 3.8125 | 4 | # Find the Access Codes
# =====================
# In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured
# with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that i... |
6e59bbbea25aca648e640db7e36bcde89272d4a4 | ArielGz08/unaj-2021-s2-unidad3-com16 | /reuso_codigo_fuente.py | 1,266 | 3.859375 | 4 | # Vamos a ver como a través del uso de funciones podemos evitar tener código fuente repetido
# Código fuente aportado por Walter Grachot (tiene unos 34 sentencias originalmente)
def carga_producto_y_calcula_subtotal():
producto= input("Ingrese nombre del producto comprado: ")
valor= float(input("Ingrese su valo... |
6ba4b5dedebb3eeca01e63654515cfbd086881aa | xiaojieluo/yygame | /game/calculator.py | 7,110 | 4.34375 | 4 | #!/usr/bin/env python
# coding=utf-8
# copy from http://blog.chriscabin.com/coding-life/python/python-in-real-world/1101.html
# Thanks
class Stack(object):
"""
The structure of a Stack.
The user don't have to know the definition.
"""
def __init__(self):
self.__container = list()
def __i... |
aee33d9d32071f96b20643094deb1c6fc6158768 | EwertonLuan/Curso_em_video | /56_cadastro_de_pessoas.py | 881 | 3.703125 | 4 | ida = 0 # idade dos dois somados
h_velho = 0 # idade do homem mais velho
h_vn = '' # Nome do homem mais velho
m_20 = 0 # mulheres com 20 anos
for i in range(1, 5):
nome = str(input('Digite o nome {}ª pessoa: '.format(i)))
idade = int(input('Dite idade {}ª pessoa: '.format(i)))
ida += idade
... |
c966acf1bedce7a5d9ff29d21a4e9db069c70141 | EwertonLuan/Curso_em_video | /41_categoria_atleta.py | 714 | 3.8125 | 4 | from datetime import date
print('\033[1;32m##\033[m' * 20+'\nPrograma para ver a categoria dos atletas\n'+'\033[1;32m##\033[m'*20)
ida = date.today().year - int(input('Qual a idade do atleta: '))
if ida <= 9:
print('Atleta esta com {} anos, sua categoria é \033[1;33mMIRIM\033[m'.format(ida))
elif ida <= 14:
pr... |
0fa3b0ba1cc789068b001406df17eba6a53c8628 | changzhai/project_euler | /project_euler/src/pe23.py | 1,726 | 4.0625 | 4 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
instructions = """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of... |
a0c074a2bca1cb02d862c7f5ce267ee28785adc4 | kbethany/LPTHW | /ex19_drill.py | 754 | 3.53125 | 4 | #create new function, cheese_and_crackers, which has two variables
def pets(cat_count, dog_count):
#the function has four things inside it contains, 4 print statements
print "You have %d cat!" % cat_count
print "You have %d dog!" % dog_count
print "Man, those are hungry pets!"
print "Give them a boost!\... |
feb27cb841884e8a2460cbe7cc645bb2ba7ae2fb | kbethany/LPTHW | /ex15.py | 912 | 3.765625 | 4 | #sys is a package, argv says to import only the vars listed
#when you call up the program (ex15.py filename), where argv is any
#module i want retrieved from that package.
from sys import argv
#argv is the arguments vector which contains the arguments passed
#to the program.
script, filename = argv
#opens the filnemae ... |
a9d1ca7beb482a72282d801a27858350ff365c7a | migeller/thinkful | /pip_001/fizz_buzz/fizz_buzz.py | 642 | 3.828125 | 4 | #!/usr/bin/env python
import sys
def modulo(x, y):
""" Determines if we can divide x from y evenly. """
return x % y == 0
def stepper(limit = 100):
""" Steps through from 1 to limit and prints out a fizzbuzz sequence. """
print "Our Upper Limit is %d! Let's go!" % limit
for n in xrange(1, limit + 1):
if modul... |
3b78e75671e8048fe45e4dfa2319d6cbc7d3bfe1 | YoZe24/lingi2364-projects | /project1/src/apriori_prefix_vdb.py | 3,406 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def apriori(filepath, minFrequency, verbose=True):
"""Runs the apriori algorithm on the specified file with the given minimum frequency.
This version has:
- intelligent candidate generation using prefixes (implemented using lists);
- fr... |
a6f2c1f7a0acbdf5f1685ebd3456be49aeb01aed | peter0703257153/School-project | /school_directory.py | 3,555 | 3.78125 | 4 | __author__ = 'pedro'
class School_directory(object):
def __init__(self):
self.schools = []
def add(self, school_name):
self.schools.append(school_name)
def find(self, name):
for school in self.schools:
if school.school_name == name:
return... |
381d4fa43d359440ffc3198333987812e06308c7 | aishwariya-7/apple | /main.py | 324 | 3.703125 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
Str ="I LOVE BEEZ LAB";
count =0;
for(i in range(0.len(Str))):
if(Str[i]!=' '):
count=count+1;
print... |
ff73cf14435050af2da53a669de66c9aa5de32aa | bruyneron/python_ds | /algo/bubble_sort.py | 625 | 3.859375 | 4 | # TC - O(n^2)
def ascending_sort(a):
n = len(a)
for i in range(0, n):
for j in range(0, n-1-i):
# (n-1)-i => n-1 becuase we are doing a[j] & a[j+1]. We don't want to go over the limit of j and get index out of range error.
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1... |
83dfa83903466ca2eca35f96a9351f76d7dc9adb | bruyneron/python_ds | /ds/queue.py | 4,221 | 3.78125 | 4 | '''
1) List
enqueue() | q.append()
dequeue() | q.pop(0) 1st element is 0
size() | len(q)
is_empty() | len(q)==0
2) SLL/DLL
(Have to use DLL. Reason: With SLL deletion takes O(n), Queue is supposed to take O(1) for deletion) <--- This is dumb
why??
SLL with head and tail.
Insertion ... |
751fab2eb3a2da8e335dff8b2ae2da160df1872f | lx881219/webley-puzzle | /webley.py | 3,392 | 3.78125 | 4 | import csv
import sys
import pathlib
class Solution:
def __init__(self):
self.result = []
self.target_price = None
self.menu = []
def handle_file_error(self):
print('Please provide a valid csv file in the following format. (python webley.py example.csv)')
print("""
... |
96265a429106573491aed434cec6d734534eea5a | backcover7/Algorithm | /15. 3Sum.py | 3,174 | 3.515625 | 4 | import bisect
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums)<3: return res
length = len(nums)
listsort = sorted(nums)
for start in range(length-2)... |
d4eec8ca65674a001474dcd2574fcbfea7d9df70 | backcover7/Algorithm | /70. Climbing Stairs.py | 1,148 | 3.59375 | 4 | class Solution(object):
def climbStairs_recurse(self, n):
"""
:type n: int
:rtype: int
"""
# recurse but time limit exceeded
# Time complexity: O(2^n)
if n <= 1: return 1
return self.climbStairs_recurse(n-1) + self.climbStairs_recurse(n-2)
... |
65da66866a817543e61627a73d2eed4cc2e6abb2 | backcover7/Algorithm | /513. Find Bottom Left Tree Value.py | 714 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
... |
ac51f8eefc234d49caf3a6a2eaee68f88f018e38 | backcover7/Algorithm | /29. Divide Two Integers.py | 862 | 3.640625 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
# https://www.youtube.com/watch?v=htX69j1jf5U
sig = (dividend < 0) == (divisor < 0)
a, b, res = abs(dividend), abs(divisor)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.