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
df33c299152157b4bd7bdb5d8178c48d0a89e217
pymft/mft-05
/S04/functions/functional_approach.py
263
3.875
4
def factorial(n): out = 1 for i in range(n + 1): out = out * i return out factorial(10) n = 5 k = 3 n_fact = factorial(n) k_fact = factorial(k) n_k_fact = factorial(n-k) combination = n_fact / (k_fact * n_k_fact) print(combination)
55d40bbc6eebe89d24d2ab543ac25597f4c8276d
pymft/mft-05
/S07/exception_handling/triangle.py
827
3.921875
4
import math class InvalidTriangleEdgeTypesError(TypeError): pass class NotATriangleError(ValueError): pass def is_triangle(a, b, c) -> bool: if not (isinstance(a, (int, float)) and isinstance(b, (int, float)) and isinstance(c, (int, float))): raise InvalidTriangleEdgeTy...
14a000a5090ea01224fa23b5001e5a4a353f5126
pymft/mft-05
/S07/generator_review/reduce_function.py
204
3.609375
4
from functools import reduce def f(a, b): return a + b lst = [1, 2, 3, 4, 5, 6, 7] res = reduce(f, lst) print(res) # 1 + (2 + (3 + (4 + (5 + (6 + 7))))) # # f(1, f(2, f(3, f(4, f(5, f(6, 7))))))
467726f8cf0328a5422fb96af2fc699361807f74
pymft/mft-05
/S09/temp/temp.py
2,177
3.796875
4
import math PI = 3.14 class Area: def __get__(self, instance, owner): if isinstance(instance, Paralleogram): angle = math.radians(instance.alpha) coef = math.sin(angle) return instance.a * instance.b * coef elif isinstance(instance, Circle): return ...
489c9f2de0ad0f51f50e067f11dbc818914559ae
pymft/mft-05
/S02/loops/avoid_infinite_loops.py
75
3.5
4
n = 1 while True: n = n + 1 print(n) if n == 10: break
8ab31d22b7e7561c380ff1a9a7e0e50f136e7154
pymft/mft-05
/S06/generators/main.py
467
3.671875
4
def fib_cpu(n): a, b = 0, 1 if n == 0: return a if n == 1: return b i = 2 while i <= n: a, b = b, a+b i = i + 1 return b for i in range(10): print(fib_cpu(i)) def fib_memory(n): if n == 0: return [0] if n == 1: return [0, 1] o...
d35e50a18fe2d18aa820b58c9a110b8202c0d8ee
pymft/mft-05
/S10/a_simple_web_service/create_db.py
227
3.703125
4
import sqlite3 conn = sqlite3.connect("my-db.sqlite") conn.execute(""" CREATE TABLE IF NOT EXISTS records ( id INTEGER PRIMARY KEY AUTOINCREMENT , username TEXT NOT NULL, weight REAL, height REAL );""") conn.close()
99dddf7531d25ca94c177a77f81c1ace561e7cd5
alina-j/6
/8.py
1,120
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Решите задачу: создайте словарь, связав его с переменной school , и наполните данными,которые бы отражали количество учащихся в разных классах (1а, 1б, 2б, 6а, 7в и т. п.).Внесите изменения в словарь согласно следующему: а) в одном из классов изменилось количество учащи...
29642adf91a92634a65e86694b796da0dd89ccde
CaptainSharf/Donkey-Kong-game
/person.py
1,549
3.6875
4
from board import board class person: char="P" x=0 y=0 def put(self,board,color): board.create(self.char,self.x,self.y,color) class queen: def __init__(self): self.char="Q" def put(self,board,x,y,color): board.create(self.char,x,y,color) class donkey(person): def __...
ae8ee4ed86a8464625edd342562270a60ec52628
Mxt3usz/python_stuff
/codewars/find_short.py
241
3.828125
4
def find_short(s): a = s.split() b = 0 for c in a: if b == 0: b = len(c) if b > len(c): b = len(c) return b print(find_short("bitcoin take over the world maybe who knows perhaps"))
d826a17bf74aeb5998c94fe07c595823ec3b3644
Mxt3usz/python_stuff
/codewars/split_strings.py
243
3.53125
4
def solution(s): a = [] try: for i in range(0,len(s)): if i % 2 == 0: a += [s[i] + s[i + 1]] return a except Exception: a += [s[i] + "_"] return a print(solution("abc"))
ba9154dbba4e3aeae83afe814287b35a2e1cb396
Mxt3usz/python_stuff
/codewars/longest.py
425
3.859375
4
def longest(a1,a2): result = "" for c in a1: if c not in result: result += c for c in a2: if c not in result: result += c alpha = "abcdefghijklmnopqrstuvwxyz" sol = "" for x in alpha: if x in result: sol += x return sol #res = "...
4ecafeb7cc52a29de7905c5c732d8103893d1f47
Mxt3usz/python_stuff
/Projects/optimizer.py
5,600
3.8125
4
""" I hate binary trees """ from tree import Node, leaf from expr_parser import parse from typing import Optional example = Node('+', Node('*', leaf(2), leaf('x')), leaf(5)) def is_var(tree: Optional[Node]): if isinstance(tree.mark,str): return True return False def is_val(tree: Optional[Node]): i...
7595f92d87ea9e4e72d201268ef56df8fc0d3c87
Mxt3usz/python_stuff
/Projects/pascal.py
407
3.96875
4
""" 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Implementation of Pascal Triangle """ def pascal(n : int): pascal_form = [] for number in range(1, n + 1): if number == 1 or number == 2: pascal_form += [1] return pascal_form print(pascal(0)) print(pascal(1)) print(pa...
32d1f75be6fbeffb7f28d21ab39044c072ba57d4
Mxt3usz/python_stuff
/Projects/map.py
489
3.53125
4
""" Normal Way """ def ctof(temp:float) -> float: return (9/5) * temp + 32 def list_ctof(cl:list[float])->list[float]: result = [] for celsius in cl: result += [ctof(celsius)] return result c_lst = [20,30,10,-1,-20] f_lst = list_ctof(c_lst) print(f_lst) maped = list(map(ctof,c_lst)) print(m...
307aed5aab6e311431964027a0ed77e8a44c8e9b
Mxt3usz/python_stuff
/Projects/expreval.py
603
3.640625
4
from tree import Node, leaf from expr_parser import parse import pytest def expreval(tree): if tree.mark == '+': return expreval(tree.left) + expreval(tree.right) elif tree.mark == '-': return expreval(tree.left)-expreval(tree.right) elif tree.mark == '*': return expreval(tree.left)...
0c546cf2b71a90ddc5084f64dc6f9df3833955e0
V-Anand97/Day2_Exe_project_Tip_Calculator
/Day 2 Exe 2.2 BMI Calculator.py
194
4.25
4
print("BMI Calculator") weight = float(input('Enter your weight in KG: \n')) height = float(input("Enter your height in meters: \n")) BMI = int(weight / (height ** 2)) print('your BMI is',BMI)
25a25385f79b2a0f2c3fa0c54f955210dd9c4621
TomSteve1102/python
/findClass.py
1,278
3.734375
4
# Author:Tom_Steve # Date:2021-07-17 def countStudentClass(studnetScoreList): if len(studnetScoreList) < 1: print("Please add at least 1 item into the list") return 0 nerdCount_list = [0] * 7 # initialize the output list # Please write your own program here for studentScore in studn...
fbee41e0deb8a6a257f6a4a6977151eb79d273f0
akomawar/Python-codes
/Practise_Assignments/reverse.py
238
4.375
4
while 1: string=input("Eneter your string: ") reverse=string[::-1] print("Reverse order is : ",reverse) if(string==reverse): print('yes it is an palindrome') else: print('No it is not a palindrome')
8a169ce8068f728716ab11ed9461af02dacbfae3
akomawar/Python-codes
/Practise_Assignments/password.py
482
3.734375
4
username1='akomawar' password1='ankit' for i in range(1,4): username=input("Please Enter your Username: ") password=input("Please Enter your Password: ") j=3 if(username==username1 and password==password1): print("Succesfully looged in by: ",username) break else: p...
848dfb6f6ec23f9a0d28a7c4b1d1f46b39827942
akomawar/Python-codes
/Minion_Game/minion.py
1,411
3.71875
4
# Kevin and Stuart want to play the 'The Minion Game'. # # Game Rules # # Both players are given the same string, S. # Both players have to make substrings using the letters of the string S. # Stuart has to make words starting with consonants. # Kevin has to make words starting with vowels. # The game ends when both pl...
e647841721113f6b0816fc00e0410a283e679400
akomawar/Python-codes
/Practise_Assignments/even_odd.py
129
4.09375
4
number=int(input('ENter any number: ')) if(number%2==0): print('Even') else: print('odd') input('press enter to exit')
bc4d91f791671dd0fa003000bcb7619793c88261
hasker/ProjectEulerSolutions
/Problem4/Problem4.py
512
3.59375
4
#!/usr/bin/python #This makes the assumption that we find a six digit palindrome! Not very good. import sys def palTest(testNum): strNum = str(testNum) if len(strNum) == 2: if strNum[1] != strNum[0]: return False for i in range(len(strNum)-1, len(strNum)/2-1, -1): if strNum[i] != strNum[len(strNum) - 1 - i...
b89fe4f9d912289da069dad201ddb5b955b7e753
vrublevskiyvitaliy/verification
/ordered tests/test.py
1,012
3.515625
4
import unittest from stack import Stack class StackTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.s = Stack() def get_items(self, reverse=False): items = [2, 5, 1, 4, 7] if reverse: items.reverse() return items def step1(self): item...
93102b09e0907e498f864f2244e0081d2a76729e
mbosio85/HGVSparse
/code/parse_vars.py
6,602
3.640625
4
import sys import re import argparse ID = 0 def RepresentsInt(s): try: int(s) return True except ValueError: return False def two_to_parse(Parts,offset= 0): # check for parentheses # if there's a parentesis adapt the logic to the part # IF '?' or '*' is there : # ...
4df8ad658b73703e0bbffcf7c752413ab9e5d793
itsmefai/suss-python-module
/ANL251 - Python Programming/Assessments/GBA/archived/backup/gba_31July_2pm.py
4,332
4
4
from datetime import datetime import os class Plant: def __init__(self, filepath = 'myplants.txt'): self.filepath = filepath self.data = self.load_data() def load_data(self): f = open(self.filepath, "r") contents = f.read() # Creating a dictionary to store the plan...
8032075c389b15cce1004211e04bfe05e5a12a17
YuxuanCao666/localgithub
/power.py
398
3.78125
4
import re formula = input () Operators = ['+','-','*','/','^','(',')'] list = re.findall('[\d\.]+|\+|\-|\*|\/|\^|\(|\)',formula ) def power(list,sign): a = list.index(sign) if x == '^': b = str(float(list[a - 1])**float(list[a + 1])) else : return list del list[a - 1] del list[a -...
8ce6664ad8178b73f783334c6059ebfce2b18083
rhehd721/programmers_algorithm
/Hash_Camouflage/Camouflage.py
1,402
3.78125
4
# -*- coding: utf-8 -*-  # 제한사항 # clothes의 각 행은 [의상의 이름, 의상의 종류]로 이루어져 있습니다. # 스파이가 가진 의상의 수는 1개 이상 30개 이하입니다. # 같은 이름을 가진 의상은 존재하지 않습니다. # clothes의 모든 원소는 문자열로 이루어져 있습니다. # 모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '_' 로만 이루어져 있습니다. # 스파이는 하루에 최소 한 개의 의상은 입습니다. def solution(clothes): answer = 0 dic = {} fo...
17ab687aea8f2853c8feadd8d729503651fd2497
saikiran-gutla/Ifassignment
/Daysinmonth.py
405
4.34375
4
month = input('Enter the month : ') mon = month[0:3].lower() print(mon) if mon == 'jan' or mon == 'may' or mon == 'mar' or mon == 'jul' or mon == 'aug' or mon == 'oct' or mon == 'dec': print(mon, "has 31 days") elif mon == 'apr' or mon == 'jun' or mon == 'sep' or mon == 'nov': print(mon, 'has 30 days') elif mon...
9ec4fc796e36856083bd46e275a5b46aef7b8baa
saikiran-gutla/Ifassignment
/tenp.py
272
4.1875
4
ch = input('Enter a character :') if ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')) : print(ch ,'is a character') elif (ch >= '0' and ch <= '9'): print(ch ,'is a number') elif ch ==' ': print('Its a space') else: print('its a special character')
c1cdba74a58045391ab14287e9e811ceacfe3961
zozni/PythonStudy
/studybasic5/calculator.py
1,104
3.625
4
class FourCal: #부모 클래스 def __init__(self, first, second): self.first = first self.second = second def setdata(self, first, second): self.first = first self.second = second def add(self): result = self.first + self.second return result def mul(self): ...
01956a8f807fea39c05553178b47c9b4a81b73c8
MarkChuCarroll/pcomb
/python/calc.py
2,172
4.34375
4
# A simple example of using parser combinators to build an arithmetic # expression parser. from pcomb import * ## Actions def digits_to_number(digits, running=0): """Convert a list of digits to an integer""" if len(digits) == 0: return running else: r = (running * 10) + int(digits[0]) return digits...
f8d243ce1401921f87ca032014ed195ef7f90482
gabbar7704/python
/Find_avg_speed.py
360
4.03125
4
d=int(input("enter distance travelled in km:")) m=int(input("enter time taken to travel the distance only min part")) s=int(input("enter time taken to travel the distance onlysec part")) tt=float(m*60 +s)/3600 DM=float(d)/1.61 at=tt/DM v=DM/tt print(f"avg time in hr taken to travel a mile:{at}") print(f"avg vel...
d43726eadb97da53b8e72cbfdc801c2182e87c0d
Vijay1234-coder/data_structure_plmsolving
/GRAPHS/floodfill.py
1,686
4.03125
4
'''IMPORTANT''' '''An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill, consider the starti...
c47df4ed506b3ee599dbf0e8f71e04b14c06aaba
Vijay1234-coder/data_structure_plmsolving
/SEARCHING AND SORTING/Binary Search/PeakELement.py
1,449
4.0625
4
'''Binary Search on unsorted Array problem ''' '''A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞....
ae22b6647831e00f1b574c31ae3c1dcb47b42997
Vijay1234-coder/data_structure_plmsolving
/Mix Questions/uniquestring.py
542
3.953125
4
# # ''' if string is unique return true else false eg "abcd" return true else "aabbcd" return false''' # # method 1: but dont use in interview # def unique_char1(s): # return len(set(s))==len(s) # # # print(unique_char1("abc")) # # # method 2: use this in interview highly recomended in order to show that you know a...
1789bc3863b74780b5dc95da3544b5ee4eee5c9b
Vijay1234-coder/data_structure_plmsolving
/Heap/NearlyKsortedArray.py
960
4.125
4
'''important''' '''Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. Example: Input : arr[] =...
b73608c9fe942ff8f0533a3c8c2396c7d42ff635
Vijay1234-coder/data_structure_plmsolving
/GRAPHS/wiredConnectionmysolution.py
1,272
4.09375
4
''' IMPORTANT ''' ''' if there is n nodes given then minimum number of edges required to connect nodes is : n-1 ''' ''' if present edges is less than n-1 then its not possible to connect all nodes ''' ''' in below question 1. we checked how many extra nodes occupied by input connected nodes 2. we count how ...
38a37a645500ce5804566b112dcee4fb44e0c015
Vijay1234-coder/data_structure_plmsolving
/Heap/KthLargestElement.py
475
3.703125
4
''' Important ''' ''' Whenever you have to find kth largest element use min Heap Time Compexity O(nlogk) ''' from heapq import heappop, heappush,heapify a =[ 7, 10, 4, 3, 20, 15 ] #[3,4,7,10,15,20] k=4 # find kth largest element minheap =[] for i in a: heappush(minheap,i) # this will create a min heap st...
2398ba79baee2e690bc4f0ff81c79e9a1e6a33bf
Vijay1234-coder/data_structure_plmsolving
/Mix Questions/BasicMatrixSum.py
431
3.609375
4
n =int(input("enter value of N")) t = [[0 for j in range(n+2)] for i in range(n+2)] for i in range(1,n+1): for j in range(1,n+1): # t[i][j]=int(input("enter value of matrix")) t[i][j] = int(input(" enter eleme")) i = int(input("enter Value of X")) j =int(input("Enter value of Y")) i = i+1 j = j+1...
78e7bed4ab2b9a0b2632fd68ea502dc27b3be668
Vijay1234-coder/data_structure_plmsolving
/PatternPrinting/newpyramid.py
1,330
3.875
4
# n =5 # for i in range(1,6): # for j in range(i): # print("*",end=" ") # print(" ") # # # print("__________________________________") # # # for i in range(1,6): # for j in range(1,i+1): # print(j,end=" ") # print(" ") # # n =5 # lis =["A"] # for i in range(1,6): # for j in range(i)...
e612b2e25a506409c90d84f6c411bf5de8644e01
Vijay1234-coder/data_structure_plmsolving
/HashMap/HashMap_implementation.py
605
3.828125
4
class HashTable: # create e,pty bucket list of given size def __init__(self,size): self.size=size self.hash_table = self.create_buckets() def create_buckets(self): return [[] for _ in range(self.size)] # Insert values into hash map def set_val(self,key,val): # Get ...
b79fb007fd0b73ee260b27ed8cd0122e6b2a3ca2
Vijay1234-coder/data_structure_plmsolving
/Dynamic Programming/LCS(longestCommonSubsequence)/longestcommonSUBSTRING.py
955
3.984375
4
'''Longest Common Substring(Dynamic Programming) Given two strings ‘X’ and ‘Y’, find the length of the longest common substring. Examples: Input : X = “GeeksforGeeks”, y = “GeeksQuiz” Output : 5 The longest common substring is “Geeks” and is of length 5.''' def longCommSubstring(x,y,m,n): Max=0 t=[[0 for j i...
db235d1b870d43e1fc55b58a6b6f07fe4f99c81f
Vijay1234-coder/data_structure_plmsolving
/Mix Questions/cloudjump.py
2,240
4
4
'''hacker rank ''' '''A child is playing a cloud hopping game. In this game, there are sequentially numbered clouds that can be thunderheads or cumulus clouds. The character must jump from cloud to cloud until it reaches the start again. There is an array of clouds, and an energy level . The character starts from ...
3380dec8073991da4e14fe2b8d90c6db4b42e896
Vijay1234-coder/data_structure_plmsolving
/HashMaporDiCT/Pairsumallelement.py
864
4
4
'''1. You are given an array(arr) of integers and a number K. 2. You have to find if the given array can be divided into pairs such that the sum of every pair is divisible by k. return True else return False ''' def PairDivisible(arr,m): dict1 = {} result = True for num in arr: if num % m not i...
3327cf1f3236d13cf15571128200f702231582e6
Vijay1234-coder/data_structure_plmsolving
/TREE/SimpleLevelOrderTraversa.py
743
3.890625
4
class Node: def __init__(self,val): self.left = None self.right = None self.val = val def levelorder(root): if root==None: return queue = [root] level =[] nextqueue =[] res =[] while(queue!=[]): for cur in queue: level.append(cur.val) ...
bf916286a29d6e32096b22af9f7cae045ef2c2f9
Vijay1234-coder/data_structure_plmsolving
/Dynamic Programming/CountSubSetSum.py
683
3.765625
4
''',,,,,''' '''Given a set of non-negative integers, and a value sum, determine count of subset of the given set with sum equal to given sum. Example: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9 Output: .''' def SubsetSum(arr,sum1): n=len(arr) t=[[False for j in range(sum1+1)] for i in range(n+1)] fo...
4fc912fe77c35b64e9ec8b13fcaf3d6dd18c9aab
Vijay1234-coder/data_structure_plmsolving
/RECURSION/homework1.py
2,061
3.953125
4
'''Problem 1 Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer For example, if n=4 , return 4+3+2+1+0, which is 10. This problem is very similar to the factorial problem presented during the introduction to recursion. Remember, always think of what the base case wi...
e11491e4a4ee97151df1055abd9ef0a5d9d9b878
Vijay1234-coder/data_structure_plmsolving
/LINKED_LISTALLMETHODS/InsertionSortLL.py
1,597
4.21875
4
class Node: def __init__(self,data): self.data = data self.nref = None self.pref = None class DoublyLL: def __init__(self): self.head = None def print_LL(self): # Forward Direction Traversal if self.head ==None: print("Empty LL") else: ...
f09d08875d8e316a144a43700cc19a5e9c7ca288
Vijay1234-coder/data_structure_plmsolving
/ARRAY/LengthOfLongestSubarrayWithequalOddEvenElmnt.py
839
3.625
4
#https://www.geeksforgeeks.org/length-of-longest-subarray-with-equal-number-of-odd-and-even-elements/ import sys def solve1(arr, n): Max = -sys.maxsize for i in range(n): odd_count = 0 even_count = 0 for j in range(i, n): if arr[j] % 2 == 0: even_count += 1 ...
19bab306ebc48e9a46f1a376faa8dbaf34dc1076
Vijay1234-coder/data_structure_plmsolving
/HACKWITHINFY/SumOfProperDivisor.py
1,235
3.859375
4
'''Write a program to determine whether a number N is equal to the sum of its proper positive divisors (excluding the number itself) since here number is excluded so base case is 1 for 1 NO will be printed you have to solve it in O(n) complexity''' '''6: 1+2+3''' '''N=36 1 x 36 2 x 18 3 x 12 4 x 9 6 X ...
84ac6b42f1afb9bd1739dcf61d86ecf244356469
Vijay1234-coder/data_structure_plmsolving
/RECURSION/sorting_arrayusingrecur.py
536
3.84375
4
def insert(a,temp): #[0,1,5] , 2 if len(a)==0 or a[len(a)-1] <= temp: a.append(temp) return a else: val= a[len(a)-1] a.pop() #[0,1] , temp=2 , val=5 insert(a,temp) a.append(val) def sortRecurr(a): #1,0,5,2 #base condition if len(a)...
427762c75840113f2cd88508a991c38a7500d1a3
Vijay1234-coder/data_structure_plmsolving
/SEARCHING AND SORTING/Binary Search/MedianOfArray.py
1,376
3.5
4
def findMedianSortedArrays( nums1, nums2): # We optimize this to run binary search on the smaller array if len(nums1) > len(nums2): return findMedianSortedArrays(nums2, nums1) end = len(nums1) n = len(nums1) # [3] [-2,-1] m = len(nums2) start = 0 idx_middle = (m + n + 1) // 2 # ...
9e7d7994f9a689826f42077e518a946a6c629670
Vijay1234-coder/data_structure_plmsolving
/Dynamic Programming/Edit_Distance.py
794
3.53125
4
''' q: u need to convert str1 to str2 u can perform 1.insert 2.delete 3.replace operation ''' '''return total number of operartion ''' def editDistance(a,b,m,n): t =[[0 for i in range(1002)] for j in range(1002)] for i in range(m+1): for j in range(n+1): if i==0: t[i][j] = ...
b6ed10576f670be063516122126826ef88918fb1
Vijay1234-coder/data_structure_plmsolving
/SEARCHING AND SORTING/Binary Search/Implementation.py
979
4.15625
4
def binary_search(arr,target): first = 0 last = len(arr)-1 found = False while (first <= last) and (found == False): mid = (first+last)//2 if arr[mid] == target: print("found at index {0}".format(mid)) found = True else: if target > arr[mid]: ...
59b9c9b36be8d0bb2acde394d83ffae0c0e4143c
Vijay1234-coder/data_structure_plmsolving
/Dynamic Programming/LCS(longestCommonSubsequence)/sequncePatternMatching.py
729
3.65625
4
'''quse''' '''Sequence Pattern Matching a: "AXY" b: "ABGXJDGY" Q: if a is subsequnce of b return True else return False ''' ''' Aproach would be first find LCS of a and b then if lcs == len(a) then True ''' def lcs(x,y,n,m): t = [[-1 for j in range(n + 1)] for i in range(m + 1)] # Base Case for i in ra...
f4185a2985f498f07206f35139b2f2063724740c
Vijay1234-coder/data_structure_plmsolving
/Mix Questions/psolving_hackerrank.py
206
3.703125
4
n = int(input("enter no. of elements").strip()) arr = [] for _ in range(n): arr.append(list(map(int,input("enter elements").stripapple().split()))) print(" ") for i in range(n): print(arr[i])
3bd2994fea9b9ee534702c3e9dc177595b4b57d8
Vijay1234-coder/data_structure_plmsolving
/GRAPHS/StronglyConnectedGraph.py
1,154
4.03125
4
'''Strongly Connected Graph means every node connect whether directly or indectly''' class Graph: def __init__(self,nodes,is_directed=False): self.nodes =nodes self.adj_lis ={} self.is_directed = is_directed for node in nodes: self.adj_lis[node]=[] def edge(self,...
b8b3a18b871761b0c5686f3a91c41234d1a24396
Vijay1234-coder/data_structure_plmsolving
/LINKED_LISTALLMETHODS/removeduplicatefromLL.py
1,035
3.90625
4
class Node: def __init__(self,data): self.data = data self.next = None class LL: def __init__(self): self.head =None def insert(self,data): new_node = Node(data) if self.head == None: self.head = new_node else: n =self.head ...
7594c9f688d4b08521876856bee71ba3ad433610
varunpatel07/Data_Structure__Algorithms_in_python
/Problem_8.py
2,298
3.984375
4
""" Tree traversal using recursive and iterative code """ # Python program to for tree traversals # A class that represents an individual node in a # Binary Tree class Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversal def printInorder...
6fe3ecd7df8bb76583d9f63f43c5405e53f9a869
varunpatel07/Data_Structure__Algorithms_in_python
/Problem_6.py
755
4.03125
4
""" Given an numsay of positive integers nums, calculate the sum of all possible odd-length subnumsays. A subnumsay is a contiguous subsequence of the numsay. Return the sum of all odd-length subnumsays of nums. nums = [1,4,2,5,3] Input: nums = [1,4,2,5,3] Output: 58 Explanation: The odd-length subnumsays of nums an...
3e3912114486249c4f9c76f7be1dd4aaa98de05f
varunpatel07/Data_Structure__Algorithms_in_python
/Array problem/1.7.py
451
4
4
""" Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. Example 1: Input: N = 5 arr[]= {0 2 1 2 0} Output: 0 0 1 2 2 Explanation: 0s 1s and 2s are segregated into ascending order. """ def solution(arr): count_arr=[0,0,0] for item in arr: count_arr[item]+=1 ...
f33ba66fc94f36982cba73ac2be4de07eb4d8340
varunpatel07/Data_Structure__Algorithms_in_python
/Array_Searching_Algorithm/Linear_Search.py
485
3.90625
4
import sys """In this Algorithm we sequentially move to every element and compare it with a desired element if the element is found we return index of that elemeent. if the element is noot found we return -1(Invalid value) Complexcity= O(n) """ def LinearSearch(arr,val1): for i in range(len(arr)): if(val...
de6cc1509767ff69bf9d28a2e70b546051032fc4
varunpatel07/Data_Structure__Algorithms_in_python
/Array problem/2.1.py
297
4.03125
4
""" Given an array, rotate the array by one position in clock-wise direction. Example 1: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 1 2 3 4 """ def sol(arr): key=arr[-1] j=len(arr)-2 while(j>=0): arr[j+1]=arr[j] j-=1 arr[j+1]=key print(arr) sol([1,2,3,4,5])
93f14834dc13e7a236b2b3f8d78ceb9102d49665
varunpatel07/Data_Structure__Algorithms_in_python
/Array problem/2.12.py
478
3.9375
4
""" Kadane's Algorithm Medium Accuracy: 51.0% Submissions: 100k+ Points: 4 Given an array arr of N integers. Find the contiguous sub-array with maximum sum. Example 1: Input: N = 5 arr[] = {1,2,3,-2,5} Output: 9 Explanation: Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which is a contiguous subarray. """ d...
e5914a4c6846f068394620b7b5f915fbf9930700
varunpatel07/Data_Structure__Algorithms_in_python
/Array_Searching_Algorithm/Binary_Search.py
1,045
4.09375
4
import sys """ In this algorithm we take a SORTED array and find the mid element, then we check if our desired element is smaller or bigger than the mid element. if a element is smaller than the mid element then we perform the same operation on elements on left hand side of mid element and vice versa Complexity--> O...
a279f6df65ebdba3f05f2be7482d6c61f14fd8ad
jringenbach/FileTreatment
/lectureMenu.py
1,198
3.984375
4
# -*- coding: utf-8 -*- import lectureTXT import lectureCSV def readOrWrite(): """Menu that asks the user if he wants to read a file or edit one """ print("Souhaitez-vous ouvrir ou éditer un fichier?") print("1. Ouvrir") print("2. Editer") print("3. Quitter") return input("\nChoix : ") def wr...
1bcaae813cc6f72b6db37fc2d5fd9bb863e7b6cb
SurendraRedd/CodingInterview
/AbhishekRoy/CodingTest.py
307
3.65625
4
#Skills - AWS EC2, S3, SNS,DYNAMO DB, PySpark, Python, Spark core, Spark Sql. #Non Coding Questions #1. Differences between list, tuple & set #2. What is Lambda Function #3. What is slicing in string #Basic Python #1. Reverse a list in python #File Operations #1. Count the number of words in a text file
07501e3fd2aebed15ea2dd3c12e7091e4af83e1f
Pedromacedo41/algorithms
/Python/DailyCodingInterView/palindrome.py
4,689
3.6875
4
# Definition for a binary tree node. import copy from collections import deque import heapq class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def prettyPrintTree(node, prefix="", isLeft=True): if not node: p...
629926266283ba2ad49c483d400dd443c71de9b8
sqelliott/cs140-Tournament
/Tournament/minMaxCapAgent.py
5,905
3.515625
4
from util import manhattanDistance from game import Directions import random, util from game import Agent class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBet...
2ee6c99e65ff3f7123cdbd5209a6f74aca2291d9
johnsayeau/uiautomator_test
/new_connect_usb.py
6,644
3.734375
4
''' How to use: to start with specified host IP and port example ip = 127.0.0.1 port 8270 - "python connect_usb.py 127.0.0.1 8270" or just "python connect_usb.py" which will use a default IP = 127.0.0.1 and a port ID of 8270 to start with the server's IP and specified port 8270 - "python connect_usb.py ...
7cfd67cc83713cec92f7ce1807bcaeed84028c0b
sprajwol/python_assignment_II
/assignment_Q11.py
863
4.71875
5
# # 11. Create a variable, filename. Assuming that it has a three-letter # # extension, and using slice operations, find the extension. For # # README.txt, the extension should be txt. Write code using slice # # operations that will give the name without the extension. Does your # # code work on filenames of arbitrary ...
487db65523fc0db80945c254b577d3a9a3cf7f61
sprajwol/python_assignment_II
/assignment_Q7.py
1,054
4.25
4
# 7. Create a list of tuples of first name, last name, and age for your # friends and colleagues. If you don't know the age, put in None. # Calculate the average age, skipping over any None values. Print out # each name, followed by old or young if they are above or below the # average age. import statistics list_of_da...
144e9bbfc1c4ec73ca2b18fe6b30a90f3072a4d5
sheelfshah/banditpylib
/banditpylib/bandits/utils.py
944
3.609375
4
from abc import ABC, abstractmethod from banditpylib.data_pb2 import Context, Actions, Feedback from banditpylib.learners import Goal class Bandit(ABC): """Abstract class for bandit environments""" @property @abstractmethod def name(self) -> str: """Bandit name""" @abstractmethod def reset(self): ...
a77d97c7e05122b0b2407363f718842ee3e176df
leogregianin/aceleradev-python-codenation
/python-1/main.py
2,604
3.5
4
# coding: utf-8 # Todas as perguntas são referentes ao arquivo `data.csv` # Você ** não ** pode utilizar o pandas e nem o numpy para este desafio. import csv from collections import Counter def iter_dataset_list(column_name, itervalue = 0): data = [] with open('data.csv', 'r', encoding='UTF-8') as csvfile: ...
5ad5a33a247b69914382a30521de788f4e31e409
Macha1804/Pizzatime
/programme.py
622
4.03125
4
def pizza_time(une_variable): for number in range(1,une_variable + 1): if number % 3 == 0 and number % 5 == 0: print("PizzaTime") elif number % 5 == 0: print("Time") elif number % 3 == 0: print("Pizza") else: print(number) # Une fois le programme terminé, redemander le numéro # print("Veuillez...
babda421c3b80f85e37b645c7c07962b95ed91ee
bhaggu97/bhaggu97
/excellence .py
689
3.640625
4
#question-1 (sum of all element of list) def sumList(x): return sum(x) lst=list(map(int,input().split())) print(sumList(lst)) #input-[2,3,5] output- 10 #question2-maximum dict return d1={} n= int(input()) for i in range(n): keys=input() value=input() d1[keys]=value d2={} for i in range(n): keys=...
ffb0b3807276913110419b7b3f6180f35ceecd3c
ddelago/Tkinter-GUI-Serial-Stream
/Tkinter Examples/ttk_nb_script.py
3,271
3.5625
4
#! /usr/bin/env python from Tkinter import * from ttk import * # NOTE: Frame will make a top-level window if one doesn't already exist which # can then be accessed via the frame's master attribute # make a Frame whose parent is root, named "notebookdemo" master = Frame(name='notebookdemo') root = master.ma...
2b630cbd8d8ec1bcab04ee277138ef33d6462285
aspferraz/Perceptron
/perceptron.py
2,062
3.546875
4
from random import uniform class Perceptron: def __init__(self, input_size): self.inputLayerSize = input_size self.weights = [] self.bias = uniform(0, 1) for i in range(input_size): self.weights.append(uniform(0, 1)) @staticmethod def normalize_value(val): ...
e53d462fc353654d6ebbc5e3b1ad3b654e135a75
korzair74/Homework
/Homework_4-20/family.py
235
4.34375
4
""" Create a variable called family Assign it a list of at least 3 names of family members as strings Loop through the list and print everyone's name """ family = ['Shea', 'Owen', 'Chris'] for name in family: print(name)
deabcd43fd9343530ff14d03c92d9aad371af216
EOT123/AllEOT123Projects
/All Python Files Directory/Year2Tutorials/2018_08_28_fizzbuzz.py
240
3.75
4
f = "fizz" b = "buzz" for i in range(1, 101): if i % 5 == 0 and i % 3 == 0: print(i) print(f + b) elif i % 3 == 0: print(i) print(f) elif i % 5 == 0: print(i) print(b) # complete
6d832510ef2179b0a5fc908e6904c4b12e4d55fa
EOT123/AllEOT123Projects
/All Python Files Directory/Bounties/Bounty11.py
495
4.3125
4
# 10/30/17 # Number flipper opposite output neg=pos/pos=neg print("") print("_______________________________________") print("Welcome To The Opposite Number Flipper") print("_______________________________________") print("") while True: num = int(input('Enter A Number To Be Flipped: ')) if num > 0: pri...
96e401d9afad2addcc87e9bb28db81611b4c9b4c
EOT123/AllEOT123Projects
/All Python Files Directory/Bounties/Bounty14.py
191
3.875
4
# 11/7/17 # Break It Up: Ex: if input 158, print 100 + 50 + 8 # Not Done breakup = str(input("Enter A Number To Break Up: ")) breakup2 = str.split(breakup) print(breakup2) print("".format())
2881eaa8dacfe2286b73577700d01d4f7ebbc20b
EOT123/AllEOT123Projects
/All Python Files Directory/RPG Game/Scratchpad/scratchpad.py
1,041
3.671875
4
Xp = 0 Player_Lvl = 0 Xp_Next_Lvl = 40 def xp(): global Xp global Player_Lvl global Xp_Next_Lvl while Xp >= Xp_Next_Lvl: Player_Lvl += 1 Xp = Xp - Xp_Next_Lvl Xp_Next_Lvl = round(Xp_Next_Lvl * 1.2) print("Xp {}".format(Xp)) print("Player_Lvl {}".format(Player_Lvl)) ...
f2208793640aa2d9f77fbef731c385415d82897d
EOT123/AllEOT123Projects
/All Python Files Directory/Bounties/Bounty09.py
478
3.703125
4
# 10/30/17 # Life potions Random potion amount 0-100 / E=Decrease Potions import random potion = (random.randint(0, 100)) print('You Have {} Potions'.format(potion)) while True: print("") action = input('Enter e To Use A Potion : ') if action == "e": potion = potion - 1 print(potion) if ...
47b0107675da47080c2d6acf6ab6ce1b3bbd9faa
EOT123/AllEOT123Projects
/All Python Files Directory/Code.Pylet Tutorials/Basic Jumping.py
1,525
3.53125
4
import pygame from pygame.locals import * import sys class player: def __init__(self, x, y, size): self.x = x self.y = y self.size = size self.jumping = False self.jump_offset = 0 def events(): for event in pygame.event.get(): if event.type == QUIT or (event.t...
709a2b2332d59a02c782efa8ce09609f7999263a
ukokuja/tweets_data
/tweets_summary.py
5,424
3.6875
4
import csv import re import numpy import pandas #INPUT INPUT_FILE_NAME = "/Users/lucaskujawski/Projects/personal/tweets.csv" TIMESTAMP = 'timestamp' TEXT = 'text' #OUTPUT OUTPUT_FILE_NAME = "tweet-data.csv" MONTH = "Month" HASHTAG = "Hashtag" MENTION = "Mention" WEBSITE = "Website" OUTPUT_HEADERS = [MONTH, HASHTAG, ...
0689815b306ffdcbe25f393725070829e750b536
drooop/learning_brand_new
/python/autoscraper_test/getting_similar_results.py
1,334
3.578125
4
from autoscraper import AutoScraper url = 'https://stackoverflow.com/questions/2081586/web-scraping-with-python' # We can add one or multiple candidates here. # You can also put urls here to retrieve urls. wanted_list = ["How to call an external command?"] scraper = AutoScraper() result = scraper.build(url, wanted_l...
bb68641df48dfcf081e066a6b5eb25f8d6f675ae
FerreiraM12/Torneio4
/src/projeto.py
8,810
3.53125
4
""" Neste torneio pretende-se que implemente um programa que ajude um arquiteto a planear os prédios a construir num bairro. Um bairro de dimensão N é uma matriz quadrada com N x N lotes de iguais dimensões. Em cada lote deve ser construído um prédio. As alturas dos prédios variam entre 1 e N, sendo que em cada linha...
0001d52120b1e13aee8fca935d54a709c77e894d
metamemelord/Hackerrank-Solutions
/Algorithms/Implementation/Encryption.py
419
3.5
4
# -*- coding: utf-8 -*- """ @author: MetaMemeLord- """ import math s = ''.join(input().split()) length = len(s) row = math.floor(math.sqrt(length)) col = row check = True while row*col < length: if check: check = False row += 1 else: col += 1 #print(row,col) i = 0 while i<row: k = ...
590a0e5378c4609091e9438ba436bd1317e3ea29
metamemelord/Hackerrank-Solutions
/Algorithms/Strings/SeparateTheNumbers.py
631
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 16 15:48:22 2017 @author: MetaMemeLord- """ def check(s): l = 1 while l <= len(s)//2: k = s[:] val = int(s[:l]) to_ret = val k = s[l:] while True: if len(k) == 0: return to_ret lel = ...
beaa9ec5f79c8d02ce0189a367f3663d752f8536
metamemelord/Hackerrank-Solutions
/Algorithms/Strings/FunnyString.py
373
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 17 00:42:28 2017 @author: MetaMemeLord- """ def check(s): x = [ord(i) for i in s] l = 0 r = len(x)-1 while l<r: if abs(x[l]-x[l+1]) != abs(x[r]-x[r-1]): return 'Not Funny' l += 1 r -= 1 return 'Funny' for _ in rang...
cb70d4b215f9c92c7395ce98ddfa911d158745ed
metamemelord/Hackerrank-Solutions
/Algorithms/Strings/Two Strings.py
353
3.765625
4
# -*- coding: utf-8 -*- """ @author: MetaMemeLord- """ def twoStrings(s1, s2): # Complete this function s = set(list(s1)) for i in s2: if i in s: return "YES" return "NO" q = int(input().strip()) for a0 in range(q): s1 = input().strip() s2 = input().strip() result = twoS...
64aa7681cb9305a0bc64a1889a1aea0476e00bd1
exsky/leetcode
/easy/21_Merge_Two_Sorted_Lists/__init__.py
1,073
3.953125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: mr = [] while True: if l1: if l2: if...
ba5e21a79a58d8be26e5c6fd7299248d033c2f63
anouarbousraou/sched_maker
/main.py
969
3.75
4
import employees import load_data import random reader = load_data.Load_data() employees = reader.load_employees() weeks = reader.load_weeks() days = reader.load_days() def make_calendar(): for week in weeks: for day in days: if day.day_number in week.has_days: while day.day_...
b7838d90f734023df37e7de90f8d01373a112fb2
mogarg/Python-Tutorial-Lynda
/variables-syntax.py
359
4.25
4
#!/usr/bin/python3 def main(): atuple = (1,2,3) #A tuple is immutable alist = [1,2,3] #A list is mutable print(atuple,type(atuple)) print(alist,type(alist)) alist.append(5) print(alist) alist.insert(2,7) print(alist) x = "string" #A string is an immutable sequence for i in x: pr...
1f877927d514c91f73c648e86383bd400e1240ff
GrijzeZeehond/pythonProject2
/six/ep_6_2.py
892
4.03125
4
card_file = 'pe_6_2_kaartnummers' def read_lines(file): """ reads the document. Places each line as an element in a list. """ with open(file) as file: lines_list = file.readlines() return lines_list def pretty_print(card_file): """ takes the name of a file with people a...
345c5d74788fab5b50b6e68c17160ff3e75a34ba
GrijzeZeehond/pythonProject2
/six/ep_6_3.py
1,052
4.09375
4
card_file = 'pe_6_2_kaartnummers' def read_lines(file): """ reads the document. Places each line as an element in a list. """ with open(file) as file: lines_list = file.readlines() return lines_list def biggest_card(file): """ takes a file with cardnumbers as input. Retur...
70080fd215688a6d81c77bf446aff86abbe6f048
GrijzeZeehond/pythonProject2
/five/pe_5_5.py
385
3.703125
4
def kwadraten_som(grondgetallen): """ Takes a list containing integers as input (grondgetallen). Returns the total sum of all the positive numbers in the list after squaring them (n1*n1) + (n2*n2) ... (n-1*n-1) """ total = 0 for num in grondgetallen: if num > 0: total...
98d35083c72029b0be7dd0e347805938cfe6609e
MasterOfTheBus/COMP424_AI
/Assignment1/breadth_first.py
1,679
3.546875
4
import json import urllib.request from collections import deque from pprint import pprint url = "http://www.cs.mcgill.ca/~jpineau/comp424/Homework/brussels_metro_v2.json" response = urllib.request.urlopen(url).read() data = json.loads(response.decode("utf8")) #pprint(data) stations = {} visited = set() queue = deque(...