blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6c62814205d3c7854fb4821036d1ff342e48c47a
David9652/Platzi
/Python 2019/Resumenes/7.Desafíos/1.Crea_una_función_que_sume_recursivamente/main.py
869
4.1875
4
def factorial(number): if (number-1 == 0): return number return number * factorial(number-1) def recursive_sum(number): if (number-1 == 0): return number return number + recursive_sum(number-1) if __name__ == '__main__': while True: try: number = int(input('Ingr...
ac4691ebaaa9b4031fa707c745ba8a2dbfd7ca69
bqmoreland/EASwift
/algs2e_python/Chapter 10/python/lca_tree.py
8,263
3.796875
4
import tkinter as tk from tkinter import ttk class TreeNode: # Space to skip horizontally between siblings # and vertically between tree levels. h_offset = 10 v_offset = 20 # The circle's radius. radius = 12 def __init__(self, parent, value): if parent != None: ...
fa370fed6ba63ac22eb3fcd14a6bc3ff3fbb9ba7
raj-maurya/data-science
/assignment/pyhon_class/assign3_3.py
340
3.890625
4
score = raw_input("Enter Score: ") scor = float(score) if(scor<=1.0 and scor>=0.0): if(scor>=0.9): print "A" elif(scor >=0.8): print "B" elif(scor >=0.7): print "C" elif(scor >=0.6): print "D" else: print "F" else: print ("error, please input correct r...
2edb7ce798d560cefa189206aa4fcb893f59593f
JoaoFiorelli/ExerciciosCV
/Ex028.py
222
3.90625
4
import random n = int(input('Digite um número de 0 a 5 para tentar adivinhar qual o computador escolheu: ')) if n == random.randint(0,5): print('PARABÉNS!! Você acertou!!') else: print('Sorry, você errou. :(')
28f22de21fbe7c400ef8fdd4434da034cfc30091
UbadahJ/project-malcolm
/src/utils/nullsafe.py
3,223
3.515625
4
from functools import wraps from typing import Union, Optional, TypeVar, Type, Sequence, Callable, Any __T1 = TypeVar('__T1') __T2 = TypeVar('__T2') def ifnotnone(value: Optional[__T1], func: Callable[..., __T2]) -> Callable[..., Optional[__T2]]: """ Execute the given function if the given is not None Desig...
62e1118628c5cb0f91cf77e8b00fd30de6623dac
chemplife/Simulated-Annealing
/Netlist generator.py
805
3.828125
4
from random import sample import random net = raw_input("Enter number of nets:") print "Number of nets are "+net nets = int(net) elementnum = raw_input("Enter number of elements:") print "Number of elements are "+elementnum elements = int(elementnum) print "Wait for the message prompt." elements_in_row = [] element...
a26b4c818c5ae2e39b21d5a03197b2a9c4255b62
Anks/euler
/014/14.py
902
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- cache = {} # keep caching lengths for the series def length_of_series(input_number): """ Returns the length of the sequence generated by the problem formula with input_number as the start point """ global cache length = 1 number = input_number...
1d9d956ac3e9d33cf2cc2e3eb7942a719fb0ea3f
vancher85/hwork
/hw2/src1/fib_1.py
453
4.0625
4
"""Task1. Написать в первом модуле функцию по расчету ряда фибоначчи. На вход принимает число n. На выходе выдает ряд фибоначчи длинной n""" # n = int(input()) def func(n): list = [] for i in range(n): if i < 2: list.append(i) else: list.append(list[i-1]+list[i-2]) pr...
44b180e2e91ba629a4b74d881566ebc4dea75a22
alekshiidenhovi/Helsinki-University-Data-Analysis-with-Python
/part03-e04_matrix_power/src/matrix_power.py
532
3.703125
4
#!/usr/bin/env python3 from functools import reduce import numpy as np from numpy.linalg import inv def matrix_power(a, n): m = a.shape[0] if n > 0: return reduce(lambda x,y: x @ y, (a for b in range(n))) elif n == 0: return np.eye(m) else: return reduce(lambda x,y: x @ y, (in...
42f5044c4f86316224bda4e5935766fa858d9af3
samuelkahn/Datascience205
/HW2/SamuelKahnAssignment2.py
3,504
4.25
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 6 22:32:09 2014 @author: samuel """ import os import sqlite3 # create a Connection object that represents the database def create_database(dbname): conn = sqlite3.connect(dbname) return conn ### Create the relevant tables if they do not already exist def cr...
26034798d0aad733cf08caea58dca7ce0bf64314
IleanaChamorro/CursoPython
/Modulo7/EjercicioRectangulo.py
385
3.78125
4
class Rectangulo: def __init__(self, base, altura): self.base = base self.altura = altura def calcular_area(self): return self.base * self.altura base = int(input('Proporciona la base: ')) #10 altura = int(input('Proporciona la altura: ')) # 5 rectangulo1 = Rectangulo(base, alt...
83654b58d339541681bc9716069c6b4b5f9dd961
andreistaicu1/TennisScoreSimulator
/src/Classes/Players.py
1,986
3.734375
4
class Players: def __init__(self, name, first_percentage, double_fault, ace, first_serve_pts_won, second_serve_pts_won, first_return_pts_won, second_return_pts_won): """ :param name: String - name of player :param first_percentage: Float - between 0 and 1, num of 1st serv...
c0ecc906ced6bd8837be4b12266ad470fc687801
amanbhal/pythonCodes
/summer work/InterviwBit/binary_single1.py
411
3.5625
4
# @param A : tuple of integers # @return an integer def singleNumber(A): bits = [0]*32 for i in A: C = list(bin(i)) C = C[2:] C = C[::-1] print C index = 0 for i in C: #print i,bits[index] bits[index] = bits[index]^int(i) index += 1 bits = bits[::-1] print bits result = "" for i in bits: ...
6d61170cc9b78518126f5608a298b0126de37c4e
io-ma/Zed-Shaw-s-books
/lpthw/ex33/ex33_sd5.py
255
3.75
4
def range_func(incr, up_limit): numbers = [] numbers = range(incr, up_limit) for number in numbers: print(f"The number is {number}") print("The numbers: ") for number in numbers: print(number) range_func(1, 6)
9da47a36f924afa943d13547c7cfdc07b0c7ae31
2damin/deeplearning_study
/activation_function.py
606
3.8125
4
import numpy as np import matplotlib.pyplot as plt #define activation function def sigmoid(x): return 1/(1 + np.exp(-x)) def step_function(x): if x > 0.0: return 1 else: return 0 def Relu(x): if x > 0.0: return x else: return 0 x = np.arange...
9159d42ae59a402eb85b219fadb986bcfc0378c1
SandaoTu/myday100
/day16-20/day16_algorithm/03_merge_sort.py
934
4.0625
4
""" 归并排序 分治算法 归并算法是稳定的排序算法 事件复杂度为 O(nlog(n)),空间复杂度为 O(N) """ def merge_sort(items,comp= lambda x,y:x<=y): # 归并算法 if len(items)<2: return items[:] mid = len(items)//2 left = merge_sort(items[:mid],comp) right = merge_sort(items[mid:],comp) return merge(left,right,comp) def merge(items1...
97b9851bbf3bad0be9569858c0217ba551fdc50d
pythonkila/learning-python
/Python.py
1,002
3.75
4
None if type(varA) == str or type(varB) == str: print ('string involved') elif varA > varB: print ('bigger') elif varA == varB: print ('equal') else: print ('smaller') n = 2 while n <= 10 : print (n) n = n + 2 print ('Goodbye!') t= 12 while t > 11 : print ('He...
b8cccbb72de9156b260c972b5ee6e0c5663be89f
saltire/starflight
/advengine/tests.py
3,270
3.828125
4
import random def is_filter(method): """Allow a test to be used as a filter for nouns. The test must take a single argument: an input word that could refer to a noun.""" method.is_filter = True return method class Tests: def __init__(self, game): self.game = game ...
98397a8d2d522be8ae8abf8c5de8e5f91e3494dc
keigezellig/stuff
/do
540
3.71875
4
#!/usr/bin/python3 import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("what", help="'stuff to do stuff, fix to fix things") args = parser.parse_args() what = args.what if what == 'stuff': for i in range(1, 200): print("doing very...
5798667e71dd546f5c25c93d39c3e1487f071385
mvillamea/Python-Exercises
/Scientific Computing with Python Projects/budget app/budget.py
4,290
3.765625
4
import math class Category: def __init__(self, name): self.name = name self.ledger = list() def deposit(self, amount, description=''): """ appends an object to the ledger list """ self.ledger.append({'amount': amount, 'description': description}) def withdraw(self, amount,...
5f0001b6a7581f12e1ac60cb19ed8d30a521cd4c
bnconti/Exercises-Primer-Python
/ch5/04_plot_Gaussian.py
473
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 5.4: Plot a function # Author: Bruno N. Conti import numpy as np from matplotlib import pyplot as plt def h(x): return (1 / np.sqrt(2*np.pi)) * np.exp(-0.5 * x**2) if __name__ == "__main__": xlist = np.linspace(-4, 4, 200) hlist = h(xlist) pl...
66bda1aac5fa0ba5b014ff2a045c9de7e292cae1
curetxy/homework
/day1/求100以内基数和.py
368
3.640625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- """ @author: davetan @license: Apache Licence @contact: curetxy@163.com @site: @software: PyCharm @file: 求100以内基数和.py @time: 2018-05-08-22:48 """ '''类描述''' sum = 0 for i in range(1,100,2): sum +=i print(sum) count = 100 sum_num = 0 for i in range(count): if i%2 == 0: ...
f8d155ab94a6501f503e91b70f6fad248046d2f1
ronitshar/oop_02
/ex04/merge.py
620
3.6875
4
from helper import Node def merge(train1, train2): current = train1 while current.next != None: current = current.next current.next = train2 return train1 def print_list(list_head): current = list_head while current != None: print(current.content) current = current.next train1Head = N...
a70644e8f4ed9eb419661aa5f5d189230e754c5e
dlindenb/spflookup
/spflookup.py
2,487
3.671875
4
#!/usr/bin/python # # SPF dns-record resolver. # # Report which IP adresses and/or subnets are included in a single SPF record. # import sys import getopt import dns.resolver from tabulate import tabulate def usage(): """ Show script usage """ print "USAGE:" print "spflookup.py [parameter] <url>\n" print "DESCR...
60612f98363116d4508680cee96688c745fce41c
Changyoon-Lee/TIL
/Algorithm/programmers/정수 삼각형.py
360
3.515625
4
# DFS하려다가 오래걸릴거같아서 안함 def solution(triangle): for i in range(len(triangle)-2,-1,-1): for j in range(len(triangle[i])): if triangle[i+1][j]>triangle[i+1][j+1]: triangle[i][j] += triangle[i+1][j] else : triangle[i][j] += triangle[i+1][j+1] return tr...
24547cf52e7c7eee41d8c8814d8dfca5d6bfd3bf
michaelzh17/python001
/personal_message.py
249
4.0625
4
person_name = 'eric smith' pname_up = person_name.upper() pname_lw = person_name.lower() pname_title = person_name.title() print(pname_up) print(pname_lw) print(pname_title) print('Hello ' + person_name + ', would you like to learn python today?')
3dc090de4ce45e53ef53a102fa15ad8e0a9fc125
fatihmms/N-Puzzle-Algorithm-with-Python
/UCS.py
1,078
3.6875
4
import queue as Q class UCS: def __init__(self, graph, root): self.graph = graph self.visited = dict() self.queue = Q.PriorityQueue() self.counter = 0 self.visited[root.UID] = root self.queue.put((root.step, root, int(root.UID))) def run(self, target): ...
59d65b084b63da836959a6c8f776057bda3ed895
ratara5/python-CS
/funcionesgeometricas.py
1,182
4.15625
4
F=3.141516 # Calcular el area de un cuadrado dado su lado def areacuadrado (): l=float(input ("Escribe el valor del lado del cuadrado (decimal usa .) ")) c=float(l*l) print ("El área del cuadrado es "+str(c)+" u^2") # Calcular el area de un triángulo dados su base y altura def areatriangulo (): b=float...
a70b6776e39d2fd81ef9e8ccedbbc315c85ccb6e
functionalnerd/SortingAlgorithms
/sorting/selection_sort.py
2,338
3.953125
4
""" Custom implementation of selection sort algorithm. Selection sort is an in-place comparison sorting algorithm, O(n^2). The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining t...
a7124975646f3fe613bf9575eb1b772056d9dc62
CodingDojoDallas/python_march_2017
/jessica_hart/assignments/OOP/animal_class.py
1,484
4.1875
4
class Animal(object): def __init__(self, name): # Initialize an animal with set health and give name self.name = name self.health = 100 def walk(self): # Walking and running drains the animal's health self.health -= 1 return self ...
05669da0ca5d9d42da20dd50ef4bc6c256c49d0a
tianshan/leetcode_py
/101.py
3,076
3.96875
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): self.queue = [root] i = 0 j = 1 ...
7081b5993a7f709bababa9e995bb116d792d4e11
sasha-pivovarov/Prog4
/homework_1/task_3.py
750
3.546875
4
class SingletonDecorator: """ Is only intended for use as a decorator. """ def __init__(self, decorated): self._decorated = decorated def create_object(self): try: return self._instance except AttributeError: self._instance = self._decorated() ...
d46c80b43f280a35f9b7ce48947ed6e122938cfb
nervaishere/DashTeam
/python/HOMEWORK/9th_Session/Answers/Correct/3.py
138
3.78125
4
for i in range(5): name , lastname ,BDy = map(str,input("Enter user's information: ").split()) BDy = int(BDy) print(name,BDy)
6c91dc5a4285250cf08275a6e88cb9ef0976f4e3
jaebradley/project_euler
/problems/pe7.py
666
4.09375
4
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number? """ import time from utils.is_prime import is_prime def nth_prime(n): counter = 0 number = 0 while counter <= n: number += 1 if is_prime(number): ...
7f1498913782d94f5e240ba7841e2aa415088999
baojianzhou/intro-dl
/simple_neural_network_1.py
14,982
4.1875
4
# -*- coding: utf-8 -*- """ A Step by Step Back propagation Example. This code is based on the implementation by Matt Mazur. Tutorial: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ Github: https://github.com/mattm/simple-neural-network """ import numpy as np def neuron_creat...
d828a2892a7f9eb70d09a50061fa31e92ee55dd7
daniel-reich/ubiquitous-fiesta
/B2jcSh2RG4GpQYuBz_0.py
100
3.578125
4
import re def is_valid_phone_number(txt): return bool(re.match('^\(\d{3}\) \d{3}-\d{4}$', txt))
05ff2e22f4756f445906162d1b81d22b1b5917e6
scriveausti/01_lucky_unicorn
/lucky unicorn.py
3,086
3.875
4
# imports import random # setting variables no = ["no", "n"] yes = ["yes", "y"] # number checker def number_check(): while True: try: print("") number_check.spend = int(input("how much money would you like to spend between $0 and $10?")) if 10 >= number_c...
15b02c9afb099bd7fd8c150df2fecd2731735b0c
lola-lambda/Sprint-Challenge--Hash-Theory
/theory/truthtable.py
261
3.75
4
# !(A || B) || ( (A || C) && !(B || !C) ) # not (A or B) or ((A or C) and not (B or not C)) for A in [False, True]: for B in [False, True]: for C in [False, True]: print(f"A: {A} B: {B} C: {C} ---- {not (A or B) or ((A or C) and not (B or not C))}")
acde2b806b802375451119d9553d9e81e9c5b5aa
icq6679166/Python
/BDPy/Py27Lab/demo26_list_access.py
655
3.859375
4
day_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] lengths = [] for day in day_of_week: lengths.append(len(day)) print lengths # type2 print [len(day) for day in day_of_week] print["**" + day + "**" for day in day_of_week if len(day) > 6] sun, mon, tue, wed, thr, fri, sa...
67a8f6ab00553eea7153ac04b335aef94362863d
Kvazar78/Skillbox
/12_def/task_123_2.py
1,556
3.53125
4
# Вот это объёмы 2 # Андрей продолжает писать курсовую работу по физике и теперь ему нужно находить не только объём планеты, # но и её площадь. Для этого он использует две такие формулы:: # # Формула для площади сферы: S = 4 * pi * R**2 # Формула для объёма шара: V = (4/3)*pi * R**3 # # Так как в самом курсовом проекте...
f30b23551b250e02f2d0b9a43d82efdce507342f
claraj/ProgrammingLogic1150Examples
/8_strings/string_character_index.py
127
3.59375
4
""" Can access charcters in a string by index """ phone = 'Android' print(phone[3]) # Prints r print(phone[5]) # Prints i
cfde12f2c610133769c926834806013cfbac6f62
ykmc/contest_old
/library/graph/dijkstra.py
395
3.671875
4
import heapq INF = float("inf") def dijkstra(nodeNum, start, adjList): cost = [INF]*nodeNum cost[start] = 0 hq = [(0,start)] heapq.heapify(hq) while hq: hc, hv = heapq.heappop(hq) for to, c in adjList[hv]: if hc + c >= cost[to]: continue cost[...
b78034500fe5b3d29771f6fd5e56e544b4fceff8
Aegir9/Curso-de-introducao-python3
/Desafios/desafio006.py
149
4.125
4
num = int(input('Digite um número:')) print('O dobro de {} é {} \no triplo é {} \ne a raiz quadrada é {}'.format(num, num*2, num*3, num**(1/2)))
aea6f585ddcf812df23990ff602b3dbb32a611bb
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day17/多线程/demo05_常用方法和参数.py
1,449
3.921875
4
""" 线程对象的常用方法和参数 Thread() 参数1: 被执行的任务 参数2: name= 线程的名字 参数3: args=() 类型为元组, 用来给被执行的函数, 传递参数 参数4: kwargs={} 类型为字典, 用来给被执行的函数, 传递参数; key为参数名, value为参数值; .join() 阻塞当前线程的执行, 直到自己线程执行完毕 如果设置了timeout(阻塞时间), 若在阻塞时间内t线程执行完毕, 则不会再继续阻塞 .is_alive() 判断该线程是否还活着 """ from ...
7ec2c525db99e6d5589c38dc69283956bef712be
DenChyang/pyDemo
/py-base/day10/code/老王开枪/老王开枪.py
1,878
3.71875
4
class Person(object): def __init__(self,name): self.name = name self.gun = None # 血量 self.hp = 100 pass # 添加子弹到弹夹中 def add_zidan_2_danjia(self,zi_dan_temp,dan_jia_temp): dan_jia_temp.add_zi_dan(zi_dan_temp) # 添加弹夹到枪中 def add_danjia_2_gun(self,dan_jia_t...
4bf67e6c10b0efa66d297faf83741df4dda75ee7
frknn/nlp-exercises
/HelloWorld.py
435
3.75
4
# from nltk.corpus import stopwords # from nltk.tokenize import word_tokenize # # example_sent = "This is an example showing off stop words filtration." # # stop_words = set(stopwords.words("english")) # # words = word_tokenize(example_sent) # # filtered_sent = [] # # for w in words: # if w not in stop_words: # ...
e442a9f80a8157c8c0b005fa35ea982a4b2f8449
tungcyang/PythonLeftTruncatablePrimes
/lefttruncatable_threading.py
21,797
4.0625
4
""" lefttruncatable.py is written to print out all left-truncatable primes. According to "Truncatable prime" in https://en.wikipedia.org/wiki/Truncatable_prime, there are 4260 decimal left-truncatable primes. The multithreading mechanism is referenced from http://www.tutorialspoint.com/python/python_multithread...
4a93f98ac66d850fffe0871aa6a3a9e5e4e447c7
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/07-Exploratory_Data_Analysis_in_Python/e23_height_and_weight.py
1,008
4
4
""" Height and weight Recall how Allen created the box plot of 'AGE' and 'WTKG3' in the video, with the y-axis on a logarithmic scale: sns.boxplot(x='AGE', y='WTKG3', data=data, whis=10) plt.yscale('log') Fill in the parameters of .boxplot() to plot the distribution of weight ('WTKG3') in each height ('_HTMG10') ...
8bc95c146dfa2cb1a60c09e9d016a50b20dcc3d9
hemxzp/leetcode
/36. Valid Sudoku.py
1,299
3.5
4
# -*- coding:utf-8 _*_ class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ b=[[],[],[],[],[],[],[],[],[]] c=[[],[],[],[],[],[],[],[],[]] for i in range(9): for j in range(9): b[j].append...
cefad73edaef8b47bfd355a7c900fb2ef221c816
rohith2506/Algo-world
/interviewbit/strings/roman2Int.py
542
3.65625
4
class Solution: def romanToInt(self, A): roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} numeric_value = roman_dict[A[0]] for i in range(1, len(A)): cur, prev = A[i], A[i-1] if roman_dict[cur] > roman_dict[prev]: numeric_value = numeric_value - roman_dict[prev] temp_v...
c4230180a83d872016b14705665722227e758a17
billyean/pyEx
/sd/module8/midterm_task_3.py
3,223
4.03125
4
import os import time import sys from datetime import datetime def main(): # Converts the values from the file midterm_input.txt into a dictionary of lists, with each key being ID # and # each value being an in-date/out-date list. with open('midterm_input.txt', 'rt') as inputf: lines = inputf.read...
762fc92edb4eaeb6c07c999b1da4a1e69c8ec123
xtudbxk/practice
/python/exchange_chars.py
3,154
3.71875
4
#Algorith Problem #字符串S由小写字母构成,长度为n。定义一种操作,每次都可以挑选字符串中任意的两个相邻字母进行交换。询问在至多交换m次之后,字符串中最多有多少个连续的位置上的字母相同 # #思路: #以每个点当做最长连续子序列中未移动的点,进行向左向右扩展 def get_max_length_of_substring_has_same_characters_after_exchaing(s,m): left_and_right_p_of_same_char = [] nearest_position_of_left_char = {} for single_index,single_c...
d2d400efa3c21c9585f606dedc800c4464f8adcc
FaisalWant/ObjectOrientedPython
/Threading/DerekExamples/Examples/Dog.py
439
3.765625
4
class Dog: def __init__ (self,name="", height= 0,weight=0 ): self.name= name self.height= height self.weight= weight def run(self): print("{} the dog runs", format(self.name)) def eat(self): print("{} the dog eats".format(self.name)) def bark(self): print("{} the dog barks"....
41312219bf688b3d58fc538563c024985b432ed6
RUPAbahadur/Python-Programs
/task-name-tag.py
352
4.0625
4
""" Task- to make a name tag """ def greet(string, age): if(age>=18): answer="So you are major." else: answer="So you are minor." greeting="Hello {}. {}" return greeting.format(string, answer) string=input("May I know your name?\n") age=int(input("and how old are you?\n...
49c121e2daa718a68ad7779bcd3f6819f9094dc5
lotspaih/automateBoringstuffPython
/Chap15PracPrettifiedStopwatch.py
1,185
3.984375
4
#! python3 #! /usr/bin/env python3 # Chapter 15 Practice Prettified Stopwatch # Simple Stop Watch Program # NOTE: Writing output to data text file rather than use pyperclip module. # Then file can be attached to email or copied as needed. And a # separate module outside the standard library is not require...
760f32d752b94b89a3ca019f48074b3e25f66990
margaretblue/traffic-simulation
/traffic-simulator.py
8,192
3.78125
4
import numpy as np import matplotlib import statistics import math import random class Road: """has length, type, chance of random slowing down, Tracks where cars are Road looks like this: | | | | | | | | | | | | | | | | | | | | | ... | <= end 0 1 2 3 4 5 6 7 8 ...
3d55a2e1658bce0952a30ab6bedec75a61a5245f
3974kjh/baekjoon
/6019_fly.py
197
3.5
4
T = int(input()) for test in range(T): n = list(map(float, input().split())) time = n[0] / (n[1] + n[2]) res = n[3] * time print("#{}".format(test+1),end=' ') print('%.6f' %res)
0fb29a54d1439676acfc01214a9b199a341e0e9c
Ingynnmon/Python
/formatString.py
752
3.796875
4
#week 5A 26.9.2019 animals = { 'Tiger' : 3000, 'Lion ' : 3822, 'Leopard': 400 } for animal, amount in animals.items(): print(f'{animal:1} ==> {amount:1d}') # bird = 'sparrow' print(f'My plane hits {bird} over the cloud.') print(f'{bird} {bird} My plane hits {bird!r} over the cloud.') #The string format x...
abe4bf5be651ddfdc2ff94d16873c40a447df1b6
predatory123/byhytest
/python_practice/python0516/Restaurant.py
1,100
3.796875
4
class Restaurant(): #定义一个 饭店 类 def __init__(self,restaurant_name,cuisine_type): # 初始化属性 name 和 type,定义一个方法 self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): #定义其中一个方法 print('This restaurant\'s name is ' +self.restaurant_name...
5e1a82f786ae5d07bb6c45a0186bf60d6689820c
Aasthaengg/IBMdataset
/Python_codes/p03260/s180009679.py
206
3.5625
4
import sys def solve(): input = sys.stdin.readline A, B = map(int, input().split()) if A == 2 or B == 2: print("No") else: print("Yes") return 0 if __name__ == "__main__": solve()
c497ffd99484d5907595f81ddbc5940e08a99806
Adasumizox/ProgrammingChallenges
/codewars/Python/5 kyu/ValidParentheses/valid_parentheses.py
204
4
4
def valid_parentheses(string): cnt = 0 for char in string: if char == '(': cnt += 1 if char == ')': cnt -= 1 if cnt < 0: return False return True if cnt == 0 else False
a5c26d50cc04067490467e5b830eb3690da0642e
wuyi365/leetcode
/leetcode/SearchforARange.py
908
3.6875
4
class Solution: # @param nums, a list of integers # @param target, an integer to be searched # @return a list of length 2, [index1, index2] def searchRange(self, nums, target): left=0 right=len(nums)-1 if target<nums[left] or target>nums[right]: return [-1,-1] while left<...
8fe26d23c8568bc4ebacffec0e35e31355eaa9a2
maggawron/Advent_of_code_2020
/Task_6_1.py
625
3.65625
4
def best_result(line): print(line) result = 0 for set_item in line: result += len(set_item) return result def main(): line = [] memory = [] try: while True: string = input() if string == "": memory = set(memory) ...
fba85b330eae1114a6bc9508cf95d984b19b6014
akshit6/hospital-management-system-using-tkinter
/hospital management system/appointment.py
6,208
3.59375
4
# import modules from tkinter import * ## notice lowercase 't' in tkinter here import tkinter as tk import sqlite3 import tkinter.messagebox # connect to the databse. conn = sqlite3.connect('database.db') # cursor to move in the database c = conn.cursor() # empty list to later appends the ids from the database ids...
a22262511b4234fa5d0b954d7366114ca45a0997
saranshbansal/learn-python
/interview_ques/compress_words.py
318
3.53125
4
def compress_words(word, K): for index, c in enumerate(word): substr = word[index:index + K] if len(set(substr)) == 1: word = word.replace(substr, "") # breaking condition if len(set(word)) == len(word): return word print(compress_words('bvsadddaa', 3))
c995f49ab5b3f5848964a72d1acc2a9188efb12b
sophiaalao/practice1
/12 practice.py
180
3.5
4
num = 10 flag = True while True: for i in range(1, 20): if(num % i != 0): flag = False if flag: break else: num += 1 flag = True print(num)
a62079b786639281c119dc8a774b49753d88a36d
Aasthaengg/IBMdataset
/Python_codes/p02844/s355906790.py
540
3.640625
4
def is_passcode_exist(S,passcode): passcode_idx = 0 passcode_is_exist = False for c in S: if passcode_idx == 3: passcode_is_exist = True break if passcode[passcode_idx] == c: passcode_idx += 1 if passcode_idx == 3: passcode_is_exist = True ...
4d0cf9d3e2c88a1dc2a882f1cf44599f9de9c654
ashish8796/Codewars
/python-kata/cdw_prlm17.py
581
3.765625
4
''' Their preference is to get the orders as a nice clean string with spaces and capitals like so: "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke" ''' order = "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza" def get_order(order): menu = ["Burger", "Fries", "Chicken", "...
250ea48461ef69bde59f0af0c8b4c5ce1bf433e9
cclaude42/python_bootcamp
/day01/ex00/test.py
858
3.8125
4
#!/usr/bin/env python3 """ Book and recipe tests """ from recipe import Recipe from book import Book if __name__ == '__main__': # Create Recipe : listy = ['Pate', 'Saumon', 'Epinard'] tourte = Recipe("Tourte", 3, 20, listy, "", "lunch") # Create second Recipe : listy = ['Miel', 'Banane', 'Yaourt...
a80d314107fb38d2cc859b1b0712378076976a28
Soumithri/coding_problems
/src/hashes/answers/palindrome_permutation.py
217
3.5
4
def has_palindrome_permutation(string): count_set = set() for i in string: if i in count_set: count_set.remove(i) else: count_set.add(i) return len(count_set) <= 1
f5a04b76cf8dc5b3a4e494a25c42bc5dd5fcedf8
Yucheng7713/CodingPracticeByYuch
/Easy/501_findModeInBinaryTree.py
689
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.t_map = collections.Counter() def dfsTraverse(self, node): if not node: return self...
5e4068efccb2c708dfb1c9960d412726a18a4409
manju838/Pytorch-Implementations
/pytorch-Neural_Network2.py
4,963
3.71875
4
# Imports import torch # Importing general library import torch.nn as nn # Importing all neural network modules,different model architectures like Linear,CNN,loss fns etc. import torch.nn.functional as F # Importing all functions that don't have any parameters like activation fns. import torch.optim as optim # Impo...
d7396b7575468633b935d7618bc3b507afd464b3
Mustafa017/python-programs-
/interpreter.py
589
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 10 22:05:40 2017 @author: mustafa """ '''fooDate='10/3/2003' month, day, year = fooDate.split('/') month=int(month) day=int(day) year=int(year) [month, day, year] = map(int, fooDate.split('/')) [month, day, year] = [int(x) for x in fooDate.split('/')]''' '''digits = '1...
76262c16e92d4f1991b5bbcfbe7fbd8db9369024
voraparth1337/System-Programming-and-Compiler-Construction-Solutions
/recursive descent parser.py
1,351
3.796875
4
# Written by Parth V # Disclaimer : I am no expert in python but just a learner. In no way is this code perfect or the most 'pythonic' implementaion # It was written for practice and understanding the concepts. Feel free to extend or make it better. Cheers !! # www.parthvora.tk # implementation of a recursive ...
ed0709bda8d3a4b1d7d7e4de62f094a926b2f769
sunggeunkim/datastructure
/codefight/restoreBinaryTree.py
1,865
4
4
''' Let's define inorder and preorder traversals of a binary tree as follows: Inorder traversal first visits the left subtree, then the root, then its right subtree; Preorder traversal first visits the root, then its left subtree, then its right subtree. For example, if tree looks like this: 1 / \ 2 3 / ...
45c7ff7e5e2c74f56487fe580a5941adeec1f09a
Mr-Roy-alt/Python
/week5.py
916
3.828125
4
#Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. #The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. #The program creates a Python dictionary that maps the sender's mail address to a count o...
179a2f63549a06c930c5eac772e1a16cff0bdea0
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-03 Leetcode Vector And Deque/Kids With The Greatest Number of Candies.py
321
3.75
4
def KidsWithCandies(candies, extraCandies): m=max(candies) for i in range(len(candies)): p=candies[i]+extraCandies if p<m: candies[i]=False else: candies[i]=True return candies print([2,3,5,1,3]) print(KidsWithCandies([2,3,5,1,3],3)) ...
f631695a0a6faaa60b664790ae453b0ab57d4a0b
thehimalayanleo/PySyft
/packages/syft/src/syft/core/smpc/approximations/exp.py
1,072
3.78125
4
"""Function used to calculate exp of a given tensor.""" # future from __future__ import annotations # stdlib from typing import TYPE_CHECKING from typing import Union if TYPE_CHECKING: # relative from ...tensor import Tensor from ...tensor.smpc.mpc_tensor import MPCTensor def exp( value: Union[Tenso...
73ee5e759692594b5e0d605b36d4025d57e1bc1f
jerrychen44/numpy_pandas_matplotlib_scipy
/numpy/01_dot_product_for_loop_time_comparsion.py
614
3.5
4
import numpy as np from datetime import datetime a = np.random.randn(100) b = np.random.randn(100) T = 100000 def slow_dot_product(a, b): result = 0 for e, f in zip(a, b): result += e*f return result # old school way t0 = datetime.now() for t in range(T): slow_dot_product(a, b) dt1 = datetime....
16b0a3173b70d2fe23cfb682de9a04367132e377
webclinic017/stock-trading-5
/strategies.py
3,049
3.53125
4
import backtrader as bt class PrintClose(bt.Strategy): """sample strategy class for printing closing prices""" def __init__(self): self.dataclose = self.datas[0].close def log(self): """print date and closing price""" date = self.datas[0].datetime.date(0) closing_price = ...
185f378b7d90ac2065bdab456d4b17758572cd34
SyedaRAlam/gwc
/week 3/twitter.py
4,254
4.0625
4
''' In this program, we print out all the text data from our twitter JSON file. Please explain the comments to students as you code. ''' # We start by importing the JSON library to use for this project. # Twitter data is stored in this format - this is the same format # students learned for their Survey Project! impo...
576105e6239eed53e13c3995035d1b394a3e1882
Maxpia/PythonStudy
/DeepLearingFromScratch/04-1 MNIST_study.py
990
3.5
4
# 04-1 MNIST_study #import import numpy as np #평균 제곱 오차 함수 # E = ½∑(y-t)² : y는 신경망 출력, t는 정답 레이블 def mean_squared_error(y, t): return 0.5 * np.sum((y-t)**2) #평균 제곱 오차 테스트 t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] print('mean_squared_error') y = [.1, .05, .6, .0, .05, .05, .0, .1, .0, .0] print(mean_squared_error(np.ar...
12164d97408f1e61848152e26dc35ec56b99af4a
bigdata202005/PythonProject
/Day06/Ex02.py
584
4.0625
4
# 10 미만의 자연수에서 3과 5의 배수를 구하면 3, 5, 6, 9이다. 이들의 총합은 23이다. # 1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라. # 1. 합계를 저장할 변수 # 2. 1 ~ 1000까지 반복 # 3. 3의배수 또는 5의배수를 판단 def my_sum(limit): sum = 0 for i in range(1, limit): if i % 3 == 0 or i % 5 == 0: sum += i return sum if __name__ == '__main__': ...
f6e30aba0dd618b2a042aaf1f4996f14bb863d58
jaishivnani/Python-Practice-Problems
/3. Chapter 3 Strings/Practice problems/46_string.py
650
4.0625
4
'''Exercise Question 4: Count all lower case, upper case, digits, and special symbols from a given string Given str1 = "P@#yn26at^&i5ve" Total counts of chars, digits,and symbols Chars = 8 Digits = 3 Symbol = 4 ''' str1 = "P@#yn26at^&i5ve" def lowerfirst(str1): charcount = 0 digitcount = 0 symbolcount = 0...
c35fc57fec26636282eba11ea122628c8a07c0a3
ericaschwa/code_challenges
/LexmaxReplace.py
1,192
4.34375
4
""" LexmaxReplace By: Erica Schwartz (ericaschwa) Solves problem as articulated here: https://community.topcoder.com/stat?c=problem_statement&pm=14631&rd=16932 Problem Statement: Alice has a string s of lowercase letters. The string is written on a wall. Alice also has a set of cards. Each card contains a single let...
606e5d654bbb37d11ccd8b6a9b6a6989b91b6347
DVampire/offer
/offer_06_01.py
885
3.75
4
# -*- coding:utf-8 -*- import time ''' 题目:从尾到头打印链表 输入一个链表,从尾到头打印链表每个节点的值。 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution(object): def func1(self, *args, **kwargs): ''' 思路一:使用栈实现 ''' if not args[0]: return []...
5f972caa89b73c0e84679fa020d38dc72a0ce861
blaylockbk/Carpenter_Workshop
/paint/terrain.py
3,432
3.65625
4
## Brian Blaylock ## June 1, 2020 """ ================ Terrain Colormap ================ """ import matplotlib.colors as mcolors import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl # Inspired by the Matplotlib docs # https://matplotlib.org/3.2.0/tutorials/colors/colormapnorms.html#custom-norm...
50cfdae35282ac5e4778138ad46de21c07d4ccf4
AndreasTang/python101
/classPractice/findPrime.py
510
4.03125
4
startNumber = int(input('Please enter start number: ')) endNumber = int(input('Please enter end number: ')) prime = [] def printPrime(startNumber, endNumber): for divisor in range(startNumber, endNumber): isPrime(startNumber, endNumber) def isPrime(startNumber, endNumber): for dividend in range(2, en...
1502ed7cd59bd4182bf5cb2247e6166650bab53e
ruthiler/Python_Socket
/clienteCHAT.py
2,108
3.625
4
#!/usr/bin/python # -*-coding:utf-8-*- import socket from threading import Thread class VerificaMensagens(Thread): def __init__(self, tcp): Thread.__init__(self) self.tcp_cliente_socket = tcp def run(self): self.tcp_cliente_socket = tcp self.fechar = False while (not s...
d1683db8e58069a27bc14490f507b1a9deedb8d3
lakshsharma07/training2019
/day22/deliveryfleet.py
2,278
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 10:47:08 2019 @author: Lakshay """ """ Q1. (Create a program that fulfills the following specification.) deliveryfleet.csv Import deliveryfleet.csv file Here we need Two driver features: mean distance driven per day (Distance_feature) and the mean percentage of tim...
f3eaf7757f9d048bc2ceb738d8375b514e865c87
saleempashaik/Python
/Intro/Dictionary.py
105
3.828125
4
D = {'name': 'Sam','location': 'Iowa', 'name': 'Sama'} print(D) print(D['name']) D['age']=27 print(D)
e358f55decf2618a5eff11db7cfbfd28f314c573
ataylor89/projecteuler
/python/problem06.py
206
3.515625
4
#!/usr/bin/python z = range(1, 101) s = 0 t = 0 for x in z: s += x**2 t += x t = t**2 diff = t - s print "Sum of squares: " + str(s) print "Square of sum: " + str(t) print "Difference: " + str(diff)
fd0f9706fc437f8ea0704348072a96d877170873
dvanatta/Exercism
/bob.py
570
3.9375
4
# This is bob # If all of the letters are caps its yelling # elif ends in question # elif blank # else whatever def check_yelling(string): return string.isupper() def check_question(string): return string[len(string) - 1] == "?" def check_empty(string): if len(string) == 0: return True else: re...
38520c92313a43642fa3613c858aa1bd02189a26
shen-huang/selfteaching-python-camp
/exercises/1901010145/1001S02E04_control_flow.py
297
3.75
4
for i in range(1,10): for j in range(1,i+1): print("%d*%d=%2d" % (i,j,i*j),end=" ") print (" ") for i in range(1,10): for n in range(1,10): if n<=i: while n*i%2!=0: print(str(i),"*",n,"=",i*n,end='\t') break print("")
0dd1a0aa09b7f58b1e071096c6dd59a91612a533
sweetpand/Algorithms
/ProjectEuler/python/p518.py
2,589
3.59375
4
# # Solution to Project Euler problem 518 import eulerlib, fractions, itertools # Suppose (a+1, b+1, c+1) are three positive integers that form a geometric sequence. # Then by definition, (c+1)/(b+1) = (b+1)/(a+1) = r for some ratio r. # r is a rational number because we are given that a, b, c are integers. # # Be...
4f128726f619958999b62bc8c45a5aac9ff88bb9
sjbrady96/matrix_mult
/matrix.py
1,613
4.0625
4
''' This program reads integers from a user specified input file into two 2D arrays (matricies). The matricies are multipled together and the rows of the product matrix are sorted. All the matricies are written to an output.txt file in the same directory as matrix.py. @author Sean Brady @version 1.0 11/11/2017 ''' in...
267751ad45ac3fcbb9d4320c6090d8fbe21f8751
Lok-Aravind-Palu/python-practice
/BeyondBasics/if_none.py
158
3.5625
4
def if_none(): if None: print("yes") else: print("No") if_none() tup = (1, 2, 3, 4, 5, 6) print(tup[1:3]) lis = [1,2,3,4,6,7]
46f19c9d29bade4c01251e58decbc8bb6f8847e9
Sniper970119/Algorithm
/chapter_10/QueueMine.py
689
3.78125
4
# -*- coding:utf-8 -*- class Queue(): def __init__(self): self.queue = [0 for _ in range(10)] self.head = 0 self.tail = -1 pass def enqueue(self, i): """ 入队 :param i: :return: """ self.tail += 1 self.queue[self.tail] = i ...
8065fba766a223248fc0e96cab2c29705e21702c
dkrajeshwari/python
/python/discount.py
215
3.828125
4
amount=float(input("Enter the amount:")) if amount>=10000: discount = amount*0.2 else: discount=amount*0.05 net_amount=amount-discount print(f"Bill amount:{amount},discount:{discount},Net Amount:{net_amount}")
c818d494dcced6ff535dd5fe06546faa69040169
Ziqi-Li/Cracking-the-code-for-interview
/Ch8. Recursion/8.4.py
483
3.921875
4
''' Ziqi Li 8.4 Write a method to compute all permutations of a string ''' def permutations(nums): def helper(nums,index,path,res): if index==len(nums): res.append(path) return for i in xrange(0,len(nums)): if nums[i] not in path: helper(nums,inde...