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
4cf6e8b0263178be722a6e2efe85420da3db09c8
JiJibrto/lab_rab_5
/individual/individual_1.py
537
3.984375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import sys # Дано предложение. Вывести все имеющиеся в нем буквосочетания нн. if __name__ == '__main__': in_file = str(input("Введите предложение> ")) in_file.lower() temp = 0 temp = in_file.count('нн') if temp == 0: print("Буквосочетания ...
f6cc45759b2a35c48c6db99e231f1baa7b3e510d
a-jennings/EDX_Midterm
/EX5.py
333
3.96875
4
#items_price takes quantity (list a) and multiplies with cost (list b) # to give a total cost of items. Lists are assumed to be equal length. def items_price(a,b): total = 0 for x in range(len(a)): total = a.pop(0)*b.pop(0) + total return(total) a = [4, 6, 3, 1, 10] b = [5, 6, 2, 4, 1] items_pri...
0bd7d806e9ad2057d04f29938e3329a2e6d7dab3
bcjordan/python
/lab01/Song.py
695
3.875
4
class Song: """Class for representing information about a song""" def __init__(self, title, artist, album): self.title = title self.artist = artist self.album = album def output(self): print('Title: "{0}"').format(self.title) print('Artist: {0}').format(self.artist) ...
ac3b0aa52b800aa5efa7a91221ade6697592b4e2
oliviagoo/movie-rater-python-assessment
/old components/movie program search frame.py
1,083
3.578125
4
#version 5 - setting up the search frame from tkinter import * RATINGS = ["No Rating", "1", "2", "3", "4", "5"] class MovieRaterGUI: def __init__(self, parent): self.search_rate = StringVar() search_frame = Frame(parent) search_label = Label(search_frame, text = "Search for movies with ...
1c0caaffdef74eb1911756360307908310c811b2
laviniabivolan/Spanzuratoarea
/MyHangman.py
2,394
4.125
4
import random def guess_word(): list_of_words = ["starwards", "someone", "powerrangers", "marabu", "mypython", "wordinthelist", "neversurrender"] random_word = random.choice(list_of_words) return random_word def hangman_game(): alphabet = 'abcdefghijklmnoprstuvwxyqz' word = guess_word() ...
7c30f6b2be5904401f1981135e8cfab6b1999c4c
NickRojckov/lab_1.1
/задание 1.py
200
3.546875
4
a = int(input()) b = int(input()) c = int(input()) X = 0 Y = 0 if a>0: X+=1 elif a<0: Y+=1 if b>0: X+=1 elif b<0: Y+=1 if c>0: X+=1 elif c<0: Y+=1 print(X,Y)
fa6057a380c53fda8b1607094f29dce90f2f510e
dgu12/Fakespeare
/genPoem.py
6,472
3.828125
4
from hyphen import Hyphenator import numpy as np import random import sys from visualize import * from rhyme import * ''' This file contains functions for generating poems from an HMM description ''' def hmmGenerate(A_Mat, O_Mat, tokens, startP = None): ''' Generates a poem from a HMM's A matrix and O matrix ...
efcb63ba80b697680a8b907923bcbcdc609ae94e
Wmeng98/Leetcode
/Easy/merge_2_sorted_lists.py
1,295
4.21875
4
# Solution 1 - Recursive Approach # Recursivelly define the merge of two lists as the following... # Smaller of the two head nodes plus to result of the merge on the rest of the nodes # Time 0(n+m) and Space O(n+m) -> first recursive call doesn't return untill ends of l1 && l2 have been reached # Solution 2 - Itera...
911b133099fdc39a5c0fee6eeb32ee9f3d1dc044
Wmeng98/Leetcode
/CTCI/Python/functions.py
1,232
3.921875
4
''' Python Inner/Nested Functions # Has access to variables and names defined in the enclosing function # Encapsulation, hide from external access In Python, Functions are **first-class citizens** Means on par with any other object such as numbers, strings, lists, tuples, modules, etc. You can dynam...
1f858c8755bb4c927e9269b9b01871f4d2b15e24
Wmeng98/Leetcode
/CTCI/Python/notes.py
5,949
3.8125
4
# Python ''' Note Python 3's int doesn't have a max size (bounded by memory) float('inf') is for infinity, guaranteed to be higher than any other int value range vs. xrange (deprc in python3) If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecat...
7210057fb5068f880b93a09ebfda8e00a8f9b0b6
Wmeng98/Leetcode
/Dynamic Programming/pramp_number_of_paths.py
2,306
4
4
# Like leetcode unique paths but restriction that car can't cross diagonal border def num_of_paths_to_dest(n): # recursive approach # return num_paths(0,0,n) # [MEMOIZATION] is top-down # Bottom up would be Tabulation # init to -1 to indicate uncomputed memo = [[-1]*n for _ in range(n)] def num_p...
54e1ec09fd057b7e7f37e1d2f8e209459ad26e19
Wmeng98/Leetcode
/CTCI/Python/types.py
516
3.6875
4
''' List Tuple - collection which is ordered and unchangeable, and allows duplicate values - written with round brackets - Can be indexed - NOTE: use when want list of constants, Tuples can also be used as key in dict Dictionary - key value pairs Sets - set items are unordered, unchangeable, a...
6479f78c861a015b6dd42adbae231014b6a4f53d
layan21-meet/meetyl1
/inheritance.py
957
3.828125
4
from turtle import Turtle import turtle class Ball(Turtle): def __init__(self,r,color,dx,dy): Turtle.__init__(self) self.penup() self.dx = dx self.dy = dy self.shape("circle") self.color(color) self.r = r self.shapesize(r/10) def move(self,screen_width,screen_height): current_x = self.xcor() new...
cfcd01b620080975032453d307479bc8016a7f8e
Jelowis/DEBER15
/Cola.py
1,302
4.03125
4
# Leonardo Altamirano Retto # 3 Semestre Software class Cola_1: def __init__(self,tamanio): self.lista=[] self.size=tamanio self.top=0 def push(self,dato): if self.top <self.size: self.lista = self.lista + [dato] self.top += 1 return True ...
1ab21a736cafc0550e8dc579170f939ae03e0bae
idixon2/csc221
/hw/hw4/hw4_solution.py
309
4.03125
4
def is_odd(number): return number%2==1 def is_even(number): return not is_odd(number) def is_mult_of_four(number): return number4 == 0 def is mult_of_divisor(number,divisor): return number%divisor def both_ ends(s): if len(s) < 2: return '' else: return s[:2] +[-2
ff234acf470b12fe21ee41df3d2a2cf69bd0af91
tejalbangali/HackerRank-Numpy-Challenge
/Arrays.py
502
4.40625
4
# Task: # --> You are given a space-separated list of numbers. Your task is to print a reversed NumPy array with the element type float. # -> Input Format: A single line of input containing space-separated numbers. # -> Sample Input: 1 2 3 4 -8 -10 # -> Sample Output: [-10. -8. 4. 3. 2. 1.] import numpy def...
0833af795b79bc5ba21775f472cf16c5a1aa7cf6
BhaskarSrinivasK/PythonZone
/PasswordGenerator(Using only random library).py
553
3.921875
4
import random print("Want a Secure a password?") length = int(input("Enter the length of password required!! : ")) lower = [] for i in range(65,91): lower.append(chr(i)) upper = [] for i in range(97,123): upper.append(chr(i)) symbols = [] for i in range(33,48): symbols.append(chr(i)) num = [0,...
1da880569a546ff5a0ab841952173e1810a3527d
SybelBlue/SybelBlue
/main/maze_maker.py
2,307
3.71875
4
import random directions = ['up', 'down', 'left', 'right'] class Cell: def __init__(self, i, j): self.pos = i, j self.visited = False self.walls = {x: True for x in directions} def move_to(self, other): if self.pos[0] < other.pos[0]: self.walls['right'] = False ...
8fc4be8aa0b68e0aabb63686cf41d514c92e8a36
Tanukiii/Keras-Functional-and-Sequential-API
/Keras Functional and Sequential API.py
11,189
3.609375
4
#!/usr/bin/env python # coding: utf-8 # # Keras Functional and Sequential APIの使い方 # ## Preparcing Tensorflow2.x and Dataset MNIST # In[1]: import tensorflow as tf import keras # Mnist mnist = keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # Normalization 0-255の値が入っているので、0-1に収まるよう正...
bea6d1297b379920ae263850f2eb40a3397c1159
sundnes/solving_odes_in_python
/docs/src/appendix1/interest_v2.py
551
3.59375
4
import numpy as np import matplotlib.pyplot as plt import datetime x0 = 100 # initial amount p = 5 # annual interest rate r = p / 360.0 # daily interest rate date1 = datetime.date(2017, 9, 29) date2 = datetime.date(2018, 8, 4) diff = date2 ...
52706c76dbdab396370d5491bc574b3ef0bca6f3
sundnes/solving_odes_in_python
/docs/src/chapter1/forward_euler_class.py
1,997
4
4
""" Forward Euler class implementation for systems of ODEs. """ import numpy as np class ForwardEuler: def __init__(self, f): """Initialize the right-hand side function f """ self.f = lambda t, u: np.asarray(f(t, u), float) def set_initial_condition(self, u0): """Store the initial co...
83243d09a2140da62c7a572d2d887e879801e104
victordity/PythonExercises
/PythonInterview/binarySearch.py
1,029
4.21875
4
import bisect def bisect_tutorial(): fruits = ["apple", "banana", "banana", "banana", "orange", "pineapple"] print(bisect.bisect(fruits, "banana")) print(bisect.bisect_left(fruits, "banana")) occurrences = bisect.bisect(fruits, "banana") - bisect.bisect_left(fruits, "banana") print(occurrences) # ...
22a28e41992b8d36c2b5b676a0ba17cc70eb7696
justdharmik/Python-Things
/5. Search.py
560
3.921875
4
def search(text, word, count): lst = list(text.split(" ")) if word in lst: result = f"Word found! '{word}'' in '{text}'" for i in lst: if i == word: count += 1 else: result = "Word not found!" print(f"Instances: {count}") return result #text ...
38200fdf05a7f80e7bce3773a0f954ec8e3e67f0
vfperez1/AdivinaNumero
/entrada/menu.py
744
4.125
4
""" Módulo que agrupa todas las funcionalidades que permiten pedir entrada de números """ import sys def pedirNumeroEntero(): correcto = False num = 0 while (not correcto): try: num = int(input("Eliga una opción del 1 al 4: ")) correcto = True except ValueError: ...
cee42d7413ad30fcfe67437b706ee14b889f0aae
loide/MITx-6.00.1x
/lessThan4.py
365
3.84375
4
''' This function returns the sublist of strings in input list that contains fewer than 4 caracters. ''' def lessThan4(a_list): lessThan4List = [] for x in a_list: if len(x) < 4: lessThan4List.append(x) return lessThan4List if __name__ == '__main__': a_list = ["apple", "cat", ...
4d51b16c7673470425579525742dd537470e48b9
loide/MITx-6.00.1x
/myLog.py
841
4.46875
4
''' This program computes the logarithm of a number relative to a base. Inputs: number: the number to compute the logarithm base: the base of logarithm Output: Logarithm value [ log_base (number) ] ''' def myLog(number, base): if ( (type(number) != int) or (number < 0)): return "Error: Number value must...
80c19732e0851baa74bd4e103ecd3c4a7090c15f
raphaelassor/snake-python-
/snake.py
1,185
3.71875
4
from turtle import Turtle STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 DIRECTIONS = { "right": 0, "up": 90, "down": 270, "left": 180 } class Snake: def __init__(self): self.segments = [] self.__create_snake() self.head = self.segments[0] def __...
7e9c4dd4ecbfdb8419acd37044c0aeb41bc0a408
zupph/CP3-Supachai-Khaokaew
/Lecture53_Supachai_K.py
159
3.84375
4
def vatCalculate(totalPrice): result = totalPrice * 1.07 return result totalPrice = int(input("enter total price : ")) print(vatCalculate(totalPrice))
4b2d0491033d18d00e87c1602fdeffea62d01abe
valeriacavalcanti/IP-2019.1
/Lista 01/lista_01_questao_02.py
115
3.640625
4
raio = float(input("Informe o valor do raio: ")) comprimento = 2 * 3.14 * raio print ("Comprimento =", comprimento)
f24127377952c8a659f4d40e86da704c9bc4b020
SpencerOfwiti/software-testing
/prime/primes.py
625
4.0625
4
import math def is_prime(a): """ Return True if number is prime :param a: :return: """ if isinstance(a, int): if a <= 1: return False for i in range(2, math.floor(math.sqrt(a) + 1)): if a % i == 0: return False return True return 'IsPrime only takes integer parameters.' def print_next_prime(a...
6902980b86ed30978f16b6f9ee21495e8b9cc5e9
AdarshNamdev/Python-Practice-Files
/ExampleOOP.py
935
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 10:40:20 2021 @author: adars """ class student(object): def __init__(self, name, marks = 0): self.name = name self.marks = marks def display_student_details(self): print("Hi {}".format(self.name)) print("Your marks are:...
00fd86dd9f3dbf758c6c0a86407e6b1e3d8ffadc
AdarshNamdev/Python-Practice-Files
/gcdRecursion.py
322
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 10 23:14:57 2019 @author: adars """ def gcdRecur(a, b): if b == 0: return a else: return gcdRecur(b, a%b) print(gcdRecur(2, 12)) print(gcdRecur(6, 12)) print(gcdRecur(9, 12)) print(gcdRecur(17, 12)) print(gcdRecur(13,17...
395b88dc71c7c358a6867bbad74dfb63b83aea5d
AdarshNamdev/Python-Practice-Files
/getter_setter_@property.py
510
4.0625
4
class celsius(object): def __init__(self, temperature = 0): self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 """ basic method of setting and getting the attribute in python """ human = celsius() print(human.temperature) # setting the temperatu...
a5c8a5b1a6cdb1852e1e404f1a970230f5d27384
AdarshNamdev/Python-Practice-Files
/Regex2-GroupCapturing-BackReferencing.py
1,386
3.578125
4
""" Regular Expression Group Capturing and Back Referencing! """ import re with open(r"C:\Users\adars\Desktop\random.txt", "r") as handle1: content1 = handle1.read() print("Actual Content:\n", content1,"\n####################################################\n") print("obtaining the phone numbers in the f...
a6b745c310326cd42e26225a55507fd8dbd9c842
AdarshNamdev/Python-Practice-Files
/AbstractClasses-AbstractMethod-2.py
3,075
4.6875
5
""" Note: a.) Concrete Method: Are methods that has a body """ from abc import ABC, abstractmethod class Car(ABC): def __init__(self, regno): self.regno = self.regno def fillfuel(self): """ 'fillfuel' method is a Concrete Method because here we are assuming that every car has the sa...
9f29473c50937834567deb43dca531addc1c8094
MarlonVictor/pyRepo
/Aula02/at04.py
450
4.09375
4
## Faça um programa que leia dois números e mostre qual o maior dos dois. O programa deve informar caso sejam iguais. valor1 = int(input('Digite um número: ')) valor2 = int(input('Agora digite um segundo número: ')) print() if valor1 > valor2: print('{0} é maior que {1}'.format(valor1, valor2)) elif valor2 >...
0d2d71708e8e72392171a4d6b88684ed13c95455
warrya/atcoder
/bigginer/180121/a.py
207
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 21:40:47 2018 @author: Yuki """ a, b = map(int,input().split()) product = a*b if product%2 == 0: print('Even') else: print('Odd')
6cd16833434bc2664faf13966458bc1796f50710
warrya/atcoder
/bigginer/171118/A.py
254
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 9 01:16:26 2017 @author: Yuki """ num = input() if num[0] == num[1] and num[0] ==num[2]: print('Yes') elif num[1] == num[2] and num[2] ==num[3]: print('Yes') else: print('No')
dc185924d79662ba00817e5fd37ddb8dab5eaf50
shafiul-haque-johny/Data-Science-in-Python-Assignment-Solution-Coursera
/Assignment1.py
3,226
4.3125
4
def example_word_count(): # This example question requires counting words in the example_string below. example_string = "Amy is 5 years old" # YOUR CODE HERE. # You should write your solution here, and return your result, you can comment out or delete the # NotImplementedError below. r...
6bd4ae3ab2f3486e1e468a7af7b091d1a6647a83
rerapony/Stepik
/Algorithms/Methods/GreedyAlgorithms/HuffmanEncoding.py
1,123
3.734375
4
from queue import PriorityQueue from collections import defaultdict def make_code(queue): code = defaultdict(str) while queue.qsize()>1: left, right = queue.get(), queue.get() for letter in left[1]: code[letter] = '0' + code[letter] for letter in right[1]: code[l...
3a79946632f8c31aa3ec6872a483d7f2e11d7efd
rerapony/Stepik
/Algorithms/Methods/DivideAndConquer/DotsAndSections.py
888
3.59375
4
from sys import stdin import random import bisect def quicksort(array, l, r): if l >= r: return i, j = l, r pivot = array[random.randint(l, r)] while i <= j: while array[i] < pivot: i += 1 while array[j] > pivot: j -= 1 if i <= j: array[i], array[j] = array[j], arr...
38299b6fc562f4b1d28588f243823b01d7fb0bf0
rerapony/Stepik
/Algorithms/Methods/DivideAndConquer/QuickSort_InPlace.py
367
3.90625
4
def quicksort(array, l, r): if l >= r: return i, j = l, r pivot = array[random.randint(l, r)] while i <= j: while array[i] < pivot: i += 1 while array[j] > pivot: j -= 1 if i <= j: array[i], array[j] = array[j], array[i] i += 1 j -= 1 qui...
6193bcd6421b4ea1cee6d23555b79a87d5557beb
anweshachakraborty17/Python_Bootcamp
/P55_Get the length of a set.py
96
3.546875
4
#Get the length of a set thisset = {"apple", "banana", "cherry"} print(len(thisset)) #3
839ab1c41846f5584b6cb10fd4d9a63fedbb0522
anweshachakraborty17/Python_Bootcamp
/P63_Print all values in a dictionary, one by one.py
197
4.03125
4
#Print all values in a dictionary, one by one thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(thisdict[x]) #Ford #Mustang #1964
3f8bf3c96fb585dec8b5d7130132d7dadaa7f6a4
anweshachakraborty17/Python_Bootcamp
/P96_Lambda Function Problem2.py
135
3.703125
4
#Lambda Function Problem3 #A lambda function that sums argument a, b, and c x = lambda a, b, c: a + b + c print(x(5, 6, 2)) #13
579e0da0253ec03a4583ba2288b552b72c0d5ced
anweshachakraborty17/Python_Bootcamp
/P48_Delete a tuple.py
295
4.15625
4
#Delete a tuple thistuple1 = ("apple", "banana", "mango") del thistuple1 print(thistuple1) #this will raise an error because the tuple no longer exists #OUTPUT window will show: #Traceback (most recent call last): File "./prog.py", line 3, in NameError: name 'thistuple1' is not defined
cf9975b6ae797b5e2eacbe1c63f55d784ebe18a6
anweshachakraborty17/Python_Bootcamp
/P45_Loop through a tuple.py
133
4.25
4
#loop through a tuple thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) #apple #banana #cherry
5cf51d431c50db3886d1daa7c5dc07ea19e133f7
harsh4251/SimplyPython
/practice/oops/encapsulation.py
543
4.4375
4
class Encapsulation(): def __init__(self, a, b, c): self.public = a self._protected = b self.__private = c print("Private can only be accessed inside a class {}".format(self.__private)) e = Encapsulation(1,2,3) print("Public & protacted can be access outside class{},{} ".format(e.public,e._protected)) """Nam...
e19c95a226506a3e23d9a5771eb17daa2b7b771c
kumarhegde76/Scripting-Language
/SL_Final/9/A/9a.py
424
3.609375
4
class Student: name='' age='' lst=[] mylst=[] def __init__(self,name,age,lst): self.name=name self.age=age self.lst=lst def Display(self): print(self.name,'',self.age,'',self.lst) def accept(self): myname=input("Enter Name\n") myage=input("Enter Age\n") mymarks=list(map(str,input().split())) p=S...
e638c537565c9d8dcf1895f248b572c3e7550000
kumarhegde76/Scripting-Language
/SL Lab/SL_Lab_Test1/aut.py
546
4.0625
4
dict = {1:'Hydrogin',2:'Lithium',3:'Boran',4:'Helium'} def AutomicDict(): while True: num=int(input("Enter Automic value Enter 0 to Exit")) if(num==0): break; else: nam=str(input("Enter The Name of an automic:")) dict.update({num:nam}) print(dict) print("Number of Automic values:",len(dict)) se...
6dee0da4be450881bb638d7b2d4163887dee29b7
stelaseldano/advent_of_code_2017
/9/stream_processing.py
1,915
3.9375
4
import sys def stream_processing(file_path): """ Day 9 | Part 1 & 2 http://adventofcode.com/2017/day/9 Removes garbage blocks from a stream (string of chars) and finds how many valid blocks of data there are in the stream. Takes a file as argument and creates 'output_91' containing the result for Part 1 and ...
9f9aa4b4aa4cc6b293043e036b2a8a73ab2ec07b
qzhou0/SoftDevSpr19WS
/temp/util/dbOperator.py
1,237
3.859375
4
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O #========================================================== DB_FILE="./data/<intended_name>" #<SUBSTITUTE FILE NAME> db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() ...
91005dad8a02f97f1487323daf79e6e3fccdc59a
hillbs/Trigonometry-Programlets
/arclength_radian.py
482
3.84375
4
# Calculate length of an arc using radius and radian angle measurement import math from stdutils import prettyFunction, inputAsDict vals = inputAsDict(('radians','radius')) # Calculate arc length vals['len'] = vals['radians']*vals['radius'] # Calculations with pi vals['lenp'] = vals['rap']*vals['radius'] vals['rap'] ...
f5983e465d80e3ed54b995418c902f65ceb5eb79
joopeed/pywizard
/classes/dragon.py
5,880
3.640625
4
# -*- coding: utf-8 -*- import pygame pygame.init() images = {} images["dragonR"] = pygame.image.load("./images/dragonR.png").convert_alpha() images["dragonL"] = pygame.image.load("./images/dragonL.png").convert_alpha() images["dragonU"] = pygame.image.load("./images/dragonU.png").convert_alpha() images["dragonD"] = p...
055de77fe286c3e14c5869e9e04fbcd2a9922103
elizabethmuirhead-toast/python-eliz
/fractal_tree.py
4,802
4.21875
4
""" CSC 111, Lab 9 Author: Sara Mathieson (modified from Lab 8 solution) Author: Elizabeth Muirhead and Maddy Kulke A program to draw a fractal tree using recursion. """ from graphics import * import math import random # GLOBALS theta = 0.7 # angle of each branch away from its trunk petal_color = "magenta4" # colo...
259e6161b173cb9975c55427158b13f76750e059
c42-arun/coding-challenges-python
/src/max_product_of_3_ints/solution_2.1.py
1,772
4.125
4
''' Greedy approach - 1 loops - O(1) space (or O(n)?) - O(n) time - considers only +ve ints ''' def pushDownValues(items, fromIndex): print(f"Before push: {items[0]}, {items[1]}, {items[2]}: {fromIndex}") for i in range(len(items) - 1, fromIndex, -1): print(f"{i - 1} -> {i}") it...
cb03be569b14995c4e68e6a32112fa021f4c2b7f
c42-arun/coding-challenges-python
/src/apple-stocks/solution_2.py
1,294
4.0625
4
prices = [15, 10, 7, 8, 5, 11, 12, 9] # prices.sort(reverse = True) # print(prices) max_profit = None # here we are seeing for each price (buy price) the maximum price # that occurs after (sell price) # Space complexity: O(1) # Time complexity: O(n) - only one loop (not sure about taking max() at each iteration?) f...
0b2deb15577ba07a878f00d91eee617d48605bec
beekalam/fundamentals.of.python.data.structures
/ch02/counting.py
583
4.15625
4
""" File: counting.py prints the number of iterations for problem sizes that double, using a nested loop """ if __name__ == "__main__": problemSize = 1000 print("%12s%15s" % ("Problem Size", "Iterations")) for count in range(5): number = 0 #The start of the algorithm work = 1 ...
db92a53991353d177176207c73e506de02723010
rodrigoadfaria/playground
/algorithms/analog_cutting_machinery.py
1,111
3.609375
4
import numpy as np def optimal_log_cutting(p, l): ''' Analog Cutting Machinery - given an array p with cutting points p1, p2, ..., pk of an analog and l which is its length, computes the minimal cost based on the best cutting arrangement. ''' p.insert(0, 0) p.insert(len(p), l) n = len(p) c = [[-1 for j in ra...
4e4a76cd1c3146b7bc8e16a1dd85f7e712a71cfb
rodrigoadfaria/playground
/algorithms/longest_common_subsequence.py
5,046
3.859375
4
import numpy as np import quicksort as qs def lcs_length(X, Y): ''' Computes the longest common subsequence of two vectors X and Y, keeping the size of those subsequences in a matrix c and the path to the longest subsequence in another matrix of same size b. We sum up 1 to m and n due to indexing of the original ...
ae674ff0b38d7c061fae09e8666072e62e95c82b
rodrigoadfaria/playground
/algorithms/binary_sum.py
1,067
4
4
def binary_sum(A, B, n): ''' CLRS - 3 ed. Problem 2.1-4 Add two n-bit binary integers, stored in two n-element arrays A and B ''' C = [0]*(n+1) carry = 0 # do the summation from the least significant to most significant bit for i in range(n-1, -1, -1): sum_ = A[i] + B[i] + carry ...
647b520d0ab13328a9a834a4c74da8c7a6beca4d
leopen-hu/python-web-demo
/base-demo/python-advanced-features/Iteration.py
854
3.796875
4
from collections import Iterable print('string iterable?', isinstance('abc', Iterable)) print('list iterable?', isinstance([1, 2, 3], Iterable)) print('int iterable?', isinstance(123, Iterable)) for i, value in enumerate(['1', 'b', '-']): print('enumerate', i, value) def findMinAndMax(source_list): if len(s...
ddb75e2eefe1cc045ca3047ee2fb97617135b84d
bubnicbf/essay_grader
/Spellings/Spellings.py
1,396
4.0625
4
## # SPELL CHECKER # -- module has a function to check and grade spellings # # @author Apoorva Rao @date 14 March 2012 # ## import enchant import re # @brief function which checks spellings # INPUT : essay # OUTPUT: returns the number of misspelt words AND key-value pairs of missplet words and suggestions to...
8e19018571298372b73695afb9139596e1524464
MITRE-South-Florida-STEM/ps1-summer-2021-luis-c465
/ps1c.py
1,706
4.125
4
annual_salary = float(input("Enter the starting salary:​ ")) total_cost = 1_000_000 semi_annual_raise = .07 portion_down_payment = 0.25 r = 0.04 # Return on investment total_months = 0 current_savings = 0.0 def down_payment(annual_salary: int, portion_saved: float, total_cost: int, portion_down_payment: float...
aeca74f1e637228b4d7e0bffcdf0f3c9dab35143
imclab/fatiando
/fatiando/inversion/datamodule.py
3,430
3.625
4
""" Base DataModule class with the format expected by all inverse problem solvers. See the docs for the :mod:`fatiando.inversion` package for more information on the role of the data modules. ---- """ import numpy class DataModule(object): """ A generic data module. Use this class as a skeleton for bu...
ab872a4d32586fe8cb30a77bf6e212a8512d9c11
Andrew7891-kip/python_for_intermediates
/copying.py
918
4.21875
4
import copy # shallow copy # interferes the original org = [[0,1,2,3],[5,6,7,8]] cpy=copy.copy(org) cpy[0][1]=9 print(cpy) print(org) # shallow func copy class Student: def __init__(self,name,age): self.name=name self.age=age p1=Student('Andrew',19) p2 = copy.copy(p1) p2.age=20 print(p1.age) ...
ff141f26969b510c1d7a03b29d2bfea0e84aa57d
Andrew7891-kip/python_for_intermediates
/process_exp.py
408
3.515625
4
# process : is an instance of a program from multiprocessing import Process import os import time def square_num(): for i in range(10): i*i time.sleep(0.1) processes = [] num_process = os.cpu_count() for i in range(num_process): p=Process(target=square_num) processes.append(p) # start ...
7835d172de44fdcaa38cba0a3c716e6b342863d0
Dragonair28/My-projects
/Stone paper scissors/Guessing game.py
246
4.0625
4
print("GAME: Guessing game") a = input("Enter your guessing number up to 100:") if a == "69": print("Well Done ! , Your guess is right") elif a == "hint": print("it's between 50 to 70 ") else: print("Your guess is wrong , Try Again")
19eb343bbdee6be18dbf77f01ad02db9cd17350c
nigelandrewquinn/Kattis
/dasblinkenlights.py
245
3.6875
4
def gcd(a,b): if b == 0: return a remainder = a % b return gcd(b,remainder) def lcm(a, b): return int( (a*b) / gcd(a,b)) p, q, s = map(int, input().split()) if lcm(p,q) <= s: print('yes') else: print('no')
4681d2bde1224f48fa6f6cd85a32b89ee7063d0d
nigelandrewquinn/Kattis
/guessthedatastructure.py
1,397
3.796875
4
from collections import deque from sys import stdin import heapq class Stack: def __init__(self): self.s = deque() def add(self, n): self.s.append(n) def pop(self): return self.s.pop() if self.s else None def ds_type(self): return 'stack' class Q...
65b80fb12e43b9fd616015f6a3e1ccc2e521243f
nigelandrewquinn/Kattis
/snowflakes.py
377
3.609375
4
from sys import stdin, stdout for _ in range(int(stdin.readline())): seen= set() count = 0 longest = 0 for i in range(int(stdin.readline())): sf = int(stdin.readline()) if sf not in seen: seen.add(sf) count+=1 longest = max(longest, count) ...
57c185df5b31ccf64519fcfb0e580fd4e402710b
johnconnor77/holbertonschool-higher_level_programming
/0x03-python-data_structures/8-multiple_returns.py
123
3.53125
4
#!/usr/bin/python3 def multiple_returns(sentence): return (len(sentence), sentence[0] if sentence is not '' else None)
c91499c701088dc38d55595d10c81c0ef5b19aee
johnconnor77/holbertonschool-higher_level_programming
/0x11-python-network_1/1-hbtn_header.py
343
3.65625
4
#!/usr/bin/python3 """ Python script that takes in a URL, sends a request to the URL and displays the value of the X-Request-Id """ import urllib.request from sys import argv if __name__ == "__main__": with urllib.request.urlopen(argv[1]) as response: dict_info = response.info() print(dict...
b915168a6b9ad8c6c44e5c1fa6565688a44efb0f
johnconnor77/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-from_json_string.py
260
4.09375
4
#!/usr/bin/python3 import json def from_json_string(my_str): """From JSON string to Object Returns an object (Python data structure) represented by a JSON string Args: my_str: JSON string being used """ return(json.loads(my_str))
a4473c948e409ac384a583620829bff08dab3646
burnettk/origin
/Python/BuckysCodeExamples/RangeWhile.py
193
3.984375
4
for x in range(10): print(x) for y in range(5, 12): print(y) for z in range(10, 40, 5): print(z) mrh_scalar = 5 while mrh_scalar < 10: print(mrh_scalar) mrh_scalar += 1
49371bccaacbff19fbb745348679df95941f1b5e
burnettk/origin
/Python/BuckysCodeExamples/ExceptionHandling.py
456
4.09375
4
#tuna = int(input("What's your favorite number?\n")) # throws exception if string entered #print(tuna) while True: try: number = int(input("What's your favorite number?\n")) print(18/number) break except ValueError: print("Make sure and enter a number.") except ZeroDivisionE...
f3db99c9ac7fdb7cadb6d025103c7d66d5d10d9b
sw2-team/sw2-team
/first_homework/20171705-조경상-assignment2.py
191
3.71875
4
while True: n = int(input("Enter a number: ")) f = 1 if n <= -1: exit() if n == 0 : print("0! = 1") if n >= 1 : for i in range(1,n+1): f = f*i print("%d! = %d"%(n,f))
2838e84d4a11ddfae046220ceb8951f48d742742
nickruta/stupidlang
/stupidlang/run.py
2,380
3.84375
4
from .parser import parse from .evaluator import eval_ptree, Program def backtolang(exp): """ Takes a expression list and converts it back into a stupidlang expression. Parameters ---------- exp : list A list representing a parsed stupidlang expression Returns ------- str ...
e04ea4abc905d69bac5ae6bf65ab123a7e8f28ce
leal26/pyfi
/auxiliary_functions.py
5,699
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 27 21:15:49 2016 @author: Pedro """ from datetime import datetime def output_reader(filename, separator='\t', output=None, rows_to_skip=0, header=0, type_data = None): """ Function that opens files of any kind. Able to skip rows and read hea...
5f21d23c5e0d090078a61c2e07103fce8dcfc595
parkseohui/git
/DashInsert.py
483
3.875
4
#Dash Insert #입력: 숫자를 입력받기 #출력: 홀수가 연속되면 두 수 사이에 - 를 추가하고, 짝수가 연속되면 * 를 추가한 문자열 a=input("숫자를 입력해주세요") b=list() for i in range(len(a)-1): b.append(a[i]) if int(a[i])%2==1 and int(a[i+1])%2==1: b.append('-') if int(a[i])%2==0 and int(a[i+1])%2==0: b.append('*') b.append(a[i+1]) print(b) b ...
fb3c128f7b232eda2fea37853247a0aa1544c8f4
parkseohui/git
/List comprehension.py
107
3.5
4
a=[1,2,3,4] result=[] for num in a: result.append(num*3) #리스트내포 result=[num*3 for num in a]
22ae7593d42eb116cf4739471a01200a7a3ec8c5
parkseohui/git
/dictest.py
461
3.515625
4
#딕셔너리표현하기!! ha={'나':1 , '너':2 , '우리':3} for h in ha: print(h) #이렇게하면 키값만 나오네! for h in ha.keys(): print(h) #위와 똑같군 for h in ha.values(): print(h) #이건 밸류값만 나오는군 for h in ha.keys(): print('{}의 숫자는 {}입니다.'.format(h,ha[h])) #키와 밸류 for key,value in ha.items(): print('{}의 숫자는 {}입니다.'.format(key...
9fbbdf6e7ddc220e5468eadaf4acefbfb56141d1
daaniel3232/dio-introducao-ao-python
/aula07_calculadora3.py
569
4
4
# como não vai inicializar nada não é necessário usar o método "__init__" class Calculadora: def soma(self, valor_a, valor_b): return valor_a + valor_b def subtracao(self, valor_a, valor_b): return valor_a - valor_b def multiplicacao(self, valor_a, valor_b): return valor_a * valor...
315ace2527ebf89d6e80aea2a47047f0484f5b40
Owensb/SnapCracklePop
/snapcrackle.py
457
4.125
4
# Write a program that prints out the numbers 1 to 100 (inclusive). # If the number is divisible by 3, print Crackle instead of the number. # If it's divisible by 5, print Pop. # If it's divisible by both 3 and 5, print CracklePop. You can use any language. i = [] for i in range (1, 101): if (i % 3 ==0) & (...
f704e93b06d68c404ffd82852902911ada4d167c
SREEHARI1994/Bioinformatics_specialization
/pattern_count_honors.py
372
3.8125
4
def pattern_count(text,pattern): count=0 for letter_index in range(len(text)-len(pattern)): if text[letter_index:letter_index+len(pattern)]==pattern: count=count +1 return count f=open('data.txt') inp=f.read() t=inp.split('\n') text=t[0] pattern=t[1] print(pattern_count(text, patter...
3f1aa1041c78f7daa41ec99ea09fe69943d2139c
BDRave/Univer
/untitled3/ClothingAccessories.py
540
3.625
4
from Clothes import Clothes class ClothingAccessories(Clothes): carried="" warm="" def __init__(self, color, size, material, carried, warm): super(ClothingAccessories, self).__init__(color, size, material) self.carried=carried self.warm=warm def getcolor(self): return s...
71be5f13b1e86c0006e7522813dce857eed54bbd
alex-fu/pytest
/http_test/debug.py
318
3.5
4
from functools import wraps def debug_entry(func): ''' Decorator that print entry of function :param func: :return: ''' @wraps(func) def wrapper(*args, **kwargs): print("=> Enter " + func.__name__) result = func(*args, **kwargs) return result return wrapper
0d12dd8d6f4796bd920de55a2e2dab71252caa89
ruthmd/Data_Structures_Algorithms
/LRU/Cache.py
846
3.515625
4
from collections import deque class LRU: def __init__(self, capacity): self.Q = deque(maxlen=capacity) def put(self, key): if key in self.Q: # if key exists push to the top self.Q.remove(key) self.Q.appendleft(key) def get(self, key): if key not in s...
eda726b6a912150ecbb24caade07080ae98a10ad
tyuno123/python-thw
/ex5.py
627
3.71875
4
# More Variables and Printing my_name = 'William Y.' my_age = 22 my_height = 173 my_weight = 75 my_eyes = 'Black' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." %my_name print "He's %d cm tall." %my_height print "He's %d kg heavy." %my_weight print "Actually that's not too heavy." print "He's got %...
475e858695c7dde18e0b30bc141d644edf3cd98f
chichutschang/6.00.1x-2T2016
/Week 2/Exercise eval quadratic.py
336
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 7 21:32:02 2016 @author: chi-chu tschang """ def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' # Your code here return...
b69eef742a8b9c5298ca6780e2796b9e8958cd45
chichutschang/6.00.1x-2T2016
/Week 2/Functions Exercise 2.py
317
3.5
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 7 21:46:54 2016 @author: chi-chu tschang """ def a(x): return x + 1 def b(x): return x + 1.0 def c(x,y): return x + y def d(x,y): return x > y def e(x, y, z): return x >= y and x <= z def f(x, y): x +...
74e94e99cd388035508406b63f184ce8b5c1e8ec
chichutschang/6.00.1x-2T2016
/Week 1/Exercise 4.4.py
239
4.03125
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 2 22:43:35 2016 @author: chi-chu tschang """ num = 10 while True: if num < 7: print('Breaking out of loop') break print(num) num -= 1 print('Outside of loop')
5addf368b2b02b23a8e77d314486794a387b9fdc
chichutschang/6.00.1x-2T2016
/Week 2/Exercise 4.py
237
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 7 21:59:48 2016 @author: chi-chu tschang """ a = 10 def f(x): return x + a a = 3 f(1) x = 12 def g(x): x = x + 1 def h(y): return x + y return h(6) g(x)
f09c97c150ae9c1661ed595ed6ca40bde2b4b4b5
chichutschang/6.00.1x-2T2016
/Week 1/Exercise for exercise 2.py
184
4
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 3 14:52:20 2016 @author: chi-chu tschang """ num = 12 print ("Hello!") for num in range(12, 2, -2): num -= 2 print (num)
51ffc1a8b36f6fc10b3910ecc0c594a4ada317f5
Olegidse/dead-or-alive
/deadoralive/deadoralive.py
4,825
3.578125
4
import random import time import sys def printM(matr): for i in range(len(matr)): for j in range(len(matr[i])): print(matr[i][j], end = ' ') if j == len(matr[i])-1: print('\n') #Случайное заполнение поля размером a*b def initDesk(a,b): Desk = [] random.seed() f...
bee754461d6e09c17c20690040a74775a3720a87
LucasGuimar/Atividade---Linguagem-de-Programa-o-Python
/04.py
335
3.78125
4
#coding: utf-8 '''Atividade 4: Implementar uma função que retorne verdadeiro se o número for primo (falso caso contrário). Testar de 1 a 100.''' num = int(input('Digite um número: ')) tdiv = 0 for c in range(1, num + 1): if num % c == 0: tdiv += 1 if tdiv == 2: print('VERDADEIRO!') else: print('FA...
672da5248da9a9a9ede263382231f9dd4707a88f
mr-shubhamsinghal/Data-Structure
/insetion_sort_test.py
214
3.5
4
arr = [7, 5, 4, 2, 3, 1] n = len(arr) for i in range(1, n): num = arr[i] hole = i while hole > 0 and arr[hole-1] > num: arr[hole] = arr[hole-1] hole -= 1 arr[hole] = num print(arr)
da0aeaaac4388f01fee9cff8930e882700c1e867
Ganesh658/Snake_Game
/python-game-updated.py
8,322
3.5625
4
# turtle import turtle import time import random delay = 0.1 delay_2 = 0.1 # Score score = 0 high_score = 0 score_2 = 0 high_score_2 = 0 # Set up the screen wn = turtle.Screen() wn.title("Snake Game by @Team 3") wn.bgcolor("green") wn.setup(width=600, height=600) wn.tracer(0) # Turns off the scree...
20db204b1fb6db98751c9fa3c74acab9e95ae1d7
Byhako/python
/scripts/calendario.py
5,951
3.9375
4
""" Me das una fecha y te digo si sera año bifiesto, cuantos dias an pasado desde el 15/10/1582, y la fecha en el calendario juliano. Ruben E Acosta 2016-02-27 """ import time print('**************************************************') print('Enter a date after 14/10/1582 and before 1/1/3700') print('...
f08a569896e35f58a043cef6eff1414cb1a73300
Byhako/python
/scripts/factores_primos.py
1,002
3.6875
4
n = int(input('Ingresa un número natural: ')) print('\nLos fatores primos para los números ente 2 y',n,'son:\n') primos = [2] def addPrimo(): """ agrego le siguiente primo a la lista primos """ numero = primos[-1] # last primo while True: numero += 1 for primo in primos: if not numero%primo: ...