blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
2b702ee8b97f223d8e77aa016848198a0f0df87f | samyhkim/algorithms | /134 - gas station.py | 611 | 3.71875 | 4 | '''
if point A cannot reach point B,
gap will measure the gas needed to travel from point A to point B
start == len(gas) means we ran off the gas array
https://leetcode.com/problems/gas-station/discuss/167542/10-lines-Python-that-beats-100-NO-PROOF-IN-HERE
'''
def can_complete_circuit(gas, cost):
tank = gap =... |
1ab19a529a3628ee1495d7272beabcc122cb06f4 | samyhkim/algorithms | /20 - valid parentheses.py | 825 | 4.0625 | 4 | '''
iterate through string and check in lookup
if key does not exist, add to stack
else, pop from stack and check if it matches with key's value
'''
def is_valid(s):
open_parens = []
lookup = {')': '(', ']': '[', '}': '{'}
for paren in s:
# only adds opening paren to stack
if paren not in... |
0ec6f3f91b29c3f545c22cf1d182dc6a668ce6cd | samyhkim/algorithms | /543 - diameter of binary tree.py | 367 | 3.6875 | 4 | def diameter_of_binary_tree(root):
diameter = [0]
depth(root, diameter)
return diameter[0]
def depth(root, diameter):
if not root:
return 0
left_height = depth(root.left, diameter)
right_height = depth(root.right, diameter)
diameter[0] = max(diameter[0], left_height + right_height)... |
69e3b7c80ab350da56af418fbd69e8f131789cbc | samyhkim/algorithms | /270 - closest binary search tree value.py | 299 | 3.6875 | 4 | def closest_value(root, target):
closest_node = root.val
while root:
if abs(root.val - target) < abs(closest_node - target):
closest_node = root
if target < root:
root = root.left
else:
root = root.right
return closest_node
|
612591aba366e4a15ab5cb1f3d64367a8374243f | samyhkim/algorithms | /114 - flatten binary tree to linked list.py | 775 | 3.890625 | 4 | '''
1. flatten left subtree
2. find left subtree's tail
3. set root's left to None, root's right to root'left, tail's right to root.right
4. flatten the original right subtree
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def flatten(root)... |
de760b96bb0c0b1f2cd374210cb5b74ca94a3c7d | samyhkim/algorithms | /14 - longest common prefix.py | 489 | 3.765625 | 4 | # O(n^2) - not sure if optimal; other solutions are O(n) but use zip() and enum()
def longest_common_prefix(strs):
if len(strs) == 0:
return ""
lens = [len(s) for s in strs]
min_len = min(lens)
res = ""
for i in range(1, min_len + 1):
prefix = strs[0][:i]
for s in strs:
... |
1416e8b7513ba2ccbb4ed39fdef251665e384dc3 | samyhkim/algorithms | /202 - happy number.py | 397 | 3.5625 | 4 | def is_happy(n):
seen = {}
while n not in seen:
seen[n] = n
sum_list = []
for i in str(n):
sum_list.append(int(i) ** 2)
n = sum(sum_list)
return n == 1
# pythonic
# def is_happy(n):
# seen = set()
# while n not in seen:
# seen.add(n)
# n ... |
07df07e0d977f286a3cb28c187f5a4adbbd2fd12 | samyhkim/algorithms | /56 - merge intervals.py | 977 | 4.25 | 4 | '''
sort by start times first
if one interval's end is less than other interval's start --> no overlap
[1, 3]: ___
[6, 9]: _____
if one interval's end is greater than other interval's started --> overlap
[1, 3]: ___
[2, 6]: _____
'''
def merge(intervals):
merged = []
intervals.sort(key=lambda i: i[0]) ... |
0eeaa67b7a094341374e70e0b5b36dc71066c73f | samyhkim/algorithms | /398 - random pick index.py | 749 | 4.0625 | 4 | import random
'''
{1,2,3,3,3} with target 3, you want to select 2,3,4 with a probability of 1/3 each.
2 : It's probability of selection is 1 * (1/2) * (2/3) = 1/3
3 : It's probability of selection is (1/2) * (2/3) = 1/3
4 : It's probability of selection is just 1/3
So they are each randomly selected.
'''
class Rand... |
dd72cd91b9e5e0811cd1f62839fe044ad764282d | samyhkim/algorithms | /438- find all anagrams in a string.py | 613 | 3.5625 | 4 | from collections import Counter
def find_anagrams(s, p):
output = []
p_lookup = Counter(p)
s_lookup = Counter(s[:len(p)])
left = 0
right = len(p)
while right <= len(s): # can come down to last comparison
if s_lookup == p_lookup:
output.append(left)
s_lookup[s[le... |
ce4ddd114c2fc8bd580f7f0ccb7d86770bb77fb3 | boyekeem/Clouding | /gradient descent.py | 246 | 3.609375 | 4 | x1=3
x2=5
error=0.00000001
step=0.001
def gd(x1):
H_x= (5*(x1**3.5))- (9*(x1**3))
return H_x
while abs(x2-x1)>error:
x1=x2
x2=x1-(step*gd(x1))
print (x1,"\n")
print x2
gd(x1)
|
cbc25e6a7a9d490b559c358d01df875db027e1af | wwshadow/leetcode | /爬楼梯.py | 882 | 4.03125 | 4 | # 题目分析:
# # **设f(n)为n阶台阶的情况下,所有不同的跳法方法的总和!**
# # 1.如果起始跳一阶的话,剩余的n-1阶就有 f(n-1) 种跳法;
# # 2.如果起始跳二阶的话,剩余的n-2阶就有 f(n-2) 种跳法;
# # 所以f(n) = f(n-1) + f(n-2),实际结果即为斐波纳契数。 fibonacci
def climbStairs():
"""
:type n: int
:rtype: int
"""
n=6
nums = [0, 1, 2]
if n == 1:
return nums[1]
elif ... |
94ad4294ea32a3c6cf6ca26d48874196b13f493e | Erik-Bornako/SSW567_HW01 | /Erik_Bornako_SSW567_HW01.py | 1,439 | 4.0625 | 4 | """
Author: Erik Bornako
Date: 29 Aug 2019
Purpose: Specifies a triangle
"""
import math
def isclose(a, b, rel_tol=1e-06, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def testNumber(number):
"""Tests to see if number is valid"""
try:
int(number)
... |
b826ec36405be321db0df1e9ab6fea011ddff5d8 | twterryh/statistical_analysis | /NumpyScipy/02_matrixConversion.py | 851 | 3.609375 | 4 | import numpy as np
# 행과 열을 바꾸는 연산
# transpose : 전치 행렬
x = np.array([[1,2,3],
[3,4,5],
[7,8,9]])
print(x.T)
'''
[[1 3 7]
[2 4 8]
[3 5 9]]
'''
x1 = np.array([[2.1],[2.3],[2.4]])
print(x1)
'''
[[2.1]
[2.3]
[2.4]]
'''
print(x1.T) # [[2.1 2.3 2.4]]
print... |
3ef3c733e56e2438a7a7fe99f365ffc4a700ffdb | twterryh/statistical_analysis | /NumpyMatplotlib/02_ftnClass.py | 582 | 3.828125 | 4 | def hi():
print("hihi")
print("more to")
print("print")
hi()
def hi2(object):
print("hi!" + object)
hi2('aaaa')
def hi3(a):
print(type(a))
hi3(3) # int
hi3('a') # str
hi3('3') # str
# class
class Person :
def __init__(self, name): # 생성자 : 클래스를 초기화하는 메서... |
4238e676e131e33e399c555feb566d9cd017edac | vidya3979/luminardjango | /guiprograming/grid_system.py | 526 | 3.59375 | 4 | from tkinter import*
root=Tk()
root.title("Log In Window")
def click_btn():
print("btn clicked")
ulabel=Label(root,text="username")
plabel=Label(root,text="password")
uentry=Entry(root)
pentry=Entry(root)
btn1=Button(root,text="Log In",command=click_btn,fg="blue")
btn2=Button(root,text="Create New Account",com... |
1222bda8f0950621e2822677f5b009977bb20154 | vidya3979/luminardjango | /languagefundamental/helloworld.py | 324 | 3.8125 | 4 | print("hello world")
name="luminar technolab"
print("company name =",name)
cname="luminar"
location= "kakkanad"
print("company",cname,"is located in",location)
name="vidya"
age=30
print("myself",name,"is",age,"year old")
name= input("enter value for name")
age= input("enter value for age")
print("name=",name)
pr... |
061403792fbcb66b1772d205b1653a6cc732dac7 | vidya3979/luminardjango | /object_oriented_prgms/prgm2.py | 437 | 3.59375 | 4 | class student:
def __init__(self,rol,name,course,total):
self.rol=rol
self.name=name
self.course=course
self.total=total
def print_student(self):
print("roll no.=",self.rol)
print("name=",self.name)
print("course=",self.course)
print("total=",self... |
96dc4a56e2344d081a8573916e641ffcac8f79f5 | vidya3979/luminardjango | /flowcontrols/looping/prgmtoprintevennum.py | 182 | 3.84375 | 4 | lowlimit=int(input("enter the lower limit"))
uplimit=int(input("enter the upper limit"))
i=1
while(lowlimit<=uplimit):
if(lowlimit%2==0):
print(lowlimit)
lowlimit+=1
|
822a45aab6338eb801d19879be78e2d758cd9289 | vidya3979/luminardjango | /collections/listprograms/listprgm1.py | 126 | 3.875 | 4 |
#find total sum of this list without using function
lst=[1,2,3,4,5]
total=0
for sum in lst:
total+=sum
print(total)
|
3c3eda290929340cd3f24cfb2fab882e0d7e522a | vidya3979/luminardjango | /different_function/fun_first.py | 224 | 3.703125 | 4 | '''def add(*num):
sum=0
for n in num:
sum=sum+n
print(sum)
add(10,20)
'''
def print_data(**num):
for k,v in num.items():
print(k,v)
print_data(birth_place="kochi",desi="develop",salary=5000)
|
a880cf151cc1366a86bbea3dccd0d3473c836a84 | vidya3979/luminardjango | /object_oriented_prgms/bank_app.py | 778 | 3.828125 | 4 | class bank:
def create_acc(self,acc_no,name,balance):
self.acc_no=acc_no
self.name=name
self.balance=balance
def deposit(self,amount):
self.balance+=amount
print("your account no.",self.acc_no,"has been credited with amt",amount,"\n","your avail balance",self.balance)... |
29e21c162dc2a22b9fbbf8c131bb1d1ae72e3454 | vidya3979/luminardjango | /collections/listprograms/listprgm2.py | 131 | 3.828125 | 4 | # add a limit of numbers in list
limit=int(input("enter limit"))
lst=[]
for i in range(1,limit+1):
lst.append(i)
print(lst)
|
399c075fac99fdd022b771679d55b633ddb8feb2 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm7abc.py | 982 | 3.96875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list1=[12,3,4,56,7,8,9,19,34,87]
>>> list2=[10,4,67,89,4,77,29,5,7,8]
>>> len1=len(list1)
>>> len2=len(list2)
>>> if len1==len2:
print('Both... |
79ca667df5a747c3926ca8806022df645789d6d5 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm4.py | 437 | 4.25 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def word_count(str):
counts=dict()
words=str.split()
for word in words:
if word in counts:
counts[word]+=1
else:
counts[word]=... |
82f41dcec66b4fe078a1a2d67b92f33fbdab956a | aish2028/M_4 | /ex3.py | 289 | 3.9375 | 4 | def cast_vote(age):
assert age>=18,"Age should not be <18,it was:{age}"
print("thank you for voting....")
try:
age=int(input("enter the age:"))
cast_vote(age)
except AssertionError as a:
print(a)
else:
print("you entered valid age...")
finally:
print("End....") |
a00231b5aaa06630c3237083ca1650384ce7d71b | FJLRivera86/Python | /Dictionary.py | 1,118 | 4.53125 | 5 | #DICTIONARY {}: Data structure Like Tuple or List
#It's possible save elements,list or tuples in a dictionary
firstDictionary = {"Germany":"Berlin", "France":"Paris", "England":"London", "Spain":"Madrid"}
#To print a value, It's necessary say its KEY
print(firstDictionary)
print(firstDictionary["England"])
#ADD eleme... |
f6439bb384d20caa8912f1e8c8448f52a21ad405 | patrickfrancis/advent-of-code | /2016/Day_1/follow_directions_2.py | 2,035 | 3.890625 | 4 | import re
class Turtle:
def __init__(self):
self.x = 0
self.y = 0
self.direction = 0 # 0 = N, 1 = E, 2 = S, 3 = W
self.visited_locations = {(0, 0)}
def follow_directions(self, moves: list):
for move in moves:
repeat_loc = self.do_move(move)
if r... |
acbeebd21f332ebe4546e2b365722f000939b143 | patrickfrancis/advent-of-code | /2016/Day_14/onetimepad_1.py | 1,197 | 3.59375 | 4 | import re
from hashlib import md5
triple_pattern = re.compile(r'([a-z0-9])\1\1')
# five_pattern = re.compile(r'([a-z0-9])\1\1\1\1')
salt = "ngcjuoqr"
hashes = {}
def get_hash(index: int) -> str:
if index not in hashes:
hash_val = md5("{0}{1}".format(salt, index).encode('ascii')).hexdigest().lower()
... |
aeba51cb823055b460b6d6223e9a8c40814d93df | rajanraman/Puzzles | /matrix_rotation_hackerrank.py | 1,976 | 3.53125 | 4 | #Get the number of rows(R), columns(C) and number of rotations(N)
R,C,N = input().split()
R=int(R)
C=int(C)
N=int(N)
#Build the input matrix
matrix=[]
for x in range(R):
matrix.append(input().split())
pass
#Add each layer to the list and then add the rotated version to the matrix
linear_list=[]
rotation... |
04a476f20007a61018315404fde8b532e052f437 | rodolfopfranco/python_projects | /Fractions/File_Manager.py | 1,273 | 3.9375 | 4 | from Fracao import Fracao
class FractionsFile:
def __init__(self):
self.fractions = []
def scanFile(self,filename):
"""proccess the file and generates fractions array"""
f = open(filename)
for s in f:
fracao = s.split(" ")
fracao = Fracao(int(fracao[0])... |
e1ec0d81a0773884796696a984c20e2c3b52a820 | Pradnya-py/Test | /excercise8_5.py | 546 | 3.890625 | 4 |
# Program checks for lines which starts with from to list all sender,
# here string is used instead list as list will require more memory space
filehand = raw_input("Enter file name") # Enter file name
try:
fi = open(filehand, "r") # read file
except:
print ("Enter file name")
quit()... |
f897657399688234357208daa2ccec470619febf | Ethan223/Legacy-Systems-W18 | /A4/sieve.py | 1,256 | 3.515625 | 4 | #!usr/bin/python
#***************************************************
#Name: Ethan Coles
#ID: 0843081
#File: sieve.py
#Description: CIS*3190 Assignment 4, Python implementation
#of Sieve of Eratosthenes algorithm.
#***************************************************
import sys
import math
import time
#Ask for upper li... |
2d042a110b5642719a60a1d5aedc4528bb40cb86 | momentum-cohort-2019-05/w2d1-house-hunting-redkatyusha | /house_hunting.py | 754 | 4.1875 | 4 | portion_down_payment = .25
current_savings = 0
r = .04
months = 0
annual_salary_as_str = input("Enter your annual salary: ")
portion_saved_as_str = input(
"Enter the percent of your salary to save, as a decimal: ")
total_cost_as_str = input("Enter the cost of your dream home: ")
annual_salary = int(annual_salary_a... |
60bf7c741b9ae5ffbfd1b0e557a03a77895fd026 | n0mn0mn0m/AM2320-python-raspi | /AM2320.py | 1,569 | 3.828125 | 4 | #!/usr/bin/env python3
## AM2320 Temperate and Humidity Sensor Library
## This library is used to get the temperate and humidity from a AM2320 sensor via i2c.
## This sensor has a sleep function to it were you need to wake it up before each call
## which can be seen in any function returning data via the wakeUp functi... |
77b44e980ce9ff1d0a425a0590ea36fc0428be66 | Brunonascdev/exercicios_python | /Lista 2/ex8.py | 493 | 4.03125 | 4 | #Exercício 8: Escreva um programa que calcule o fatorial de um número informado
#pelo usuário. Dica: O fatorial de um número N é dado pela fórmula:
#N! = 1 * 2 * 3 * 4 * 5 * ... * N
#num = int(input("Insira um número para saber seu fatorial: "))
#for i in reversed(range(1, num)):
def main():
n = int(input("Digit... |
afe88be76bd1c2cda0800c46e6fa2daeb07cedc0 | Brunonascdev/exercicios_python | /Lista 1/ex2.py | 199 | 3.984375 | 4 | # Exercício 2: Escreva um programa que leia um número inteiro,
# calcule e exiba o resultado do dobro deste número.
numero = int(input("Insira um número: "))
result = numero * 2
print(result)
|
780bf2329fb269ef091a1ac9f86258a1926abb92 | LeenaKH123/API_DB | /databases/Exercise_05.py | 1,880 | 3.5625 | 4 | # Using the API from the API section, write a program that makes a request to
# get all of the users and all of their tasks.
# Create tables in a new local database to model this data.
# Think about what tables are required to model this data. Do you need two tables? Three?
# Persist the data returned from the API to y... |
6ad9ada006b2dad27c5e61c28c722ed12ed09332 | RafaelMalena03/ProyectoFinal | /Operaciones.py | 547 | 3.921875 | 4 | class Operacion:
def sumar(self, num1, num2):
if num1 < 0 or num2 < 0:
return "NoPermitido"
return num1 + num2
def restar(self, num1, num2):
if num1 < 0 or num2 < 0:
return "NoPermitido"
return num1-num2
def multiplicar(self, num1, num2):
if ... |
f2ce62028c31efdc396f3209e1c30681daa87c17 | pmxad8/cla_python_2020-21 | /test_files/test_1.py | 769 | 4.21875 | 4 | ################### code to plot some Gaussians ####################################
#### import libraries ####
import math
import numpy as np #import numerical library
import matplotlib.pyplot as plt #allow plotting
n = 101 # number of points
xx = np.linspace(-10,10,n) #vector of linearly spaced points
s = 0.5,1,1.5... |
bad4ef863c77c5e42c02725021490501fea4def6 | hafizadit/MuhammadHafizAditya_I030064_AbyanNaufal_Tugas7 | /I0320064_exercise 7.7.py | 49 | 3.625 | 4 | str = "hello world"
s = str.capitalize()
print(s) |
c6e34c2445b3227f2157452933effcca4aaae916 | hafizadit/MuhammadHafizAditya_I030064_AbyanNaufal_Tugas7 | /I0320064_Soal1_Tugas7.py | 1,697 | 3.71875 | 4 | import math
import sys
def headerFooter(teks):
print("")
print("="*50)
print(teks.center(50))
print("="*50)
print("")
def kapital():
print("\n-----Huruf Kapital-----\n")
print("\nHasil Kapitalisasi :")
print(teks.title())
mainmenu()
sys.exit()
def string():
global teks
... |
ddeb9f5f8329c04d381ded0d63e24c3be44b9169 | centre-for-humanities-computing/DaCy | /src/dacy/datasets/names.py | 4,546 | 3.59375 | 4 | """Helper functions for loading name dictionaries for person augmentation."""
import os
from typing import Dict, List, Optional
import pandas as pd
def load_names(
min_count: int = 0,
ethnicity: Optional[str] = None,
gender: Optional[str] = None,
min_prop_gender: float = 0,
) -> Dict[str, List[str]]... |
29b806e4aec0c7058c0d2ebac6d5a219162bf202 | centre-for-humanities-computing/DaCy | /src/dacy/utils.py | 956 | 4.0625 | 4 | from collections.abc import MutableMapping
def flatten_dict(d: dict, sep: str = "_") -> dict:
"""flattens a nested dictionary.
Args:
d (dict): The nested dictionary to be flattened. Keys are assumed to be strings.
sep (str, optional): The seperator between keys. Defaults to '_'.
Returns:... |
b5931e6858360437295730c6ff61199daa41bcb2 | yonjuuni/lits | /flatten.py | 398 | 3.921875 | 4 | input_string = ''
while (not input_string.startswith('[') or
not input_string.endswith(']') or
'for' in input_string):
input_string = input('Enter a list: ')
input_list = eval(input_string)
# input_list = [1, [2, 3], 4, [[6, 7]]]
temp = str(input_list).split()
res = []
for i in temp:
element =... |
b708990ef5d70f151ca468a13784f9b6c49745db | san33eryang/learnpy | /sorted.py | 896 | 4.21875 | 4 |
# -*- coding: utf-8 -*
# 排序数字,或按照绝对值排序
print(sorted([-2,-6,-99,9,8]))
print(sorted([-2,-6,-99,9,8],key = abs))
#排序字母,按照大小写或忽略大小写排序
print(sorted(['bob','about','Zoo','Credit','credit']))
print(sorted(['bob','about','Zoo','Credit','credit'],key=str.lower))
print(sorted(['bob','about','Zoo','Credit','credit'],key=str.l... |
6b98f1855df2a55f008d5ef76c628d4610fba0a0 | san33eryang/learnpy | /class_learning.py | 3,282 | 3.8125 | 4 | # -*- coding: utf-8 -*
class Student(object):
def __init__(self,name,score):
self.__name=name #内部变量访问
self.__score=score #内部变量访问
def get_scoretype(self):
if self.__score>=90:
return 'A'
elif self.__score>=60:
return 'B'
else:
... |
7deff2841c1b9164ff335a4b1cb11c3266482a00 | SuryaDhole/tsf_grip21 | /main.py | 2,683 | 4.125 | 4 | # Author: Surya Dhole
# Technical TASK 1: Prediction using Supervised ML (Level - Beginner)
# Task Description: in this task, we will predict the percentage of marks that a student
# is expected to score based upon the number of hours
# they studied. This is a simple linear regression task as it involves just two var... |
4dc31bada43c4ec72dc8109196a5171a985c1997 | iriagzz/la-casa-de-marcelo-pygame | /menu.py | 2,185 | 3.546875 | 4 | # imports
import pygame
from messenger import *
from settings import *
# initialize pygame
pygame.init()
class Menu():
"""
class to create and handle the start and game over screens
"""
def __init__(self, options, font, win):
"""
initialize the class
it recieves a main message... |
6540c8e6bf90b409f425228510e7f25debf65534 | iriagzz/la-casa-de-marcelo-pygame | /timer.py | 1,940 | 3.921875 | 4 | # imports
import pygame
# initialize pygame
pygame.init()
# constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
TIMER_FONT = pygame.font.Font("fonts/advanced_pixel.ttf", 34)
REL_POS = [75, 10]
# Timer class
class Timer():
"""
class for the timer that appears at the top-right corner of the screen
"""
... |
1c5ebd90b94a64860e9a3b0d8912cea0bcb75e32 | notandrewsimpson/Quzmaster | /Quizmaster.py | 8,776 | 3.6875 | 4 | import random
import time
import os
money = 0
x = 1
questions_asked = []
def questions(end): # function that calls the questions
x = 1
while x % 2 != 0:
x = random.randint(0,end)
return x+1
def answers(end): # function that varifys the answer
x = 1
while x % 2 == 0:
x = random.rand... |
bb2e091ec140ebde9eb996b0fe5ca7b3bc4f98ad | vardanabroyan/ChangedCodeCoverage | /Kod.py | 393 | 3.75 | 4 | def Pow(a,b):
i = 0
s = a
if a==0 and b>0:
return 0
if a>0:
for i in range(b-1):
s=s*a
return s
else:
if b%2==0 :
return Pow(abs(a),b)
else:
return -(Pow(abs(a),b))
def Max(x,y,z) :
if x>y :
max=x
else :
max=y
if max>z :
return max
else :
max=z
return max
def Search(sim... |
7341a7ae39123c8ed2aa78ca7434bce2bcdd9f76 | AntonKulik1980/itea_october | /Lesson5/Lesson_5dz/Lesson5dz_1.py | 858 | 3.5625 | 4 | # Создать декоратор, который будет запускать функцию в отдельном
# потоке. Декоратор должен принимать следующие аргументы:
# название потока, является ли поток демоном.
from functools import wraps
import time
from threading import Thread
def decorartor(name='first', daemon=False):
def actual_decorartor(func):... |
8412d478cc289caf22b0ecc630b15415a3a46d0e | AntonKulik1980/itea_october | /Lesson_4/new_example.py | 489 | 3.5 | 4 | class Person:
def __new__(cls, *args, **kwargs):
person_odbject = super().__new__(cls)
person_odbject.age = 25
return person_odbject
def __init__(self, first_name, sername):
self._first_name = first_name
self.sername = sername
@property
def first_name(self):
... |
7500198d34471e22f461ed8ef62e9a5d92152aa3 | Neeraj2002/ml-ai-projects | /Face_Detection/face_detection_livevideo.py | 1,266 | 3.59375 | 4 | import cv2
from random import randrange
# Loading some pre-trained data on the face frontal from opencv
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Choosing an image to detect the face
"""img = cv2.imread('RDJ2.jpeg')"""
webcam = cv2.VideoCapture(0)
# Iterating over t... |
7e04d94223eb258ce97cc26e39cd9b4a043b5e01 | CCooley88/AddressBook | /AddressBook.py | 3,537 | 4 | 4 | from pip._vendor.distlib.compat import raw_input
# This program is designed to work as an electronic address book taking in various pieces of information about contacts.
# It offers the ability to use a number of multi-level sorting functions, to add and remove contacts,
# and an option to display single contacts base... |
f0f452c0b367fee1b337e5d9d40aa80188688543 | nptit/checkio-solution | /CheckIO/elementary/three_words.py | 702 | 3.984375 | 4 | def checkio(words):
succ = 0
for word in words.split():
succ = (succ + 1) * word.isalpha()
if succ == 3:
return True
else:
return False
"""
import re
def checkio(words):
return bool(re.compile("([a-zA-Z]+ ){2}[a-zA-Z]+").search(words))
# or re.sub(r'\D+ \D+ \D+',... |
ed09dc30500a1f96bc73ed27a68cd08e955603be | nptit/checkio-solution | /CheckIO/alice/hidden_world.py | 502 | 3.578125 | 4 | from itertools import zip_longest
def checkio(text, word):
l = [list(i) for i in text.lower().replace(" ", "").split("\n")]
l1 = ["".join(i) for i in l]
l2 = ["".join(i) for i in list(zip_longest(*l1, fillvalue='-'))]
for x, y in enumerate(l2, start=1):
if word in y:
return [y.ind... |
ba25884073253e27092b9da0c88bfeb635534e68 | nptit/checkio-solution | /CheckIO/scientific-expedition/network-attack.py | 2,630 | 3.5 | 4 | def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(n... |
1b97c1ded8d0cefb085098dc1279890f5a5f8714 | SN-Koarashi/guessnumber | /main.py | 522 | 3.609375 | 4 | # Python 3
import random
ans = random.randint(1,100)
for i in range(1,4):
q = int(input("Type number: "))
if q == ans:
print("SUCCESS!",ans)
break
elif i == 3:
print("FAILD, Correct answer",ans)
else:
higher = ans+random.randint(1,10)
lower = ans-rando... |
a5d02ff50e1ad7708c08aa475200bdd695ecaa8e | ElizabethFoley/Text-Based-Game | /game.py | 15,871 | 3.59375 | 4 | # CMPT 120L 113
# Libby Foley
# 20 Sep 2018
###
##
# In my final commit, I added a class object for the player and the locales
# I added and "use item" feature for the candle
# I made the candle have "limited uses"
# I added the ability for the player to asce... |
2d9e71378874c8f8347bab57c5c12bd436f94c7e | masterkanch/Python_DataStructure | /Recursion/HW1P5_633040206-5.py | 348 | 3.96875 | 4 | def isPalin(word):
if len(word) < 1:
return True
else:
if word[0].lower() == word[-1].lower():
return isPalin(word[1:-1])
else:
return False
myword = ""
myword = input("Enter a word: ")
while(myword.lower() != "done"):
print(myword, isPalin(myword))
mywor... |
1c10ab058206bd4a9f8cb0de7ae5949aa1f5b166 | JubieRoo/DataProcessing2019 | /Homework/Week_2/eda.py | 2,740 | 3.890625 | 4 | #!/usr/bin/env python
# Name: Ruby Bron
# Student number: 12474223
"""
This script explores and analyzes the data and outputs it as a .json file
Focus on following variables:
Country, Region, Pop.Density (per sq. mi.), infant mortality (per 1000 births) and GDP
"""
import csv
import numpy as np
import matplotlib.pyplo... |
a82779d2c4c376332c99b13a3a48a14edbe0228f | hackclubcoet/Batch-1 | /Nivedhitha A N.py | 339 | 3.953125 | 4 |
height = float(input()) #in meter
# NivedhithaAN-01-bmi
weight = float(input()) # in kilogram
bmi = weight/(height**2)
print(round(bmi))
if (bmi<18.5):
print("Underweight")
elif (bmi>18.5 and bmi<25):
print("Normal weight")
elif (bmi>30 and bmi<35):
print("Obese")
elif (bmi>35):
print("Cli... |
eeb9ffe5b8ebe9beb9eda161b15b61ccea90ba9a | RezaZandi/Bank-App-Python | /old_code/switch_satements.py | 758 | 4.15625 | 4 |
"""
def main():
print("hi")
main_console = ("\nSelect an option to begin:")
main_console += ("\nEnter 0 to Create a new account")
main_console += ('\nEnter 1 to Deposit')
main_console += ('\nEnter 2 to Withdraw')
main_console += ('\n What would you like to do?: ')
while True:
user_option = int(i... |
bcb736f5f18b18038fbb12d235f9caec01a3fc32 | pombreda/comp304 | /Assignment4/atom3/Kernel/LayoutModule/HierarchicalLayoutModule/CrossingModule/Utilities.py | 2,559 | 3.515625 | 4 | """
Utilities.py
Simple but useful methods...
By Denis Dube, 2005
"""
def isSorted(nodeList):
"""
Use:
Returns True if the node list is already sorted by barycenter value
Parameter:
nodeList, a list of nodes with a getBarycenter() method
Pre-condition:
nodeList is a non-empty l... |
34ddae150a6484915bca424e0e84cbded902cc08 | pombreda/comp304 | /Assignment4/atom3/Kernel/ATOM3Types/ATOM3String.py | 4,804 | 3.53125 | 4 | # __ ATOM3String _________________________________________________________________________________
# This is the class for String types. It inherites from ATOM3Type
# Last Modified: 27/July/2002
# Changes:
# - 27/July/2002: Changed methods "writeConstructor2File" and "writeValue2File" in order to allow
# ... |
ad48c51aa2c40286a4016c5b0fe25cac356150b7 | pombreda/comp304 | /Assignment2/a2/Purchase.py | 607 | 3.578125 | 4 |
import time
class Purchase(object):
def getDate(self):
return self.date
def getStore(self):
return self.store
def getWarranty(self):
return self.warranty
def prettyPrint(self):
print "*** Purchase ***"
print "Date:",time.asctime(time.... |
b9729e5d756389e3ddf2df8a37d73c6d54b69af9 | VSRPraneeth/pyScripts | /first/init.py | 358 | 3.65625 | 4 | class Tuna:
def __init__(self):
print('This is a tuna class')
def swim(self):
print('I\'m swimming')
flipper = Tuna()
flipper.swim()
class Enemy:
def __init__(self, x):
self.energy = x
def get_energy(self):
print(self.energy)
enemy1 = Enemy(5)
enemy2 = Enemy(18)
ene... |
ca89dea905b96fabfa436e214575a97880d4eaf7 | parkerdu/SentenceDistance | /edit_distance_demo.py | 324 | 3.5 | 4 | import distance
def edit_distance(s1, s2):
return distance.levenshtein(s1, s2)
strings = [
'你在干什么',
'你在干啥子',
'你在做什么',
'你好啊',
'我喜欢吃香蕉'
]
target = '你在干啥'
results = list(filter(lambda x: edit_distance(x, target) <= 2, strings))
print(results)
|
b3c851ab9e56bf07510bc13c81950d3c3ef44e4c | masc7859/csci5448_proj2 | /zookeeper.py | 2,324 | 3.65625 | 4 | from Subject import Subject
class Zookeeper(Subject):
state = ""
observers = []
#Makes the zookeeper observable by our observer
def registerobserver(self,observer):
self.observers.append(observer)
#Makes the zookeeper UNobservable by our observer
def deregisterobserver(self,observer):
... |
31dc915175c57ce7e30a198ad4e37bd38a3ec9f6 | masc7859/csci5448_proj2 | /animals/hippo.py | 585 | 3.546875 | 4 | from animal_classes.pachyderm import Pachyderm
import random
class Hippo(Pachyderm):
#This is our random action implementation. Instead of making noise the animal may do something else
def makeNoise(self):
randAction = random.randint(0,100)
if(randAction < 25):
print(self.name + " ... |
27bf93159f33c8cdffb4bc7961cdcbffd89d8244 | dhruvbabbar/chatbot | /chatbot-master/dummycal.py | 1,072 | 4.0625 | 4 | import calendar
import Tkinter
class TkinterCalendar(calendar.Calendar):
def formatmonth(self, master, year, month):
dates = self.monthdatescalendar(year, month)
frame = Tkinter.Frame(master)
self.labels = []
for r, week in enumerate(dates):
labels_row = []
... |
382fbdd4d1b95633025b9f2951ddaa904a1727f1 | AdaniKamal/PythonDay | /Day2/Tuple.py | 2,762 | 4.53125 | 5 | #Tuple
#1
#Create a Tuple
# Set the tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekend = "Saturday", "Sunday"
# Print the tuples
print('-------------------------EX1---------------------------------')
print(weekdays)
print(weekend)
#2
#Single Item Tuples
a = ("Cat")
b = ("Cat",)
print('... |
57b95cd62e2feba438a84c013f9d177ffd767863 | Natalia-Kurylko/common | /relational_database/homework.py | 5,638 | 3.578125 | 4 | import psycopg2
from relational_database.config import DATABASE
conn = psycopg2.connect(**DATABASE)
def task_1_add_new_record_to_db(con) -> None:
"""
Add a record for a new customer from Singapore
{
'customer_name': 'Thomas',
'contactname': 'David',
'address': 'Some Address',
... |
06a57be531234b2b5456719ce600072de74faa22 | roSievers/termReplacer | /lib/trees.py | 1,952 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from random import randrange, choice
# BTree a b = Node (a, (Tree a b, Tree a b))
# | Leaf b
# :: Random (BTree () ())
def randomBinaryTree(leafNumber):
if leafNumber == 1:
return None
elif leafNumber == 2:
return (None, [None, None])
elif leafNumber > 2:
... |
95d5cc0efbfd2f80420084e4cfdd3ceb1bd6d94c | jcsmei/IS211_Assingment9 | /football_stats.py | 1,962 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""IS211_Assingment09; A simple web scraping app with BeautifulSoup."""
import urllib2
from bs4 import BeautifulSoup
web_page = ('https://www.cbssports.com/nfl/stats/'
'playersort/nfl/year-2018-season-regular-category-touchdowns')
html = urllib2.url... |
8d96260c69e129db0e133a1d23042af4eea88c40 | gongnanxiong235/fullstack | /day10/lesson_set.py | 990 | 4.15625 | 4 | # author:gongnanxiong
# date:2018/11/22
'''
set的两大用途:
1.去重,把列表转换成set之后自动去重
2.关系式
set的key都是可哈希的,也就是key不能是列表和字典
set是可变的,非可哈希的,所以set也不能作为dict的key
set是无顺序的,所以不能像list一样通过下标找到元素,只能通过遍历和iter的方式
set是无顺序的,所以set.pop()是随机删除一个值
'''
set_a=set([1,2,3])
set_b=set([1,2,3])
print(set_a==set_b)
set_b.add(4)
print(set_a<set_b)
set_a.u... |
26192fa0e2b9977a72e719d5fbdde74e6cd19892 | gongnanxiong235/fullstack | /day10/lesson_func_gaojiehanshu.py | 1,803 | 3.953125 | 4 | # author:gongnanxiong
# date:2018/11/26
'''
参数作为对象进行传递
'''
def func_hello(number):
if number%2==0:return number*number
else:return number+2
def func_hello_2(a,b,fun):
return fun(a)+fun(b)
result=func_hello_2(2,3,func_hello)
print(result)
'''
推导式列表
'''
list_a=[x for x in range(5)]
print(list_a)
list... |
6493109722c44d3ce7484dbe99222d45378dd0c7 | gongnanxiong235/fullstack | /day33/ttttt.py | 1,317 | 3.671875 | 4 | # author:gongnanxiong
# date:2018/12/13
from itertools import combinations,product,permutations,combinations_with_replacement
# a=combinations(['A','B','C','D','E','F','G'],1)
# # for i in a:
# # print(i)
# def combination(code):
# result_list=[]
# code=code.lower ()
# for i in range ( len ( code ) ... |
66cfbb36be7eedf4f90c2232a3283d63c6de1699 | noararazzak/codewartests | /Katas Python/Parabolic_Arc_Length.py | 565 | 3.71875 | 4 | import math as math
def len_curve(n):
x_squared = (1/n)**2
y_squared_list = []
z_squared_list = []
i = 0
k = 1
sum = 0
for i in range(n):
y_squared = (k/(n**2))**2
y_squared_list.append(y_squared)
k = k + 2
for x in y_squared_list:
z_squared = math.sqrt(... |
48f77c9b25c2f2016e38b139e7b0dddeb82a8bf6 | Allegheny-Computer-Science-102-F2020/cs102-F2020-challenge3-starter | /linecounter/linecounter/__main__.py | 713 | 3.65625 | 4 | """Define the command-line interface for the linecounter program."""
from pathlib import Path
import typer
def main(
data_file: Path = typer.Option(...),
display: bool = typer.Option(False, "--display"),
):
"""Display and count the lines inside of a file."""
# TODO: Confirm that the input file is p... |
6c99cb6b7c8341699b93583f4468f6365ce53696 | viachaslau-nistratau/Indie_programming_course_in_Python- | /conditions_and_cycles.py | 17,328 | 4.28125 | 4 | """
Как вы знаете, в нашей стране граждане платят подоходный налог 13%.
Представьте, что люди с доходом меньше 20000 рублей освобождены от уплаты налога.
Напишите программу, которая получает на вход значение дохода и выводит на экран сумму,
оставшуюся после уплаты налога в 13%.
"""
n = int(input())
if n >= 20000:
a... |
6d6adee24ebea7c28ce5ad80de7607910a184985 | jlutch/SeniorATCSFinalProject | /ATCSFINALPROJECT/TheChessBotExpirence.py | 45,464 | 3.546875 | 4 | import pygame
import random
from pygame.locals import (
RLEACCEL,
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,)
pygame.init()
SQUARE_HEIGHT = 64
SQUARE_WIDTH = 64
TURNCOUNT = 0
WHITE = 0
BLACK = 1
moving_piece = None
def BoardSetup():
# Set up the drawi... |
f9316cf646a21ae84207b39e383ff6a1751458cd | jordanbsandoval/python3_al-descubierto | /capituloDos/diccionarios/acceso-insercion-borrados/insertar-element-diccionario.py | 260 | 3.765625 | 4 | #!/usr/bin/python3
""" Insertar un nuevo elemento, es tan sencillo como modificar uno ya extistente, si la clave no existe, creara el nuevo elemento"""
dicc = {'edad': 28, 'nombre':"jordan", 'peso':"67.2"}
print(dicc)
dicc['apellido'] = "Buitrago"
print(dicc)
|
a5a0355898f90ebce97ddbb74547283078178a52 | jordanbsandoval/python3_al-descubierto | /capituloTres/sentencias-control/bucles/for-iterar-listas-tuplas.py | 175 | 4.03125 | 4 | """ Iterar a traves de for sobre los elementos de una lista o una tupla """
lista = ['hola', "parce", 'contrasena']
string = ""
for i in lista:
string += i
print(string)
|
4bf93de510890276b8356f6538818e3c3b1e74d6 | jordanbsandoval/python3_al-descubierto | /capituloDos/diccionarios/acceso-insercion-borrados/function-del.py | 176 | 3.875 | 4 | """ function del(): Elimina un elemento del diccionario atraves de su clave """
dicc = {'edad': 28, 'nombre':"jordan", 'peso':"67.2"}
print(dicc)
del(dicc['peso'])
print(dicc)
|
ec25820218ac8bd77563d3d1ae032b3ae3081a96 | jordanbsandoval/python3_al-descubierto | /capituloDos/lista/insercionYborrado/metodo-pop.py | 195 | 3.6875 | 4 | #!/usr/bin/python3
""" Metodo pop: elimina un elemento de la lista, atraves de su indice y devuelve el valor eliminado """
lista = ["parce", 5, 9.7]
print(lista)
print(lista.pop(0))
print(lista)
|
17c3ffb44208bca252d8361ffcfb5826a9f64904 | jordanbsandoval/python3_al-descubierto | /capituloDos/strings/metodo-strip.py | 174 | 3.984375 | 4 | #!/usr/bin/python3
"""Metodo strip: Elimina espacios en blanco de un string"""
message = " hola como estan "
print("{}".format(message))
print("{}".format(message.strip()))
|
268d24cae8949edbc347065c1a85415f9374aa2b | jordanbsandoval/python3_al-descubierto | /capituloDos/diccionarios/acceso-insercion-borrados/modificar-element-diccionario.py | 205 | 4.09375 | 4 | #!/usr/bin/python3
""" Modificando el valor de un elemento del diccionario, atraves de la clave """
dicc = {'edad': 28, 'nombre':"jordan", 'peso':"67.2"}
print(dicc)
dicc['nombre'] = "Ronaldo"
print(dicc)
|
6ef3a5c8f5e72f9c767635a4f32d2fe7f855f904 | jordanbsandoval/python3_al-descubierto | /capituloDos/diccionarios/function-dict.py | 146 | 3.671875 | 4 | #!/usr/bin/python3
""" function dict: Nos permite declarar un diccionario """
dicc = {}
print(dicc)
dicc = dict(a=1, b=4, c="jordan")
print(dicc)
|
6e9a8ad63cdc7b36ba1f3e844a4198a0d6c1ec3e | jordanbsandoval/python3_al-descubierto | /capituloDos/lista/ordenacion/metodo-sort.py | 193 | 3.953125 | 4 | #!/usr/bin/python3
""" Metodo sort: Los elementos son ordenan de menor a mayor. La lista queda modificada de manera permanente"""
lista = [7, 5, 9, 2, 8]
print(lista)
lista.sort()
print(lista)
|
6f7c9016f4a6007773731c90e30f3c73f053fde1 | wangtsemin/opensource_workshop | /session_2/4_text_mining.py | 2,006 | 3.8125 | 4 |
# coding: utf-8
# # python hands-on session
# By: Ties de Kok
# Version: Python 2.7 (see any notes for Python 3.5)
# 1. handling files
# 2. data handling
# 3. web scraping
# 4. **text mining**
# 5. (interactive) visualisations
# ## Introduction
# In the previous notebooks we have either worked with quantitative... |
8c66817d3a9d6bb53015ae71e974c5a854791fe5 | MathSena/12-Beginner-Python-Projects---Coding-Course | /BinarySearch/BinarySearch.py | 1,073 | 4 | 4 | import random
import time
def naive_search(l, target):
for i in range(len(l)):
if l[i] == target:
return i
return -1
def binary_search(l, target, low=None, high=None):
if low is None:
low=0
if high is None:
high = len(l) -1
if high<low:
return... |
91767b30db8f5d04888cb03d821c76d1f3c0f479 | RobsonDaniel/Treinamento-python3 | /aula5.py | 999 | 4.0625 | 4 | # Estrutura de dados
# Lista ([])
frutas = ['Abacaxi', 'Uva', 'Melancia', 'Banana']
print(frutas[0])
for fruta in frutas:
print(fruta)
if 'Abacaxi' in frutas:
print("A fruta Abacaxi existe na lista de fruta!")
# Tupla (()) é igual a uma lista. Porém, não é possível adicionar ou remover, ou sej... |
9ab16b835f79e48d35d6ceed5b216e73cc9a090b | RobsonDaniel/Treinamento-python3 | /aula6_atividade.py | 1,235 | 4.21875 | 4 | '''
Exercício: Escreva uma função que recebe um objeto de coleção e retorna o valor do maior número
dentro dessa coleção. Faça outra função que retorna o menor número dessa coleção.
'''
# def maior_numero(lista_numero):
# return max(lista_numero)
#
# def menor_numero(lista_numero):
# return min(lista_... |
1c3eadade02ac51792085597ddd856ff3159b447 | RobsonDaniel/Treinamento-python3 | /aula8.py | 732 | 3.671875 | 4 | # Entrada e saída de arquivos
america_latina = [
'Brasil',
'Argentina',
'Uruguai',
'Paraguai',
'Chile',
'Peru',
'Colombia',
'Venezuela',
'Bolivia',
'Equador'
]
arquivo = open('aula8_arquivo.txt', 'a', encoding='UTF-8') # nome do arquivo, modo de abertura do arqui... |
0596251c79f04f076aba4573e26543809f3f0f26 | RUSHATH/TutorialVideoFiles | /choose your ending SR.py | 825 | 4 | 4 | def playagain():
answer = input("Play again? Y or n \n")
if answer == "Y":
print("OK")
levelone()
elif answer == "n":
print("Goodbye!")
def levelone():
print("Your journey begins here.")
print("There is a fork in the road.")
choice = input("Do you choose lef... |
75d5cf0988feb78e792bebe07f018f0fb34a5b1e | lvirgili/programming_challenges | /uri/uri2334.py | 123 | 3.71875 | 4 | p = int(input())
while p != -1:
if p == 0:
print(p)
else:
print(p - 1)
p = int(input())
|
b9a7ce60bcb1b47049ef9dee3bb150b03e016742 | satyagraha5/CodeJam_Python | /2017/Cruise_Control/Cruise_Control.py | 3,723 | 3.875 | 4 | '''
Annie is a bus driver with a high-stress job. She tried to unwind by going on a Caribbean cruise,
but that also turned out to be stressful, so she has recently taken up horseback riding.
Today, Annie is riding her horse to the east along a long and narrow one-way road that runs west to east.
She is currently at k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.