blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ad167e15a8ab436ee37c720a019363d90bc3876e
pittcat/Algorithm_Practice
/common_sort/merge_sort.py
871
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution: def mergesort(self, seq): """ :type seq: List[int] """ if len(seq) <= 1: return seq mid = len(seq) // 2 left = self.mergesort(seq[:mid]) right = self.mergesort(seq[mid:]) retur...
04fa404861a5aff879a5ccb49b9071c95071f72f
laurencourtney/Robotics
/class2_ws/src/assignment2/assignment2/assignment2.py
6,049
4.15625
4
''' #################### EN605.613 - Introduction to Robotics Assignment 2 Coordinate Transforms Lauren Courtney - lcourtn5 September 2020 ------- For this assignment you must implement the all the functions in this file ================================== Copyright 2020, The Jo...
d057cb5302700e93e3adbc235df6e175336dec5d
Amudah41/EPAM_homeworks
/hw3/tasks/task32.py
1,080
3.609375
4
# Here's a not very efficient calculation function that calculates something important:: import hashlib import random import struct import time import timeit from multiprocessing import Pool def slow_calculate(value): """Some weird voodoo magic calculations""" time.sleep(random.randint(1, 3)) data = hash...
d241899d7d9921c2dbeab6dacc70a50fdac20311
Raenllanthos/week6
/day2/whiteboard.py
553
4.125
4
# Find Middle Number # Given a number (n) and an array of numbers (num_list) as input to a function, # return True if the number is greater than the middle number of the array. # Return False if the number is less than the middle number of the array. # Example Input: n = 6, array = [3,5,8,10] # Example Output: True #...
58440cf92b64ce737642b57fc86664e0aa1d9e6e
olya-bo/A_level
/Lesson5/Classwork/example_funk.py
433
3.890625
4
# def plus(num1, num2, num3=0, *vasya, **qwqwqwq): # print(qwqwqwq) # return num1 + num2 + num3 # # print(plus(1, 3, x = 4)) def plus(num1, num2): return num1 + num2 def minus(num1, num2): return num1 - num2 operations = { 'plus': plus, 'minus': minus } def operation(num1, num2, operations_d...
17f1ce1bc789c69e280a06231dd4eb0576faf168
EduardoSlonzo/python_project
/Exercicio_em_python/Pares_consecutivos.py
187
4.09375
4
x = int(input("Digite um numero inteiro: ")) while x != 0: if x % 2 != 0: x = x +1 soma = 5 * x + 20 print(soma) x = int(input("Digite um numero inteiro: "))
77944d12d256a5cf62f61a495b1fb9edb463832e
damien75/Training-Algos
/HackerRank/search/max_mod_sum.py
6,026
3.671875
4
from bisect import bisect_right, insort from typing import List, Optional class BST: class TreeNode: def __init__(self, key: int, left=None, right=None, parent=None): self.key = key self.leftChild = left self.rightChild = right self.parent = parent ...
ae6395d15f160d466d4323cbcbd263053efa2f0c
black-christopher/PythonExercises
/Python for Beginners/nestif.py
391
3.9375
4
country = input('What country do you live in?') country = country.capitalize() tax = 0.0 if country == 'Canada': province = input('What province do you live in? ' ) province = province.capitalize() if province in('Alberta','Nunavut','Yukon'): tax = 0.05 elif province == 'Ontario': tax...
279314f2fef56f9fbe9b9fc77da91c41f3d990f7
FabioFab/py100days
/Pandas01.py
6,812
4.21875
4
import pandas as pd from matplotlib import pyplot as plt # ############################################ # # pandas 01 - cupofcode youtube # ############################################ # # # Reading a file, which is the one that will be processed # dataframe01 = pd.read_csv("gapminder.tsv", sep="\t") # # Default separ...
8830eb0319280a1e3d6a4507556ce2b8c9fe76e1
john-nhoj/advent_of_code_2019
/1.py
1,029
3.59375
4
import requests def getFuel(mass: int): print("mass: {}".format(mass)) result: int = mass // 3 print("divided by 3: {}".format(result)) if result <= 0: return 0 fuelQtty: int = result - 2 if fuelQtty <= 0: return 0 print("Qtty needed: {}".format(fuelQtty)) return fue...
736ab5f2e46778faa79881b9a1394ab1ab67b117
Ron-Chang/MyNotebook
/Coding/System/Sentdex/OpenCV/05_Image_Arithmetic_Logic/main.py
2,183
3.609375
4
import cv2 import numpy as np img_1 = cv2.imread("../samples/3D-Matplotlib.png") img_2 = cv2.imread("../samples/Basic-Plot.png") python_logo = cv2.imread("../samples/python.png") # unpack the python_logo info # np.shape(foo) and foo.shape. # see also: https://www.zhihu.com/question/38768460 rows, cols, channels = py...
83e5cb8798a3a4fa0bd858745beaddb9eb0b482d
adi-797/Python-Hackerrank
/Introduction/Python If-Else.py
273
4.09375
4
#!/bin/python # Enter your code here. Read input from STDIN. Print output to STDOUT N = int(raw_input()) if N%2 !=0: print "Weird" else: if N>=2 and N<=5: print "Not Weird" elif N>=6 and N<=20: print "Weird" else: print "Not Weird"
9895024d8b5fc2df0c841d67c74bb2da68737a33
Bibin22/pythonpgms
/Tutorials/Polymorphismpgm/fullname.py
241
3.765625
4
class Name: def __init__(self, name): self.name = name def __add__(first, second): name = first.name + second.name return name first = Name("bibin") second = Name("joy") full = first + second print(full)
a1ef98e3bdd720d932d562b2be97b3b666381378
snowdj/NumericalMethods
/Worksheets/Worksheet2_Functions.py
3,972
3.765625
4
## Worksheet 2 import numpy as np import scipy.linalg as la #### Answer Coding Question 1 def LU_decomposition(A): """Perform LU decomposition using the Doolittle factorisation.""" L = np.zeros_like(A) U = np.zeros_like(A) N = np.size(A, 0) for k in range(N): L[k, k] = 1 ...
a9dcd8cd597dfccab4d4868e8c12c69565e11fbd
aiden0z/snippets
/leetcode/543_diameter_of_binary_tree.py
3,612
4.0625
4
"""Diameter of Binary Tree Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. Its path may of may not pass through the root node. The length of a path between two nodes is represented by the n...
cdbbad9aadde358742b2356d8eb677320e65c2b8
zackcpetersen/data_structures_algorithms
/trees/binary_search_tree.py
5,509
3.796875
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def __str__(self): return '{}'.format(self.val) class Tree: def __init__(self): self.root = None def __str__(self): return '{}'.format(self.root) def insert(sel...
580e0f78925a02948901e491fceb392d97f4a623
ravikiran32/Code
/Python/ExamplePyScripts/Exceptions.py
640
4.09375
4
#EXCEPTIONS #use the try and catch method #print("Lets divide some number") #print("Press q to quit") #while True: #first_number = input("\nPlease enter your first number:") #if first_number == 'q': #break #second_number = input("\nPlease enter your second number:") #if second_number == 'q': #break ...
03181fb2158dd9f5b745e92e6ccf6b7e814b550d
emelyalonzo/vaccination-system
/phase-3/phase3.py
18,631
3.5
4
# -*- coding: utf-8 -*- """ third phase """ import sys class HealthCenter(): def __init__(self, name = None): self.name=name def __eq__(self,other): return other!=None and self.name == other.name def __str__(self): return self.name class AdjacentVertex(): ...
9d9a32f98c7b0decbd2901f8b428cfbc3414ecc0
patrick473/TCIT-V1PROG-15
/2.18.py
272
4.03125
4
flowers = ['rose', 'bougainvillea', 'yucca','marigold', 'daylilly', 'lilly of the valley'] print('potato' in flowers) thorny = [flowers[0], flowers[1], flowers[2]] poisonous = [flowers[-1]] dangerous = thorny + poisonous print(thorny) print(poisonous) print(dangerous)
86a0a79b89256d6cb393086a9ba8a60591897f3a
douglasrodriguess/basic-to-advanced-python-course
/04-Variables-and-data-types/exercise/Exercise50.py
276
4.09375
4
import datetime year = datetime.date.today().year idade = int(input(f'Quantos anos voce tem? ')) print(f'Voce nasceu em {datetime.date.today().year - idade}') print(f'Data {datetime.date.today().day}/{datetime.datetime.today().month}/{datetime.datetime.today().year}')
04b0f5a007dcccbf65607b742b44a3922cc6df2f
klitscher/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py
13,805
3.625
4
#!/usr/bin/python3 """Testing module for rectangle class""" import unittest import io from contextlib import redirect_stdout from models.base import Base from models.rectangle import Rectangle class TestRectangleClass(unittest.TestCase): """Tests for Rectangle class""" #----------------Tests general------...
2e137aef475494edc31c522fb4bb9a26f4027c56
Indiana3/python_exercises
/wb_chapter7/exercise165.py
1,880
4.25
4
## # Find the most popular boy's name and the most popular girl's name in # a given period of time # from exercise163 import all_paths # Read the period of time from the user ab, ad = input("Please, enter a time period (from 1900 to 2012): ").split() ab, ad = int(ab), int(ad) # Create a list with all the years to ana...
691f805d9b3085b0e3eeb899109fe14d9880aae2
nownabe/competitive_programming
/AizuOnlineJudge/ITP1_Introduction_to_Programming_1/ITP1_11_A_Dice_I.py
1,234
3.515625
4
class Dice: def __init__(self, faces): self.faces = faces def roll(self, direction): if direction == 'N': self.faces = [ self.faces[1], self.faces[5], self.faces[2], self.faces[3], self.faces[0], ...
3ea4105960a84392aa3da0555f777c3b2f952402
FAndersson/polynomials_on_simplices
/polynomials_on_simplices/algebra/multiindex.py
22,129
3.59375
4
r"""Operations on multi-indices (elements of :math:`\mathbb{N}_0^n`).""" import math from operator import add, sub import numpy as np from polynomials_on_simplices.algebra.modular_arithmetic import IntegerModuloN class MultiIndex: r""" A multi-index (element of :math:`\mathbb{N}_0^n`). This class defi...
6e3bd457db16e37768828b323fcabe1796847441
hbk-world/Open-Interface-for-Sound-Level-Meter
/Python examples/02 - Metadata.py
703
3.65625
4
""" 02. Reading metadata -------------------- """ import requests host = "http://10.100.38.87" """ DisplayScheme is a node that determines wether the display is dark or light. This node is under "/webxi/applications/slm/setup/displayscheme" """ response = requests.get(host + "/webxi/applications/slm/setu...
6f2bc5191b996b050654b3fafe50795d5611008f
deybanperez/Algorithms
/QuickSort/main.py
1,543
3.5625
4
import random def quicksort(array, lo, hi): total = 0 if lo < hi: # swap(array, lo, lo) # first element as pivot 162085 # swap(array, lo, hi) # last element as pivot 164123 swap(array, lo, median(array, lo, lo + ((hi - lo) // 2), hi)) # median number as pivot 138382 # swap(arra...
eb28c26dd50808d38fba711927a125e8b47cbf09
FishRedLeaf/my_code
/leetcode/探索中级算法/8数学/6 两数相除.py
1,349
3.78125
4
''' 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 返回被除数 dividend 除以除数 divisor 得到的商。 示例 1: 输入: dividend = 10, divisor = 3 输出: 3 示例 2: 输入: dividend = 7, divisor = -3 输出: -2 说明: 被除数和除数均为 32 位有符号整数。 除数不为 0。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。 ''' # ...
7b133c13c62ca14b2a8fd856e273920c0ab4f93e
jonatanwestholm/garageofcode
/garageofcode/euler/049.py
1,146
3.625
4
""" The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit get_primes, exhibit...
59ed456488f8484637f0bb89b94c554695d3b924
ebo-arcadia/learn-python
/fundamentals/weight_converter.py
528
3.890625
4
weight = input("Enter your weight: ") lbsOrKilos = input("(L)bs or (K)ilos? ") # refactor if lbsOrKilos.upper() == "L": converted = int(weight) * 0.45 print(f"You are {converted} kilos") else: converted = int(weight) // 0.45 print(f"You are {converted} pounds") # brute force solution if lbsOrKilos == ...
3cec1891af0e3cb9cd08234c9d9f89e69f3caabb
pannchat/1day1commit
/python/section05-2.py
807
3.78125
4
# ten = 0 # while ten != 10 : # print(ten) # ten += 1 # range(5,10) # 5 6 7 8 9 for i in range(0, 6, 2): # 0 2 4 6 print(i) names = ["kim", "park", "Cho", "Choi", "Yoo"] for name in names: print("He is ", name) str1 = "Hello" for i in str1: print(i) dict = { 'name': 'kim', 'age...
da6a6ffbf4c27e509f101e3672ec39d3829b86a2
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/mslmdu002/question2.py
2,098
3.96875
4
"""Assignment 9 Question 2 Masilela Mduduzi 16 May 2014""" infileName=input("Enter the input filename:\n") #obtain input file from user infile=open(infileName,"r") #open the specified file in read mode contents=[] for line in infil...
5b8867667869f18cbcd4e5c4c83cced8146b590e
varunkamra/Chess-moves
/Chess_moves.py
19,317
3.609375
4
# This program calculates the moves of all the chess pieces from a given chess board configuration # board variable represents the chess board configuration; # lower case characters represent black pieces and upper case represents white peices. board=[['r','kn',' ','q','k',' ',' ','r'],[' ','b',' ','p',' ','p',' ','p'...
26259c27a0f6b7c88eb57040a1b96fdd84abf7a8
minkles/STEM-degrees
/stem_low_memory.py
19,835
3.515625
4
# The goal of this project is to build a logistic regression model to predict # the likelihood of working in a STEM (Science, Technology, Engineering, and Math) # career, based on basic demographics: Age, sex, race, state of origin. print("Importing packages") import matplotlib.pyplot as plt import pandas as pd imp...
6aad90b6a1161d7cc9a8e3d5a56e53052190d981
ArchAiA/lpthw
/ex42.py
2,043
4.3125
4
##Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## ?? class Dog is-a Animal class Dog(Animal): def __init__(self, name): ## ?? class Dog has-a function that sets the name attribute (class Dog has-a name) self.name = name ## ?? class Cat is-a Animal class Cat(A...
70b90930c73c6e390f8d598cb96429d7ba9a01ef
markovico/Python
/Python3/starter_conditions.py
350
3.890625
4
f1 = 'apple' f2 = 'orange' print(f1 == f2) print(1 == 1.0) print(f1 != f2) print(f1 < f2) print(f1 > f2) print(f1.isalpha()) #validation on input aand combining conditions print( 'Conditions : ' + str(1<2 and 1<-1)) # in condition print ('n' in 'mississipi') inTheList = 1 in [1, 2, 3] print ("in used in the ...
03c988708281406fbdaa9ac8caf7660ec424d922
mgopi1990/George3Hacker
/diff_min_unordered_list.py
630
4.0625
4
#!/usr/bin/env python3 ## Finds difference between min element in the list def diff_min_list(num_list): if len(num_list) < 2: return 0 if (num_list[0] < num_list[1]): min1,min2 = num_list[0], num_list[1] else: min1,min2 = num_list[1], num_list[0] for num in num_list[2:]: if (num < min1): min2,min1 = m...
99024ef29972ac860a8977083dbf8ce79bdb6880
Rosa-Phoebe/MachineLearning
/JAX_JVP_VJP.py
8,734
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 26 22:24:17 2022 Reference: Machine Learning & Simulation @author: """ import jax import jax.numpy as jnp import matplotlib.pyplot as plt """ Often, one is not interested in the full Jacobian matrix of a vector-valued function, but its matrix multiplicati...
6c34c6deb21b5dfef6061af7ae5c27d9b1efdf0f
marceloazambuja/Python
/ler_CSV.py
850
3.734375
4
import csv, sys filename = 'csv_sample.csv' titles = [] years = [] with open(filename, 'r') as f: reader = csv.reader(f) next(reader) # remove header try: for row in reader: title = row[0] year = row[1] titles.append(title) years.append(year) ...
83b67ca871589f594a11d630ea8da2e1bf7562de
SteveTaylorDev/credential-system-area-calculator
/code/credentialchecker.py
6,392
3.75
4
#Import local 'datamanager' module to allow '\data' path acquisition import datamanager #Import Regular Expression ('re') module to allow precise string formatting import re #Login Functions############################################################## def usernamecheck(): """Checks if the username is more than 5 ch...
6c5e49fac901f5d80a9b6c4bbfeedfef94301de1
yanzhenchao/algorithms-in-python
/test_sort.py
1,254
3.75
4
import random from sort import * # Bubble Sort array = [random.randint(0, 100) for n in range(40)] print('Bubble Sort:\n') print('Before:\n', array) bubble_sort(array) print('After:\n', array) print('\n') # Selection Sort array = [random.randint(0, 100) for n in range(40)] print('Selection Sort:\n') print('Before:\...
73aff4fae875353fe4d5d69b8af50daaabba2f53
olufemi424/algorithms
/ALGO/PY/findClosestValueInBst.py
2,057
4.0625
4
# Find Closest value in BST (Binary Search Tree) nodes. # You are given a BST data structure consisting of BST nodes. Each BST node has an integer value stored in a property called 'value' and two children nodes stored in properties called 'left' and 'right', respectively. A node is said to be a BST node if and only i...
4797af71b9a7634e64568efdca49a16a8b2f7543
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Medium/003_Medium_Longest_Substring_Without_Repeating_Characters.py
1,682
3.8125
4
# # # Given a string, find the length of the longest substring without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be...
cf4a42e70339b890e42c08b37d45d5cd5313f86b
delturge/Polyglot
/Python/Griddy/Files/TextFileReader.py
1,205
3.75
4
from TextFile import TextFile # A class for reading text files. class TextFileReader(TextFile): def __init__(self, fileValidator, name=None): super().__init__(name, 'rt', fileValidator) def setName(self, name): if not self.validator.isString(name): raise TypeError('File names...
ea0b2a6f3861a05e48bc44c3bb08e12066e7e66f
mayankbhagya/PythonEssentials
/HelloPython/02_ObjectModel/4_copy.py
318
4.03125
4
x = [1, 2, 3, [4, 5]] y = [] y.append(x) x.append(y) #reference # y = x # x.append(6) #shallow copy # y = list(x) # x.append(6) #problem with shallow copy # y = list(x) # x[3].append(6) #deepcopy # import copy # y = copy.deepcopy(x) # x[3].append(6) import copy z = copy.deepcopy(y) print z print x print y
2e25dace558147b388add1d28b583d56caccc0a1
serenatse98/Checkers-AI
/Checkers_Student-master/src/checkers-python/StudentAI.py
4,095
3.734375
4
from random import randint from BoardClasses import Move from BoardClasses import Board import timeit # The following part should be completed by students. # Students can modify anything except the class name and exisiting functions and varibles. class StudentAI(): def __init__(self, col, row, p): self...
4925f244026b0aafd86771a0bc76306eab0155bb
smohler/advflu
/lecs/Boundary Layer/lecture13.py
4,732
3.546875
4
from manimlib.imports import * # To run the code: # cd.. back into C: drive # cd manim\manim-master # To run and produce video # python -m manim work\animations\advanced_fludis\"file_name.py" Scene -pl class Lecture13_Introduction(Scene): def construct(self): # title card: can work one something which can...
ba61fecb509caaac2b6ac5bdd9aaff343d0a9891
MachineLearningUCG2019/MachineLearning
/Nikas_code/Lecture 2 LinearRegression.py
1,445
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[3]: dataset= pd.read_csv('/Users/MacroCosmos/Desktop/GG/petrol_consumption.csv') # In[4]: dataset.head() # In[12]: ...
8a38e8ed9cf205dfc1d06a0f4026cfa7ac61da7f
rondou/HopeBayInterFace
/linkenList.py
1,986
3.640625
4
import itertools class Node(object): def __init__(self, d, n=None): self.data = d self.next_node = n def set_next(self, n): self.next_node = n def get_next(self): if self.next_node != None: return self.next_node.data else: return self.next_n...
8437d74d203ae74e43cc2e55db6904f1fc5632dc
VictorBoYang/Ferry_Queues
/function_storage.py
7,032
3.546875
4
from Circle_Queues import * def move_car_into_queue(car_left, car_line_list, car_added_count, list_index_count, car_id): car_id_count = Car(car_id) car_line_list[list_index_count].push(car_id_count) car_id = car_id + 1 car_added_count = car_added_count + 1 car_left = car_left - 1 return car_le...
f6a96b0c83e676df69327ca6e2a27cabdafd763c
league-python/Level1-Module0
/_02_strings/_b_string_methods_test.py
2,199
4.1875
4
""" String methods: Create the necessary functions to make the tests pass """ import unittest # TODO: 1) Implement the functions below so that the test cases in the string # methods test file pass. You can delete the 'pass' instruction. # # TODO: 2) Run the string test file. A summary of the test results on your # c...
0bc076d8a94298956bb41ddc8a2beaec649d4609
Billshimmer/blogs
/algorithm_problem/depth_first_search_and_breadth_first_search.py
2,235
3.875
4
#-*- coding:utf-8 -*- # 深度优先搜索 # 广度优先搜素 class Graph(object): def __init__(self, *args, **kwargs): self.node_neighbors = {} self.visited = {} def add_nodes(self, nodelist): for node in nodelist: self.add_node(node) def add_node(self, node): if not node in self.no...
872b5ecb945a98e6b014ee0b0e79cdcf969c5641
matzhananar/python-course
/Махамбет/06-08.py
134
3.5
4
n = [1,2,3,4,5,6,7,8,9,10] # i = индекс # n[i] = элемент i = 0 while i<len(n): n[i] = n[i]-1 i +=1 print(n)
c8b5eeef91b02be53dabd44ced07b2f9fa137556
jaygaha/Python3
/Examples/Functions/12-sum-natural-no.py
318
4.25
4
# Python program to find the sum of natural number using recursive function def recursive_sum(n): if n <= 1: return n else: return n + recursive_sum(n - 1) num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: print("The sum is", recursive_sum(num))
56387149f5c3709f189ef93e1de7012abc5917b0
shraddhabhise/Cracking-the-coding-interview
/Strings and Arrays/Palindrome permutation.py
543
3.90625
4
class palindrome_check: #using hashmap; set , requires memory but. # explanation: no of counts of all letters should be same except one def palindrome(self, str1): hash1 = set() for ch in str1.replace(" ", "").lower(): if ch not in hash1: hash1.add(ch) else: hash1.remo...
92e63e6815129f93b2fb15f6e7129c2ba2360ef8
vinuh42/Python-Code
/vinuh42/mathlibexercises.py
695
4.03125
4
# Vinu Harihar # Math Library Exercises import math # functions def distance(x1, y1, x2, y2): dist = math.sqrt((x2-x1)+(y2-y1)) return(dist) def slope(x1, y1, x2, y2): slp = (y2-y1) / (x2-x1) return(slp) def quadroot1(A, B, C): if (B*B - (4*A*C)) <= 0: return("No Solution") el...
3b26d97133c01869682074b336d75239e821f264
thinhduong/MITx6.00.2x
/pset1/ps1.py
4,772
4
4
########################### # 6.00.2x Problem Set 1: Space Cows from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ def load_cows(filename): """ Read the contents of the given file. Assumes the file conte...
6d61794902cf78ce6cbdccef57407d79678bc390
jkrukowski/pyMorfologik
/pymorfologik/parsing.py
2,852
3.546875
4
# coding=utf-8 import abc from collections import OrderedDict, defaultdict class BaseParser(object): """Base parser for the morfologik output""" @abc.abstractmethod def parse(self, output, **kwargs): """Parse output of the morfologik""" return parse.__annotations__ = {'output': str} ...
6c2a976a5cbbbd040c682eac1f7245baab39548b
jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_DECISAO
/exercicio15.py
1,576
4.34375
4
# 15. Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar # se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se # o mesmo é: equilátero, isósceles ou escaleno. # Desenvolvido por Jonathan Silveira - Instagram: @ jonathandev01 lado1 = int(input("Digite o v...
5d3a3fb9d675ee1f2dcce93929314d888bfb6bd4
21harley/conexion_SQLite_python_consultas_SQL
/crearTablas.py
2,509
3.765625
4
import sqlite3 import json from sqlite3 import Error #crear la conexion def sql_connection(): try: con = sqlite3.connect('SQLite/test.sqlite3') return con except Error: print(Error) #codigo crear tabla def sql_table(con): cursorObj = con.cursor() cursorObj.execute("CREATE TABLE...
ec62cce1efe4810a6ea34caa336100eac1301fac
esineokov/python
/01/01_05.py
432
4.21875
4
# Пример кода для вычисления ежемесячного платежа по кредиту user_name = input("Ведите имя: ") credit = input("Размер кредита: ") duration = input("Срок кредита: ") percent = input("Процентная ставка: ") credit = float(credit) duration = int(duration) percent = float(percent) pay = (credit / duration) + ((credit * p...
f6b35f69add0c0193767b54cd2187de0eae731cb
myomi2767/python
/intro/definition.py
260
3.859375
4
def hello(): return "Hello, World!" def add(num, number): return num + number nums = add(3, 4) def ran(num, number=10): return num + number nums = ran(3) print(nums) def m_num(a, b): return a - b a=3 b=4 minus = m_num(b, a) print(minus)
897cc9cec3d6864a52d3c04e0984fec7ec8a5351
miaojiang1987/LeetCode
/Python/isMonotonic.py
531
3.53125
4
class Solution(object): def isMonotonic(self, A): """ :type A: List[int] :rtype: bool """ store=0 for i in range(len(A)-1): if A[i]-A[i+1]>0: compare=1 elif A[i]-A[i+1]<0: compare=-1 else: ...
3056fa00b95411ac359fa2a34845390914051a83
shunz/Python-100-Days_Practice
/PythonExam/北京理工大学Python语言程序设计-Book/Chapter4/4.1GuessNum.py
535
3.53125
4
"""猜数字""" from random import randint num = randint(1, 10) time = 0 while 1: try: guess = eval(input('请输入你猜的数字:')) time += 1 if guess > num: print('遗憾,太大了') elif guess < num: print('遗憾,太小了') else: print(f'预测{time}次,你猜中了!') bre...
e599bc9c585e11cc80735b438f585b884f1b707f
Rida97/PythonCode
/StudentClass.py
758
4.125
4
class Student(): def __init__(self, name, **student_info): self.name = name # we need to unpack this invisible dict into our own handmade dict ! Info = {} Info['name'] = name for eachKey, eachValue in student_info.items(): Info[eachKey] = eachValue ...
d4544a8f0d17646c46605c1a1c62cbcb0ab352b6
genius-2/python-files
/5.3.py
183
3.796875
4
def chet(a): if a%2==0: return "четное" else: return "нечетное" a=int(input()) print(chet(a)) print("type 'end' to exit ") e=str(input())
41696c85fc497346b475cc5dd54d2dfb7dd71d0f
hkowrada/new
/prime_number.py
802
4.1875
4
num = int(input('enter a number')) if num == 0: print(''' '0'(Zero can never be a prime number as it can be divided by 1, and any other number. It has an infinite number of divisors and therefore doesn't meet the definition.)''') elif num == 1: print(''' A number divisible by only 2 (different) number...
3b955e2d260d7da6b5d00f2680e8df299b05d397
EliMason/Final_Project
/FinalProject.py
1,170
4.34375
4
''' Eli Mason Final Project 3/14/19 This will tell the user their soccer Shot Percentage. Will Waldorf helped me with a couple problems I had run into ''' #This program will tell you your shot to goals percentage. name = input('What is your name?: ') #This will ask you for your name. def greeting(): print('Hello,...
7a66fd9e35e73b790c8e25f258797757835ccc0f
druthvik/Python-Programming
/Program1.py
321
4.15625
4
num = float(input( " a =")) op = input("Enter the Operator") num1 = float(input(" b = ")) if op == "Addition": print(num + num1) elif op == "Subraction": print(num - num1) elif op == "Multipliction": print(num * num1) elif op == "Divison": print(num / num1) else: print("Invalid Number"...
7c5a3edec32dbb7ee93708f4d3eb8ab555192b30
ishita2108/python_ds
/binary_search.py
393
3.6875
4
list = [2,5,9,14,26,85] n = 26 pos = -1 def binary_search(list,n): l = 0 u = len(list)-1 while l<=u: mid = (u+l)//2 if list[mid] == n: globals()['pos'] = mid return pos else: if list[mid] < n: l = mid elif list...
b1f4e80ed77b6847b496a66fecb300ee5ef84f96
dopiwoo/basic-algorithm
/pattern1-sliding-window/8. Longest Subarray with Ones after Replacement (hard).py
2,402
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 15 13:59:35 2020 @author: dopiwoo Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s. Example 1: Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2 Output: 6 E...
68a892a13ee55c54b395258c2927bedc1652d40a
whhwxy/hello-world
/汉诺塔.py
269
4
4
#/usr/bin/env python #-*- coding: UTF-8 -*- #一个简单的条件循环实现汉诺塔问题 def my_print(args): print args def move(n,a,b,c): my_print ((a + '-->' + c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c)) move(3,'a','b','c')
cc77d33493762bee5f2618bf39b3380345b52dc1
DineshBE/fjod7ofofk
/d8.py
59
3.53125
4
m1=int(input()) a=0 for j in range(m1+1): a+=j print(a)
dd91a4d8d04f0b175ecb3fa65af7fc77f6fb8120
algoritmos-2019-2/clase-1-NancyEscamilla
/Práctica2.py
3,626
3.671875
4
Funciones ¿Por qué son ventajosas las funciones para tener en sus programas? Porque se pueden llamar en cualquier parte del código y hacer uso de ellas ¿Cuándo se ejecuta el código en una función:cuando se define la función o cuando se llama a la función? El codigo se ejecuta cuando se llama a la funcion que se defin...
9d971358c8d97842f35530a18f8ac342d2e96ecc
rjayswal-pythonista/DSA_Python
/Practice/trie_test.py
2,042
3.859375
4
from typing import List class TrieNode: def __init__(self): self.childrens = {} self.endOfStrings = False self.words = list() self.n = 0 class Trie: def __init__(self): self.root = TrieNode() def insertNode(self, word): current = self.root ...
f00f3aeee22a5b5d14542ee51b601c195d5448b6
DenisLamalis/cours-python
/lpp101-work/index_23.py
984
4.28125
4
# Functions - calling, parameters, arguments, defaults # def greeting(): # declaration # print('Hello friend !') # greeting() # call # def greeting(name): # with argument # print(f'Hello {name} !') # greeting('toto') # def greeting(name, age): ...
62d4a09fcac3a5385478fd627597cdc745803b00
jshams/cs-1.3
/sierpinski.py
2,947
4.375
4
''' This program uses the turtle module. The tutrtle module allows you to draw on a canvas turtle methods include: import turtle # imports turtle pen = turtle.Turtle() #creates an instance of turtle pen.fd() # will go forwards pen.bk() # will go backwards pen.lt(angle) # turns left default 90 pen.rt...
92bf78e09580339541b97972766afcbe90614f5d
roytalyan/Python_self_learning
/Leetcode/String/Reverse Integer.py
1,038
4.1875
4
# -*- coding: utf-8 -*- """ Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−...
cd3b4e3ecfdbfde194586fe12d717db519dd8245
wovari/webinf
/movie.py
747
4
4
class Movie: """ Contains data about a movie """ def __init__(self, title, url): self.title = title self.url = url self.cast = set() @property def cast(self): return list(self.__cast) @cast.setter def cast(self, x): self.__cast = x def __r...
efae138512bc5370a77f0dc8ca169b51c482be29
xblh2018/LeetcodePython
/longest_palin_substr.py
4,340
3.9375
4
#!/usr/bin/env python ''' Leetcode: Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html http://...
be2e5a32e1f84926050365f952c8f56de57b24e8
milesmackenzie/python_scripts
/descending_order.py
171
3.6875
4
def Descending_Order(num): s = str(num) s = list(s) s = sorted(s) s = s[::-1] s = ''.join(s) return int(s) s = 46738847 print Descending_Order(s)
571517fdc2d3d87d1fc68cd0e559d7c044f2328f
nakaosensei/TwitterSpark
/utils.py
337
3.96875
4
minutes_15 = 15*60 def date_to_string(date, hours = True): """return datetime in string format args: hours(boolean) : Specifies whether the string should contain the time as well. Default is True""" if(hours): return f"{date:%Y-%m-%d}T{date:%H:%M:%S}" else: return f"...
4b140152a19d007b06dfcf65f8f94d57967c5c23
Tearrockster/Prepro---Python
/Sublime pt/000022.py
275
3.75
4
"""Number Digit""" def main(): """Main function""" amount = str(abs(int(input()))) num = int(input()) if num > len(amount): print("Index out of range.") elif num <= 0: print("Index error.") else: print(amount[-num]) main()
5844463f64c7980594410b3d77e94896438c94c7
alvinwang922/Data-Structures-and-Algorithms
/DynamicProgramming/Unique-Paths-Two.py
2,187
4.3125
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added t...
6ab7e456f00592fd59a5b579c65e055da7d85e1f
scott63a/codePlatoonWeekTwo
/factorial_recursive.py
81
3.5
4
def fact(num): if num == 1: return 1 return num * fact(num - 1) fact(5)
0d83856e87a5b0d26c4c02a492fd7ddc168c5d95
LuluwahA/100daysofcode
/Day 11.py
220
4.09375
4
x= 6 print(x>3 or x<5) x=['apple','orange'] y=['apple','orange'] z=x print(x is not z) print(x is not y) print(x is y) print(x!=y) x=['apple','orange'] print('orange' in x) print('banana' not in x)
9a21b61f82cf01783c2ea15b101bfa7b1b016b83
pawpaw2022/Proj02-Flatmates-Bill
/flat.py
674
3.875
4
class Bill: """ Object that contains data of a bill, such as total amount and period of the bill. """ def __init__(self, amount, period): self.amount = amount # 'option + enter + enter' for shortcut self.period = period class Flatmate: """ Creates a flatmate person who li...
d863d809f0d58662eedc0fa64d0bffd1c772edf2
Elt0nN0vais/Curso_Python
/aula1/condicoes.py
665
3.734375
4
#!/usr/bin/python3 #Abaixo de 200 minutos cobra R$ 0.20 por min. #Entre 200 e 400 minutos cobra R$ 0.18 #Acima de 400 minutos o preço é R$ 0.15 minutos = int(input('Minutos utilizados: ')) if minutos < 200: preco = 0.2 elif minutos <= 400: preco = 0.18 else: preco = 0.15 exit() idade = int(input('Digite idade: ...
56e73f987dad203ced690aed00c148e9523d6b29
BorisVV/try-your-luck-app
/play.py
1,844
3.703125
4
import games as _g import compute_data as _c_d from games_classes import NorthStar, GopherFive def main(): '''Display instructions to select games then enter years followed by how many times''' _g.display_options() # This will return the number of years the user wants to play the numbers. numb_of_yea...
870cc9df9592a7fea4395450c8439c0c9c12fda6
sinasiruosnejad/tamrin
/1.py
1,158
3.8125
4
def string_to_list(): x=input() result=[] i=1 while x[i]!=']': if x[i]!=',': j=i temp='' while x[j]!=',': if x[j]==']': break temp+=x[j] j+=1 i=j result.append(int(...
695a32e30dc54faab10d44a76a75e674fab77c86
lordzizzy/leet_code
/04_daily_challenge/2021/06-june/week5/lowest_common_ancestor_binary_tree.py
4,713
3.875
4
# https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/607/week-5-june-29th-june-30th/3797/ # Lowest Common Ancestor of a Binary Tree # Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. # According to the definition of LCA on Wikipedia: “The lowest common...
ecf5ce21289d7a90703739dd8308ed60b43146f2
idan1ezer/LeetCode
/125 - Valid Palindrome.py
324
3.890625
4
def isPalindrome(s): newString = "" for c in s: if (c.isalnum()): newString += c.lower() if (newString != newString[::-1]): return False return True print(isPalindrome(s = "A man, a plan, a canal: Panama")) print(isPalindrome(s = "race a car")) print(isPalindrome(s = "0P"...
6d5e5d22256a97d13c2c3702ee2d0ba7427330ab
psarahdactyl/CGpractice
/CS430_CG/hw2/hw2_new/pointin.py
566
3.59375
4
#!/usr/bin/python # x, y -- x and y coordinates of point # poly -- a list of tuples [(x, y), (x, y), ...] def isPointInPath(x, y, poly): num = len(poly) i = 0 j = num - 1 c = False for i in range(num): print i,j if ((poly[i][1] > y) != (poly[j][1] > y)) and \ (x < (poly[j][0] - poly[i][0])...
ccae59b03549e76d1ec0adc5d62256cdfa354214
kepasta/Python_sandbox
/calculator.py
972
3.671875
4
def calc(sentence): j = 0 sign = '' isign = 0 sentence = sentence.replace(' ', '') i = '' for i in sentence: if i in '123456789': j += 1 elif i in '+-*/': sign = i isign = j j += 1 else: j += 1 ...
3d682ab1ff3778913011fabcaf400de9a9f32d70
Maxic/advent2020
/day3/problem2.py
1,058
3.546875
4
def main(): with open("input.txt", "r+") as file: content = file.readlines() forest = [row.strip() for row in content] width = forest[0].__len__() x_pos = 0 y_pos = 0 tree_count = 0 trees_slope_1 = count_trees(forest, tree_count, width, x_pos, y_pos, 1, 1)...
5812c70547b63f1547c01b31947a0555391a8187
huybv1999/PythonSolution
/ch9/bai9.34.py
233
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 22 03:10:19 2020 @author: huybv1998 """ HoTen = input("Nhập họ và tên: ") res = HoTen.strip().split(" ") word = input("Nhập từ cần đếm: ") print(res.count(word))
03d0d9f5827077773a19e92448c964e0e11fa387
roskakori/talks
/pygraz/readwrite/test_binary.py
1,128
3.703125
4
''' Examples to read and write binary files. ''' import unittest def writeBinary(): targetPath = 'data.bin' with open(targetPath, 'wb') as targetFile: targetFile.write(bytes(range(16))) targetFile.write(bytes([17, 83, 194])) targetFile.write(b'some text bytes') def readBinary(): s...
7acf1ef5c6c49931236236bfcc1d46265c9ddd6c
green-fox-academy/ilcsikbalazs
/week-02/day-2/21exercise.py
1,082
4.21875
4
# Write a program that asks for two numbers # Thw first number represents the number of girls that comes to a party, the # second the boys # It should print: The party is exellent! # If the the number of girls and boys are equal and there are more people coming than 20 # # It should print: Quite cool party! # It there ...
9cc20e321530c6113c6e8b9e11f4cb21f8a7a187
gschen/where2go-python-test
/1906101007李和龙/Day20191126/实验六2.py
413
3.65625
4
""" 2. 有helloWorld()函数,请使用装饰器,在每次调用该函数的时候可以显示当前时间,注意引入datatime def helloWord(): print(‘Hello wolrd’) """ from datetime import datetime def now(func): def wrapper(*args,**kw): print(datetime.now()) return func(*args,**kw) return wrapper @now def helloWord(): return 'Hello world' print(hell...
cf28f71853bbaea19e8718667f988c5688713c75
Calavoow/hack-a-game1
/obstacles.py
10,264
3.578125
4
import pygame #import numpy from numpy import * #Class representing a line segment class Line: def __init__(self, p1, p2): #The points between which the line segment runs self.p1 = p1 self.p2 = p2 # custom toString method (called __repr__ in python) def __repr__(self): return "LINE[(%f, %f), (%f, %f)]" ...
a6430e79143b8e5bc34f06d774797d9f7baec75d
abaldeg/EjerciciosPython
/PROGRAMACION I SEGUNDO CUATRIMESTE TP1 EJ 3.py
1,273
3.859375
4
""" Una persona desea llevar el control de los gastos realizados al viajar en el subterráneo dentro de un mes. Sabiendo que dicho medio de transporte utiliza un esquema de tarifas decrecientes (detalladas en la tabla de abajo) se solicita desarrollar una función que reciba como parámetro la cantidad de viajes realizado...