blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
20b40fc8afd01b0d09b0c80997abd5d6549364ea | my13/fa_mbd_2015b | /H3.py | 4,765 | 3.640625 | 4 |
# coding: utf-8
# ### H.3) Human Assisted Binning
# Program will let user decide number of bins for each variable that should be binned, bin them and return the comparisons. It will not suggest the number of bins as this can be garnered from the automatic version of the program
#
# In[2]:
import pandas as pd
impo... |
f3169cd9441ce5e923cef3dc990365995e1be1a8 | tomatiks/course_tests | /tin_2019/2_count_letters.py | 301 | 3.875 | 4 |
def count_letters(s):
unique = set(s)
result = ''
for letter in unique:
if s.count(letter) > 1:
result += letter
return result
#assert sorted(count_letters('rtoplkghrtlkrtsazcvbcxwqx')) == ['c', 'k', 'l', 'r', 't', 'x']
s = input()
print(count_letters(s))
|
145096b2065f51ecef3fa821cc4999388a5fbfa4 | n02696438/ELSpring2016 | /code/myBlinkingLed.py | 478 | 3.625 | 4 | import RPi.GPIO as GPIO
import time
# set mode of GPIO and set up pin 17 as gpio output
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.OUT)
#blinks pin 17 led rapidly argument "blinks" number of times
def Blink(blinks):
for i in range(0,blinks):
GPIO.output(17,True)
time.sleep(.25)
GPIO.output(17,False)
... |
069ecf78bf7f2a455e754f0f147bb46d0e9765aa | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/109/15254/submittedfiles/decimal2bin.py | 243 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=input('Digite um número binário:')
a=0
b=n
while b>=1:
b=b/10
a=a+1
cont=0
for i in range (0,a,1):
u=n%10
c=(u*(2**i))
cont=cont+c
n=n//10
print (cont) |
c5ffe60cdb113df30598ed1cc1c30bbbdb08cfb2 | joyfulbean/Algorithms | /leetcode/Hash/LOW/jewls-stones.py | 440 | 3.5625 | 4 | # https://leetcode.com/problems/jewels-and-stones/
class Solution(object):
def numJewelsInStones(self, jewels, stones):
"""
:type jewels: str
:type stones: str
:rtype: int
"""
# a, A
result = 0
for char in jewels:
result += collections.Cou... |
b0b8a33d0f46684943333ed83578c4064a8e402c | 2XL/Python4Everyone | /tiposbasicos/__init__.py | 1,663 | 4.125 | 4 | # tipos: entero/coma flotante/ complejos/ strings/ booleans
# esto es una cadena
c = "Hola Mundo"
# y esto es un entero
e = 21
# podemos comprobar con la funcion type
print type(c)
print type(e)
# type (enteros) devolveria int
entero = 23
enteroL = 21L
print type(enteroL)
# asignacion ocatal
# 027 octal = 23 en de... |
27b6ce0eeaaacea45fde431ee739c8da81db6a99 | mangalagb/Leetcode | /Easy/AddStrings.py | 1,967 | 4.03125 | 4 | # Given two non-negative integers num1 and num2 represented as string,
# return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or... |
e67e093fc55269facf58a3a0b7ad0d421f6e7a4e | Sumeet1601/a-program-to-print-table-of-the-given-number-in-python- | /Table_of_a_bumber.py | 102 | 3.9375 | 4 | num=int(input("enter a number="))
sum=0
for i range(1,11):
sum=num*i
print(num,"*",i,"=",sum)
|
f1be4196df1bfcbed5256489a6c56ac17ac1b8d3 | Bernishik/universityAlgorithms | /lab1/main.py | 747 | 3.90625 | 4 | from Tree import Node, create_tree, show_tree_before, PrefixOrder, show_tree,\
PostfixOrder, InfixOrder,SearchNodeBST,InsertNodeBST,DeleteNodeBST,topview
if __name__ == '__main__':
tree = None
# tree =create_tree(tree,5)
# print("Create tree:")
# show_tree(tree)
# print()
# PrefixOrder(tree... |
60b41a859968073a08855480ddba699d857d7bd7 | hsiaohan416/stancode | /SC_projects/image_processing/stanCodeshop_basic/green_screen.py | 1,379 | 3.578125 | 4 | """
File: green_screen.py
-------------------------------
This file creates a new image that uses
MillenniumFalcon.png as background and
replace the green pixels in ReyGreenScreen.png
"""
from simpleimage import SimpleImage
def combine(background_img, figure_img):
"""
:param background_img:
:param figure... |
75f9c292acae8fa96ab751efff72bcff35467ace | aphexer/sewer | /sewer/dns_providers/common.py | 4,091 | 3.65625 | 4 | from hashlib import sha256
from sewer.auth import BaseAuthProvider
from sewer.lib import safe_base64
def dns_challenge(key_auth: str) -> str:
"return safe-base64 of hash of key_auth; used for dns response"
return safe_base64(sha256(key_auth.encode("utf8")).digest())
class BaseDns(BaseAuthProvider):
de... |
d61d917569b2c6bdb455d288ff5ab6fe01beeda3 | zhaolijian/suanfa | /swordToOffer/64.py | 1,420 | 3.546875 | 4 | # class Solution:
# def maxInWindows(self, num, size):
# queue, res, i = [], [], 0
# while size > 0 and i < len(num):
# if len(queue) > 0 and i - size + 1 > queue[0]:
# queue.pop(0)
# while len(queue) > 0 and num[queue[-1]] < num[i]:
# queue.po... |
c61e6143061d5d4dcb8a876eb8756bbea422598d | 51ngularity/custom-modules | /python/list_operations.py | 438 | 3.75 | 4 |
from collections import deque
#make single value list with .popleft ability
def single_value_list(value_list, length_list):
list_temp = deque([])
for x in range(0, length_list):
list_temp.append(value_list)
return list_temp
# update list: new element in, last element out
de... |
52aefb8ad14d9aa4b242047a17d72390f450c366 | Isaac-Tolu/code-snippets | /swapdict.py | 847 | 4.5625 | 5 | def swapdict(dict_: dict) -> dict:
"""
Swaps the keys and values of a dictionary.
Returns a new dictionary.
- If any of the values of dict_ is unhashable i.e list or dict,
the key-value pair would be ignored.
- If multiple keys in dict_ have the same value,
the keys would be a list in ... |
dbb0177df1027fc102f89ed636e2b17ad72eb4af | anjalisgrl/MyCaptain | /fibonacci.py | 290 | 4.0625 | 4 | a=0
b=1
n=int(input("Enter the number of terms:"))
if n<0:
print("Input invalid")
elif n==1:
print(a)
else:
print("The fibonacci sequence is: ")
print(a, b , end=" ")
for n in range (0,n):
c=a+b
a=b
b=c
print(c ,end=" ")
|
93b9e41e38bef06e2804716cf9ed1ec278fea03b | chazkiker2/code-challenges | /misc/return_next_number/return_next_number.py | 285 | 3.921875 | 4 | """
Challenge: Create a function that takes a number as an argument, increments the number by +1 and returns the result.
Difficulty: Very Easy
Examples
addition(0) ➞ 1
addition(9) ➞ 10
addition(-3) ➞ -2
Author: @joshrutkowski
"""
def addition(num):
pass # Your code here
|
f5561436ae0bd60044bf4d702919d564e58c9095 | ltzp/LeetCode | /字符串/LeetCode1002_查找常用字符.py | 1,733 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/10/14 0014 18:26
# @Author : Letao
# @Site :
# @File : LeetCode1002_查找常用字符.py
# @Software: PyCharm
# @desc :
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
... |
be23f75f33ac7f59bfb10d2de765897376a36a83 | bdt-group01/bdt | /Apriori algorithm/reducer2.py | 510 | 3.609375 | 4 | #!/usr/bin/env python
import sys
# input : "count,item1,item2,...,itemi+1"
# output : "count,item1,item2,...,itemi+1"
def readLine(line):
numbers = line.strip().split(',')
lineData = [int(number) for number in numbers]
count = lineData[0]
data = lineData[1:]
return count, data
for line in sys.... |
3ffe263aae624dfffe25b3b7a448096d8a98e2f6 | pppk520/miscellaneous | /ib/level_5/hashing/equal.py | 1,572 | 3.75 | 4 | '''
Given an array A of integers, find the index of values that satisfy A + B = C + D, where A,B,C & D are integers values in the array
Note:
1) Return the indices `A1 B1 C1 D1`, so that
A[A1] + A[B1] = A[C1] + A[D1]
A1 < B1, C1 < D1
A1 < C1, B1 != D1, B1 != C1
2) If there are more than one solutions,
th... |
8ae7ce27147fe574b5eb9bb4f6fa6213c42eb419 | GongFuXiong/leetcode | /topic10_queue/T621_leastInterval/interview.py | 2,527 | 3.578125 | 4 | '''
621. 任务调度器
给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 :
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
... |
b8abfe2c722bcfac9f723ca6a81fe6bc1f261159 | andrew-yarmola/python-course | /solutions/homework-3/primes.py | 1,993 | 4.4375 | 4 | def primes_less_than(n) :
""" Given an integer n, returns the list of primes less than n. """
if type(n) is not int or n < 3 : return []
# We use a sieve algorithm to
# elimiane all multiples of
# numbers in increasing order
primes = [2]
sieve = list(range(3,n,2)) # all odds less than n
... |
3a86b75997c9cd42341a2b0e2b17db8ad6bd4e25 | reallybigmistake/hello-world | /gui6.py | 658 | 3.53125 | 4 | from tkinter import *
from sys import exit
class Hello(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
self.data = 42
self.makeWidget()
def makeWidget(self):
widget = Button(self, text='Hello frame world', command=self.messag... |
6de77eb4a33a0818328c47647dd1bd8a1fa6ade9 | RawitSHIE/Algorithms-Training-Python | /python/Mountain Demmyeiei.py | 255 | 4.03125 | 4 | """Mountain Demmyeiei"""
def main():
"""ar rai mai ru"""
raw = float(input())
size = int(raw)
for i in range(1, size*2, 2):
for _ in range(size-1):
print(("*"*i).center(size*2), end="")
print(("*"*i).center(size*2))
main()
|
5b5aec4ffbdaedb3e3f222dbd721d561b1c17dc0 | MattChale123/Python-102 | /Phone_Book_App.py | 1,514 | 4.09375 | 4 | import time
phone_book_entries = {
'Melissa': '584-3934-5857',
'Igor': 'You do not contact Igor, Igor contacts you',
'Jazz': '334-584-2345',
}
def phone_book_function(phone_book_entries):
user_input = input('Would you like to: Search, Add, Delete, List All Entries, or Quit? )').lower()
... |
aeabe885c36864264c38b80b723db83852992e6d | gustavo-mota/Artificial_Intelligence_Playground | /NRainhasFormigueiro/NRainhas_Fixo/Roleta.py | 1,098 | 3.703125 | 4 | import random
'''
01. var pesos[10]:int = {1,1,1,1,2,3,4,5,5,5};
02 var somaPeso:int = 0;
03. PARA var i=0 ATE 9 FAÇA
04. somaPeso+=pesos[i];
05. FIMPARA
06. var sorteio:INT = ALEATORIO(0,somaPeso);
07. var posicaoEscolhida = -1;
08. FAÇA:
09. posicaoEscolhida++;
10. somaPeso -= pesos[posicaoEscolhida];
11. E... |
95b28f33c20cbb6bd849b683bc4d13dc608961d1 | WhosKhoaHoang/db_solid | /hud.py | 2,963 | 3.5 | 4 | #Contains the class that represents a HUD.
import pygame
from colors import *
class HUD(pygame.Surface):
'''A class that represents the HUD for Snake.'''
def __init__(self, width, height, snake):
'''Initializes the attributes of a HUD object.'''
pygame.Surface.__init__(self, (width, heigh... |
56e024fb42801acf7fd62dc5063d69669cb2c474 | LGiave/TPSIT | /Python/Es_vari/Es_11 copy.py | 957 | 3.625 | 4 | import random as rnd
def push(stack,element):
stack.append(element)
return stack
def pop(stack):
element = stack.pop()
return stack,element
def coppaMazzo(stack):
pos=rnd.randint(0,len(stack)-1)
stack = stack[pos:len(stack)] + stack[0:pos]
return stack
def shuffle(stack):
stack1=[]
... |
eaa4368a796ffd3c034304dad9855f23579039d9 | SaiSudhaV/coding_platforms | /remove_nth_node_from_end.py | 675 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def removeNthFromEnd(self, A, B):
tem, res ... |
afe3e5614b6dc66a879029a650fbc6b37c73df92 | wai030/Python-project | /wolfs_goats_cabbages.py | 5,884 | 3.734375 | 4 | import copy
#Missionaries and Cannibals (Missionaries and Cannibals)
#######################
## Data Structures ####
#######################
# The following is how the state is represented during a search.
# A dictionary format is chosen for the convenience and quick access
LEFT=0; RIGHT=1; BOAT_POSITI... |
0728e135bdbaaa89ecf243db145ead9645a8c362 | jc003/datascience_yeah | /notes/lecture2/notes.py | 253 | 3.890625 | 4 | ### LECTURE 2 CODE NOTES ###
n = 100
%cpaste
for x in range(100000000):
print(n)
if n % 2 == 0:
#n is even
n = n / 2.0
elif n % 2 == 1:
n = n * 3 + 1
if n == 1:
break;
--
4 2 1
|
195b251226e10cb5afa2103ad0360b18ff434b5d | KamiMoon/python | /crash-course/ch2/strings.py | 360 | 3.875 | 4 | name = "ada lovelace"
print(name.title())
# Ada Lovelace - titlecase
print(name.upper())
print(name.lower())
#concatenation uses +
first_name = "ada"
last_name = "loveland"
full_name = first_name + " " + last_name
print(full_name)
# \t \n work the same
# trim using rstrip(), lstrip, and strip()
favorite_lanague... |
2c19d4a96328c69cfde86a7f44c218c554e037d6 | joanvaquer/SDMetrics | /sdmetrics/report.py | 8,727 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""MetricsReport module.
This module defines the classes Goal, Metric and MetricsReport, which
are used for reporting the results of the different evaluation
metrics executed on the data.
"""
from enum import Enum
import pandas as pd
class Goal(Enum):
"""
This enumerates the `goal`... |
c4493af7958e4dce4e45a92803e09c92d624bb2f | Aasthaengg/IBMdataset | /Python_codes/p03262/s772435440.py | 303 | 3.578125 | 4 | import math
from functools import reduce
def gcd(*numbers):
return reduce(math.gcd, numbers)
def gcd_list(numbers):
return reduce(math.gcd, numbers)
N, X = map(int, input().split())
if N>1: x = [int(_)-X for _ in input().split()]; print(gcd_list(x))
else: x = int(input()) - X; print(abs(x))
|
021e08f279a91503133e71909a6ec0a12bfb08e1 | george-marcus/problems-vs-algorithms | /Search in a Rotated Sorted Array/rotated_array_search_tests.py | 741 | 3.609375 | 4 | from rotated_array_search import rotated_array_search
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_searc... |
0225879ee2e3dd7cd3aae9d537a577c1bcd30f91 | avantika0111/YouTube_Video_Downloader | /downloader.py | 543 | 3.546875 | 4 | from pytube import YouTube
"""
streaming all the formats available for download
"""
link = input("Enter Video URL: ")
yt = YouTube(link)
videos = yt.streams.all()
video = list(enumerate(videos))
for i in video:
print(i)
print("Select download format: ")
dn_option = int(input("Enter the number: "))
try:
... |
2c24b086da29869121c4cef26f119195207f0f2e | Miktus/Dissertation | /DSGE_estimation/DSGE/Kalman.py | 5,477 | 3.5 | 4 | """
Implements the Kalman filter for a linear Gaussian state space model.
"""
import numpy as np
from numpy import dot
from scipy.linalg import inv
from textwrap import dedent
class Kalman:
"""
Implements the Kalman filter for the Gaussian state space model
.. math::
x_{t+1} = A x_t + C w_{t+1} \\... |
6c96e894d8d868a81f6c3abe03814b943029cd64 | erchauhannitin/prod-reports | /readobject.py | 788 | 3.6875 | 4 | class Entry(object):
def __init__(self, NAME, ID, ROLES, STATUS):
super(Entry, self).__init__()
self.NAME = NAME
self.ID = ID
self.ROLES = ROLES
self.STATUS = STATUS
self.entries = []
def __str__(self):
return self.ID + " " + self.ROLES + " " + self.STATU... |
19e2d5628966c452305b3f6630f1f7128afaf4ba | jiadaizhao/LeetCode | /1301-1400/1352-Product of the Last K Numbers/1352-Product of the Last K Numbers.py | 573 | 3.75 | 4 | class ProductOfNumbers:
def __init__(self):
self.product = [1]
def add(self, num: int) -> None:
if num == 0:
self.product = [1]
else:
self.product.append(self.product[-1] * num)
def getProduct(self, k: int) -> int:
if k >= len(self.product... |
fc51c4001e6b351ab1ef5776015f1372700383e8 | AdityanJo/Leetcode | /problem_0234_palindrome_linked_list.py | 565 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None: return True
if head.next is None: return True
curr = head
... |
8c62cd7c8d8aaf4b6577f19f14c5c7260a4f40c8 | Faizz79/Python-project-Protek | /Praktikum 9/C9_project 04,faiz.py | 313 | 3.796875 | 4 | #project 4
import random
def shufflestring(kata, n):
listkata = []
while (len(listkata) < n):
acakkata = random.sample(kata, len(kata))
acakurut = ''.join(acakkata)
if(acakurut not in listkata):
listkata.append(acakurut)
print(listkata)
shufflestring('kamu', 7)
|
1d3c5df04a52d231b843c5301c06003b36009576 | miradouro/CursoEmVideo-Python | /aula007 - OPERADORES ARITMETICOS/aula007.py | 274 | 4.03125 | 4 | n1 = int(input('Digite um numero: '))
n2 = n1 - 1
n3 = n1 + 1
print('seu numero é o {}, ele vem depois do numero {} e vem antes do numero {}!'.format(n1, n2, n3))
print('O dobro do seu numero é o {}, o triplo é {} e a raiz quadrada é {}!'.format(n1*2, n1*3, n1**(1/2)))
|
8746feaa87e972879318a2f3afb38e4883847471 | zitorelova/python-classes | /sum.py | 276 | 3.9375 | 4 | def sum(arr):
total = 0
for element in arr:
total = total + element
return total
def sum(arr):
total = 0
if len(arr) > 0:
total = arr[0] + sum(arr[1:])
else:
return 0
return total
test = [1, 2, 3, 4]
print(sum(test)) |
4aaac230de4ad2e5bb06a2f7514c3ef1a4beb125 | mttaborturtle/Image-converters | /JPGtoPNGconvert.py | 997 | 3.765625 | 4 | import sys
import os
from PIL import Image
# Take in the image folder/image and the dest folder
# from the command line
image_folder = sys.argv[1]
dest_folder = sys.argv[2]
# Check to see if the destination folder already
# exists and create it if it does not
try:
if os.path.isdir(dest_folder) == False:
... |
5b8592c2c7ed423e99a3eee42b31358dd2b3dc71 | nevepura/python3 | /hardway/ex37.py | 937 | 3.6875 | 4 | ''' Symbol review '''
# assert
def my_assert():
value = 12
treshold = 10
assert value <= treshold, "Value > treshold not allowed: {} > {}".format(value, treshold)
print(isinstance(value, int))
def my_excepion():
print("Exception management starts...")
try:
number = int(input('input a... |
683b52f2f49a93b3df53d52457845bcab80608bd | krimeano/euler-py | /problem504.py | 2,936 | 4 | 4 | """
Let ABCD be a quadrilateral whose vertices are lattice points lying on the coordinate axes as follows:
A(a, 0), B(0, b), C(−c, 0), D(0, −d), where 1 ≤ a, b, c, d ≤ m and a, b, c, d, m are integers.
It can be shown that for m = 4 there are exactly 256 valid ways to construct ABCD. Of these 256 quadrilaterals,
42 o... |
1dc765de9c28d6114a3a43975f80e82a3b398406 | cloew/WiiCanDoIt-Framework | /src/BinaryTreeGame/TwoTeamVersusScreen.py | 3,366 | 3.515625 | 4 | import sys, os
import pygame
from pygame.locals import *
from GameboardClass import *
SCREEN_SIZE = (1152, 864)
BACKGROUND = (235,240,255)
""" Builds the screen for the Two Team Versus Mode game """
class TwoTeamVersusGameScreen:
""" Builds both gameboards and adds their allsprites to the screens allsprites """... |
8e089aec92d6010b5c764c31e53b42bc3f47f3d3 | 418003839/TallerDeHerramientasComputacionales | /Clases/Programas/Tarea4/Problema1.py | 244 | 3.703125 | 4 | # _*_ coding utf-8 _*_
def euc(num1, num2):
if num2 == 0:
return num1
return euc(num2, num1 % num2)
num1 = int(input("Anota el número menor"))
num2 = int(input("Anota el número mayot"))
print("El MCD es:", euc(num1, num2))
|
b304fbb3269e80704e60f478a0b33b9ae833b856 | Ajay6533-hacker/my_python_tutorial | /firstfrog/stringslicing and method.py | 649 | 4.40625 | 4 | str1 = "this is a string and her sometypes of functions"
# str1 = "this" , "is" , "a " ,"string", "and", "her"," sometypes", "of", "functions "
# str1 = "this ,is, a, string, and, her, sometypes, of, functions "
# str1 = "thisisastringandhersometypesoffunctions"
print(str1[0:8])
# print(str1[0:20:2])
# print(str1[0:])... |
ea972532545ead192edd5d49d0ce1bef22d0ae11 | AndreaBruno97/AdventOfCode2020_python | /day_03/puzzle_1.py | 552 | 3.75 | 4 | ''' Open file '''
filename = 'input.txt'
with open(filename) as f:
content = f.readlines()
trees = 0
current_x = 0
module = len(content[0][:-1])
slope = 3
for line_dirty in content:
''' The last character is \n, so it must be removed '''
line = line_dirty.replace("\n", "")
trees += (line[current_x] ... |
d1c1b77bd395ae006cde976817c8a8599a96cfce | timtadh/crypt_framework | /qcrypt.py | 2,211 | 3.65625 | 4 | #methods for AES encryption of stream
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import os
def create_aes_key():
sha256 = SHA256.new()
sha256.update(os.urandom(64))
for x in xrange(5000): sha256.update(sha256.digest())
return sha256.digest()
def pub_decrypt(ciphertext, key):
try... |
dca43c14024ec1e5183179e300f0fddca72e112a | palabandladileep/python | /hello.py | 1,529 | 4.1875 | 4 | #question 1 ,2
num1 = int(input("Enter the first number"))
num2 = int(input("enter the second number"))
num3 = int(input("enter the third number"))
def find_largest():
if(num1 > num2):
if(num1 > num3):
largest = num1
else:
largest = num3
elif(num2 > num3):
lar... |
234478e7dbde6f941d5524029bf5e0ee369fb5f8 | devpilgrin/computer-vision-algorithms | /computer-vision/gauss.py | 1,685 | 3.59375 | 4 | """Apply gaussian filters to an image."""
from __future__ import division, print_function
from scipy import signal
from scipy.ndimage import filters as filters
import numpy as np
import random
from skimage import data
import util
np.random.seed(42)
random.seed(42)
def main():
"""Apply several gaussian filters one ... |
dc3134099a74c5d207fbc186134c460300816732 | sakshi9401/python-files | /arithmatic operations.py | 252 | 3.90625 | 4 | print("enter two numbers")
n1 = input()
n2 = input()
print("sum of two no, is",int(n1)+int(n2))
print("multiplication of two no. is",int(n1)*int(n2))
print("division of two no. is",int(n1)/int(n2))
print("modulus of two no. is",int(n1)%int(n2))
|
37bb37542f107209e4c7f67e2478ffb9ac92b879 | zzh730/LeetCode | /String/Reverse words in a String.py | 878 | 3.609375 | 4 | __author__ = 'drzzh'
"""
one pass without split();
Trick is to keep track of when the word starts and ends,
use substring(i,j) to append
Watch out for the base case:
1)one word
2)no whitespace in head
3)last whitespace in the result
"""
class Solution:
# @param s, a string
# @return a string
d... |
0ef6f218241ba83ec96f958100d068fcb979459c | tzhou2018/LeetCode | /arrayAndMatrix/566matrixReshape.py | 770 | 3.8125 | 4 | '''
@Time : 2020/3/8 16:31
@FileName: 566matrixReshape.py
@Author : Solarzhou
@Email : t-zhou@foxmail.com
'''
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
... |
bd21d58371b3ae3d56e10bd7f8d63241e24fa5e8 | leskeylevy/IntelTest1 | /RSA.py | 1,092 | 3.9375 | 4 | " RSA is a public-key encryption asymmetric algorithm and the standard for encrypting information transmitted via the internet. RSA encryption is robust and reliable because it creates a massive bunch of gibberish that frustrates would-be hackers, causing them to expend a lot of time and energy to crack into systems"
... |
1cc6ccb0b0827e153134978974d9ba5b01e12663 | saleh99er/LeetcodePractice | /Problem1689/Solution.py | 1,375 | 3.984375 | 4 |
"""
Problem 1689: Partioning into min number of Deci-Binary Numbers
a decimal number is called deci-binary if each of its digits is either 0 or 1
without any leading zeros. For example, 101 and 1100 are deci-binary, while
112 and 3001 are not. Given a string n that represents a positive decimal
integer, return the... |
46c4e070b7c9b2b7cee7441c848cb376b5da254a | JustATester123/learnPython | /dir1/test.py | 789 | 3.5625 | 4 | name=['abc','qwe','rty']
def normalize(name):
def zhuanhuan(s):
return str.upper(s[0]) + str.lower(s[1:])
return list(map(zhuanhuan,name))
print(normalize(name))
from functools import reduce
DIGITS ={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2float(s):
def char2num(c):
... |
d9b0dd26cdc8220242c13c2597d8fa9ce11fdacc | TranLuongBang/HackerRank_Python | /scripts.py | 28,612 | 4.0625 | 4 |
# Tran Luong Bang - bangtranluong195@gmail.com
# ADM - HW1
#---------------------------------------------------------------------------------------------------------------
# Problem 1
# A. Introduction total: 7/7
# 1. Say "Hello, World!" With Python
print("Hello, World!")
# 2. Python If-Else
import math
import os
... |
7fa5c5f9392834557627d91c898fe1abc2a257da | andrilor/riskFactors | /hw6/riskFactors.py | 1,695 | 3.53125 | 4 | import csv
import string
def openfile(file_name):
try:
ls = []
with open(file_name, newline="", encoding='utf-8') as dataFile:
readCSV = csv.reader(dataFile)
for row in readCSV:
ls.append(row)
return ls
except FileNotFoundError:
print("Cann... |
1ab1466c6e8e8f21c74b4b994e063e2bca41ef56 | hongdonghyun/Project | /09.function/arguments.py | 531 | 3.96875 | 4 | def make_student(name,age,gender):
return {
'name' : name,
'age' : age,
'gender' : gender
}
def print_student(student):
for key,value in student.items():
print('{} : {}'.format(key,value))
s1 = make_student('hongdonghyun',27,"남성")
print_student(s1)
# m... |
a1512417f04def396e74338274538865a4b31887 | lawson0628/python200804 | /day2.2.py | 206 | 3.59375 | 4 | n=int(input('請輸入一個數來判別它是否為質數'))
c=2
while c<n:
if n%c==0:
print('不是質數')
break
c+=1
if c==n:
print('是質數')
|
46bb20a0e813834357687f4efc537e8238df9d20 | klknet/geeks4geeks | /algorithm/searchsort/linklist_merge_sort.py | 2,157 | 4.125 | 4 | # Merge sort for doubly link list
class LinkedList:
def __init__(self):
self.head = None
def push(self, v):
node = Node(v, None, self.head)
if self.head is not None:
self.head.prev = node
self.head = node
def merge_sort(self, temp_head):
if temp_head is ... |
c1363ba5759147172d52336d062cc7fed12b170e | kinow/python-dependency-injector | /examples/providers/overriding_simple.py | 783 | 3.796875 | 4 | """Simple providers overriding example."""
import dependency_injector.providers as providers
class User:
"""Example class User."""
# Users factory:
users_factory = providers.Factory(User)
# Creating several User objects:
user1 = users_factory()
user2 = users_factory()
# Making some asserts:
assert user1 is n... |
164bcc66f31595d93c63b1acdfa439aa3cfd09fb | neesh7/Neesh_Python_Dictionaries | /dictionary3.py | 1,418 | 4.8125 | 5 | # like key method we can also use value method in order to get a list of values
fruit = {"Orange": "a sweet, oranges, citrus fruit",
"grapes": "a small, sweet fruit, grows in bunches",
"Mango": "Nice shape,Beautiful, so juicy",
"lemon": "citrus fruit , so juicy , so sour, women likes lemon",
... |
abc835c96cfb6837d3871ffb004535c9bebaa1eb | js837/project-euler | /1-100/30/digits.py | 254 | 3.734375 | 4 | def isPower(n,power):
t=n
tot=0
while t>0:
dig=t%10
tot=tot+dig**power
#print tot
t=(t-dig)//10
if n==tot:
return True
else:
return False
sum=0
for n in xrange(10,1000000):
if isPower(n,5):
sum=sum+n
print sum
|
e0195581775916fa9a1e57f130f2989872d3f305 | greeshmasunil10/Word-Guessing-Game | /guess.py | 4,619 | 3.703125 | 4 | '''
Created on May 19, 2019
@author: Greeshma
'''
from msvcrt import getch
class guess(object):
def __init__(self):
self.gameobjects=[]
def _newgame(self):
self.gobj= game()
base=stringDatabase()
base._readwords()
self.gameword= base._loadword()
s... |
497bf3093130858b422dbb8040baa1c7c11a8e69 | coremedy/Python-Algorithms-DataStructure | /Python-Algorithms-DataStructure/src/general_problems/string/count_unique_words.py | 808 | 3.828125 | 4 | '''
Created on 2014-12-13
Copyright info: The code here comes, directly or indirectly, from Mari Wahl and her great Python book.
I'm not the original owner of the code.
Thanks Mari for her great work!
'''
import string
def count_unique_word(file_name):
words = dict()
... |
1d52f2b34bba51ae04f633b2f0df658c4e7475ab | angelorohit/tictactoe_python | /game/game_board.py | 2,606 | 3.59375 | 4 | from typing import Optional
import numpy as np
from game.player import Player
class GameBoard:
def __init__(self, size: int = 3):
self.empty_cell_symbol = '-'
self.clear(size)
def gather_board_size(self):
size = input(
'Enter a game board size between 3 and 9 (inclusive)... |
2f71c033d7132a203e3017effce9558c636c0836 | mdezylva/coursera | /machine-learning-ex1/python/computeCost.py | 309 | 3.828125 | 4 | def compute_cost(X,y,theta):
'''
Compute cost for linear regression
J = COMPUTECOST(X, y, theta) computes the cost of using theta as the parameter for linear regression to fit the data points in X and y
'''
# Initialise some useful values
m = length(y)
h_theta = X*theta
|
04896f127475d2054d644634a2e5519daa1bdab2 | ilia-makhonin/python-simple-example | /python-math-master/power_recurs.py | 127 | 3.578125 | 4 | def power_recurs(num, pow):
if pow == 1:
return num
result = num * power_recurs(num, pow - 1)
return result |
388570282788ce6ff456a70e35d263b94cb7af89 | wliu24/creative-cooking | /ingredients-image-detection/ingredients-prediction-with-preprocessing.py | 4,138 | 3.734375 | 4 | #!/usr/bin/env python3
# Making single image predictions
# use: python3 (y or n for using preprocessing) file_path
def preprocess_background(input_img):
'''
This function preprocesses an image based on cv2.
It tries to remove the background of an image.
The intention is to make then prediction easier ... |
3f1aa6741fc6e9b978eb57c53ca507827e44fc0a | luixeiner/semana-8 | /problema8.py | 170 | 3.71875 | 4 | num = 0
suma = 0
n = int(input("ingrese un numero"))
for i in range(1, n):
if num % i ==0:
suma = num
print ("perfecto")
else:
print("no perfecto")
|
d094983a5e2e43a42bd7ef84b5109c227e1a0e37 | juraj80/myPythonCookbook | /days/10-12-testing-your-code-with-pytest/sample_tests/107_filter_numbers_with_list_comprehension/test_list_comprehension.py | 507 | 3.515625 | 4 | from list_comprehension import filter_positive_even_numbers
def test_filter_positive_and_negatives():
numbers = list(range(-10,11))
expected = [2, 4, 6, 8, 10]
actual = filter_positive_even_numbers(numbers)
assert expected == actual
def test_filter_only_positives():
numbers = [2, 4, 51, 44, 47, 10... |
1ebc27af1ae880611a317b0641d0b01682ed0d97 | loumatheu/ExerciciosdePython | /Mundo 1/Exercicio19.py | 937 | 3.6875 | 4 | from random import choice
import emoji
cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m',
'lilas':'\033[1;35m', 'amarelo':'\033[1;33m', 'verdepiscina':'\033[1;36m'}
print(f"""{cores['azul']}====================================================================
... |
572e3360307f2fe1290a6903eb1642352ea7976e | connordittmar/avoidance | /avoidance/logic_motion.py | 2,904 | 3.6875 | 4 | from bin import gpsutils
from math import sqrt, sin, cos, atan2
def diff_dist(obj1,obj2):
if len(obj1)==2:
calc_dist = sqrt( abs(obj1[0]-obj2[0])**2 + abs(obj1[1]-obj2[1])**2 )
return calc_dist
elif len(obj1)==3:
calc_dist = sqrt( abs(obj1[0]-obj2[0])**2 + abs(obj1[1]-obj2[1])**2 + abs(... |
dc8bdc5cd8ef7aab8d4d154fa62197fb7f0fddc4 | PytlaaS/Python-Project-Spring-2019 | /test 4.py | 1,508 | 3.703125 | 4 | from random import choices
def main():
print("Bienvenue au Jeu du juste prix, vou connaisez le concept")
print("Choisissez un chiffre compris entre 0 et 1000")
print("Une fois que Gustave aura choisie, vous pourrez essayer de trouver le meme que lui")
number = list(range(0, 1001))
Gustav =... |
1a6b9a8f5b07cf710026ffef89e4f6aacbc546ca | rexhzhang/LeetCodeProbelms | /TwoPointers/TwoSumUniquePairs.py | 1,252 | 3.953125 | 4 | """
Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target
number. Please return the number of pairs.
Have you met this question in a real interview? Yes
Example
Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47
2 + 45 = 47
"""
... |
80df1078bb9763c68e4b01366171cea80168632c | Argton/ProblemsFromWebsites | /CyclicRotation.py | 558 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 22:35:46 2018
This programs takes a list A an rotates every element by one position,
K times.
@author: Anton
"""
def CyclRot(A, K):
if len(A)==0 or K==0:
return A
else:
for nbrOfTurns in range(0, K):
tempArr=[]
... |
ebae29093f8063cbfd72d5fe813c00e468ae9355 | stephenjayakar/problems | /reverseWords.py | 927 | 4.125 | 4 | # reverses the words in the string in place
def reverseWords(s: str) -> str:
s = list(s)
N = len(s)
# first reverse string's characters
i, j = 0, N - 1
reverseSubstring(s, i, j)
i, j = 0, 0
reverse = False
# for each word, reverse it
for index in range(N):
if s[index] == ' ' ... |
01d1925672fb5a4604e4ef5e6a4c2fea85420979 | wasimashraf88/Python-tutorial | /argr_kwargs.py | 922 | 3.921875 | 4 | # # Arbitrary Arguments or *args
# def my_func(*kids):
# print("The youngest child is:",kids[3])
# my_func("Emil", "Tobias","Sara","Nib")
# # Keyword Arguments
# #You can also send arguments with the key = value syntax.This way the order of the arguments does not matter.
# def my_func1(child1,child2,child3):
... |
6a9325dbc0099b786556cac12e463220f08be518 | bi0kemika21/tweet | /app/loy.py | 500 | 3.609375 | 4 | from datetime import datetime
from apscheduler.scheduler import Scheduler
import time
# Start the scheduler
sched = Scheduler()
sched.start()
@sched.interval_schedule(seconds=5)
def job_function():
return fun()
def fun():
print "Loloy"
# Schedule job_function to be called every two hours
#sched.add_interval... |
f73ce622037d91e15b1d9068928b5d6273d86dd2 | Mark-Zhang-007/python_from_Liao | /exercise/函数式编程/高阶函数/mapreduce.py | 1,263 | 3.5 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
def normalize(name):
name = str.lower(name)
return name.capitalize()
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
def prod(L):
return reduce(lambda x, y: x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([... |
708998f496192a5d4d89f3dafcc4499908f17a2c | BasilBibi/Coursera_Python | /test/exceptions/test_exceptions.py | 3,878 | 3.796875 | 4 | import unittest
import traceback
from coursera_python.exceptions.ManagingFailure import *
class ManagingFailureTests(unittest.TestCase):
def test_00_basic_try_except_finally_none_failing(self):
try:
print('test_00_basic_try_except_finally_none_failing TRY')
n = int('0')
... |
61cdb6e7729e8e0acf90b1b2c94100766c9e2dd4 | arteev/stepik-course-python | /week-3/week-3-2-step7.py | 150 | 3.59375 | 4 | d = dict()
for x in [int(input()) for x in range(int(input()))]:
if x in d:
print(d[x])
else:
d[x] = f(x)
print(d[x])
|
f884c61a4f49a88af21de0421c275c7d9aa87cb3 | IslaMurtazaev/PythonApplications | /MIT/searchingSorting.py | 1,921 | 4 | 4 | # BUBBLE SORT
def bubbleSort(L):
'''
Because of the two nested loops (which can possibly be of linear complexity O(n))
fns's order of growth is O(n^2)
'''
swap = False
while not swap: # by the end of first loop, I'm sure that the biggest e is at the end -> O(n)
swap = True
... |
18ac9f285c54b7127b67f2e8a4ed4077ebe46c7b | robinfelix/coding-algorithms | /algorithms/sorting_algo/selection_sort.py | 484 | 3.6875 | 4 | '''
O(n^2)
selection sort can be used when min number of swaps is required
'''
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
j = i + 1
# print(len(arr[j:]))
while j < len(arr):
if arr[min_idx] > arr[j]:
min_idx = j
j += 1... |
90ca1e2800d837333115c5ad021b0d08e579a562 | wilbertgeng/LintCode_exercise | /BFS/788.py | 2,516 | 4.09375 | 4 | """788. The Maze II
"""
class Solution:
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: the shortest distance for the ball to stop at the destination
"""
def shortestDistance(self, maze, start, destination):
# write your code here
... |
68f710e132605c543b0172a2047a888972896267 | peitruthxxx/learning_log_python | /estimate.py | 867 | 4.03125 | 4 | import math
def cal(x ,a):
y = (x + a/x) / 2
return y
def main():
a = float(input("Enter a value to find square root: "))
x = 3.0
prev = 0
curr = cal(x, a)
while abs(prev - curr) > 0.0000001:
print(curr)
prev = curr
curr = cal(prev, a)
print(curr)
... |
543a75494783ae3e5a2b559ec15611941bf8ea8f | paulm29/tkinter-tutorial | /3-widgets/widget_table.py | 395 | 3.609375 | 4 | from tkinter import *
from tkinter.ttk import *
root = Tk()
tree = Treeview(root)
tree["columns"]=("one","two")
tree.column("one", width=100 )
tree.column("two", width=100)
tree.heading("one", text="coulmn A")
tree.heading("two", text="column B")
tree.insert("" , 0, text="Line 1", values=("1A","1b"))
tree.insert... |
85d1e75364d2924540a6e5236d10fdc744cb2b88 | hercilioln/python_studies | /new2.py | 905 | 4.15625 | 4 | '''
soma de dois numeros
num1 = int(input())
num2 = int(input())
print (num1 + num2)
'''
'''
#converter Farenhait em Celcius
F = int(input())
C = (5*(F-32)/9)
print(C)'''
'''num1 = int(input())
num2 = int(input()) #numero inteiro
numR = float(input()) #numero real usar float
prod = num1 * 2 * (num2/2)
print('o produt... |
f383ac9b6a80a2d72da58b1bfd6d970aa6f430cf | YTnogeeky/leetcode | /Lowest Common Ancestor of a Binary Tree.py | 597 | 3.671875 | 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 lowestCommonAncestor(self, root, A, B):
if root is None or root == A or root == B:
return ro... |
4658026e765d5680d98f7df50da306fc41b899bb | DmitryTsybin/Study | /Coursera/Algorithmic_Thinking/Project_3-Closest_pairs_and_clustering_algorithms/closest_pairs_and_clustering_algorithms.py | 8,925 | 4.21875 | 4 | """
File with functions to calculate different pairs and clustering algorythms.
"""
import math
import alg_cluster
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are ... |
e2fb0febbe02e8f4a58d9da56898e34f80abc64a | ankurjain8448/leetcode | /search-insert-position.py | 692 | 3.53125 | 4 | #https://leetcode.com/problems/search-insert-position/description/
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start = 0
end = len(nums) - 1
s = 0
e = len(nums)-1
index = -1
if target < nums[0]:
index = 0
elif targ... |
036741075e6b880713124c6c302f7ffde0f39b76 | ZorkinMaxim/Python_school_lvl1 | /recursion.py | 84 | 3.578125 | 4 | def repeat(n):
print('>', n)
if n < 8:
repeat(n+1)
repeat(1) |
d4cc38bb1211524669ad8c97162e6225c9b2aacd | uzuran/AutomaticBoringStuff | /Loops/loops.py | 285 | 4.125 | 4 | #spam = 1
#if spam < 5:
# print('Hello World')
# spam = spam + 1
# This loop can repeat 5 times, end is spam = spam + 1 if we change value
# to + 2 its equal 5 - 2 = 3, thats mean its
# repeat 3 times!
spam = 0
while spam < 5:
print('Loop Loop Loop')
spam = spam + 1
|
2e5144d43dbdbd1a31289b266be3a0701e2309a3 | u101022119/NTHU10220PHYS290000 | /student/101022219/ack.py | 312 | 3.890625 | 4 | m = float (raw_input('Enter the value of m:'))
n = float (raw_input('Enter the value of n:'))
def ackermann(m, n):
if m == 0:
return n + 1
elif m >= 0 and n == 0:
return ackermann(m-1, 1)
elif m >= 0 and n >= 0:
return ackermann(m-1, ackermann(m, n-1))
print ackermann(m, n)
|
182a35d1b9b483d223337b261bf7367b0247c090 | SiddhiPevekar/Python-Programming-MHM | /prog24.py | 293 | 4.28125 | 4 | #leap year(number divisible by 4 and 400 is leap year and year divisible by 4 and 100 is not a leap year)
year=int(input("enter any leap:\n"))
if(year%4==0 and year%100!=0 or year%400==0):
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
|
cbc08657b411f25ebc2defabf05d223f7379e82b | SSRTLandscapeEvaluation/Deng | /City_Color/生成器.py | 926 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 20:24:53 2018
@author: Administrator
"""
'''
# 简单的生成器函数
def my_gen():
n=1
print("first")
# yield区域
yield n
n+=1
print("second")
yield n
n+=1
print("third")
yield n
a=my_gen()
print("next method:")
# 每次调用a的时候,函数都从... |
74541996e03fe00d803b020ab72eab02eb32feeb | Harlow777/crabs | /crabgender.py | 2,320 | 3.84375 | 4 | import math
import random
import string
import csv
import random
# Jacob Harlow
# October 4, 2014
# CSC 475 Artifical Intelligence
#
# This program is a single perceptron built to learn what crabs are male
# or female based on two attributes from the csv CW(carapace width) and
# RW(rear width).
# initialize weight... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.