blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
742f533db87bf97b4f665b264d91564abf939fd6
kathiressan/Mathematical-Language-Parser
/ShiftReduceParser.py
4,391
3.734375
4
# Start Symbol: # <EXP> # Terminal Symbols: # {+,-,*,/,(,),NUM}, where "NUM" is any number # Production Rules: # <EXP> -> NUM # <EXP> -> -<EXP> # <EXP> -> (<EXP>) # <EXP> -> <EXP> + <EXP> # <EXP> -> <EXP> - <EXP> # <EXP> -> <EXP> * <EXP> # <EXP> -> <EXP> / <EXP> import sys class Parser: def __init__(self, text)...
9a1f24ea607781da1498b9c0f985f925ca83527e
grgoswami/Python_202011
/source/Rishaan0_Do or Die.py
5,035
3.9375
4
name = str(input("Welcom to ^Make the wrong choices and you die^ Today you will be tested on 6 life or death questions. What is your name?:")) health = 1 while health > 0: action = str(input('You enter a room because you are being chased by a tiger. You close the door behind you and are immediately locked inside. Th...
b300d785046b93cc5829c98ede2cdb5bfd12e105
grgoswami/Python_202011
/source/Tista3.py
818
4.21875
4
colors = { 'Tista': 'Purple', 'Gia' : 'Turquoise', 'Anya':'Minty Green' } print(colors) for name , color in colors.items(): print(name + "'s favorite color is " + color) print(name + ' has ' + str(len(name)) + ' letters in her or his name') print('\n') #Survey na...
6324d338be0da588a7694aba0ef3f5b24a92acd0
grgoswami/Python_202011
/source/reg10.py
1,009
3.953125
4
# The following is a list of dictionaries # List of dictionaries is essentially a row based relational database, such # as mysql menu = [ {'item': 'Pasta', 'description': 'with sauce', 'price': 10.0}, {'item': 'Pizza', 'description': 'slices', 'price': 3.0}, ...
41c3f5039e71c2ea562a61ddb37987b3e80ad0fc
grgoswami/Python_202011
/source/reg17.py
465
4.28125
4
def Fibonacci0(num): """ The following is called the docstring of the function. Parameters ---------- num : int The number of elements from the Fibonacci sequence. Returns ------- None. It prints the numbers. """ a = 1 print(a) b = 1 print(b) for i in r...
c0dfe2aa84bf9cc8e5e33ecdd36a8712e3601f13
grgoswami/Python_202011
/source/reg6.py
442
4.21875
4
# String indexing str0 = 'Tista loves chocolate' print(len(str0)) print(str0[3]) # String slicing print(str0[5:7]) print(str0[4:7]) # String mutation # Strings are not 'mutable'; they are called immutable str0[3] = 'z' print(str0) s2 = 'New York' zip_code = 10001 # The following is called string concatenation pr...
07fda431408295677da702510acfb054483e7b48
Peiyu-Rang/LeetCode
/845. Longest Mountain in Array.py
831
3.6875
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 26 20:04:43 2021 @author: Caven """ class Solution: def longestMountain(self, arr: List[int]) -> int: n = len(arr) i = 0 res = 0 while i < n: base = i # walk up while i + 1 < n ...
3ec579da8e7e4bb8ea2f1fe35fd9098efdce8fb7
Peiyu-Rang/LeetCode
/987. Vertical Order Traversal of a Binary Tree.py
1,078
3.734375
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 16:36:29 2021 @author: Caven """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(...
0c9eb855df7caeba5f470452fe25235274d3cbb9
Peiyu-Rang/LeetCode
/461. Hamming Distance.py
192
3.640625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 21:38:02 2021 @author: Caven """ class Solution: def hammingDistance(self, x: int, y: int) -> int: return bin(x ^ y).count('1')
0bb4e80ba7252302d64b971d63efd9d2633834ef
Peiyu-Rang/LeetCode
/1762. Buildings With an Ocean View.py
460
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 12 16:51:30 2021 @author: Caven """ class Solution: def findBuildings(self, heights: List[int]) -> List[int]: n = len(heights) res = [] max_height = -float('inf') for i in range(n-1, -1, -1): if heights[i] > max_h...
87a459e50698a68beb59752ab4cd40f47e5c28bc
Peiyu-Rang/LeetCode
/348. Design Tic-Tac-Toe.py
1,923
3.859375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 22 02:04:35 2021 @author: Caven """ class TicTacToe: def __init__(self, n: int): """ Initialize your data structure here. """ self.player1row = [0] * n self.player1col = [0] * n self.player1diag = 0 self.playe...
a79ebe1cf3448040a5147fc7949da0f84de4f0d1
Peiyu-Rang/LeetCode
/844. Backspace String Compare.py
476
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 16 17:38:46 2020 @author: Caven """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: def F(S): skip = 0 for x in reversed(S): if x == '#': skip +=1 elif skip: ...
73a14b0a4b5bb0a5c8cbb4a009c02e5b06a9c81d
Peiyu-Rang/LeetCode
/965. Univalued Binary Tree.py
700
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 31 07:53:50 2021 @author: Caven """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isUnivalTree(self,...
8e4af6d25e0d71a21f56e617d47dc25ff11d98e7
Peiyu-Rang/LeetCode
/716. Max Stack.py
1,336
3.734375
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 14 19:48:23 2021 @author: Caven """ class MaxStack: def __init__(self): """ initialize your data structure here. """ self.bucket = [] self.maxStack = [] def push(self, x): self.bucket.append(x) ...
312bf3dd892eb3d5ddd309b6b70588cad04483ac
Peiyu-Rang/LeetCode
/20. Valid Parentheses.py
1,003
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 20:44:06 2020 @author: Caven """ class Solution: def isValid(self, s: str) -> bool: open_p = {'(':')', '[':']', '{':'}'} stack = [] for ss in s: if ss in open_p: stack.append(ss) elif len(stack) > 0: ...
e37becb3f0ae6f9af0094034495d9737c6cbbce5
Peiyu-Rang/LeetCode
/814. Binary Tree Pruning.py
831
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 31 09:24:04 2021 @author: Caven """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pruneTree(self, ro...
fff1e59274c585bd7521540a506eb668e90c38a9
Peiyu-Rang/LeetCode
/680. Valid Palindrome II.py
1,707
3.625
4
class Solution: def validPalindrome(self, s: str) -> bool: def is_palindrome(s): return s == s[::-1] l, r = 0, len(s)-1 while l < r: if s[l] == s[r]: l, r = l+1, r-1 else: return is_palindrome(s[l:r]) or is...
e21556c29989952346d294d8bc2022abfe5685a4
Peiyu-Rang/LeetCode
/15. 3Sum.py
1,622
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 23:02:05 2020 @author: Caven """ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i in range(len(nums)): if nums[i] > 0: break elif i == 0 or ...
172f316f21296afa4eff358d4ad47549527eca47
Peiyu-Rang/LeetCode
/905. Sort Array By Parity.py
382
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu May 6 21:42:36 2021 @author: Caven """ class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: n = len(A) even = 0 p = 0 while p < n: if A[p] % 2 != 1: A[even], A[p] = A[p], A[even] ...
44d1dbfc6a56abfbfbb4a3b8779426ff23b78a0b
Peiyu-Rang/LeetCode
/733. Flood Fill.py
1,775
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sun May 23 22:35:40 2021 @author: Caven """ class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: m = len(image) n = len(image[0]) ori_color = image[sr][sc] if ori_c...
5d455264e6d531868ab3496c6b1d256c1f8f024e
Peiyu-Rang/LeetCode
/437. Path Sum III.py
974
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 31 16:51:46 2021 @author: Caven """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root...
a1baf93a53445ba57ad6715a22e26df400802f85
Gal-Gilor/NeuralNetworkClass
/NeuralNetworks.py
5,026
3.71875
4
import numpy as np class RegressionNetwork(object): ''' Single hidden layered neural network that applies uses the sigmoid activation functions and returns predictions for regression purposes ''' def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of n...
8a0fcd96d2e7a22e2ef1d45af7dd914f4492d856
vamsikrishnar161137/DSP-Laboratory-Programs
/arrayoperations.py
1,774
4.28125
4
#SOME OF THE ARRAY OPERATIONS import numpy as np a=np.array([(1,4,2,6,5),(2,5,6,7,9)])#defining the array. print '1.The predifined first array is::',a b=np.size(a)#finding size of a array. print '2.Size of the array is::',b c=np.shape(a)#finding shape of an array print '3.Shape of the array is::',c d=np.ndim(a) print '...
b2854e73dd90bf6ad9fe38c81b419c3e7484151c
mona251/Intriguing-Properties-of-Contrastive-Losses
/src/data_generation/utils.py
6,206
3.734375
4
import cv2 as cv import numpy as np import matplotlib.pyplot as plt def get_height_width_ratio(old_height: int, old_width: int, new_height: int, new_width: int) -> (float, float): """Returns the two ratios: - new height / old height - new witdh / old witdh Args: ...
1677a1399dfbeac12726631a3ce8504fecf7484f
lichenysq/practice
/leetcode/primary_algorithm/tree/isValidBST.py
1,270
3.921875
4
class Tree(object): def __init__(self): self.root=TreeNode(None) self.t=[] def add(self,val): treenode=TreeNode(val) if self.root.val==None: self.root=treenode self.t.append(self.root) return else: tree_exist_node=self.t[0]...
860534ab7f19dbe81c4ddcf841040f43e8691c6a
ShaunGee/instaMutualFollowerFinder
/venv/get_followers.py
1,542
3.546875
4
from igramscraper.instagram import Instagram from time import sleep class Get_followers: ''' This class will recieve two seperate users as inputs then compare both of thier followers to find mutual followers. It will then return a list of followers ''' def __init__(this, user1,user2): th...
eb1eabd35dc520b4511781bf9e384f685050e7b5
lucasspereira/python
/conversor (dรณlar).py
260
3.8125
4
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dรณlares ela pode comprar. reais = int(input('Quanto dinheiro (em R$) vocรช tem?')) dolar = reais/5.13 print('Com R${}, vocรช consegue comprar U${}'.format(reais, dolar))
a01dd0a4c6df5dca0b1ebb21d82cdc627d9f4a8b
lucasspereira/python
/seno, cosseno e tg.py
638
4.0625
4
# Faรงa um programa que leia um รขngulo qualquer e mostre o valor do seno, cosseno e tangente desse รขngulo. from math import sin, cos, tan angulo = int(input('Digite um valor: ')) seno = sin(angulo) cosseno = cos(angulo) tangente = tan(angulo) print('O seno de {} รฉ {}. O cosseno de {} รฉ {}. E a tangente de {} รฉ {}.'.for...
bc16a054e3eee1730211763fe3d0b71be4d41019
shevdan/programming-group-209
/D_bug_generate_grid.py
2,259
4.375
4
""" This module contains functions that implements generation of the game grid. Function level_of_dif determines the range (which is the representation of the level of difficulty which that will be increased thorough the test) from which the numbers will be taken. Function generate_grid generates grid, with a one spe...
b184583d8cb0f477ccec471e8f2c05038e068e81
tonyyo/PycharmProjects
/ๆ•ฐๆฎ็ป“ๆž„็ปƒไน /ไบŒๅ‰ๆ ‘้ๅކ/็”จ้˜Ÿๅˆ—ๅฑ‚ๆฌก้ๅކไบŒๅ‰ๆ ‘.py
1,073
3.828125
4
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution(): def buildTree(self, start, A): # ไปŽstartๅค„ๅผ€ๅง‹ๆž„้€ ๆ™ฎ้€šไบŒๅ‰ๆ ‘๏ผŒไธ€่ˆฌไปŽ0ๅผ€ๅง‹ if start >= len(A): return node = TreeNode(A[start]) node.left = self.buildTree(2 * start + 1...
4816ec528e2fe1e772d1c20ddd63d196e6adec67
tonyyo/PycharmProjects
/ๆ•ฐๆฎ็ป“ๆž„็ปƒไน /Python็ฎ—ๆณ•ๆŒ‡ๅ—ๆ•ฐๆฎ็ป“ๆž„/145_็ฟป่ฝฌไบŒๅ‰ๆ ‘.py
1,272
4.03125
4
# ๆ ‘็š„ๅฎšไน‰ # ๅ‚ๆ•ฐrootๆ˜ฏไธ€ไธชๆ ‘่Š‚็‚น๏ผŒ่กจ็คบไบŒๅ‰ๆ ‘็š„ๆ น่Š‚็‚น # ่ฟ”ๅ›ž็ฟป่ฝฌๅŽๅ€ผ class invertBinaryTree: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: def invertBinaryTree(self, root): self.dfs1(root) def dfs(self, node): left = node.left right = node.right ...
49c4e434aa2d8b97c3c5a21ad214e431f51425a2
ajaygk95/CSE-519-Data-Science-Kaggle
/house-prices-advanced-regression-techniques/cse519_hw3_gopalkrishna_ajay_112688765.py
30,130
3.59375
4
#!/usr/bin/env python # coding: utf-8 # # Homework 3 - Ames Housing Dataset # For all parts below, answer all parts as shown in the Google document for Homework 3. Be sure to include both code that justifies your answer as well as text to answer the questions. We also ask that code be commented to make it easier to f...
85eabae3f59160f726d1c0e552dc534a3c99d7b2
Nahla-Thabet/problemSolving
/football.py
86
3.828125
4
f=input() if (7*"1" in f or 7*"0" in f): print("YES") else: print('NO')
9d3d41867a03a683a4c09233691cd1a4e5a4560a
mneygri56/Engineering_4_Notebook
/Python/Strings and Loops.py
537
4
4
#Strings and Loops #Written By David and Miles while(True): #Get a User Input sentence = input("Enter a Sentence: ") #Split the Input by Spaces splitsentence = sentence.split() for n in range(len(splitsentence)): #if the sentence is over, end the system if (splitsentence[n] == "-1"): ...
8243c50d7dd21b459d942b5beb5289f2c30b06af
mahdikafi/learning_python
/.ipynb_checkpoints/debug-checkpoint.py
438
3.875
4
with open("Python.txt") as file: content = file.readlines()[2] print(content) char_count = 0 word_count = 0 line_count = 0 for char in content: char_count += 1 if char == ' ': word_count += 1 if char == '\n': line_count += 1 word_count += 1 ...
c276ea60f0cb61fa34e98ee03410d2231e0edae1
arthur109/ImpossibleTicTacToePython
/TicTacToe.py
14,036
3.65625
4
# sorry for bad spelling in the comments import random # text effect codes CEND = '\33[0m' CBOLD = '\33[1m' CITALIC = '\33[3m' CURL = '\33[4m' CBLINK = '\33[5m' CBLINK2 = '\33[6m' CSELECTED = '\33[7m' # text color codes CBLACK = '\33[30m' CRED = '\33[31m' CGREEN = '\33[32m' CYELLOW = '\33[33m...
65c679d64da76f7c2e6afe21e669e0dd4302a2ee
Sagar3195/Deep-Learning-Car-Brand-Predict
/car_brand_classification_using_deep_learning.py
4,438
3.5625
4
# -*- coding: utf-8 -*- """ ### Car Brand Classification Using Deep Learning """ ###importing required libraries from tensorflow.keras.layers import Input, Lambda, Dense, Flatten from tensorflow.keras.models import Model from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.applications.resn...
67c0ce31869cfc46c1b23b87b7f58c64dab5142e
Eze148/Python_Exer
/binary_search.py
344
3.8125
4
def search(x): a = 100 z = 0 y = 0 while(x != y): y = (a + z) // 2 if (x == y): break print('Is this number larger than', +y, ' (y/n)?: ') w = input() if(w == 'y'): z = y elif(w == 'n'): a = y print("Input number is:...
440722d33b3a0e440ea4317b9f0050ca2d70364e
esovm/esolangs
/n-refine/n-refine.py
1,524
3.5625
4
import sys, random def n_refine(code, debug=True): try: code = list(map(int, code.split())) except ValueError: my_filename = sys.argv[0].replace("\\", "/").split("/")[-1] print(f"{my_filename}: Error: invalid syntax") sys.exit(1) numbers = {} i = 0 while 0 <= i < len(code): a, b = code[i]...
dc3a74923821c533c2852ef36837dd90ac12c172
esovm/esolangs
/plus-or-minus/plus-or-minus.py
1,296
3.90625
4
import sys def plus_or_minus(code, is_original): accumulator = 18 if is_original else 0 max_value = 461 if is_original else 255 for char in code: if char == "+": accumulator += 1 if char == "-": print(end=chr(accumulator)) accumulator -= 1 if accumulator < 0: accumulator = max...
2ae689fbf5c83c4766b9dfe58ba5a72b328d2ba1
jensiner/futoshiki
/main.py
34,394
3.65625
4
import copy def readfile(file): """ reads from input file to develop 3 2D arrays. One is the board with cells that are empty and those that are assigned, another is a 6x5 (6 rows, 5 columns) containing the horizontal constraints, and the last one is a 5x6 (5 rows, 6 columns) containing the vertical c...
9f5e61940618f45b588c67b70200f71342a58f03
tlusk/rectangle-intersection
/src/main.py
3,479
4.15625
4
import unittest class Point: def __init__(self, x, y): """ :param int x: X coordinate for the point :param int y: Y coordinate for the point """ self.x = x self.y = y class Rectangle: def __init__(self, top_left, bottom_right): """ :param Poi...
207ecaf23e5e81a223b5c257da5ff2c3c2879909
yrafalin/LadderProject
/PermFinder.py
374
3.765625
4
#!/usr/bin/env python3 permutation = input('Put your permutation string (i.e. \"1 2 3 4\"): ') permutation = permutation.split() columns = len(permutation) new_matrix = [] for num in permutation: zeros = ['0' for _ in range(columns)] zeros[int(num) - 1] = '1' mat_row = '[ ' + ' '.join(zeros) + ' ]\n' ...
3da0639a03ae3f87446ad57a859b97af60384bc4
blafuente/SelfTaughtProgram_PartFour
/list_comprehension.py
2,397
4.65625
5
# List Comprehensions # Allows you to create lists based on criteria applied to existing lists. # You can create a list comprehension with one line of code that examins every character in the original string # Selects digigts from a string and puts them in a list. # Or selects the right-most digit from the list....
09d65cba54ccdb9818d5fe5ba12bb9d8b25f9f5b
FairozaAmira/python-training
/Module-04/hello/text.py
305
3.609375
4
class Text: def __init__(self, text): self.text = text def print_input(self): try: return print(self.text) except Exception as e: message = f"Exception in print_input: {str(e)}" print(message) raise Exception
831095b6414d54cde63dc9857bf341726befa0db
Kakurouta/Python_Data_Science
/Tensorflow_Real_Example.py
4,116
3.546875
4
import numpy as np from sklearn import preprocessing #load csv file into np array raw_csv = np.loadtxt('Example_TF.csv', delimiter = ',') #drop first column (customer id) and last column (target) unscaled_inputs_all = raw_csv[:,1:-1] #last column is the target that we want to predict (buy or not) targets_all...
bcd23e258cba5c49f7f530131cead332d28960d1
IEEEsbUS/curso_python3
/Workspace/bucle.py
466
4
4
#! /usr/bin/env python3 # Declaramos las variables con las que vamos a trabajar n = 30 i = 0 lista = ['Juan', 'Antonio', 'Perico', 'Amancio', 'Jose Manuel'] # While while i < n: print('El numero i es menor que n') i += 1 # Actualizamos la condicion para no mantenernos en un bucle infinito # For con integ...
41531f8bb2a2b929f1d3296b69459908d061adcb
IEEEsbUS/curso_python3
/Sources originales/tiposdedatos.py
426
3.625
4
#! /usr/bin/env python3 # Boolean b = True b2 = False # Integer i = 2 i.bit_length() # Float f = 2.5 f.is_integer() # String s = "Hola!" s.isdecimal() s.isdigit() s.isalnum() s.islower() s.isupper() # Tuple t = (s, i) t.count() # Listas l = [] l.count() l.append() l.remove() l.reverse() l.clear() l.insert()...
6265ffef041e2ca847e18d295a1c7a8e5f5c9576
marom17/fblivedisplay
/control_musicPorgress.py
3,592
3.703125
4
""" __Author__: Romain Maillard __Date__: 29.09.2017 __Name__: control_musicProgress.py __Description__: Get the actual music, display it and control startTime and bar """ import time from threading import Thread class MusicProgress(Thread): ''' Class MusicProgress functions: - run...
3dfd84b379ddf5c85fc3cdb5e65db03fb038f176
concpetosfundamentalesprogramacionaa19/clase4-2do-BrandonVS
/ejercicios-python1/principal1.py
289
4
4
""" @reroes Manejo de estructuras """ diccionario = {"nombre": "Fernando", "apellidos": "Quizhpe"} print("Imprimir diccionario") # for l in diccionario.keys(): print("%s: %s %s: %s" % ("Mi nombre es", diccionario["nombre"], \ "y mi apellido es", diccionario["apellidos"]) \ )
a80a0e355f1350efca9ff52ee6eb351e67a4480a
arunabhagupta/Machine_Learning_Python
/Data_PreProcessing_TEMPLATE_Udemy.py
946
3.796875
4
#Importing the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the dataset dataset = pd.read_csv("E:/AI_ML_DA/R_Python_Code_Datasets/DataSets/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------...
72ed4f0593fc1fcb78edc0cfdcd7ef88c19eadab
LakshmiRajend/FST-M1
/Python/Activities/Activity10.py
117
3.890625
4
numbers= tuple(input("Enter numbers for tuple").split(",")) for n in numbers: if int(n)%5==0: print(n)
6160a5c8c62b3a83f8c80e5ed5a418c446c00b34
KamilyaBikmaeva/Python_Course
/Py3/Decorators.py
1,079
3.71875
4
import time def max_freq(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) max_freq_word = '' max_count = 0 for key in result: if result[key] > max_count: max_count = result[key] max_freq_word = key print(f'Most ...
2be3086df56cac6b0cbad1760edb3861e76923de
vigge93-BTH-courses/DV1625-Algoritmer-och-datastrukturer
/Assignment 1/mergesort_notinplace.py
913
4.09375
4
"""Mergesort not in place.""" import math from typing import List def merge(A: List[float], p: int, q: int, r: int) -> None: """Split A at q and merge together in order.""" n_1 = q-p+1 n_2 = r-q L = [] R = [] for i in range(n_1): L.append(A[p+i]) for j in range(n_2): R.appe...
d4b55856210fd5110796fc7344dfb3d6822cdb95
vigge93-BTH-courses/DV1625-Algoritmer-och-datastrukturer
/coin_problem.py
831
3.609375
4
import math import time import random def coin_greedy(n): coins = [1, 2, 5, 10, 25][::-1] res = 0 for coin in coins: res += n // coin n %= coin return res def coin_dynamic(n): coins = [1, 2, 5, 10, 25] if n == 0: return 0 known_values = [math.inf for idx in ...
52d94f2b38559062c20863a947d24388dfb03b4f
sde1000/aoc2020
/day21.py
878
3.65625
4
#!/usr/bin/env python3 from functools import reduce import operator def parse_food(l): l = l.strip()[:-1] ingredients, allergens = l.split(" (contains ") return ingredients.split(), allergens.split(", ") with open("day21-input.txt") as f: foods = [ parse_food(l) for l in f ] allergens = {} for i, a ...
d9c7c08f0dca9751d6d10a962580375183d4963d
NiCrook/PS_Assessment
/Rotated Digits.py
937
3.890625
4
def rotate_digits(num: int) -> int: # create check for num value if num < 0 or num > 10000: return 0 # create list of bad numbers because these are known bad_numbers = [0, 1, 3, 4, 7, 8] # create placeholder variables counter = 0 good_numbers = 0 # iterate through range of num ...
72ed79f23ea0bc396869ca6442e30dfe297d3320
NiCrook/PS_Assessment
/Capacity to Ship Packages Within D Days.py
1,666
3.859375
4
def max_capicity(weights: list, days: int) -> int: max_capicity = sum(weights) // days counter = 0 daily_weight = 0 cur_days = 1 # iterate through each weight while counter != len(weights): # check if current weight exceeds capacity if weights[counter] > max_capicity: ...
e35694db45a4fa82356430c3e2a8ad164522cf02
mdhussain7/Python-Basic-Project
/ml-training-master/projects/1.py
1,278
3.984375
4
''' 1) Array and pointers(?) How are arguments passed in functions (call by value or reference) What happens when: Def: Foo (a): a[3]=10 return a = [1,2,3,4,5] foo(a) Print (a) Def foo (a): print(id(a)) Assume variable โ€œaโ€ ultimat...
dbcce424928c19f7e4cda02e3f7ceab7df84bb2d
luwangg/GNUnetwork
/gn/libevents/events.py
1,755
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Classes and functions to handle events. Class Event is a generic class for all types of events. Class Event is expected to be specialized into different, more specific types of events, implemented as subclasses. A hierarchy of event types and subtypes is possible. Even...
bd487ae72ea178ea763310ec6f453e3da952dc68
C-GDA-TC1028-016-2113/tarea1-A01641441
/assignments/03Promedio/src/exercise.py
759
3.984375
4
def main(): #escribe tu cรณdigo abajo de esta lรญnea #Modifica el programa para que realice lo siguiente: En una universidad cada estudiante cursa 4 materias en el semestre. Desarrolla un programa que reciba la calificaciรณn de cada materia (tipo float), calcula el promedio de las 4 materias y lo despliega. #A...
2167f15f1abb49e6ffdb1b84a6efe91aa6808304
BobbyRoche/programming_2
/hw3_directory/vader.py
1,296
3.671875
4
from enemy import Enemy import random class Vader(Enemy): #enemy subclass called vader def __init__(self, n, h): #uses init of enemy and adds a dictionary of attacks and damage to be randomly selcted. super(Vader,self).__init__(n, h) self.attack_dic = {'saber throw' : 5, ...
56c774860cffd8e90563019e27807ecbbd8ec625
BobbyRoche/programming_2
/hw3_directory/dragon.py
1,001
3.78125
4
#Robert Roche #CS-172 Section A, Lab 062 from enemy import Enemy class Dragon (Enemy): #subclass of enemy called dragon def __init__(self,n,h): #uses enemy init for name and health, creates two of its own attributes super(Dragon,self).__init__(n,h) self.attack_name= 'Fire breadth' ...
cad124b6d3605374423ccade324728df9e208d31
apatel3112/SoftwareCarpentryWC3
/mundaneMath.py
175
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 19 15:28:51 2019 @author: Anusha """ sum = 0 for i in range(0,101,2): sum += i print(sum)
a0c256b89e86788e449f30c987baeee638a835e0
ritu-kartik/Sudoko_Solver
/sudoku_solver.py
3,342
3.8125
4
board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] ###### THE ACTUAL ALGORITHM #this is the recursive algo which stops if the conditi...
b1cac9b7dc95bd978cf4a546623baa3a2eeaa41d
avinash273/InterstingProblems
/MoveZeros.py
621
3.90625
4
""" Move all Zeros to the end of the array, maintaining the relative orders of other elements Time Complexity :O(n) Space Complexity :O(1) inplace algorithm inp = arr = [1, 3, 0, 3, 0, 5, 12] out = 1->3->3->5->12->0->0 """ def MoveZeros(arr): arrLen = len(arr) print(arrLen) if arrLen <= 0: return...
2f2ab1a99654d3abb50160aed8cfd8f587224c7f
skeller88/data-structures-in-python
/linked_list.py
3,366
3.9375
4
__author__ = 'Shane' class LinkedList: """A doubly linked list.""" def __init__(self): self.head = self.tail = None def __len__(self): length = 0 n = self.head while n: length += 1 n = n['next'] return length def __contains__(self, k...
a4a62f29fc36bba81de9add6f6131a48f8a5f4ec
AAKASH707/PYTHON
/different ways find sum of GP series.py
1,857
4.0625
4
# Python Program to find Sum of Geometric Progression Series import math a = int(input("Please Enter First Number of an G.P Series: : ")) n = int(input("Please Enter the Total Numbers in this G.P Series: : ")) r = int(input("Please Enter the Common Ratio : ")) total = (a * (1 - math.pow(r, n ))) / (1- r) tn = a * (ma...
d2f172a112ec5a30ab4daff10f08c5c4c5bc95a1
AAKASH707/PYTHON
/binary search tree from given postorder traversal.py
2,332
4.21875
4
# Python program to construct binary search tree from given postorder traversal # importing sys module import sys # class for creating tree nodes class Node: def __init__(self, data): self.data = data self.left = None self.right = None # initializing MIN and MAX MIN = -sys.maxsize - 1 M...
a079327ad1c4c1fcc01c22dc9e1e8f335f119958
AAKASH707/PYTHON
/Print Square Number Pattern.py
234
4.25
4
# Python Program to Print Square Number Pattern side = int(input("Please Enter any Side of a Square : ")) print("Square Number Pattern") for i in range(side): for i in range(side): print('1', end = ' ') print()
5b90a261a667a86387e49463f49a8855b477174c
AAKASH707/PYTHON
/Count Words in a String using Dictionary Example.py
639
4.34375
4
# Python Program to Count words in a String using Dictionary string = input("Please enter any String : ") words = [] words = string.split() frequency = [words.count(i) for i in words] myDict = dict(zip(words, frequency)) print("Dictionary Items : ", myDict) *******************************************************...
fd685bd297241d3de47dbb055a2bd50bedd5b314
p-gonzo/python-toy-problems
/merge_sort.py
896
3.953125
4
def merge_sort(l, comparator=lambda x, y: x < y): def split(l): if len(l) < 2: return l left = l[ : len(l) // 2 ] right = l[ len(l) // 2 : ] sorted_left = split(left) sorted_right = split(right) return(merge(sorted_left, sorted_right)) def...
79e2d4f844b381f7ad9801a665af2e46295db1be
himanshutiwari14/TextUtils
/Leet_Code/longest_common.py
282
3.53125
4
class Solution: def longestCommonPrefix(self, nums): nums=sorted(nums,key=len) for i in nums: print(i[0]) s=Solution() print(s.longestCommonPrefix(["flowerss","flow","flighjt"] ))
fda03e9fd89f590ccb95495650477cbdca105004
himanshutiwari14/TextUtils
/Recursion_problem/recursion1.py
480
3.765625
4
import datetime import time current_time=datetime.datetime.now() print("start time is ",current_time) def reverse_def(s): #base case if len(s)<=1: print("Computing {}...".format(s)) return s print("Computing {}...".format(s)) return reverse_def(s[1:]) + s[0] res=rever...
a090b39b68d0638923c88b46b0c1f484d448f9e0
himanshutiwari14/TextUtils
/Recursion_problem/recursion2.py
282
3.6875
4
def fact(n): print("bhai pehla base case",n) #base case if n==0: print("yha mat aao",n) return 1 print("ye aap ki baap ki jagah hau",n) # print(n,"1") # print(fact(n-1),"2") # print(n*fact(n-1),"3") return n*fact(n-1) print(fact(6))
9b649a5f7d3c3db4f83e3070b6fc6344e2431b6c
dnsdigitaltech/aulas-de-python3
/estrutura-de-repeticao-while.py
538
4.09375
4
# Comando que repentem treรงos de cรณdigos enquanto uma condiรงรฃo for verdadeira # ou enquando uma ocndiรงรฃo pre determinada for passada pra ele """ x = 1 while x < 10: print(x) # neste caso se executar x valerรก 1 sempre chamado de lop infinito e travarรก o computador, รฉ necessรกrio dar um novo valor pra x """ x = 1 ...
35d76db2c786b8d4bec786699466b294d98b9855
dnsdigitaltech/aulas-de-python3
/funcoes.py
755
4.46875
4
#Funรงรตes permitem as chamadas modularizaรงรตes do meu cรณdigos #Sรฃo blocos de cรณdigos que spรก serรฃo chamados executados quando forem chamados #Em python as funรงรตes sรฃo definidas pela palavra reservada def """ Definiรงรฃo def NOME(parรขmetros): COMANDOS Chamada NOME(argumentos) """ #Funรงรฃo que faz a soma de ...
ab975ef466da96fb72d1996b1df0c8ee155934c5
dnsdigitaltech/aulas-de-python3
/lista-parte-2-ordenar-lista.py
509
4.15625
4
#ordenar as listas lista = [124,345,72,46,6,7,3,1,7,0] #para ordenar a lista usa-se o mรฉtodo sort lista.sort() # altera ardenadamente a lista que jรก existe print(lista) lista = sorted(lista) # retorno uma lista ordenada print(lista) #Ordenar decrescente lista.sort(reverse=True) print(lista) #Inverter a lista lista....
9b4e7e7c30e41a390d7dc88a18c6a07ce0460b62
dnsdigitaltech/aulas-de-python3
/numeros-aleatorios.py
526
4.0625
4
# O pyton fornece um mรณdulo chmado randon para este fim # Com este mรณdulo podemos chmar alguns mรฉtodos quen germa numeros aleatรณrios import random numero = random.randint(0, 10) #numeros aleatล•ios de 0 a 10 print(numero) #Existe um forma de focar a o pyton a exibir sempre o mesmo numero random.seed(1) numero = random...
7b82acb19a37b66634b76ad2beaf34ff069a5c83
josh-folsom/exercises-in-python
/coins.py
197
4.09375
4
coin = 0 while True: print("You have {} coins".format(coin)) want = input("Do you want a coin? ") if want == "yes": coin += 1 elif want == "no": break print("Bye")
5d464a64a9d8ef963da82b64fba52c598bc2b56c
josh-folsom/exercises-in-python
/file_io_ex2.py
402
4.4375
4
# Exercise 2 Write a program that prompts the user to enter a file name, then # prompts the user to enter the contents of the file, and then saves the # content to the file. file_name = input("Enter name of file you would like to write: ") def writer(file_name): file_handle = open(file_name, 'w') file_handle....
f36220a4caae8212e34ff5070b9a203f4b5814f8
josh-folsom/exercises-in-python
/python_object_ex_1.py
2,486
4.375
4
# Write code to: # 1 Instantiate an instance object of Person with name of 'Sonny', email of # 'sonny@hotmail.com', and phone of '483-485-4948', store it in the variable sonny. # 2 Instantiate another person with the name of 'Jordan', email of 'jordan@aol.com', # and phone of '495-586-3456', store it in the variable '...
32d71b0f5025c7487f3ff5d9b022514dac1b5a60
josh-folsom/exercises-in-python
/turtle_ex_4_2.py
585
3.796875
4
from random import * from math import * from turtle import * #def vary(): #randint(2, 7) def repeat(times, f): for i in range(times): f() def smaller(): width(randint(2, 7)) def walk(): goto(randint(-300, 300), randint(-300, 300)) def star(size): for i in range(5): def nifty(): ...
725b2b592e53fbeb18c5babe2d6862a643f4c761
josh-folsom/exercises-in-python
/string_ex_reverse_a_string.py
190
4.3125
4
#created a sting that uses standard all lower case a = "i am a string" #used .capitalize() to capitalize the first char in the string for i in reversed(a): print (i, end="") print("")
02ed030f37c4e6e330c97f502340916a99beb081
muskankumarisingh/function_2
/keyword arugument example.py
59
3.546875
4
def divide(a=5,b=3): c=a/b print(c) divide(b=4,a=8)
6f8e30e66f0061b4c68b1a743a216bb0e5235d6b
muskankumarisingh/function_2
/more exercise factorial.py
129
4.0625
4
def function(): i=int(input("enter the number")) fac=1 while i>0: fac=fac*i i=i-1 print("factorial","=",fac) function()
9491ebbc22057329ba8205c8e3175377d1b9ba1e
yas373/Hesaplamal-Geometri
/hafta1.py
710
3.6875
4
# coding: utf-8 # In[5]: import matplotlib.pyplot as plt def my_draw_a_vector_from_origin(v): plt.axes().set_aspect('equal') x=[0,v[0]] y=[0,v[1]] plt.xlim(-10,15) #sฤฑnฤฑr deฤŸerler plt.ylim(-10,15) plt.plot(x,y) def my_draw_a_vector_from_v_to_w(v,w): x=[v[0],w[0]] y=[v[1],w[1]] ...
33a54c2f2a1e83fb55347a1f6f618445e6edd078
SleeP-isn-Cool/Dice
/dice.py
2,346
3.546875
4
import tkinter import random canvas_width = 640 canvas_height = 480 canvas = tkinter.Canvas(width=canvas_width, height=canvas_height) canvas.pack() number = random.randint(1,6) print("Number {}".format(number)) print("Making dice") size = 255 x, y = canvas_width / 2, canvas_height / 2 unit = size / 5 radius = size...
4ffe4db32ef0bfd215f89ae83c1c86a0d20773b7
mishka245/intellectual-systems
/lib/board.py
1,942
3.953125
4
import random class Board: """ Board class to represent nodes and work with them """ def __init__(self, param=None): if param: self.from_list(param) else: numbers_array = list(range(9)) random.shuffle(numbers_array) self.from_list(number...
692e75a669d79ef485a2f3ce150740de43ce18a2
Chadlo13/pythonTutorials
/Test4-String.py
296
4.0625
4
sentence = "This is a String" print(sentence.lower()) print(sentence.capitalize()) print(sentence.upper()) print(sentence.upper().isupper()) print(len(sentence)) print(sentence[3]) print(sentence.index("S")) print(sentence.replace("This" , "Thus")) print(sentence.replace("i" , "U"))
953751722d3d968d169e147a78ea2716fcb573ce
Chadlo13/pythonTutorials
/Test13-Compare.py
279
4.21875
4
def maxFunc (num1,num2,num3): return max(num1,num2,num3) input1 = input("Enter a number: ") input2 = input("Enter a number: ") input3 = input("Enter a number: ") maxNum = maxFunc(int(input1),int(input2),int(input3)) print("the largest value is: " + str(maxNum))
fd2e4e3084d07a101dd7edff00006a1c1175668f
baruwaa12/Projects
/Roman Numerals.py
2,718
3.6875
4
import math numerals = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"] def one_to_nine(input_number): if (input_number <= 10) and input_number > 0: return numerals[input_number] else: return "Romans did not have any negative numbers or zero" def get_thousands(inp...
44a8928562fb6acbe55c4316c924f25be84404fc
baruwaa12/Projects
/Wordyproblem.py
306
4.09375
4
from operator import add, mul, truediv as div def calculate(operators): operators = { '+': add, '/': div, '*': mul, } number1 = int(input("Pick a number")) number2 = int(input("Pick another number")) question = str(input("What is") + number1 + operators + number2)
fb43c863de622e34082d1d3c8f88d864662cbcf8
nypgit/FYPJ
/Dataset Collection/Scripts/Sampling Method/load_data.py
1,348
3.546875
4
#!/usr/bin/python3 # Program to load a numpy file # Display data stored in numpy array import numpy as np import os import argparse # Display full numpy array np.set_printoptions(threshold=np.nan) def main(): parser = argparse.ArgumentParser(description="Load numpy file and display its data in numpy array.") ...
79d6cf0b8c1a1e51c481598459e44ebb124c6306
asirhameem/Python-For-Everybody
/groosPay.py
223
3.96875
4
hours = input("Enter Hours:") hrs = float(hours) rate = input("Enter rate per hour:") rte = float(rate) if hours > 40 : pay = 40 * rte +(rte * 1.5 * (hrs-40)); print(pay) else: pay = hrs * rte print(pay)
148d522629291871a09349a97c1320c7ecf23dde
asirhameem/Python-For-Everybody
/FileRead.py
128
3.5625
4
fname = input("Enter file name: ") fhandle = open(fname) line = fhandle.read() upline = line.upper().rstrip() print(upline)
3466e9d8acbc31778886b47a62206483c2a5adb5
dennis1219/algorithm_study
/python/01_basics/2digits1_de_morgan.py
273
3.96875
4
print('2์ž๋ฆฌ์˜ ์–‘์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.') while True: no = int(input('๊ฐ’์„ ์ž…๋ ฅํ•˜์„ธ์š”.: ')) if not(no < 10 or no > 99): break print(f'์ž…๋ ฅ๋ฐ›์€ ์–‘์ˆ˜๋Š” {no}์ž…๋‹ˆ๋‹ค.') #De Morgan's law. If not 2 digit number, makes the user input again.
bb25e89891b086bb769ebd3d98b45709a9c0dc33
hungphat/hackerrank-30days
/day_23/BST_Level_Order_Traversal.py
857
3.796875
4
import sys class Node: def __init__(self, data): self.right=self.left=None self.data = data class Solution: def insert(self,root, data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left, data) ...
fde1cef5e0f3283966c77d7075776443e6207b7a
hungphat/hackerrank-30days
/day_13/Abstract_Classes.py
1,110
3.859375
4
def run(input, output): from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self, title, author): self.title = title self.author = author @abstractmethod def display(): pass #Write MyBook class class my_book(Book):...
be3869632dcd643f3ac7181629cb18de798de251
drop-table-lol/Fartcraft
/Minions/Hero.py
4,101
3.59375
4
"""Hero.py HEROS are the main characters per faction. They allow building of structures, advanced unit tactics, and are excellent fighters. They provide a way to change the course of battle through a single unit. Here, we are setting it up for the player-input.""" import pygame from Displays import Display import ra...