blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a11050b799bb6300d66320f050bfd9b49adc7cf0
MatthewNewell006/udemy
/src/advanced_python_modules/os_module.py
2,447
3.6875
4
# Python's os module and shutil allow us to easily navigate files and directories on the computer and then perform actions on them, # such as moving them or deleting them. f = open('practice.txt', 'w+') f.write('This is a test string.') f.close() print('\n') # =========================================================...
08009499fbdc68cc08c87c01663139450cfded26
mkacz91/sdf
/misc/bilinear_error.py
3,907
3.671875
4
from math import hypot, sgn, sqrt # Function d: [0, 1] x [0, 1] -> [-1, 1] is defined through bilinear interpolation of the # four corner values: d00, d01, d10, d11. This funciton computes the maximal distance of the # implicit curve d(u, v) = 0 against a line through points (x0, y0) and (x1, y1). def eval_bilinear_er...
cec0c686f13b754ab31e714e9d9b849e28dd6c59
XJjch/changwonai
/if_test.py
569
3.625
4
# <<그냥 주석. [Ctrl + /] #나이가 20세 미만이면 '청소년 할인'을 출력 나이 = int(input("나이를 입력하시오.")) if 나이 < 20: print("청소년 할인") else: print("할인 없음ㅋ") #1000걸음 이상 걸으면 '목표 달성'을 출력 걸음 = 100 if 걸음 > 1000: print("목표 달성") else: print("좀 더 걸으세요.") #시간이 12시 이전이면 '오전입니다.', 12시 이후면 '오후입니다.'를 출력 시간 = 18 if 시간 < 12: print("오전입...
eeab4e08eeeb19b4deb163f02e753ab86494a959
jason-little/python
/add_two_numbers.py
570
3.65625
4
class Node: def __init__(self,val): self.val = val self.next = None # the pointer initially points to nothing l1 = Node(2) l1.next = Node(4) l1.next.next = Node(3) a = "" l2 = Node(5) l2.next = Node(6) l2.next.next = Node(4) b = "" c = "" while l1 is not None: a = a + str((l1.val)) l1 = l1.ne...
9d0d1311f7b1a08c6fa65bbb55a1bd81597d0bad
jason-little/python
/scale_up.py
760
3.734375
4
import time old_desired_capacity = 60 new_desired_capacity = 120 scaler = 10 if new_desired_capacity - old_desired_capacity >= scaler: #Scale up nicely print("Scaling up nicely in increments of %d" % scaler) while new_desired_capacity > old_desired_capacity + scaler: old_desired_capacity += scaler ...
48460ac3a78d06182db1f23ad7c2458bed4133e4
advaer/webacademy
/recursion/is_concatenetion.py
651
4.03125
4
def is_concatenation(dictionary, key): # base case: checks for empty string if not key: return True # recursive branch idx = 1 while idx <= len(key): if key[0:idx] in dictionary and is_concatenation(dictionary, key[idx:]): return True idx += 1 return...
5e28aec04724197978ab09f3ba349ed99e8afee0
VictorW77-ios/Python-Calculator
/main.py
372
4.3125
4
num1 = float(input("Hey! Welcome to Victor's Calculator. Enter the first number: ")) op = input("Enter * , + , / , or - :") num2 = float(input("Enter another number: ")) if op == "+": print(num1 + num2) elif op == "*": print(num1 * num2) elif op == "/": print(num1 / num2) elif op == "-": print(num1 - num2) e...
144259dad7edbc130d658bae8d29cbabb4abddef
prachichouksey/Competitive_Coding_2
/Problem2.py
2,095
3.6875
4
# Problem link : https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ # Time Complexity : O(n * m) # Space Complexity : O(n * m) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach ''' Basic appro...
38827611697003e9983dbf57ac4576f000aa592d
ak-alam/CodePrep
/animal_legs_count.py
558
4.1875
4
''' In this challenge, a farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three species: chicken = 2 legs cows = 4 legs pigs = 4 legs The farmer has counted his animals and he gives you the a subtotal for each species, you have to implement a function that returns...
5912bfcbe3010b01807543d8eee366bce3cc948f
l3k3bim/Firstpushtogithub
/mockATMupdated.py
3,586
3.90625
4
#Register and Login #To register: (First name, Last name, Email, Password) #To login: (Email, Password) #Bank Operations: Register, Login, Current Date and Time, Generate account number, Deposit, Withdraw, Check Balance, Buy airtime, Complaint, Logout. #Welcome function: To initialize the transaction #database for a...
d7199dd3de2a75d4e657e839cdf513c5278fd2fb
SophieChien/today
/temperature.py
92
3.625
4
temp_F = input('please enter temperature_F') F = float(temp_F) C = (F - 32) * 5 / 9 print(C)
2f162538625d0de0d14524ccf7e93adaab85d54d
jlarfors/architector
/lib/util.py
180
3.5
4
class UniqueDict(dict): def __setitem__(self, key, value): if key not in self: dict.__setitem__(self, key, value) else: raise KeyError("Key already exists")
271808aaf48e9e5e009a89619ad45da812b7be1b
PrinceCuet77/Sorting-algorithm
/Python/Merge sort.py
683
3.84375
4
def Merge(ar, L, R) : nl = len(L) rl = len(R) i = j = k = 0 while ( i < nl and j < rl ) : if L[i] <= R[j] : ar[k] = L[i] i += 1 else : ar[k] = R[j] j += 1 k += 1 while i < nl : ar[k] = L[i] i += 1 k += 1 while j < rl : ar[k] = R[j] j += 1 k += 1 def mergeSort(ar) : n ...
aa2c883eb8cd1f31764017b00c4d439ff8457456
markitus83/a-byte-of-python
/addressbook.py
2,287
3.53125
4
# -*- coding: utf-8 -*- # Creació d'una agenda # Permet: afegir, modificar, eliminar o cercar contactes i la seva informació com adreça de correu i/o telèfon import addressbook_module as ab import helper_module as helper import person_class as person import sys addressbook = {} addressbookfile = 'addressbook.txt' ...
429fa289d5a95d9173c69b803f9e51e7e669761b
davidissak-zade/HealthierEveryDay
/alrgorithms.py
210
3.75
4
def my_capitalize(txt): words = [] words = txt.split(' ') out = '' for i in range(0, len(words)): words[i] = words[i].capitalize() out += words[i] + " " return out
8d83c3f7c748de92a1a48816e048f15d568f21e9
aj178/snake-possible_paths-python
/SnakePaths.py
3,561
3.875
4
import sys class SnakeProblem: def __init__(self, snake_length): self.snake_length = snake_length def __create_grid(self, row, col): """ The function creates a row X col two dimensional list with values starting from 0 to maximum. :param row: Number of rows in the grid. ...
9c87fe1a0b355e2588b153fbac0addfdf5fd2d81
Praful-Prasad/COMPLETED
/COMPLETED/ex3/4. list operations.py
511
3.71875
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 15:44:37 2018 @author: user """ list1=[1,2,3,4,5,6,7,8] print('3rd element = ',list1[2],' 6th element = ',list1[5]) for i in range(0,5): print(list1[i]) print('7th element from end = ',list1[-7]) list1[1]='x' list1[4]='y' print('After changing 2nd an...
537c26cbe8a365edef9b8da16d3feb764dce0ef7
Praful-Prasad/COMPLETED
/COMPLETED/ex4 - day2/6. multiply.py
180
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 18:04:55 2018 @author: user """ d1={'Praful':1,'x':2,'z':3,'d':7} sum=1 for i in d1: sum=sum*d1[i] print(sum)
9373762491e8a970fa8fed770624cd5185d1a879
Praful-Prasad/COMPLETED
/COMPLETED/ex1/5. Quadratic Equation.py
410
3.890625
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 23 15:24:31 2018 @author: user """ import math print('Quadratic Equation - a*x^2+b*x+c') a=int(input('Enter value of a - ')) b=int(input('Enter value of b - ')) c=int(input('Enter value of c - ')) var1=((-b)+(math.sqrt(b*b-(4*a*c))))/(2*a) var2=((-b)-(math.s...
36b0cce28cac86a4f51de6cf0c750170ff40b5fa
Praful-Prasad/COMPLETED
/COMPLETED/ex1/11. Factorial.py
108
4.03125
4
n=int(input('Enter a number : ')) sum=1 for i in range(1,n): sum=sum*i print("Factorial = ",sum)
e809a231ee26ef3d78f1eec52c728878f006c087
Praful-Prasad/COMPLETED
/COMPLETED/ex3/6. tuple.py
308
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 15:58:17 2018 @author: user """ n=0 l=[] while(n!=-1): n=int(input('Enter a number (Enter -1 to end) :')) if(n!=-1): t=(n,n*n) l.append(t) print('Final list with tuples = ',l) l.sort() print('After sorting = ',l)
cd960511f8255a66348cd54b40241268d2833fe8
Praful-Prasad/COMPLETED
/COMPLETED/ex2/10. comma separated words.py
200
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 28 09:28:39 2018 @author: user """ s=input('Enter a string (comma separated ):') s=s.split(",") s.sort() print('Sorted words = ',",".join(s))
a1a0b5a6ec96c924cdff7667e82a96a24804e484
piti118/PID-class
/drone.py
7,849
3.546875
4
import gym from gym import spaces import numpy as np class DroneEnv(gym.Env): """The main OpenAI Gym class. It encapsulates an environment with arbitrary behind-the-scenes dynamics. An environment can be partially or fully observed. The main API methods that users of this class need to know are: ...
786e74ba3ae937d380812dbc94b48c5833afd921
Eliopausa/Stepik_Selenium_Python
/Stepik_Selenium_Python/Module_3/3.2_8.py
677
3.5625
4
def test_input_text(expected_result, actual_result): assert expected_result == actual_result, f"expected {expected_result}, got {actual_result}" # Решение ниже работает только с числами, оно было расценено как не верное, хотя тут дело в # двусмысленности задания + примеры решения # assert int(expe...
ccf8c8687e43dd6b3bc676798228e1c842dc02da
sameervirani/week-1-assignments
/twonumbers.py
212
3.984375
4
no1 = input("enter number One:") no2 = input("enter number two:") def addition(a,b): result= float(a) + float(b) return result result = addition(no1,no2) print('And the total is... ' + str(result) + '.')
2c8c58ec0c38a5c871ab26a0c364e1a8ebb01333
j-ran/notes
/savage_sassy_classes.py
1,106
3.671875
4
"""created by Katrina Huber-Juma for a Hackbright Academy lecture, Jan 2021""" class Savage: """ define the Plantonic Ideal of a Savage Specifically 'Savage' as described by Megan Thee Stallion """ # class attributes shared by all instances of class Savage classy_bougie_ratchet = True sassy_...
c58b7ef1cf3db0fb5b5965b9bd21be99c5c504cd
wlockwood/ConnectX
/Color.py
812
3.953125
4
class Color: """Color and only things related to the color itself.""" color_list = {} # Color-tracking dictionary abbreviation_length = 3 def __init__(self, full_name: str, color_code: str, abbreviation: str = None): """ :param full_name: Full name of a color: "Yellow" :param...
c9f1c7d5547db6432bc1672e6910cb2afc4696e6
SeungJun9164/BaekJoon-online
/BaekJoon_1Level.py
1,480
3.8125
4
# 2557번 print("Hello World!") # 10718번 print("강한친구 대한육군") print("강한친구 대한육군") # 10171번 print("\ /\\") print(" ) ( ')") print("( / )") print(" \\(__)|") # 10172번 print("|\_/|") print("|q p| /}") print('( 0 )"""\\') print('|"^"` |') print('||_/=\\\__|') # 1000번 a, b = input().split() # ...
9860da5fbec3dc531556021194b4c410f2cf7fb3
ycctw1443/StudyWorkshopForPython
/kondo/kadai4_1.py
558
3.984375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- def main(): fruits = ["apple","orange","lemon","strawberry","apple","cherry","melon","apple","lemon"] print(fruits[::-1]) print([item[::-1] for item in fruits]) from collections import Counter counted_dict = Counter(fruits) print(counted_dict) dic...
c78b938cd7b95d391a1d32ff1c786c61b1bb36bd
ycctw1443/StudyWorkshopForPython
/yamamura/kadai4.py
403
3.828125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def main(): print('分を入力してください') m = float(input()) s = m * 60 print('%f分は' % m, end='') hr = s // 3600 print('%d時間' % hr, end='') mi = (s - hr * 3600) // 60 print('%d分' % mi, end='') se = (s - hr * 3600 - mi * 60) % 60 print('%d秒です'...
bc7c0b3ab106b6b3ff3ed0f7975f26c659143eb4
Lionning/CovidPooling
/bayesianExperiment.py
18,022
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 25 09:00:07 2020 @author: mallein Simulation of a Bayesian implementation of the measure of the prevalence based on group testing. """ import numpy as np import numpy.random as npr from math import log,exp,ceil, sqrt, floor import matplotlib.pyplo...
390054fb8f087061cbb4e7e6f7261c066978d0bd
Mashimo/datascience
/datascience/stats.py
9,348
3.734375
4
## Module stats.py ## ## Copyright (c) 2015 Mashimo ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applic...
08b4dbd1c7740f9416b8bd4e14596c21358fdb8f
Nabdi22/TTA
/Task3.py
374
3.90625
4
Name = input("Enter your Name: ") Starter = input("Enter your favourite starter: ") Main_course = input("Enter your favourite main course: ") Dessert = input("Enter your favourite dessert: ") Drinks = input("Enter your favourite drinks: ") print("Hello "+ Name + ", your favourite meal is "+ Starter + ", "+ Main_...
e7bacb85614d6c7caa441dcabaf84ab69c326c6d
kavyajadav/Student-Repository
/Student_Repository_kavyaJ.py
4,703
3.78125
4
""" This program is a data repository of courses, students, and instructors. The system will be used to help students track their required courses, the courses they have successfully completed, their grades, GPA, etc. The system will also be used by faculty advisors to help students to create study plans Author ...
533d9e4604d8c8a6c88bd60de77967474d43b1b3
VenkateshNarayana/PyPackRecommendationTool
/PyPackMasterData.py
1,222,811
3.5625
4
def GetAllChannelsData(pd,MonthlyNetworkFee=153.40,MandatoryOnly='All'): ''' This is a function to return all the channels along with its cost, language, genre and type ''' #set the custom columnnames that you want to use while parsing #columnNames=['Channel_Name','Channel_Cost','Genre','Language',...
edede07a48db6b26b57e098ec5c0a9bf73848bca
static716/Riskmanagemenet_0.4
/AppDesignLayout/ToDoList/To_Do_List_Design_Layout.py
3,093
3.609375
4
from tkinter import * class ToDoListFrame: def __init__(self, root): # To Do List Gadget toDoListMainFrame = Frame(root, bg="blue", width=480, height=270) toDoListMainFrame.grid(row=1, column=0, columnspan=1, padx=(0, 0), pady=(25, 0)) toDoListMainFrame.grid_propagate(True) ...
eadcf25f17d424720d933887f881a6d8a07d603b
HTDPNJ/Researchandexperimentation
/Automatic differentiation.py
2,128
3.5
4
import tensorflow as tf tf.enable_eager_execution() tre=tf.contrib.eager # from math import pi # def f(x): # return tf.square(tf.sin(x)) # assert f(pi/2).numpy()==1.0 # # #grag_f将返回f的导数列表 # #关于其论点。 由于f()只有一个参数, # #grag_f将返回包含单个元素的列表。 # grad_f=tre.gradients_function(f) #求导 # assert tf.abs(grad_f(pi/2)[0]).numpy()...
b10093c296b562384de29a154121ad8909888300
cerkiewny/exercises
/project_euler/12/main.py
393
3.609375
4
import math def countdiv(num): i = 2 res = 1 cur = 1 temp = 1 while( i <= num): if(num%i == 0 ): num = num / i cur+=1 continue res = res * cur + (cur - 1) i+= 1 cur = 1 return res i = 1 sume = 0 div = 0 while (div <= 500): ...
7dae8d7cf91d7f2f1c385f0c3704c2ca1e1edad7
cerkiewny/exercises
/project_euler/17/main.py
1,513
4.03125
4
def numtostring(num): if(num == 0): return "" elif(num == 1): return "one" elif(num == 2): return "two" elif(num == 3): return "three" elif(num == 4): return "four" elif(num == 5): return "five" elif(num == 6): return "six" elif...
feb59cbf579c9ef037a626c1fd127c8fb88078ef
lakshyarawal/pythonPractice
/Strings/palindrome_check.py
412
3.953125
4
""" Palindrome Check : To see if a given string is palindrome or not """ """Implementation""" def palindrome_check(str_in) -> bool: for i in range(len(str_in)//2): if str_in[i] != str_in[-(i+1)]: return False return True def main(): str_input = "ABCDCBA" print(palindrome_check(...
a8a796959888c238bf7dd728a93e24389202f95a
lakshyarawal/pythonPractice
/Binary Search Tree/delete.py
1,228
3.953125
4
""" Delete Operation in BSTs """ from insert import Node def delete(root_n, val_in): if root_n is None: print("Element Not Found") return root_n elif root_n.key < val_in: root_n.right = delete(root_n.right, val_in) elif root_n.key > val_in: root_n.left = delete(root_n.left,...
a6f084d81eb9803c62ebe0013ed394b9f0c74b41
lakshyarawal/pythonPractice
/Heap/implementation.py
889
3.890625
4
""" Binary Heap Data Structure Implementation in Python """ class Heap: def __init__(self, cap): self.capacity = cap self.arr = [0 for _ in range(cap)] self.size = 0 def insert(self, val): if self.capacity > self.size: self.size += 1 self.arr[self.size ...
8371703e9eabed8f13673d7b6f48f8023cac4651
lakshyarawal/pythonPractice
/Sorting/naive_partition.py
975
3.796875
4
""" Naive Partition : We are given an array and an index in the array. We have to put all elements smaller than this element to left and bigger to the right""" """Implementation""" def naive_partition(arr, low, high, pivot) -> int: # Create a temp array temp = [0] * (high - low + 1) index = 0 fo...
a2b8ca8bedddaa979ec28cdb032a9298baaeaa43
lakshyarawal/pythonPractice
/Sorting/meeting_max_guests.py
1,060
3.953125
4
""" Meet Maximum guests at a party: You are given two arrays that denote the arrival and departure time of the guest and you have to print the mx guest you can meet. Time for party is 0 < t < 2359. Eg: arrival = [800, 700, 600, 500], departure = [840, 820, 830, 530] O/P: 3 (800 to 820)""" """Solution""" def ...
681a1b72d2e0a479bf91407dcbd9a609f0d547ac
lakshyarawal/pythonPractice
/Binary Search Tree/floor.py
1,598
3.65625
4
""" Floor Operation in BSTs """ from insert import Node def floor_iter(root_n, val_in): temp = None while root_n: if root_n.key == val_in: return root_n elif root_n.key > val_in: root_n = root_n.left if root_n.key < val_in: temp = root_n ...
a466e688ff03aff1bbb5ce48766cb6f42f66f87a
lakshyarawal/pythonPractice
/Arrays/leaders_in_array.py
885
3.921875
4
""" Leaders in Array: Given an array find Leaders (Element on the right are smaller than the num) """ """Solution: """ def leaders(a) -> list: n = len(a) leader_list = [] for i in range(n): bool_leader = True for j in range(i+1, n): if a[j] >= a[i]: bool_lead...
ba66ff630b41855aa30d3b7b83ad6a2114c6f31d
lakshyarawal/pythonPractice
/Arrays/stock_buy_sell.py
930
3.625
4
""" Stock Buy and Sell: Given an array of prices find maximum profit using buy and sell variations """ """Solution: """ def stock_buy_rec(a, s, e) -> int: if e < s: return 0 profit = 0 for i in range(s, e): for j in range(i+1, e+1): if a[j] > a[i]: cur_profit ...
b7eaba45bab8b5c06fb673cce4f155373a8d1c5f
lakshyarawal/pythonPractice
/Arrays/trapping_rain_water.py
1,071
3.71875
4
""" Trapping rain water: Given an array of non negative integers, they are height of bars. Find how much water can you collect between there bars """ """Solution: """ def rain_water(a) -> int: n = len(a) res = 0 for i in range(1, n-1): lmax = a[i] for j in range(i): lmax ...
aa7fe658b80634a8a408f7322d02fd2aaf7ff490
lakshyarawal/pythonPractice
/Stack/largest_rectangular_area.py
1,469
4
4
""" Finding the Largest Rectangular Area in a histogram: """ """ Naive Approach here is that you should find the area with every element as the smallest bar""" def easy_area(arr_in): res = 0 for i in range(len(arr_in)): area = arr_in[i] k = i - 1 while k >= 0: if arr_in[...
98dbc42e1c3d918ca525b6eeec0858358f11b242
lakshyarawal/pythonPractice
/Stack/balanced_parentheses.py
1,025
3.734375
4
""" Balanced Parentheses using Stack Data Structure """ from collections import deque def is_balanced(str_input): stack = deque() open_br = ['(', '[', '{'] close_br = [')', ']', '}'] for i in range(len(str_input)): print(str_input[i], stack) if any(item == str_input[i] for item in open...
e68617f0d4edeea675a59cd4453de3b2109f2a09
lakshyarawal/pythonPractice
/Searching/count_occurrences.py
535
3.9375
4
""" Count Occurrences: """ from index_of_last_occurrence import last_occur from index_of_first_occurrence import first_occur """ Solution: """ def count_occur(arr, num) -> int: low_index = first_occur(arr, num) if low_index == -1: return 0 high_index = last_occur(arr, num) return (high_index -...
e2cf69ac66d7d879a6b94081877d1adb5469aef9
lakshyarawal/pythonPractice
/Hashing/frequencies_of_elements.py
500
4.09375
4
""" Counting frequency of elements in a given array of numbers """ def frequency_elements(arr) -> int: new_dict = dict() for i in range(len(arr)): if arr[i] in new_dict: new_dict[arr[i]] += 1 else: new_dict[arr[i]] = 1 print(new_dict) return len(new_dict) de...
c83794c8ef88a8f602446f3e128204f0c0a7c392
lakshyarawal/pythonPractice
/Stack/postfix_eval.py
1,461
4.15625
4
""" Converting an postfix expression into output value""" def check_precedence(op): operators = ['(', ')', '^', '*', '/', '+', '-'] has_op = {'(': 0, ')': 0, '^': 3, '*': 2, '/': 2, '+': 1, '-': 1} for i in range(len(operators)): if op == operators[i]: return has_op[operators[i]] r...
dd201ce28595e89138d179c3e0627f6ba31d502d
lakshyarawal/pythonPractice
/Tree/max_width_tree.py
1,054
4
4
""" Finding the maximum width of the tree""" from binary_tree_traversal_and_height import Node from collections import deque def max_width(root_n): if root_n is None: return 0 else: max_wid = 0 q1 = deque() q1.append(root_n) while len(q1) > 0: curr_size = len(q1) ...
ff8966efcf1e900a90bf3afdbe1ab59e62b4c179
lakshyarawal/pythonPractice
/Sorting/sort_array_three_types.py
735
4.34375
4
""" Sort Array with three types of elements: You are given three types of elements in the array and you have to sort them accordingly""" """Solution""" def segregate_elements_three(arr) -> list: i = 0 j = len(arr)-1 mid = 0 while mid <= j: if arr[mid] == 0: arr[i], arr[mid] =...
c60526c9d0823da993e0a25478223435f6c03856
lakshyarawal/pythonPractice
/Recursion/subset_sum.py
1,028
4
4
""" Subset Sum: Given an array/set of integers and a sum value, count the number of subsets which add up to the sum Eg: { 10, 5, 2, 3, 6 } , Sum = 8 then the output will be: 2 for { 5, 3 } and { 2, 6 } """ """Solution: Create a tree of options including and excluding the element and return 1 if subset sum is same"...
0df4f1712006ea00a1525260dd165f715b1975a7
lakshyarawal/pythonPractice
/Tree/lca_of_binary_tree.py
1,798
3.890625
4
""" LCA: Lowest Common Ancestor of two values in a binary tree """ from binary_tree_traversal_and_height import Node from collections import deque def find_path(root_n, path_a, n): if root_n is None: return False path_a.append(root_n.value) if root_n.value == n: return True if find_pat...
a4f9d0573642bcd1e13e3aeef3fc680e52deb507
lakshyarawal/pythonPractice
/Arrays/prefix_sum.py
1,225
3.828125
4
""" Prefix Sum Technique: Given a fixed array and multiple queries of following types on array are to be performed how to do it efficiently: I/P: [ 2, 8, 3, 9, 6, 5, 4 ], get_sum(0,2) will return 2+8+3""" """Solution: """ def prefix_sum(a, l, r) -> int: prefix_sum_arr = [0] * len(a) prefix_sum_arr[0] =...
abeea02f0a515ce03adf72951ab3d75502c8a417
lakshyarawal/pythonPractice
/LinkedList/palindrome_list.py
1,085
4.09375
4
""" Palindrome List """ from reverse_list import LinkedList, Node def is_palindrome(l_list): if l_list.head is None or l_list.head.next is None: return slow_node = l_list.head fast_node = l_list.head # Find Length of List while fast_node.next and fast_node.next.next: slow_node = s...
30aa2c268b4d3941dc73e40d4bbe24b79b54649e
lakshyarawal/pythonPractice
/Hashing/open_addressing.py
1,971
3.609375
4
""" Open Addressing to remove chaining problem: using a array and doing a linear search in case of a collision""" class my_hash: def __init__(self, capacity): self.array = [] for i in range(capacity): self.array.append(-1) self.length = capacity def insert(self, element)...
e6b234b02dd2872731455ae66c3d3551cde723bd
lakshyarawal/pythonPractice
/Queue and Deque/first_circular_tour.py
1,235
3.5
4
""" Finding the First Circular tour """ from collections import deque def first_circular_t(p_a, d_a): d_q = deque(d_a) p_q = deque(p_a) curr_count = 0 i = 1 carry = 0 if sum(p_a) < sum(d_a): return -1 while curr_count < len(p_a): p_1 = p_q.popleft() d_1 = d_q.poplef...
50e12d78e19c29528d66dd332c6dcfd8a32e3a08
lakshyarawal/pythonPractice
/Hashing/more_than_window_occurances.py
1,496
3.515625
4
""" More than n/k occurrences """ def distinct_in_window(arr, win_sz) -> list: new_dict = {} occur = len(arr)//win_sz for i in range(len(arr)): if arr[i] in new_dict: new_dict[arr[i]] += 1 else: new_dict[arr[i]] = 1 new_dict = {k: v for k, v in new_dict.items() ...
254302dc69db6e0836a7f532689d1a2fc80558c8
lakshyarawal/pythonPractice
/Graph/adjacency_list.py
669
3.84375
4
""" Representing graph present in code as an adjacency list""" class Graph: def __init__(self, cap): self.capacity = cap self.arr = [[] for _ in range(cap)] def insert(self, u, v): if self.capacity > len(self.arr[u]): self.arr[u].append(v) else: print("...
c810cb700e55c7a8a060c8e543cf60dcd17e6afc
lakshyarawal/pythonPractice
/LinkedList/inserting_in_sorted_list.py
1,402
4.28125
4
""" Inserting an Element in a sorted LinkedList so that the linked list remains sorted """ class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null class LinkedList: # Function to initializ...
3cf9d591c424413d48c581d8e6fec143407e8583
kimko567/Python_specifics
/VectorCompare.py
467
3.65625
4
def compare(a, b): for n in a: test = True for m in b: if n == m: test = False if test == True: print(n) def Vinput(): vec = [] while True: x = input() vec.append(int(x)) if int(x) == 0: break return vec ...
c8c0c276a85934032f808f006e48385ed274c103
kishormarpina/eWar
/EwarFrontendTasks/task1.py
193
3.796875
4
def PrintNnums(n): arr = [] while(True): for i in range(1,n+1): arr.append(str(i)) print("".join(arr), end="") num = int(input()) print(PrintNnums(num))
ad6b9afd612d2bb7867057d9f66c7153c030cdad
cesperon/Python-Interpreter
/assignTest.py
179
3.6875
4
# using assignment statements with interpreter myInt = 11 print myInt # myNextInt = 21 # print myNextInt # newInt = myInt + myNextInt # print newInt # print newInt + myInt
0ae37f1a984c5f1a7991ee8be878faed88d9dcc3
BALAJI-IT19/img-to-txt-convertor
/main.py
785
3.625
4
# import the following libraries # will convert the image to text string import pytesseract # adds image processing capabilities from PIL import Image from langdetect import detect # opening an image from the source path img = Image.open('cn_sc01.png') # describes image format in the output print(img) ...
c9c8bd84a6eeac9b7b89c66f7aa84c0c3bd75716
charry07/MisionTic2022
/Ciclo 1 profesor - PYTHON/Semana_5_3/ejemplo.py
690
3.53125
4
from claseCola import Cola import random cola = Cola() for i in range(4): cola.encolar(random.randint(1,10)) cola.imprimirCola() cola.encolar(6) cola.imprimirCola() d = cola.desencolar() print(f"El dato {d} sale de la cola.") d = cola.desencolar() print(f"El dato {d} sale de la cola.") sig = cola.siguiente()...
aa19ae19cf4df6a0988c0e16bc51631d7fc1ed8b
charry07/MisionTic2022
/Ciclo 1 profesor - PYTHON/Semana_3_3/clase_vector/ejemplos_4.py
1,690
3.5625
4
import random from claseVector import vector n = int(input("Entre tamaño del vector ")) v = vector(n) v.construyeVector(n // 2) print("VECTOR CONSTRUIDO, tamaño = ", v.tamagno(), end=",") print("Posiciones usadas: ", v.posicionesUsadas()) v.imprimeVector("Primer vector construido ") v.agregarDato(69) v.imprimeVector(...
4ab5093705ab338559bd073900538a2a515a1c33
nuttaponkhamkul123/cs439_2019
/mytriangle/triangle.py
672
3.765625
4
import math class Isosceles(object): def __init__(self , w=0 ,h=0): self.w = w self.h = h def perimeter(self): param = ((self.w/2)**2)+((self.h)**2) return math.sqrt(param) def __str__(self): #print(f'Perimeter function : {self.perimeter()}' ); return (f'สามเหลี...
744a72ac9ae6544de5b270ab76c2c84fea513610
danielsantosead1/python-4linux
/fun_par_impar.py
259
4.125
4
#!/usr/bin/python3 import pdb pergunta = int(input("digite um numero: ")) def verifica(pergunta): if (pergunta % 2 == 0): return 'o numero digitado eh PAR' else: return 'o numero digitado eh IMPAR' a = verifica(pergunta) print(a)
a11fc24104601af569cd14c4ce87febbc221d518
gustavo-ifpb/esd
/stack/stack_utils.py
1,148
3.53125
4
def novaPilha(): return [] def contar(pilha): cont = 0 for item in pilha: cont += 1 return cont def empilhar(pilha, item): pilha.append(item) def desempilhar(pilha): if contar(pilha) > 0: return pilha.pop() return None def removerCentral(pilha): tam = contar(pilha) ...
bb04a986834327a073002898027990390b7e66e6
aghotikar/ComputationalBiology
/dummy.py
211
3.625
4
def overlaps1(a, b): for i in range(1, min(len(a), len(b))): if a[-i:] == b[:i]: print(a + b[i:]) def overlaps2(a, b): overlaps1(a, b) overlaps1(b, a) overlaps2('bbb', 'bbab')
86b2a829312f49e3ba514538e1d08e137a3f647a
muliarska/homeworks_ucu
/examples/adt_usage_example/tweets_linked_usage.py
571
3.625
4
"""Example of the usage of TweetsLinkedList""" from examples.adt_realization.tweets_linked_list import TweetsLinkedList TWEETS_LIST = TweetsLinkedList('realDonaldTrump') TWEETS_LIST.create_linked() print("Description of the user:") CUR_NODE = TWEETS_LIST.data print(CUR_NODE.data) CUR_NODE = CUR_NODE.next print("\n...
6f510d147f13d76cdbbda6d90815a2304c62ea41
dvanduzer/advent-of-code-2020
/day1-1.py
938
3.71875
4
""" Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn't quite adding up. Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together. For example, suppose your expense report contained...
3fae6f478af10915c49d23615bd0b01aaf7e3124
djcohen03/MachineLearning
/bayes/bayes.py
4,250
3.859375
4
''' Naive Bayes Bayes Theorem: P(A|B) = P(B|A) * P(A) / P(B) ''' import time from utils import Utils from posterior import Posterior from priori import Priori class BayesClassifier(object): ''' Naive Bayes Classifier - inputs: 2-D lists or 2-D numpy.ndarrays (categorical) - outputs: ...
27f45ccdf52eb7b1d80b46650d2975576ed5e5b9
djcohen03/MachineLearning
/bayes/priori.py
3,517
3.671875
4
import math import statistics import scipy.stats class Priori(object): ''' Helper methods to define a priori output distributions ''' @classmethod def uniform(cls, values): ''' Assume that the output values follow a uniform priori distribution ''' # Make sure we are only using u...
be2aedd7b53cf727a39e8103f62e194782d5fa0c
Muradali2022/CSCI_1133
/homeworks/HW2/HW2_C.py
2,951
4.09375
4
#CSCI1133, Lab Section 008, HW2 Murad Ali, Problem C def calories_short(height, weight, heart_rate, age, time): calories_burned = (((age * .074) + (heart_rate * .4472) - (weight * .05741) - 20.4402) * (time/4.184)) return(calories_burned) <<<<<<< HEAD def calories_tall(height, weight, heart_rate, age, ti...
b99eef999c9d8ac3d189f8f593dd9d55093d21ab
zzztpppp/TicTacToe-AI
/utils.py
2,463
4.03125
4
""" Utility funtions """ import numpy as np from typing import Tuple from functools import wraps from exceptions import NonEmptySlotError def get_string_grid(col: int, row: int, vals: np.ndarray) -> str: """ Return a string representation of a rectangle grids with given size of n by n and width and given ...
ff0b6efec665f52610bd9e147216d2d2ffdeddcd
nguyenthihangtn1996/training_login
/bai2/main.py
1,035
3.578125
4
import csv import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database = "customer_db" ) mycursor = mydb.cursor() mycursor.execute("DROP TABLE IF EXISTS customers") mycursor.execute("CREATE TABLE customers (customerid INT PRIMARY KEY, firstname VARCHAR(255), last...
3cfb4115fd55120781c23b23b57007eb71165447
jorgemedinafd/akademy.ai
/Akademy.ai/weekend_python-master/1808_Sunday/livecoding_lecture/cesars_cypher.py
1,161
3.765625
4
def main(): cypher(20, "./message.txt") def cypher(key, file): f= open(file,"r") w = open("chyper.txt", "w+") f1 =f.readlines() for line in f1: char_list = [] if line =='\n': print("found an empty line") else: for char in line.lower(): if char.isalpha(): if (ord(char) + key) >= 122: n...
ce24f5f672becf5d29764947396206ca5f1495ee
ravali231/UITestingpython
/Testcase2.py
1,139
3.609375
4
import unittest def setUpModule():#will be executed before executing any class or method present in the test class print("setup Module") def tearDownModule():#will be executed after completing everything in the python module print("teardown Module") class AppTesting(unittest.TestCase): @classmethod ...
05a5331114a80120ca96a2ac5581ddcd7fcfc113
anricoj1/CSC225
/Assingment 8/merge.py
807
3.890625
4
def merge_sort(a_list): print("Splitting ", a_list) if len(a_list) > 1: mid = len(a_list) // 2 left = a_list[:mid] right = a_list[mid:] merge_sort(left) merge_sort(right) i = 0 j = 0 k = 0 while i < len(left) and j < len(right): ...
1c66de26840dc63b5f9de2fd2b6c4a5831bac6c6
anricoj1/CSC225
/Assingment 8/Assingment8.py
1,561
3.921875
4
# program executes 4 algorithms with different time efficiencies (Selection, bubble # merge and tree) and measures execution time as a function of input size. import time import random import math def selection_sort(a_list): for fill_slot in range(len(a_list) - 1, 0, -1): pos_of_max = 0 for location in ran...
c3921959608b0213043c06323d79c5289bbf2d93
karishmakaushik/Mobile-Price-Comparison-System
/Front_end.py
6,877
3.65625
4
#Library Used import tkinter as tk import Back_end from tkinter import messagebox import webbrowser #checking for the main file if __name__ == '__main__': # creating main window root = tk.Tk() # getting original screen data X = root.winfo_screenwidth() Y = root.winfo_screenheight() ...
66fd74199b37d4a53a66cd106776464619769235
MarilizePi/Basic_Python_Exercises
/CS57-2016-HW-5.py
878
3.890625
4
#Exercise 1 def RecFact(n): if n <= 1: return 1 else: return n * RecFact(n-1) print RecFact(5) #Exercise 2 def RecPower(x,y): if x and y >= 0: return x*y else: return 0 print RecPower(2,6) #Excercise 3 def numOrder(n): for x in range(len(n)-1, 0, -1): for ...
36572599ca8fbe15ea364265c76e2b0d42dd28f6
samkintoye/Plaid-challenge
/first.py
444
3.5
4
#!/usr/bin/python import requests headers = { 'Content-type': 'application/json', } data = '{"query":"first", "products":null, "public_key":"3d22185375faf9e074b43c76dd0827" }' response = requests.post('https://sandbox.plaid.com/institutions/search', headers=headers, data=data) response_txt=response.text print(respo...
f3c592189e76e4c5e561cb3daa220b15ceb90efe
clairebroderick/BasicPythonExamples
/Cyphers/CypherTest2.py
403
3.6875
4
#Cypher Task letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] code = input ("Please enter the word you want to code: \n") codeword = " " n = 0 for i in code: #Get the letter n index from list fi = (letters.index(code[n])) n = n+1 #Add two to the inedx ni = int(fi)+2 #Get the ...
cdbcf5d8078c447a401248099752ce88825a927f
clairebroderick/BasicPythonExamples
/While/Counting from 1 to 10.py
158
3.953125
4
# Counting from 1 to 10 in 1s print ("Hi! I am going to count from 1 to 10 in 1s") number = 1 while number<= 10: print (number) number = number +1
beafd41b1b87b3bb248ecd9cc624eb903258f450
clairebroderick/BasicPythonExamples
/IF ELIF ELSE/Conversion App.py
458
4.375
4
# Conversion App print ("Welcome to the Conversion App") print ("1) Miles to Kilometers\n2) Kilometers to Miles \n3) Meters to cm \n4) Cm to Meters") conversion = input ("Please select your conversion type: \n") num = input ("What number would you like to convert: \n") n = int(num) conv = int(conversion) if conv =...
42eff4309b9c455839d4a1d9c81fb84e2ffe4c70
antongoransson/project-euler
/solutions/problem002.py
300
3.515625
4
import sys def fibonacci_sequence(length = sys.maxsize, max_val = sys.maxsize): prev, curr = 1, 1 for i in range(length): if curr > max_val: break yield curr prev, curr = curr, curr + prev print(sum([i for i in fibonacci_sequence(max_val = 4000000) if i % 2 == 0]))
529167afa5ec6a27ce587810906ddba9cf2b109a
smitthakkar96/flask-nsfw
/util.py
1,452
3.6875
4
""" All the crazy utilites are present here """ import base64 import binascii import re def is_base64(string): """ Checks wether the given string is base64 or not """ try: base64.decodestring(str.encode(string)) return True except binascii.Error: return False def is_...
3e005838664f9fef60b1ba1dbfa7b7590d4b571f
juxnior1/PythonRepositorio
/MostrandoComoPegarInformacaoDoteclado.py
133
3.90625
4
nome = input('Olá, digite seu nome sem quebra o teclado amiguinho: ') print('Obrigado por não quebra o teclado {}! '.format(nome))
4cc805eefd52e051abb82f78f24296e527b7fe56
nkitsan/trello_clone
/tasker/libs/apis/list.py
3,003
3.546875
4
""" This code provide responses in a dict format for client requests about lists """ from tasker.libs.managers import user_manager, public_task_manager class List: def __init__(self, api): self.api = api def get_lists(self): """ Returns a short info about lists in the format ...
cf530b774b5d25e5e3dea786a6ba21fccb523367
nilay121/battle_ship_game_for_begineers
/battle_ship_game.py
1,781
3.984375
4
############################################################################################################### ############################################################################################################### ##############################################################################################...
21dee0e6d6b6bf37826bc760e788139c18165cbd
qelias/Udemy
/Python/tkinter-tutorial/temperature_converter.py
1,078
3.53125
4
import tkinter as tk import numpy as np window = tk.Tk() window.title('Farenheit to Celsius') # window.columnconfigure([0,1,2,3,4],weight=1,minsize=50) # window.rowconfigure(0,weight=1,minsize=50) def convert(): result = np.round((5/9)*(float(ent_temperature.get())-32),2) lbl_result["text"] = str(result) fr...
340c4f209c78b489a2346a782726a16388567bb4
li13546282771/tutorial
/L11常用包/5csv.py
913
3.71875
4
# csv # csv 一种简单格式的纯文本文件,结构类似python中的列表,类似excel。场景:excel的替代格式,数据库导出文件 import csv # 读数据 # file_path = 'D:\\PycharmProjects\\tutorial_shanxi\\L11常用包\\5test.csv' # file_path = '5test.csv' file_path = r'D:\PycharmProjects\tutorial_shanxi\L11常用包\5test.csv' with open(file_path, mode='r', encoding='utf-8') as file: rea...
7e5896dc3ca95f0408103e6efec292b4142ad66e
ChoiJE/sparta_algorithm
/week_2/06.py
913
3.875
4
# 이진탐색 finding_target = 12 finding_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] # 1단계 : 최솟값 1, 최댓값 16 의 중간이 8 시도 # 2단계 : 최솟값 9, 최댓값 16 의 중간이 12 시도 # 3단계 : 최솟값 13, 최댓값 16 의 중간이 14 시도 def is_existing_target_number_binary(target, array): current_min = 0 current_max = len(array)-1 current_...
d5636571d9901038746a71dd42cca36d7e8db7fd
arishudson/cscs-531-pd-tournament
/src/pd/agents.py
810
3.859375
4
''' @date 20131124 @author: mjbommar ''' class Agent(object): ''' The Agent class is a base class, meant to be extended by our individual players in the PD world. The Agent class defines a shared set of methods and variables that the World needs to assume are available to "run." ...