blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bc0618eaecd139467ec2cd12ef96f12dc6f21e80 | jayChung0302/DeepPipe | /python_demo/key_frame_selection.py | 4,279 | 3.890625 | 4 | import torch
import cv2
import operator
import numpy as np
def smooth(x, window_len=13, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signa... |
59093ce4b4dd8241159405d6a91774a44237d633 | edagotti689/PYTHON-5-FUNCTIONS | /0_function_NOTE.py | 596 | 4.375 | 4 | 1. Using functions we can give a name to the block of code.
2. Using functions we can re use code.
3. Using def we can create a function.
# Use of Parameters
1. Using parameters we can make a function dynamic
2. Using parameters we can pass values to the function
3. Python function support 4 types of parameter... |
fc4f5c9ee03f686683e1785f452554882fb4c33a | shubham18121993/algorithms-specilaization | /3_greedy_algo_and_dp/maximum_weight.py | 800 | 3.609375 | 4 |
def get_max_weight(n, lst):
optimal_solution = [0]
prev = 0
curr = 0
for elem in lst:
optimal_solution.append(max(prev+elem, curr))
prev = curr
curr = optimal_solution[-1]
solution_set = []
val = optimal_solution[-1]
for i in range(n, 0, -1):
if val < ... |
6085ff54033faf5f2dc438aef6f7420116bccb3f | firstknp/FinalProject | /main.py | 4,285 | 3.609375 | 4 | from game1 import *
from game2 import *
from game3 import *
import sys
userlist = []
# class GameStat:
# def __init__(self,game ,win, user_num , userlist):
# self.game = game
# self.win = win
# self.user_num = user_num
# self.userlist = userlist
# def check_game(self):
# ... |
108620ce4fc02ef179f7b500cd2d33f15960c8fb | code1990/bootPython | /python/05Numpy/NumPy011.py | 972 | 3.6875 | 4 | # NumPy 广播(Broadcast)
# 广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式, 对数组的算术运算通常在相应的元素上进行。
# 如果两个数组 a 和 b 形状相同,即满足 a.shape == b.shape,那么 a*b 的结果就是 a 与 b 数组对应位相乘
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
c = a * b
print(c)
# 当运算中的 2 个数组的形状不同时,numpy 将自动触发广播机制。如:
a = np.arr... |
a6d7a616ef82785a4c3d2e94e3c4a21409c4a86c | EpicureanHeron/automatedEmailMessages | /response.py | 4,903 | 4.09375 | 4 | import datetime
def whichToRun():
# prompts the user for what type of email message this is
voucherOrReceipt = raw_input("Is the PO missing a voucher[1], receipt[2], or no receipt AND no voucher [3]? Please enter 1, 2, or 3: ")
# checks the value, and runs the necessary function to generate the message
if vouc... |
dce6bff9e08f046f22e8cfc3fdf50a98594c9808 | AK-1121/code_extraction | /python/python_23402.py | 185 | 3.53125 | 4 | # Python adding lists of numbers with other lists of numbers
>>> lists = (listOne, listTwo, listThree)
>>> [sum(values) for values in zip(*lists)]
[10, 9, 16, 11, 13]
|
63daeec489cf006865d8f656693ef8a85e718530 | shayandaneshvar/Introduction-To-Computer-Vision-Labs | /cv-lab5/sobel1.py | 1,205 | 3.75 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
I = cv2.imread("agha-bozorg.jpg", cv2.IMREAD_GRAYSCALE)
# Compute the gradient in x direction using the sobel filter
# Method 1: using filter2D **********
Dx = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]) # Sobel fil... |
0534ec08872413fb1674286b885c8099e478648c | rishabhCMS/IIPP_mini-projects | /Guess_the_number_game.py | 2,919 | 4.03125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
count = 0
trial = 0
secret_number = 0
# helper function to start and restart the game
def new_game():
... |
55f84f2c087886d891db3e2b42b93d2dcf4cd2ef | k0syam/workshop01 | /dai13shou/code13-7.py | 385 | 3.625 | 4 | #dfsによる根無し木の走査
from collections import deque
n=5
graph=[[] for _ in range(n)]
edges=[[0,1],[1,2],[1,4],[3,4],[3,0]]
for i in range(len(edges)):
a,b=edges[i][0],edges[i][1]
graph[a].append(b)
graph[b].append(a)
def dfs(v,p=-1):#v:頂点、p:vの親
for c in graph[v]:
if c==p:#親への逆流を防ぐ
continu... |
9eba37b423e09906a92fe117ed5b67c785da26de | jeancre11/PYTHON-2020 | /CLASE3/codigo7.py | 290 | 3.515625 | 4 | """LINSPACE"""
def linspace(to, tf, N):
razon=(tf-to)/N
#primera forma
lv=[]
for val in range(N):
lv.append(to+val*razon)
lv.append(tf)
return lv
#creando una lista desde el valor to hasta tf con N valores
#linspace(to, tf, N)
l1=linspace(0, 20, 4)
print(l1) |
3e1c1b714db2362118ba26b7ef0f1725bf4397e3 | RodMdS/Redes_de_Computadores | /Calculadora_UDP_V2/server/operations.py | 1,042 | 3.609375 | 4 | def add(op1, op2):
try:
return float(op1) + float(op2)
except ValueError:
return "Error: the message isn't correct"
def sub(op1, op2):
try:
return float(op1) - float(op2)
except ValueError:
return "Error: the message isn't correct"
def mpy(op1, op2):
try:
re... |
35a59340498cb189cb0c73227ca982a67269c4d7 | esineokov/ml | /lesson/1/exercise/6.py | 216 | 4 | 4 | a = float(input("Enter start: "))
b = float(input("Enter finish: "))
day = 1
current = a
while current < b:
day += 1
current = current + current*0.1
print(f"You will reach the result on the {day}th day")
|
64aca9510f99b2371e5e2fa541d16688c0bbe469 | xmtsui/python-workspace | /data_process/csv/csv.py | 1,056 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: csv
# Purpose: read and write csv files
# Author: tsui
# Created: 9 Apr, 2013
# Copyright: ©tsui 2013
# Licence: GPL v2
#-----------------------------------------------------------... |
77f31d9b29670e12bddc869f4ed80c340333cd52 | MathewTheProgrammer/CLI | /main.py | 3,546 | 3.703125 | 4 | import os
import sys
import datetime
import calendar
import colorama
from colorama import Fore
colorama.init()
print(Fore.RESET + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
# COMMANDS
command = input('Please enter a command:')
while True:
if command == "Help" or command =... |
00d7bf36b8369a60a5ed8dcecc1005e4ab6d1f2c | tks2103/python-coding-interview | /3_chapter/stack.py | 814 | 4.0625 | 4 | class Node(object):
def __init__(self, data):
self.next = None
self.data = data
class Stack(object):
def __init__(self):
self.top = None
self.size = 0
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
self.size += 1
def pop(self):
if(self.top !=... |
09b785c7e51006b2aa34194879f7b751825af793 | Alejandra2254/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 257 | 3.5625 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary == {} or a_dictionary is None:
return None
m = sorted(a_dictionary.values())
max = m[-1]
for i in a_dictionary:
if max == a_dictionary[i]:
return i
|
e1e9d30819fe47b8aa749dd324a67df4de94b8aa | PrivateVictory/Leetcode | /src/ziyi/Array/MaximumProductSubarray.py | 666 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-15 09:47:27
# @Author : Alex Tang (1174779123@qq.com)
# @Link : http://t1174779123.iteye.com
'''
description:
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
1aff6f75ef1eca9e63961e08d88f8c80458d6f76 | JonhFiv5/aulas_python | /aula_28_desafio_contadores.py | 319 | 3.84375 | 4 | # Criar dois contadores dentro do mesmo laço
# Uma vai de 0 a 8 e o outro de 10 a 2
for progressivo, regressivo in enumerate(range(10, 1, -1)):
print(progressivo, regressivo)
# regressivo vai guardar o valor devolvido pela função range
# progressivo vai guardar o valor de enumerate, o número de iterações
|
e25505b3253f112e8a186e16f19fe3ac1d28ae20 | CosmicTomato/ProjectEuler | /diophantine_min.py | 1,680 | 3.59375 | 4 | #designed for help on project euler problem 66:
#Consider quadratic Diophantine equations of the form:
#x^2 – Dy^2 = 1
#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
#It can be assumed that there are no solutions in positive integers when D is square.
#By finding minimal solutions in x for D ... |
16ba2e84b59d5c324e95f6980e6a8b5b907b8956 | RohitUttam/ProjectEuler | /7-10001st prime number.py | 310 | 3.84375 | 4 |
'''listprime=[]
for num in range(3,1000000,2):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
listprime.append(num)
if len(listprime)==10002:
break
print(listprime[10001])'''
skip=[]
l=range(3,1000,3)
skip.extend(l)
print(18 in skip) |
ff931194f658c93d1a70d2167941cc81b2f07cad | m4mayank/ComplexAlgos | /square_root_of_integer.py | 776 | 4.3125 | 4 | #!/usr/local/bin/python3.7
#Given an integar A.
#
#Compute and return the square root of A.
#
#If A is not a perfect square, return floor(sqrt(A)).
#
#DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY
#
#For Example:
# Input 1:
# A = 11
# Output 1:
# 3
#
# Input 2:
# A = 9
# Output 2:
# ... |
1972c072e4bf29edf5d776aa43378dd4cc251c30 | sameertulshyan/python-projects | /NYC_job_listings/NYC_data_scrubbing.py | 4,935 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 17:17:04 2018
Data taken from: https://data.cityofnewyork.us/City-Government/NYC-Jobs/kpav-sd4t/data
@author: sameertulshyan
This program allows the user to extract a list of government jobs in NYC that meet their criteria for salary/work-type/pay... |
8bdff3cfd4fd6c41af4e187bfb0bab7d66d880fc | hsnylmzz/Python-Learning | /pytprojects/ciro.py | 1,406 | 3.546875 | 4 | def calculateCiro(sell_amount, sell_value):
return sell_amount-sell_value
def writeCiro(name, ciro):
try:
with open("ciro.txt","r+") as ciroText:
allData = ciroText.readlines()
already = False
for i in allData:
if i.startswith(name):
... |
aa987b5b2d13224ea9472f8c8f9061d5401dea87 | sagelga/prepro59-python | /139_LetsFreshIt.py | 485 | 4.03125 | 4 | """This program will ask input then, run the program, later then print out the results"""
def major_branch():
"""This is the main fuction. It will do everything."""
message = input()
count = 0
message.split(" ")
sorted(message)
print(message)
while message[0] != 1:
sorted(me... |
791df87235f5da634fc62ebc3a3741cea6e2deca | AlbertRessler/itam_python_courses | /homeworks/chapter_2/task_2_1_2.py | 574 | 3.65625 | 4 | def summation(numbers):
positive_numbers = []
normalized_numbers = []
numbers_list = numbers.split()
for idx, arg in enumerate(numbers_list):
int_arg = int(arg)
if int_arg < 0:
new_arg = abs(int_arg) * 2
else:
new_arg = int_arg
positive_numbers.app... |
309e92f27b2c08d8433115c7eb705a0114966a8d | MiniMidgetMichael/Old-HS-shit | /turtle_test.py | 1,548 | 3.53125 | 4 | #! C:/Users/MichaelLFarwell/AppData/Local/Programs/Python/Python35-32/python.exe
#! C:UsersMichaelLFarwellAppDataLocalProgramsPythonPython35-32python.exe
import turtle
import sys
import os
"""TO REFERENCE TURTLE OBJECTS: 'turtle.module.object'
EX.
print (turtle.math.pi)
>>> 3.14159265
"""
my_turtle = turtle.T... |
22ff3d19c404883f438e7c27567fda3e2f2fd8c6 | Yuki-Sakaguchi/python_study | /challenge/part4.py | 842 | 4.21875 | 4 | # 文字列
kamyu = "カミュ"
print(kamyu[0])
print(kamyu[1])
print(kamyu[2])
nani = input('何を書いた?')
dare = input('誰に書いた?')
print("私は昨日、{}を書いて{}に送った".format(nani, dare))
print('aldous Huxley was born in 1894.'.capitalize())
print("だれが? いつ? どこで?".split(' '))
text_list = ['The', 'fox', 'jumped', 'over', 'the', 'fence', '.']
p... |
c715f17e47139246f06b7fbf916c017eb0f87cd5 | af-orozcog/Python3Programming | /Python functions,files and dictionaries/assesment3_5.py | 353 | 3.734375 | 4 | """
Create a dictionary called wrd_d
from the string sent, so that the key is a word and the value is how many times you have seen that word.
"""
sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good"
words = sent.split()
wrd_d = {}
for word in words:
wr... |
02d46ae3a4107955c75ff34831295a5e3eee878d | NegiArvind/NeroFuzzyTechniques-Lab-Program | /applyingFilter.py | 1,261 | 3.640625 | 4 | import numpy as np
from PIL import Image
img=Image.open("emma.jpg") #used to open the image
img=np.array(img) # it converts image into numpy array
img.transpose(2,0,1).reshape(3,-1); # converting 3d numpy array into 2d numpy array
img.resize(500,500); # Resizing the given image into 500*500
img=np.insert(img,0,0,axis=1... |
d8948abd484ce27096f5ddadc06324ded8251b5a | Ironside-github/python-tutorials | /chapter 5 dictionary&Sets/Setsexample.py | 1,497 | 4.65625 | 5 | #Use of Set along with example
# Set is a collection of non repititive elements./Unordered and unindex/ Bo way to change items in sets/can't contain duplicate values
#defining a set-----first way
a={1,2,3,4,1}
print(type(a))
#defining a set -----second way
b=()
print(type(b)) #Here the type is tupple
c= set()
print(typ... |
de1af259934d2a2d41e456b9a5472fad9d9c17a9 | kingssafy/til | /ps/swea/calculator3.py | 1,122 | 3.515625 | 4 | import sys
sys.stdin = open("calculator3.txt")
priorities = {"+":0, "*":1, "(":-1}
for tc in range(1, 11):
a = input()
given = input()
nums = []
operators = []
stack = []
#convert
for char in given:
if char in '0123456789':
nums.append(char)
elif char == '(':
... |
ed80018b52ff6041bce5f155a79eafd9851b8f51 | jaycody/mypy | /hardwaypy/ex8.py | 1,249 | 4.34375 | 4 | # Printing Printing
# create variable and assign it a format string composed of only format characters
formatter = "%r %r %r %r"
# print the format string and use a list of ints to inform the format variables
print formatter % (1, 2, 3, 4)
# print the format string and use a list of strings to inform the format vari... |
01c097d17e5ef6c5e08cdc0279be37110f95bd38 | ohjerm/sudoku-solver | /py-sudoku.py | 10,622 | 3.984375 | 4 | import random
import numpy as np
def read_puzzle(in_line):
"""
reads a sudoku puzzle from a single input line
:param in_line: 9 space-separated 9-digit numbers ranging from 0-9
:return: returns the numbers in a numpy array
"""
arr = np.zeros((9,9), dtype=int)
for i, line in enumerate(in_li... |
b9c4effe0bc2585b0623e91194fea80dec4e2e31 | sudhanshuptl/MyCodeDump | /Python/Algorithm/Binary_search.py | 1,598 | 4.15625 | 4 | # Binary Search Only Applicable on sorted array
import random
def binary_search_recursive(arr, low, high, key):
if high >= low:
mid = int((low + high)/2)
if arr[mid] == key:
return mid
elif arr[mid] > key:
return binary_search_recursive(arr, low, mid-1, key)
... |
15511bdf4c0d8edc8d767e4f5672ad60ca64ba3d | SanyaBoroda4/Coursera_Python | /2 WEEK/while test 2.py | 166 | 3.984375 | 4 | now = int(input())
max_num = now
while max_num != 0:
now = int(input())
if now == 0:
break
if now > max_num:
max_num = now
print(max_num)
|
a469365d9fb3f23b05018f91730ec069c7ce1bed | jasonxiaohan/DataStructure | /ArrayQueue.py | 1,332 | 3.921875 | 4 | # -*- coding:utf-8 -*-
from DataStructure.Queue import Queue
from DataStructure.Array import Array
"""
数组队列
"""
class ArrayQueue(Queue):
def __init__(self, capacity=10):
self.__array = Array(capacity)
def __str__(self):
res = ('Queue:size = %d,capacity = %d\n') % (self.__array.getSize(), self.... |
5db6e5a662576b871c3216424fe5e2b23f51f33f | markabrennan/code_challenges | /triplet_sum_close_to_target.py | 959 | 3.734375 | 4 | """
From Grokking The Coding Interview
"""
def triplet_sum_close_to_target(arr, target):
triplets = []
for i in range(len(arr)):
if i > 0 and arr[i] == arr[i-1]:
continue
sub(arr, i, target, triplets)
triplets.sort()
return triplets[0][1]
def sub(arr, i, target, triplets):
... |
da40cd97917a3d11922bc2143ad02e0d2dc5dd14 | Arfameher/3D_houses | /create_csv.py | 1,274 | 3.75 | 4 | import csv # To write a csv file for bounds.
import pandas as pd
import rasterio # We can read in a GeoTiff file into a dataset using rasterio module.
def bounds():
"""Create a csv file that reads each tif file and stores the bounds of
each one of them... |
eeec7a128558a1274dfe2c0daefedb0c704f38a5 | TonsOfBricks/projects | /iterative-functions.py | 5,314 | 4.1875 | 4 | """
Author: Nikita Sinkha
Date: 1/31/2018
File: iterative-functions.py
"""
def gcd(a, b):
"""
func: gcd():
Takes 2 positive numbers and computes the Greatest Common Divisor using the method
of iteration.
param1: a -> A positive number.
param2: b -> A positive number.
"""
whi... |
67248a4d1f62d5ddfc694fc6b567303572b2ebaa | maomao905/algo | /add-bold-tag-in-string.py | 1,859 | 3.828125 | 4 | """
for word in dict:
find all matching position
save start and end position
result is [[start, end], [start, end]]
sort and if end1 > start2, merge them
string matching takes (SL) each time in worst case
time: O(SLD) + O(D) + O(S) = O(SLD)
S: string s size
L: average dict string length
D: dict si... |
023e23700c85e91cb7bda57f58b07e1b30f40a3c | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/ndxshe013/question4.py | 583 | 3.578125 | 4 |
def main():
x = input("Enter a space-separated list of marks:\n")
marks = x.split()
faL = 0
trd = 0
Low = 0
upper = 0
fst = 0
for i in marks:
if eval(i) < 50:
faL += 1
elif eval(i)<60:
trd += 1
elif eval(i)<70:
... |
ff2565184cfe8370891cdf0b1d1d4b571f4ed892 | EswarAleti/Python | /password_validity.py | 922 | 4.09375 | 4 | def get_validity(password):
# If password have less than 10 character then it is invalid
if len(password)<10:
return False
# Initalize 3 varibales to False
exist_digit = False
exist_alpha = False
exist_symbol = False
# For each letter in password
for letter in password:
# If alphabet exist then make exist_a... |
bb7c25ccd7d508b9e6098e750892758c3867be5d | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/02.Estrutura de Decisão/12. Folha de pagamento.py | 3,050 | 4 | 4 | #coding: utf-8
"""
Faça um programa para o cálculo de uma folha de pagamento,
sabendo que os descontos são do Imposto de Renda, que
depende do salário bruto (conforme tabela abaixo) e 3%
para o Sindicato e que o FGTS corresponde a 11% do
Salário Bruto, mas não é descontado (é a empresa que deposita).
O Salário Líq... |
b7ccfcec04d309efb3819534577ad02758b3df10 | perceive203/python_excercise | /quicksort.py | 3,544 | 3.859375 | 4 | #! /usr/bin/env python2.7
# encoding=utf-8
""" 快速排序的练习程序
"""
import sys
import getopt
class QuickSort(object):
""" 快速排序类
"""
def __init__(self, idata = None):
if idata is not None:
self.data = list(idata)
def sort(self, idata = None):
""" 实际排序
Args:
... |
ccdc375a3faf3c973712fd60b9c7c8110d8c4a87 | andersonkramer/Python | /Desafio01.py | 205 | 3.9375 | 4 | #Pergunga a idade e responde se você é Adulto
idade = int(input('Qual é a sua idade?'))
type(idade)
if idade > 20:
print('Vocé é uma pessoa adulta!')
else:
print('Vocé é um Adolescente!') |
1b6b956fe17f1b4c6303159d97d30843c8695bea | elitejakey/schoolks4 | /cake.py | 163 | 3.96875 | 4 | print('There are 25 people coming to the party.')
cake = (25*2)
print('This means that if you have 2 cakes per person, there will be', cake, 'cakes!')
|
40e07725b0441dc0093903a959a635691e89f5ce | shen-huang/selfteaching-python-camp | /exercises/1901050029/1001S02E03_calculator.py | 1,019 | 4.0625 | 4 | # Filename : 1001S02E03_calculator
# author by : Ž
# 庯
def add(x, y):
""""""
return x + y
def subtract(x, y):
""""""
return x - y
def multiply(x, y):
""""""
return x * y
def divide(x, y):
""""""
return x / y
########################################################
status = 1
# û
pr... |
6f9cdbf8af7137fab3258868afd267fe39240768 | 4g/reinforce | /classic_control/mountain-car.py | 4,636 | 3.59375 | 4 | # -*- coding: iso-8859-15 -*-
"""
--Learning to balance a pole--
learn a q-network, which learning the q function directly from (s,a,r,s')
http://neuro.cs.ut.ee/demystifying-deep-reinforcement-learning/
As per https://arxiv.org/pdf/1312.5602.pdf
"""
import gym
from keras.layers import Dense, Input, concatenate
from... |
34120c178132dbea67d72c7528ffd0e35206e0cc | Mux-Mastermann/codewars | /katas.py | 6,327 | 4.0625 | 4 | """This file contains different solution functions from codewars challenges for python"""
def function_test():
"""Test functions here"""
print(halving_sum(25))
def halving_sum(n):
"""Kata: Halving Sum """
x = n
while n != 1:
n = n // 2
x = x + n
return x
def rgb(r, g, b):
... |
9463611e087d0575c93f3770774ee933548736c9 | vinaykumar7686/Leetcode-Monthly_Challenges | /April/Week4/Powerful Integers.py | 1,511 | 4.1875 | 4 | # Powerful Integers
'''
Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.
An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.
You may return the answer in any order. In your answer, each value s... |
934b7cbeac35aa2816efe4bacc97ecb2fe3e50bd | Simurgh818/AutostitchingProject | /DrawingFunctions.py | 777 | 3.625 | 4 | import numpy as np
import cv2
# To create a black image
img = np.zeros((512,512,3), np.uint8)
# To draw a diagonla blue line with 5 pixel thickness
img = cv2.line(img,(0,0),(511,511),(255,0,0),5)
#cv2.imshow('Drawing Practice', img)
img2 = cv2.rectangle(img,(384,0),(510,128),(0,255,0), 3)
img3 = cv2.circle(img,(447,... |
6530f80d3cb30cd28af279977db10de424cd5589 | Yinlianlei/Work | /AI-Learn/test-5.py | 3,407 | 3.765625 | 4 | import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as graph
import numpy as np
from sklearn import linear_model
# %matplotlib inline
graph.rcParams['figure.figsize'] = (15,5)
graph.rcParams["font.family"] = 'DejaVu Sans'
graph.rcParams["font.size"] = '12'
graph.rcParams['image.cmap'] = 'rainbow'... |
590bb202f506ca316634cc8b449e6ff8b61a85fe | merveeMalak/260201043 | /lab6/example1.py | 331 | 4.09375 | 4 | right_email = "ceng113@example.com"
email = input("Enter a email: ")
email_at_index = email.index("@")
email_at_before = email[:email_at_index]
email_at_after = email[email_at_index+1:]
email = email_at_before.replace(".","").lower()+"@"+email_at_after.lower()
if email == right_email:
print("Valid email")
else:
... |
18932a500044f6fa340fb0c16cfb869ce7014098 | keepmoving-521/LeetCode | /程序员面试金典/面试题 01.08. 零矩阵.py | 2,326 | 4.0625 | 4 | """
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
"""
# 方法一:
class Solution(object):
def setZeroes(self, matrix):
"""
:type... |
1578b368b318ebfe4ea4e55e8bc467a009228826 | DanielGB-hub/PythonDZ | /DZ2_1.py | 1,638 | 3.5 | 4 | # 1) Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
result_list = [] # создаем пустой список и добавляем в не... |
11f0b3bd1bd3906a20d2bc5aa31db8c84bb9d492 | chendaniely/sphinx-rtd-test | /sphinx_rtd/mod.py | 520 | 3.65625 | 4 | """ Test module and some documentation
"""
def my_square(x):
"""Square a given value
:param x: value to be squared
:type x: a number
:rtype: float
"""
return x ** 2
def my_square_alternative_doc(x):
"""Square a given value
Parameters
----------
x : number
The number ... |
edcb64ff4d5e2baf43c3aaac6236fd46c0d9efcb | xren/algorithms | /4-4.py | 550 | 3.96875 | 4 | # Given a binary tree, design an algorithm which creates linked list of all the
# nodes at each depth
def getLinkedList(root):
result = []
current = getLinkedList()
if not root:
current.add(root)
while current:
result.append(current)
parents = current
currentLinkedList... |
de7476dd256feb9153f76a24dd06f8110c0c3355 | jessica1127/python_leetcode | /leetcode/leetcode535_encode-and-decode-tinyurl.py | 1,370 | 4.1875 | 4 | '''
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. ... |
ce08769389a0d4323cc30f9672974d427296232a | JesusAMR/Programas-S1 | /bafu.py | 1,331 | 4.09375 | 4 | #Area bajo una curva
#Funcion (sin(x))^2 de 4 a 7 x³ / 3 - 2x² + 12
from decimal import *
from threading import *
from math import *
def f1(x,power,u=2):
return (pow(x,3))/(3-(2*pow(x,2))+12)
def f2(x):
return Decimal((1/(x+1)))
def smrare(b,a):
sm=((b-a)/6)*(f2(a)+4*f2((a/2+b/2))+f2(b))
return sm
def f... |
d120cbb5300504b3b5b0f242ff7ea2f49d860e72 | UCMHSProgramming16-17/github-intro-mshih18 | /addition.py | 451 | 4.25 | 4 | # import sys module
import sys
# assign command line arguments to variables
value1 = int(input("First number: "))
value2 = int(input("Second number: "))
value3 = int(input("Thrid number: "))
# find sum of values
result = value1 + value2 + value3
# checks if number is even or odd
if result%2 == 0:
print ("The sum... |
523d9c78dfc4d620b9c069fd42ca2c596b54e965 | cgat-developers/cgat-apps | /cgat/Histogram.py | 19,547 | 3.8125 | 4 | """
Histogram.py - Various functions to deal with histograms
===========================================================
:Author:
:Tags: Python
Histograms can be calculated from a list/tuple/array of
values. The histogram returned is then a list of tuples
of the format [(bin1,value1), (bin2,value2), ...].
"""
impor... |
cbd6c7f839a492dbc77dd9f5a2f09135f35395c7 | mattmaggio19/Code_eval | /Easy_challenges/Odds_to_99.py | 258 | 3.84375 | 4 | #print all odd from 1 to n
def isodd(arg): #is a number odd?
if not arg % 2 == 0:
return True
else:
return False
def count_up_execute(n):
for ii in range(1,n):
if isodd(ii):
print(ii)
count_up_execute(100) |
f170d291b1518bc6aae995e89ed207595062c731 | pusparajvelmurugan/ral | /83.py | 250 | 3.859375 | 4 | num=input("Enter your seqence (Mod/Dividee):")
op=['%','/']
for x in num:
if(x=='%'):
k1=int(num.split(x)[0])
k2=int(num.split(x)[1])
ans=k1%k2
elif(x=='/'):
k1=int(num.split(x)[0])
k2=int(num.split(x)[1])
ans=k1//k2
print(ans)
|
ed318faf9b3c8b1525115a857f50e0b93fee37dd | rohinrohin/python-lecture | /Day 1/Assignment/3_wicketfall.py | 311 | 3.515625 | 4 | wicket = []
while True:
print("1. Wicket")
print("2. Game Over")
print("3. Exit")
i = input()
if i=='1':
run = int(input("partnership run:"))
wicket.append(run)
elif i=='2':
print("Highest partnership: ", max(wicket))
break
else:
break
|
6c3ab72e38db4b524408b8352e4a04b59890aeb5 | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 2/Repetições em Python (while)/DESAFIO 057 - Validação de Dados.py | 335 | 4.09375 | 4 | """Faça um programa que leia o sexo, mas só aceite os valores 'M' ou 'F'.
- Caso esteja errado, peça a digitação novamente até ter um valor correto"""
sexo = str(input('Insira o sexo [M/F]: ')).upper()
while sexo != 'M' and sexo != 'F':
sexo = str(input('ERROR!, Digite sexo novamente: ')).upper()
print('Sexo regis... |
f3460d56250f3421f888a07c2799a3e7b85aee31 | im4faang/Coffee-Machine | /main.py | 2,030 | 4.09375 | 4 | from data import MENU, resources
water = resources["water"]
milk = resources["milk"]
coffee = resources["coffee"]
money = 0
turn_off = False
def report():
print(f"Water: {water}ml\nMilk: {milk}ml\nCoffee: {coffee}g\nMoney: ${money}")
def check_resources(choice):
check = True
if choice !=... |
c5d7e9342af92e657f8e1896567c87cf47028d94 | OmarFaruq502/Python-Basics | /Chanllenges 52-59/random-chapter.py | 1,465 | 3.9375 | 4 | ####################################################
# Python by example
# Problem : 052 - 059
# Author: Omar Rahman
# Date: 1/1/2020
####################################################
import random
#------------------------------------
# Problem 052
#------------------------------------
def fifty_two()... |
e4a2060dbdf3d7ea85f2e0f2de9ca00cc2f40dbd | BrandonDoggett/pyapivz | /readinjson04.py | 467 | 3.546875 | 4 | #!/usr/bin/python3
import json
def main():
with open("datacenter.json", "r") as datacenter:
datacenterstr = datacenter.read()
datacenterdict = json.loads(datacenterstr) # gives a dict
print(datacenterdict["row1"])
with open("datacenter.json", "r") as datacenter:
dat... |
b28beb0c0dbd4f1c023c798a0d9361e976068277 | Swisy/CSC-110 | /decrypter.py | 805 | 3.90625 | 4 | ###
### Author: Saul Weintraub
### Course: CSc 110
### Description:
###
###
###
def main():
encrypted_file_name = input('Enter the name of an encrypted text file:\n')
index_file_name = input('Enter the name of the encryption index file:\n')
encrypted_file = open(encrypted_file_name, 'r')
index_file = op... |
90e297a786d781b9055895bb7afb554d30b6aaf1 | ramonvaleriano/python- | /Cursos/Curso Em Video - Gustavo Guanabara/Curso em Vídeo - Curso Python/Exercícios/desafio_11.py | 477 | 3.921875 | 4 | # Programa: desafio_11.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 22/09/2020 - 22:47
def area(numero1, numero2):
result = numero1*numero2
return result
def tinta(calculo, num1, num2):
dado = calculo(num1, num2)
quantidade = (dado/2)
return quantidade
comprimento = float(input('Digi... |
8784115fdb1a667df3137bcbfce647f51e0b3f52 | Shreyash840/Practice | /util/Single_Linked_List/SLL_base_util.py | 4,881 | 4.125 | 4 | """ Linked List util"""
newline = "\n-------------"
def print_linked_list(head):
itr_node = head
if itr_node is None:
print("Empty List")
return
while itr_node is not None:
print(itr_node.data, sep=' ', end='-->')
itr_node = itr_node.next
class Node:
def __init__(se... |
a47c53b4044019deb7c6c544806c442371c056c9 | pootatookun/Gravity-Engine | /Gravity Engine/Gravity_Maths/Kinematics.py | 1,661 | 4.1875 | 4 | '''
kinematics class used newtonian Kinematics to find out distance travelled by a mass,
under constant acceleration
'''
import numpy as nn
class kinematics(object):
'''
Usage: a = kinematics(delta_time, vector_array, initial_speed_array)
vector_array: contains effective force vector experienc... |
d3a77a9df9f1eb222c3fa6d923f9a131ccf6a976 | dsspasov/HackBulgaria | /week1/1-Python-OOP-problems-set/employee_hierarchy.py | 1,509 | 3.78125 | 4 | #employee_hierarchy.py
class Employee:
def __init__(self,name):
self.name = name
def getName(self):
return self.name
class HourlyEmployee(Employee):
def __init__(self,name,hourly_wage):
self.hourly_wage = hourly_wage
super(HourlyEmployee,self).__init__(name)
def weeklyPa... |
eacf33b3950b3959ed13b0ee58523f6ce6f2bae7 | preethika-ajay/N-Queens | /Nqueensmodule.py | 1,093 | 4.03125 | 4 | #Fn to check if queen can be placed at the given position
def is_safe(board,row,col,n):
#For loop to check if the row on the left of the given row is safe
for i in range(col,-1,-1):
if board[row][i]=="Q":
return False
r=row
c=col
#While loop to check is lower diagnal is... |
a9704080316b3f4433ce6f5a3b896f21431d86f5 | hahalima/PracticeProbs | /8.py | 140 | 3.984375 | 4 | def alphabetically(n):
items = n.split(',')
items = sorted(items)
return ','.join(items)
print alphabetically("without,hello,bag,world") |
fd9425f915b582edef606dd16f2cab30920db0ac | angrytang/python_book | /python-3/day6-3.py | 168 | 3.8125 | 4 | def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 3, 5))
a = (1, 2, 3, 5)
print(add(a)) |
963e8433bbf634518baf07e598ac30a72a4ee768 | Megg25/PROJEKT2 | /main.py | 3,006 | 3.59375 | 4 | import random
def tajne_cislo():
num = []
pocet_cisel = 4
i = 0
if pocet_cisel in range(1, 10):
while i < pocet_cisel:
cislo = random.randint(1, 9)
if cislo not in num:
num.append(cislo)
i += 1
return num
def tvoje_cislo_spravne(tvoje_... |
07397021fc0bb0d4f10c2c6a2f0ead39390b7115 | Ziadpydev/PythonTutorials | /ifelif.py | 157 | 4.09375 | 4 | x = int(input("Enter a number between 1 and 10"))
if x==1:
print("One")
elif x==2:
print("Two")
elif x==3:
print("Three")
else:
print("Ten") |
c295856b36668cff3e7921f2acd252619dca393f | YazanAhmad18/data-structures-and-algorithms-python | /data_structures/stack-and-queue/stack_and_queue/stack_queue_animal_shelter.py | 1,965 | 3.734375 | 4 | class AnimalShelter:
def __init__(self):
self.rearcat=None
self.frontcat=None
self.reardog=None
self.frontdog=None
def enqueue(self,animal):
if animal.type=="cat":
if self.frontcat ==None:
self.frontcat=animal
self.rearc... |
4a413666d1d6d9d313a4ae4f66b3599a3827c054 | FedoseevaAlexandra/string.2 | /problema.1.py | 147 | 3.828125 | 4 | cuv=str(input('introdu cuv :'))
k=str(input('introdu o litera :'))
if len(k)==1:
for i in cuv:
x=cuv.replace(i,k)
print(x) |
6301c12dccb74b7c684564268560a2df412dd821 | OskitarSnchz/POO2 | /poo2/vehiculo/Vehiculo.py | 3,242 | 4.125 | 4 | '''
Created on 26 feb. 2019
Crea la clase Vehiculo, así como las clases Bicicleta y Coche como subclases
de la primera. Para la clase Vehiculo, crea los atributos de clase
vehiculosCreadosy kilometrosTotales, así como el atributo de instancia
kilometrosRecorridos. Crea también algún método específico para cada una... |
56f5e0ac22dc5ab0086e41e7b8cd56d7e0cbdfe0 | prabodhtr/ComputerSecurityS8 | /complexityCalc.py | 1,406 | 3.78125 | 4 | import math
import matplotlib.pyplot as plt
import numpy
# Function to count total bits in a number
def plotGraph(data):
x_val = numpy.arange(1,10001,1)
y_val = [item[0] for item in data]
plt.plot(x_val, y_val)
plt.scatter(x_val, y_val, c = "black", marker= '^', label = "LenofNum")
y_val = [... |
02cc0bbca8500b695d6b7f772907734300c51d58 | NilsFriman/nilslibrary | /nilslibrary.py | 2,327 | 4.375 | 4 | # Takes input in form of a text that will appear to the user when asked for input, and gives back an integer value only.
def intinput(text):
done = False
while not done:
finaltext = input(text)
try:
finaltext = int(finaltext)
done = True
except Exception:
... |
200bb0064780ca5ff5b8e419f05e18638a59a409 | orangeblock/fanorona | /src/utils.py | 612 | 3.59375 | 4 | #
#
# Helper functions used by the modules.
#
#
import pygame
def load_image(path):
return pygame.image.load(path).convert_alpha()
def tsub(tup1, tup2):
""" Subtracts tup1 elements from tup2 elements. """
return (tup1[0]-tup2[0], tup1[1]-tup2[1])
def tadd(tup1, tup2):
""" Adds the elements of tup1... |
71911562df07e70e7114eeeae2ce0ee585091269 | kennedycAlves/pythonlab | /exer_if.py | 203 | 3.953125 | 4 | a = int(input("Informe a velovidade de do veículo: "))
if a > 110:
b = a - 110
b = b * 5
print ("Veículo multado no valor de", b, "Reais")
else:
print ("O veículo não foi multado")
|
5fe4d95bd569fb5c9844abd075c8eb69f6df70e4 | Aasthaengg/IBMdataset | /Python_codes/p02843/s348339150.py | 203 | 3.625 | 4 | import sys
input = sys.stdin.readline
def main():
X = int(input())
NUM = X//100
A = X%100
if A <= NUM*5:
print(1)
else:
print(0)
if __name__ == '__main__':
main() |
52822882e7050f48d802b81c295d28da56ed3b51 | MP076/Python_Practicals_02 | /09_User_Input/29_parrot.py | 229 | 3.953125 | 4 | # How the input() Function Works
# 153
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# O/p:
# Tell me something, and I will repeat it back to you: tell me something
# tell me something
|
9600828491147fd3f81a71618a6bcfc46119f4ee | rduvalwa5/BasicPython | /Collections_List_src/mapped_dictionary_example.py | 1,085 | 3.53125 | 4 | '''
Created on Mar 15, 2016
@author: rduvalwa2
'''
class map_dictionary:
def __init__(self):
# self.t_name = t_name
self.name = {}
print(type(self.name))
def add_item(self,element, value):
self.name[element] = value
def print_tuple(self):
... |
a6fbe55c63c5cecdf621bac4ce1de4166507e52a | Kivike/nlp-project | /app/map/heat_map.py | 2,997 | 3.53125 | 4 | from pandas import DataFrame
import plotly.graph_objects as go
from enum import Enum
class MapboxStyle(Enum):
"""Enum value for mapbox styles.
"""
STAMEN_TERRAIN = "stamen-terrain"
OPEN_STREET_MAP = "open-street-map"
DARK = "dark"
CARTO_POSITRON = "carto-positron"
class HeatMap:
"""Simple ... |
b506089ffadcf5d310d4e0e0a937d4f32b203289 | Ruslan5252/all-of-my-projects-byPyCharm | /курсы пайтон модуль 7/задание 29.py | 250 | 3.765625 | 4 | def dva_chisla(*args):
a=int(input("a="))
b=int(input("b="))
if a%2==0 and b%2==0:
return a*b
elif a%2==1 and b%2==1:
return a+b
elif a%2==1 :
return a
elif b%2==1:
return b
print(dva_chisla())
|
15bd61b556f719421adb8dc46a239c37678b30ab | Logesh-vasanth101/jeya | /reversenum.py | 96 | 3.703125 | 4 | n1=int(input("Enter the number"))
d1=0
while(n1>0):
r1=n1%10
d1=d1*10+r1
n1=n1//10
print(d1)
|
705c522ed09a4e1dd8b783c4956f6bbb6537fc61 | brbbrb/python-challenge | /PyBank/main.py | 2,256 | 3.921875 | 4 | # PyBank
# Import the os module
# This will allow us to create file path to budget data
import os
# Import the module for reading csv files
import csv
# os.path.join would not work, so I had to use full CPU location
#csvpath = os.path.join('Resources','budget_data.csv')
csvpath = '/Users/bradleybarker/Documents/GT_B... |
a7e642bd72f6c4bb372a7c3ac3e4592e5dbc88db | knishant09/LearnPythonWorks_2 | /Hackerrank/sock_merchant.py | 660 | 3.84375 | 4 | from collections import Counter
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
print(ar)
print(n)
dict_1 = dict(Counter(ar))
print(dict_1)
print(dict_1.values())
# print(type(dict_1.values()))
# print(len(dict_1.values()))
#print(sum(dict_1.values()))
print(... |
41a515bdc66d89d4a70108e01fb57491c103fde0 | dundunmao/LeetCode2019 | /708. Insert into a Cyclic Sorted List.py | 1,022 | 4 | 4 | # Definition for a Node.
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
if not head:
node = Node(insertVal, None)
node.next = node
return node
... |
362d71f2c73c886573399edfde480c4d9abb2593 | Alexanderklau/Algorithm | /Everyday_alg/2021/06/2021_06_08/coin-change.py | 1,334 | 3.515625 | 4 | # coding: utf-8
__author__ = "lau.wenbo"
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
示例 2:
输入:coins = [2], amount = 3
输出:-1
示例 3:
输入:coins = [1], amount = 0
输出:0
示例 4:
输入:coins = [1], ... |
e87350eafa3570c11b2395ad889d816ced9aff0f | jdibble21/Random-Cipher | /cipher.py | 3,288 | 3.953125 | 4 | #/usr/bin/python3
from random import randrange
import time
import ast
keyMapperFile = "exampleKeyMap.txt"
def main():
print("=== Welcome to python cipher v0.1.0 ===")
userInput = ""
while(True):
print("\nCurrent encrypt/decrypt key mapper is: " + keyMapperFile)
userInput = input("\nChoose... |
0a57f38bdb9e7febcf6853b53a9c028e0fd0f303 | csws79/SummerStudy_Python | /0702 day1/day1.py | 318 | 3.890625 | 4 | A = raw_input("subject1: ")
a = input("score: ")
B = raw_input("subject2: ")
b = input("score: ")
C = raw_input("subject3: ")
c = input("score: ")
sum = a + b + c
aver = round(float(sum) / 3, 3)
print A + " " + str(a)
print B + " " + str(b)
print C + " " + str(c)
print "sum: " + str(sum)
print "average: " + str(aver) |
3c0d16d9135d9e582dfb13874726692af22daf8a | ChangHChen/python | /Introduction to Python/09(6.22)/1.py | 1,132 | 3.546875 | 4 | from tkinter import Frame, StringVar, Label, Entry, Button, TOP, LEFT, END
class CountDownTimer(Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.master.title("Count Down Timer")
self.time_left = StringVar()
Label(self, textvariable=self.ti... |
c88e4de0b4600ff390457d16e82d0b0a26a5b4d3 | notexactlyawe/microbit-snake | /snake.py | 3,011 | 4.3125 | 4 | from random import randint
from microbit import *
class Snake:
""" This class contains the functions that operate
on our game as well as the state of the game.
It's a handy way to link the two.
"""
def __init__(self):
""" Special function that runs when you create
a "Sn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.