blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
3bd68486e51753134cef0461c41bc1f01fa9d68c
NicholasTancredi/python_examples
/examples/simple.py
6,812
3.703125
4
""" File with simple examples of most common use cases for: - unittest - pytypes - pydantic - typing - enum """ from unittest import TextTestRunner, TestLoader, TestCase from argparse import ArgumentParser from typing import NamedTuple, Tuple, Union from enum import Enum from math import hypot ...
d8eea6878b92a31589a7b58cc6a3cdbc5a7299db
Bawya1098/python-Beginner
/day_2_assignment/list_sum.py
263
4.09375
4
number = input("enter elements") my_array = list() sum = 0 print("Enter numbers in array: ") for i in range(int(number)): n = input("num :") my_array.append(int(n)) print("ARRAY: ", my_array) for num in my_array: sum = sum + num print("sum is:", sum)
44971d0672295eea12f2d5f3ad8dad4faea2c47f
Bawya1098/python-Beginner
/Day3/Day3_Assignments/hypen_separated_sequence.py
273
4.15625
4
word = str(input("words to be separated by hypen:")) separated_word = word.split('-') sorted_separated_word = ('-'.join(sorted(separated_word))) print("word is: ", word) print("separated_word is:", separated_word) print("sorted_separated_word is: ", sorted_separated_word)
67a947661af531ea618cb15951041076cfaab19b
Bawya1098/python-Beginner
/Week2_day1/Multi_level_inheritance.py
873
3.734375
4
class Micro_Computers(): def __init__(self, size): self.size = size def display(self): print("size is:", self.size) class Desktop(Micro_Computers): def __init__(self, size, cost): Micro_Computers.__init__(self, size) self.cost = cost def display_desktop(self): ...
af0200ae519c67895fbb02c24de47233935b9b0b
Bawya1098/python-Beginner
/Day_1_Assignments/mystery_n.py
762
3.8125
4
def mystery(numbers): sum = 1 for i in range(0, numbers): if i < 6: for k in range(1, numbers): #num1 to 5: sum=2^(numbers**2) sum *= 2 print(sum) else: #number6: sum=2^(5*number)*5 if i < 10: ...
abde32d028db53073878822c4ab038eda0b5a507
ranellegomez/Object-oriented-Python-calculator
/test/CalculatorTest.py
3,317
3.5
4
import unittest import ModularCalculator import RecursiveExponentCalculator class MyTestCase(unittest.TestCase): def test_add(self): for a in range(-100, 100): for b in range(-100, 100): for c in range(-100, 100): print( 'add_test', a...
fcd96d8a74d9a565277a2ee8b44e9056943a3f30
tonyfg/project_euler
/python/p04.py
473
3.875
4
#Q: Find the largest palindrome made from the product of two 3-digit numbers. #A: 906609 def is_palindrome(t): a = list(str(t)) b = list(a) a.reverse() if b == a: return True return False a = 0 last_j = 0 for i in xrange(999, 99, -1): if i == last_j: break for j in xrange(9...
35d047c6d9377e87680dcc98b62182b49bf89a3e
tonyfg/project_euler
/python/p21.py
424
3.546875
4
#Q: Evaluate the sum of all the amicable numbers under 10000. #A: 31626 def divisor_sum(n): return sum([i for i in xrange (1, n//2+1) if not n%i]) def sum_amicable(start, end): sum = 0 for i in xrange(start, end): tmp = divisor_sum(i) if i == divisor_sum(tmp) and i != tmp: ...
8ea1a9399f7b7325159494391e648245e0e76179
Danielkaas94/Any-Colour-You-Like
/code/python/PythonApplication1.py
2,115
4.1875
4
def NameFunction(): name = input("What is your name? ") print("Aloha mahalo " + name) return name def Sum_func(): print("Just Testing") x = input("First: ") y = input("Second: ") sum = float(x) + float(y) print("Sum: " + str(sum)) def Weight_func(): weight = int(input("Weight: ...
7b1c346f4ef2097de68fbd0b2a4430765ee1d13e
TeknikhogskolanGothenburg/Docker_MySQL_Alembic_SQLAlchemy
/app/UI/customers_menu.py
2,117
3.578125
4
from Controllers.customers_controller import get_all_customers, get_customer_by_id, get_customer_by_name, store_changes, \ store_new_first_name def customers_menu(): while True: print("Customers Menu") print("==============") print("1. View All Customers") print("2. View Custom...
b8d583b681f9579475e30829ac3a596c41406e94
lsiddd/ml
/NeuralNets/ELM.py
1,882
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np verbose = False erro = lambda y, d: 1/2 * sum([np.sum (i **2) for i in np.nditer(y - d)]) def output(x, d, w1, w2=[]): sh = list(x.shape) sh[1] = sh[1] + 1 Xa = np.ones(sh) Xa[:,:-1] = x #ati...
f2540cf61a8935116b8ed9153e693541e3c91706
fear-the-lord/Structural-Balance-Identificator
/manual_network.py
4,432
3.625
4
# Import all the necessary dependencies import networkx as nx import matplotlib.pyplot as plt import random import itertools def checkStability(tris_list, G): stable = [] unstable = [] for i in range(len(tris_list)): temp = [] temp.append(G[tris_list[i][0]][tris_list[i][1]]['sign...
18f50b38f9ef8dfc927c8850927d6739bba3dac7
Philthy-Phil/practice-python
/ex3-ListLessThanTen.py
541
3.765625
4
__author__ = 'phil.ezb' a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] ui = "\n*************************" print("Given list of numbers: ", a) print(ui) for num in a: if (num < 5): print(num, end=", ") print(ui) for num in a: if (num < 5): x.append(num) print("here are all the numbers < 5:...
b698727d6dfa278ead4845b0b150dde2e8439b6e
stawary/LeetCode
/LeetCode/Median_of_Two_Sorted_Arrays.py
796
3.96875
4
#There are two sorted arrays nums1 and nums2 of size m and n respectively. #两个排好序的数组,求这两个数组的中位数。 #Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). #Example 1: #nums1 = [1, 3] #nums2 = [2] #The median is 2.0 #Example 2: #nums1 = [1, 2] #nums2 = [3, 4] #The median is (2...
692a0421d4258a93f1a16759976a4a98c5f1af41
Ejas12/pythoncursobasicoEstebanArtavia
/dia7/tarea6.py
936
3.5
4
import csv input_file = csv.DictReader(open("C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\serverdatabase.csv")) outputfile = open('C:\\Users\\Esteban Artavia\\Documents\\scripts\\\Pythoncourse\\dia7\\output.txt', 'w+') outputfile.write('NEW RUN\n') outputfile.close outputfile = open('C:\\Users\...
26b5cff2b5c9a9eca56befae9956bc895690c60e
sundusaijaz/pythonpractise
/calculator.py
681
4.125
4
num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) op = input("Enter operator to perform operation: ") if op == '+': print("The sum of " + str(num1) + " and " + str(num2) + " = " +str(num1+num2)) elif op == '-': print("The subtraction of " + str(num1) + " and " + str(num2) + " = " +...
1a301b5f2b834fb833f81fcb8060853474736c87
pjjefferies/python_practice
/huffman_encoding.py
6,229
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 13 21:10:34 2019 @author: PaulJ """ # import unittest # takes: str; returns: [ (str, int) ] (Strings in return value are single # characters) def frequencies(s): return [(char, s.count(char)) for char in set(s)] # takes: [ (str, int) ], str; returns: String (with...
10c1c00ec710a8a6e32c4e0f6f73df375f5a72d5
pjjefferies/python_practice
/find_anagrams.py
824
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 21:59:44 2019 @author: PaulJ """ def anagrams(word, words): anagrams_found = [] for a_word in words: a_word_remain = a_word poss_anagram = True for a_letter in word: print('1: a_word_remain:', a_word_remain) firs...
e7eb877dfa1edc9e2f3e0c59c71338453ff9b964
pjjefferies/python_practice
/censor_test.py
545
3.75
4
def censor(text, word): word_replace = "*" * len(word) for i in range(len(text)): print (i, text[i], word[0]) if text[i] == word[0]: for j in range(len(word)): print (i, j, text[i+j], word[j]) if text[i+j] != word[j]: break ...
07a627b0e4ab6bb12ec51db84fb72f56032649c4
Skyorca/deeplearning_practice_code
/FC_tf.py
3,607
4.03125
4
import tensorflow as tf import numpy as np from numpy.random import RandomState #Here is a built-in 3-layer FC with tf as practice """ how tf works? 1. create constant tensor(e.g.: use for hparam) tensor looks like this: [[]](1D) [[],[]](2D)... tf.constant(self-defined fixed tensor, and type(eg. tf.int16, should be def...
26d288b468e8cf62b3d27a5ab20513e6889373bf
Wigrovski/Python3
/SandwichApp/sandwich.py
399
3.625
4
import sys if sys.version_info < (3, 0): # Python 2 import Tkinter as tk else: # Python 3 import tkinter as tk def eat(event): print("Вкуснятина") def make(event): print ("Бутер с колбасой готов") root = tk.Tk() root.title("Sandwich") tk.Button(root, text="Make me a Sandwich").pack() tk.Button(r...
9c013a6131b469a6d40a294243ec6b6f1c0da02d
JenniferHhj/UcBerkeley-IndustryEng135
/Neural_Network/NN.py
4,743
3.671875
4
import tensorflow as tf import tensorflow_datasets as tfds tfds.disable_progress_bar() import math import numpy as np import matplotlib.pyplot as plt import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten ...
ac62e611bd36e4117f7705720bf39692148835f5
elvirich04/myOOP
/OOP/OOP2.PY
724
3.796875
4
class Person: def __init__(self, Name, Sex, Age): self.Name=Name self.Sex=Sex self.Age=Age def Show(self): if self.Sex=="Male": pronoun="Mr." else: pronoun="Ms." print("%s %s is %i years old."%(pronoun, self.Name, self.Age)) Person1=Perso...
ac79e5ed6bfa7b1d928aa2d6eb07f9fcab72d39f
elvirich04/myOOP
/OOP/OOP.PY
473
3.8125
4
class Person: def __init__(self): self.Name="" self.Sex="" self.Age=0 def Show(self): if self.Sex=="Male": pronoun="Mr." else: pronoun="Ms." print("%s %s is %i years old."%(pronoun, self.Name, self.Age)) Person1=Person() Person1.Name="Joh...
4f2f5eb803fee7c8ba6e73a1a142864f6ae91660
dmnjzl/jupyter
/class-and-object/maxHeap.py
2,471
3.921875
4
#MaxHeap class from Lab 3 class MaxHeap(object): def __init__(self,data=[]): # constructor - empty array self.data = data def isEmpty(self): # return true if maxheaph has zero elements return(len(self.data)==0) def getSize(self): # return number of elements in maxhe...
8d048eb12a10e55edafe9d0e56ac4c4313eb0137
srawlani22/LSystems-Genetic-Algorithms-with-Python3
/Intro-to-L-Systems/recursionexamples/tutorial.py
1,104
3.984375
4
import turtle import time import math #from turtleLS import randint draw = turtle.Turtle() # # drawing a square # draw.forward(100) # draw.right(90) # draw.forward(100) # draw.right(90) # draw.forward(100) # draw.right(90) # draw.forward(100) # # time.sleep(3) # # draw.reset() # draw.penup() # draw.forward(100) # ...
20821b277bb38285010d11b0bace9a4da4d539b5
shreo-adh/Python
/PDF_rotator.py
485
3.890625
4
import PyPDF2 file_path = input("Input file path: ") rotate = 0 with open(file_path, mode='rb') as my_file: reader = PyPDF2.PdfFileReader(my_file) page = reader.getPage(0) rotate = int(input("Enter the degree of rotation(Clockwise): ")) page.rotateClockwise(rotate) writer = PyPDF2.PdfFileWriter()...
c03f949e619ad6bdec690bd942043a3bfca7d816
acstibi02/4.ora
/hf4_4.py
403
3.625
4
bekert_szöveg = input("Írjon be egy szöveget: ") i = 0 j = 1 lista=[] a = 'False' while i < (len(bekert_szöveg)//2): if bekert_szöveg[i] == bekert_szöveg[len(bekert_szöveg)-j]: lista.append('True') i+=1 j+=1 else: lista.append('False') i+=1 j+=1 if a in lista: ...
c0a4b3de94544033bfa95b7a208f58f2b5c0eedc
NBALAJI95/Python-programming
/inClass/Class - 2/inClass-charac-freq.py
471
3.984375
4
def findCharFreq(s, c): if c not in s: return 'Letter not in string' else: count = s.count(c) return count def main(): inp_str = input('Enter the string:') distinct_letters = [] for i in inp_str: if i not in distinct_letters: distinct_letters.append(i) ...
8a869f9cc02943a51c4d0ce03dafe50c15740dc3
NBALAJI95/Python-programming
/inClass/Class - 4/inClass.py
729
3.703125
4
import requests from bs4 import BeautifulSoup import os def main(): url = "https://en.wikipedia.org/wiki/Android_(operating_system)" source_code = requests.get(url) plain_text = source_code.text # Parsing the html file soup = BeautifulSoup(plain_text, "html.parser") # Finding all div tags r...
10becb5b4a704625c66e56c5a66b975ab3c1628e
NBALAJI95/Python-programming
/inClass/Class - 3/inClass-1.py
905
3.859375
4
def print_horiz_line(): return '---' def print_vert_line(): return '|' def main(): inp = input('Enter dimensions of the board separated by "x":') inp = inp.split('x') inp = list(map(lambda a: int(a), inp)) print(inp) op ='' t = 0 case = '' it = 0 if (inp[0] + inp[1]) % 2 ...
fb213cb12399aa1b08a15d4040ef3ce15457e9e9
NBALAJI95/Python-programming
/Assignments/Week - 3/Task-3.py
1,624
3.953125
4
# Getting input co-ordinates from the user def getCoordinates(turn, tt): player = '' while True: if turn % 2 == 0: inp = input("Player 1, enter your move in r,c format:") player = 'X' else: inp = input("Player 2, enter your move in r,c format:") pl...
9154ab03fa537db195606670fe318a1240ca20ba
djd1283/UndiagnosedDiseaseClassifier
/get_random_submissions.py
2,058
3.5
4
"""Get random submissions from Reddit as negative examples for classifier.""" import os import csv import praw from filter_reddit_data import load_credentials from tqdm import tqdm data_dir = 'data/' negative_submissions_file = 'negative_submissions.tsv' accepted_submissions_file = 'accepted_submissions.tsv' def ge...
775bc457736c4a7dd6c98a389e63432c814cd1a4
custu2000/curs_python
/lab1/lab1.py
843
3.8125
4
#ex 1 for i in range(100): print ("hello world") # ex 2 s="hello world"*100 print (s) #ex 3 #fizz %3, buzz %5, fizz buzz cu 3 si 5 #rest numarul for i in range(100): if i % 3 ==0 and i % 5 ==0: print "fizz buzz for: ",i if i % 3 ==0 : print "fizz for: ",i if i % 5 ==0 : pr...
3da597b2bcdcdaf16bfa50bc86a060fa56173667
ND13/zelle_python
/chapter_2/futval.py
792
4.15625
4
#!/usr/bin/python3.6 # File: futval.py # A program that computes an investment carried 10 years into future # 2.8 Exercises: 5, 9 def main(): print("This program calculates the future value of a 10-year investment.") principal = float(input("Enter the principal amount: ")) apr = float(input("Enter the ann...
7482b65b788259f74c8719944618f9d856417780
ND13/zelle_python
/chapter_3/pizza.py
450
4.3125
4
# sphere_2.py # calculates the price per square inch of circular pizza using price and diameter def main(): price = float(input("Enter the price for your pizza: $")) diameter = float(input("Enter the diameter of the pizza: ")) radius = diameter / 2 area = 3.14159 * radius ** 2 price_per_sq_inch = ...
bd85de544ae4984bddacf4f091f186fec0b8e3f4
AmarJ/ieeeCodingChallenge
/2018-Fall/solutions/Q1.py
484
3.671875
4
def rot_1(A, d): output_list = [] # Will add values from n to the new list for item in range(len(A) - d, len(A)): output_list.append(A[item]) # Will add the values before # n to the end of new list for item in range(0, len(A) - d): output_list.append(A[...
4e58aa912b1e41bf3fb42cfc8917909137174ea6
jsy2906/Portfolio
/프로그래머스/실력 테스트/Q2.py
198
3.53125
4
# Q2) 입력된 숫자만큼 문자 밀기 def solution(s, n): string = '' for i in s: result = ord(i) + n string += chr(result) return string solution('eFg', 10)
f1a0cde50de74b36ff22705364f41fb62a26f56a
jsy2906/Portfolio
/파이썬/동명이인 찾기.py
193
3.53125
4
def find_same_name(a): n = len(a) result = set() for i in range(n-1): for j in range(i+1,n): if a[i] == a[j]: result.add(a[i]) return result
1e284588df9d0a43fde6af4e7358c1d1691c82c7
nikdavis/poker_hand
/poker_hand/parsers/card_parser.py
559
3.6875
4
class CardParser(object): RANK = { "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": 12, "K": 13, "A": 14 } SUIT = { "H": "heart", "D": "diamond", "C": "club", "S": "spade" } def __init__(self, card_str)...
6cf792b36892e4c8372d95eb9857034bf939e378
leogao/examples
/hackerrank/isFib.py
763
3.734375
4
#!/usr/bin/env python # https://www.hackerrank.com/challenges/is-fibo import sys T = int(raw_input()) assert 1<=T<=10**5 def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) X = 10 fibs = [] for i in xrange(X): fibs.append(fib(i)) for i in xr...
415ceea1e04a46bbab094f7abe18de80e487e0b5
heartthrob227/kenstoolbox
/convfilecheckerV0.1.py
2,049
3.5625
4
import csv, re, pandas from collections import defualtdict print('=================================') print('Welcome to the Conversion File Checker') #Ask for file to parse rawfile = input('What file do you want to test (without extension; must be csv)? ') firstfile = rawfile + '.csv' #Open file fout=open(out...
d95ad94be6d99173fbab10e23b772a94d8ed0cd8
mclearning2/Algorithm_Practice
/math/204_Count_Primes.py
508
3.953125
4
''' Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. ''' class Solution: def countPrimes(self, n: int) -> int: answer = 0 memory = list(range(n)) memory[:2] = None, ...
61b71063cf7828bbb2806a7992b43da37d41a9a2
Cathelion/Numerical-Approximation-Course
/Assignment4_Remez_algo.py
3,736
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 3 20:16:53 2021 @author: florian A short demonstration of the Remez algorithm to obtain the best approximation of a function in the supremum norm on a compact interval. The test function used is f(x) = x*sin(x) and we use 7 points We also plot t...
5a8aef01cc4e4dd1ec33a423b4b7fe01134371be
kcarson097/Beginner-Projects
/Text-editor.py
560
4.03125
4
def read_text_file(file): #file name is entered as 'file.txt' with open(file) as f: contents = f.read() return contents def edit_text_file(file, new_text): #this function will overwrite the current txt file with open(file, mode = 'w') as f: #opens file as read and write o...
c41a32b3bc188f45b33e89d1d4f9f8ada85abe84
RikaIljina/PythonLearning
/word_count_script/count_words.py
4,264
4.0625
4
import os import sys from pathlib import Path # Add your file name here file_path = r"counttext.txt" result_path = r"result.csv" # Remember names of source and target files f_name = Path(file_path) r_name = Path(result_path) print("#" * 86) print(f"This script will read the file {f_name} that must be placed in the s...
99add258003c36dcd2023264fd4af8c2e7045333
RikaIljina/PythonLearning
/cypher_1/cypher_template.py
6,030
4.5
4
############################################## # This code is a template for encoding and # decoding a string using a custom key that is # layered on top of the string with ord() and # chr(). The key can be any sequence of symbols, # e.g. "This is my $uper-$ecret k3y!!" # Optimally, this code would ask users to # choos...
f75081ff4aa02c2d226247c160a69e941149c980
zhaokaiju/fluent_python
/c07_closure_deco/p05_closure.py
728
4.34375
4
""" 闭包: 闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。 函数是不是匿名的没关系,关键是它能访问定义体之外定义的非全局变量。 """ def make_averager(): """ 闭包 """ # 局部变量(非全局变量)(自由变量) series = [] def averager(new_value): series.append(new_value) total = sum(series) return total / len(series) retu...
77d5735d02e893939063d955f7e32ca4b64a1f48
kescott027/PythonHacker
/ransomnote.py
1,365
3.578125
4
#!/bin/python3 import math import os import random import re import sys def checkMagazine(magazine, note): d = {} result = 'Yes' for word in magazine: d.setdefault(word, 0) d[word] +=1 for word in note: if word in d and d[word] -1 >= 0: d[word] -=1 else: ...
feb5d900ebb46fd80cfa86d8346b12c17e94ce0b
kescott027/PythonHacker
/maxmin.py
2,527
4
4
#!/bin/python3 import math import os import random import re import sys # Complete the maxMin function below. def maxMin(k, arr): """ given a list of integers arr, and a single integer k, create an array of length k from elements arr such as its unfairness is minimized. Call that array subarr. unfairnes...
162e451ee6116712ba11c38246234fd1ea324138
suhyeok24/Programmers-For-Coding-Test
/Programmers Lv.1/lv1. 최소직사각형.py
1,037
3.5
4
# 내 풀이 import numpy as np def solution(sizes): sizes=np.array(sizes).T.tolist() print(sizes) #[[가로],[세로]] width=sizes[0] height=sizes[1] big=max(max(width),max(height)) #가장 big을 찾는다. > 나머지 가로(세로)를 최소화시켜야 함. # index끼리 대소비교해서 smaller를 나머지 선분으로 몰빵 if big in width: ...
ce89c9d119563e15bdf426ae3d6d18800802ffe0
suhyeok24/Programmers-For-Coding-Test
/Programmers Lv.1/프로그래머스 lv1. 나누어 떨어지는 숫자 배열.py
858
3.53125
4
# 가장 흔한 for문 def solution(arr, divisor): answer = [] for n in arr: if n % divisor == 0: answer.append(n) if not answer: return [-1] else: return sorted(answer) # lIST COMPRHENSION 이용 def solution(arr, divisor): return sorted([ num for num in arr ...
3895cae859876b54b659f2b8a8b4edec12fddee3
corneliag08/Rezolvarea-problemelor-IF-WHILE-FOR
/problema 9.py
250
3.6875
4
n=int(input("Dati un numar: ")) suma=0 if(n!=0) and (n!=1): for i in range (1,n): if n%i==0: suma+=i if suma==n: print("Numarul", n,"este perfect.") else: print("Numarul", n,"nu este perfect.")
eb8542490893d3b99e9a8cfd416e0f363182de13
codeking-hub/Coding-Problems
/AlgoExpert/balanceBrackets.py
585
3.90625
4
def balancedBrackets(string): # Write your code here. stack = [] opening_brackets = "([{" closing_brackets = "}])" matching_brackets = { ")": "(", "}": "{", "]": "[" } for char in string: peek = len(stack)-1 if char in opening_brackets: sta...
8401b89e555a10d530a528355193b0207ac6be6c
codeking-hub/Coding-Problems
/AlgoExpert/moveElementToEnd/spacealsoopt.py
321
3.578125
4
def moveElementToEnd(array, toMove): # Write your code here. left = 0 right = len(array)-1 while left < right: while left < right and array[right] == toMove: right -= 1 if array[left] == toMove: array[left], array[right] = array[right], array[left] left += 1 return array # time O(n) # space O(n)...
171042e8da302efa359e350feaf92915e9d33b8b
codeking-hub/Coding-Problems
/AlgoExpert/find3LargestNums.py
711
4.125
4
def findThreeLargestNumbers(array): # Write your code here. three_largest = [None, None, None] for num in array: updateThreeLargest(num, three_largest) return three_largest def updateThreeLargest(num, three_largest): if three_largest[2] == None or num > three_largest[2]: shiftValu...
e328b1b43b04ea504d88dc37e936a0c3925cea60
codeking-hub/Coding-Problems
/AlgoExpert/2Sum/s2.py
257
3.875
4
def twoNumberSum(array, targetSum): # Write your code here. nums = {} for num in array: complement = targetSum-num if complement in nums: return [complement, num] else: nums[num] = True return [] # time complexity O(n)
e2519f0ca1c42f5cb04287a8d63bd563e136a2de
codeking-hub/Coding-Problems
/AlgoExpert/branchSums.py
601
3.703125
4
# This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def branchSums(root): # Write your code here. sums = [] findbranchSums(root, 0, sums) return sums def findbranchSums(node,...
49e336496e2452c7c33621dbd888c78ba43405b0
codeking-hub/Coding-Problems
/AlgoExpert/binarySearch/recersive.py
476
3.875
4
def binarySearch(array, target): # Write your code here. return binarySearchHelper(array, target, 0, len(array)-1) def binarySearchHelper(array, target, low, high): if low > high: return -1 mid = (low+high)//2 match = array[mid] if match == target: return mid elif target <...
3ddab9cd05622d64529fb633064ee8cfa0db0492
luciano588/d30-family-api
/src/datastructures.py
2,768
4.0625
4
""" update this file to implement the following already declared methods: - add_member: Should add a member to the self._members list - delete_member: Should delete a member from the self._members list - update_member: Should update a member from the self._members list - get_member: Should return a member from the sel...
77d7c4b29aad0ad0d7d7ab04b1f7d3231bf2d0b7
Symas1/metaprogramming_lab1
/meta_method.py
1,468
3.703125
4
import utils class MetaMethod: def __init__(self): self.name = utils.input_identifier('Enter method\'s name: ') self.arguments = [] self.add_arguments() def add_arguments(self): if utils.is_continue('arguments'): while True: name = utils.input_agru...
48458c3ba2011e0c23112d26a5b65d7d0822c5bf
RECKLESS6321/Libaries
/BFS(queue).py
483
4
4
def bfs(graph, start_vertex, target_value): path = [start_vertex] vertex_and_path = [start_vertex, path] bfs_queue = [vertex_and_path] visited = set() while bfs_queue: current_vertex, path = bfs_queue.pop(0) visited.add(current_vertex) for neighbor in graph[current_vertex]: if neighb...
8e7e80d3e42f32e4cb414d8e90e3c4ae079d8038
RahulNewbie/Job_REST_API
/job_insertion.py
984
3.84375
4
import csv import sqlite3 import os import constants def job_insertion(): """ Read the CSV file and insert records in Database """ con = sqlite3.connect(constants.DB_FILE) cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS job_data_table (Id,Title,Description,Company," ...
6c0dc7a54d1e00bd5cb02b06bf6fa804cd665de9
kadhirash/leetcode
/problems/happy_number/solution.py
593
3.546875
4
class Solution: def isHappy(self, n: int) -> bool: #happy = # positive integer --- (n > 0) # replace num by sum of square of its digits --- replace n by sum(square of digits) # repeat until == 1 # if 1 then happy, else false hash_set = set() total...
4d138ec4e0f4349b3eeb9842acc10f2a0c1ca748
kadhirash/leetcode
/problems/minesweeper/solution.py
1,131
3.6875
4
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: x, y = click surround = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, -1), (1, 1), (-1, 1), (-1, -1)] def available(x, y): return 0 <= x < len(board) and 0 <= y < len(board[0]) ...
374eb12b1ec6126e692a94315444e4a7bcf0621b
kadhirash/leetcode
/problems/search_suggestions_system/solution.py
1,011
3.671875
4
class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() # time O(nlogn) array_len = len(products) ans = [] input_char = "" for chr in searchWord: tmp = [] input_char += chr inse...
5b27c86e6e8a8286719120abc005c3766632d7f0
ElenaPontecchiani/Python_Projects
/0-hello/16-for.py
306
4.09375
4
for letter in "lol": print(letter) friends = ["Kim", "Tom", "Kris"] for friend in friends: print(friend) #altro modo per fare la stessa cosa con range for index in range(len(friends)): print(friends[index]) for index in range(10): print(index) for index in range(3,10): print(index)
8467f46df1d0750c60bdd4c67ece16ef34707c48
ElenaPontecchiani/Python_Projects
/0-hello/35-sortedAdvanced.py
531
3.53125
4
#format=(nome, raggio, denisità, distanza dal sole) planets =[ ("Mercury", 2440, 5.43, 0.395), ("Venus", 6052, 5.24, 0.723), ("Earth", 6378, 5.52, 1.000), ("Mars", 3396, 3.93, 1.530), ("Jupiter", 71492, 1.33, 5.210), ("Saturn", 60268, 0.69, 9.551), ("Uranus", 25559, 1.27, 19.213), ("Nept...
a9bbd74af9b343cf940c2a7eeb6de12dbcc4bdd9
ElenaPontecchiani/Python_Projects
/0-hello/12-calculatorV2.py
466
4.1875
4
n1 = float(input("First number: ")) n2 = float(input("Second number: ")) operator = input("Digit the operator: ") def calculatorV2 (n1, n2, operator): if operator == '+': return n1+n2 elif operator == '-': return n1-n2 elif operator == '*': return n1*n2 elif operator == '/': ...
e5d0c701272a91bb56882ffb433ead594311d5b5
ElenaPontecchiani/Python_Projects
/0-hello/2-variable.py
555
3.953125
4
character_name= "Jhon" character_age= 50.333 is_male= False #cincionamenti con le variabili print("His name is " +character_name) print (character_name) print (character_name.upper().islower()) print(len(character_name)) print(character_name[0]) print(character_name.index("J")) print(character_name.index("ho")) phrase...
0eeeef457fd8543b7ba80d2645b0bac3624dffc3
fanjiamin1/cryptocurrencies
/scratchpad/exponentiation.py
564
3.703125
4
def modularpoweroftwo(number,poweroftwo,module): #returns number**(2**poweroftwo) % module value=number%module currexponent=0 while currexponent<poweroftwo: value=(value*value)%module currexponent+=1 return value def fastmodularexponentiation(number,exponent,modu...
c9a49ce478ccbe1df25e3b5c0ee18932ae222f86
mateuszkanabrocki/LMPTHW
/ex11/project/tail.py
804
3.734375
4
#! /usr/bin/env python3 from sys import argv, exit, stdin # history | ./tail -25 def arguments(argv): try: lines_num = int(argv[1].strip('-')) return lines_num except IndexError: print('Number of lines not gien.') exit(1) def main(): count = arguments(argv) if len(ar...
def2e855860ded62733aa2ddcfe4b51029a8edd2
PSReyat/Python-Practice
/car_game.py
784
4.125
4
print("Available commands:\n1) help\n2) start\n3) stop\n4) quit\n") command = input(">").lower() started = False while command != "quit": if command == "help": print("start - to start the car\nstop - to stop the car\nquit - to exit the program\n") elif command == "start": if started: ...
f6b50fb2c608e9990ed1e3870fd73e2039e17b3d
ananyo141/Python3
/uptoHundred.py
301
4.3125
4
#WAP to print any given no(less than 100) to 100 def uptoHundred(num): '''(num)-->NoneType Print from the given number upto 100. The given num should be less than equal to 100. >>>uptoHundred(99) >>>uptoHundred(1) ''' while(num<=100): print(num) num+=1
004253ee0f2505f145d011e35d28ed4e9f96f36b
ananyo141/Python3
/Automate The Boring Stuff/sandwichMaker.py
1,484
4.09375
4
# Make a sandwich maker and display the cost. from ModuleImporter import module_importer pyip = module_importer('pyinputplus', 'pyinputplus') orderPrice = 0 print("Welcome to Python Sandwich!".center(100,'*')) print("We'll take your order soon.\n") breadType = pyip.inputMenu(['wheat','white','sourdough'],prompt="How...
437c321c8a52c3ae13db3bfa5e48c7a5dac2c1eb
ananyo141/Python3
/gradeDistribution/functions.py
2,519
4.15625
4
# This function reads an opened file and returns a list of grades(float). def findGrades(grades_file): '''(file opened for reading)-->list of float Return a list of grades from the grades_file according to the format. ''' # Skip over the header. lines=grades_file.readline() grades_list=[]...
65c9becebedca46aed5c13c04aa0bff47460d23b
ananyo141/Python3
/Automate The Boring Stuff/clipboardNumbering.py
1,238
4
4
#!python3 # WAP that takes the text in the clipboard and adds a '*' and space before each line and copies to the # clipboard for further usage. import sys from ModuleImporter import module_importer pyperclip = module_importer('pyperclip', 'pyperclip') def textNumbering(text, mode): '''(str,str)-->str Returns...
0cc53ef8c755669e55176ebad4cd5b0c0d758eef
ananyo141/Python3
/Automate The Boring Stuff/passwordStrengthNOREGEX.py
3,765
4.03125
4
# Give the user option to find the passwords in the given text, or enter one manually. # Check the password and give rating as weak, medium, strong, unbreakable and include tips to improve it. import re, time, sys from ModuleImporter import module_importer pyperclip = module_importer('pyperclip', 'pyperclip') def pass...
67613b888eaa088a69a0fec26f1ace376f95cbbb
ananyo141/Python3
/calListAvg.py
624
4.15625
4
# WAP to return a list of averages of values in each of inner list of grades. # Subproblem: Find the average of a list of values def calListAvg(grades): '''(list of list of num)--list of num Return the list of average of numbers from the list of lists of numbers in grades. >>> calListAvg([[5,2,4,3],[...
aba312740d42e2f175d79984bc2d3ec8042b891b
ananyo141/Python3
/area_of_triangle.py
184
4.1875
4
def area(base, height): ''' (num,num)--> float Return the area of a triangle of given base and height. >>>area(8,12) 48.0 >>>area(9,6) 27.0 ''' return (base*height)/2
0689366efad35236c8baddc7eb27bd398a51da8b
ananyo141/Python3
/Automate The Boring Stuff/blankRowInserter.py
1,735
3.828125
4
# Insert blank rows in a excel spreadsheet at a given row import tkinter.filedialog, openpyxl, sys, os from ModuleImporter import module_importer openpyxl = module_importer('openpyxl', 'openpyxl') def main(): print("Enter the file you want to add rows to:") filename = tkinter.filedialog.askopenfilename(filety...
b7e98df96a4a263667a93d2ae87d397457cd0cb4
ananyo141/Python3
/addColor.py
362
4.1875
4
#WAP to input colors from user and add it to list def addColor(): '''(NoneType)-->list Return the list of colors input by the user. ''' colors=[] prompt="Enter the color you want to add, press return to exit.\n" color=input(prompt) while color!='': colors.append(color) ...
1fe0f75ae821de46be7b338fc5d738d2a9a499e8
ananyo141/Python3
/doubleAltObj.py
348
3.890625
4
#WAP to modify the given list and double alternative objects in a list def doubleAltObj(list): '''(list)--> NoneType Modify the list so that every alternative objet value is doubled, starting at index 0. ''' # for i in range(0,len(list),2): # list[i]*=2 i=0 while i<len(list): ...
61c640eccbdf20c3ad65081414f33e8adba4475e
ananyo141/Python3
/Automate The Boring Stuff/DataExtractorTool/functions.py
3,547
4.34375
4
import re # Regex to find the phone numbers def findPhoneNumbers(string): '''(str)-->list Return all the matching phone numbers in the given string as a list. ''' phoneNumbersIN = re.compile(r'''( # Indian phone numbers (+91)9590320525 ( ((\+)?\d{2}) | \(((\+)?\d{2})\) )? # (+91) p...
190135679eb8848b33a40be02482aca18b41aa7e
tscotn/tscotn.github.io
/Python Scripts/web scraping/__main__.py
1,456
3.5
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup import sys import os def GetHTML(article_url): article_raw = requests.get(article_url) article_soup = BeautifulSoup(article_raw.content, 'html.parser') return article_soup #def GetArticleHeader(article_soup): # article_header: str = ...
1766b55fbf0337bcff4a3514a1e6542c8bceb78e
ktkthakre/Python-Crash-Course-Practice-files
/Chapter 3/guestlist.py
1,767
4.4375
4
#list exercise 3.4 guest = ['dog','cat','horse'] print(f"Please join us to dinner Mr.{guest[0].title()}.") print(f"Please join us to dinner Mr.{guest[1].title()}.") print(f"Please join us to dinner Mr.{guest[2].title()}.") #list exercise 3.5 print(f"\nOh No, Mr.{guest[2].title()} cannot join us for dinner."...
22da279601e248edb946f76cc4dba2e12b02315b
sakshitonwer/course-1
/HW3/Student-2/src/one.py
85
3.609375
4
def diff(a, b): c=a + b return c print("The sum is %i" % (6, 8, diff(6, 8)))
f063e7b57973fe43d7b4cefc481775c2c949a262
wdavid73/TheBigBangTheory_NumeroPecfecto
/NumeroPerfecto.py
1,915
3.90625
4
from typing import AnyStr def NumeroPerfecto(numero : int): cont = 0 cont2 = 0 # Validar si es primo if numero < 9: print("el numero debe ser mayor a 9") else: if( es_primo(numero) == True): cont = contar_primos(numero) newNumber = str(numero)[::-1] ...
f05be9154a3ddf89509d7075cd35f35df216800b
IPcamerabykitri/nmap
/ISEEU_Interface_new/Network_Scan_Module/entropy.py
579
3.59375
4
import math from collections import Counter def calculate_entropy(symbol_list): entropy = 0 total_symbol_count = float(len(symbol_list)) values_symbol = Counter(symbol_list) # counts the elements' frequency for symbol_count in values_symbol.values(): percentage = symbol_count/total_symbol_coun...
1a67cbcabc8f93f42cbb39a1b30531e12226b655
katesorotos/module3
/ch05_testing_tools/calculator_app_test.py
498
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 09:59:29 2019 @author: Kate Sorotos """ import unittest from calculator_app import Calculator class calculator_test(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_add_method(self): result = self.calc.add(2,2) s...
93bb07c59455eb12a995e7597807d619dc4823ac
DavieV/Euler
/test.py
220
3.78125
4
import math def is_prime(x): if x % 2 == 0: return False for i in range(3, int(math.sqrt(x))): if x % i == 0: print i return False return True print is_prime(2433601)
a1ee96883d6f41e3cd4d75f535658b95e4cb3780
yang4978/LeetCode
/Python3/0994. Rotting Oranges.py
855
3.5
4
class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: oranges = 0 queue = [] m = len(grid) n = len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 1: oranges += 1 elif grid[i][...
2057326205e39c27b6f96b6718983578a90425b4
yang4978/LeetCode
/Python3/0143. Reorder List.py
1,046
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverse_list(self,head): if not head: return head temp = head new_head = None while temp: tt = ...
2f0e0aeb2b240f6a771ac67d4e5bae902da83481
yang4978/LeetCode
/Python3/0461. Hamming Distance.py
337
3.578125
4
class Solution: def hammingDistance(self, x: int, y: int) -> int: # n = x^y # res = 0 # while n: # res += n%2 # n //= 2 # return res res = 0 mask = 1 while(mask<=x or mask<=y): res += mask&x!=mask&y mask <<= 1 ...
f6c7ca63b6a6915e6ee3024460bb39df878604f1
yang4978/LeetCode
/Python3/0500. Keyboard Row.py
277
3.859375
4
class Solution: def findWords(self, words: List[str]) -> List[str]: set1 = set('qwertyuiopQWERTYUIOP') set2 = set('asdfghjklASDFGHJKL') set3 = set('zxcvbnmZXCVBNM') return [s for s in words if(set(s)<=set1 or set(s)<=set2 or set(s)<=set3)]
098f29472231beddb24634a49769bc3fa9c61c90
yang4978/LeetCode
/Python3/0538. Convert BST to Greater Tree.py
1,305
3.75
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def convertBST(self, root: TreeNode) -> TreeNode: stack = [] total = 0 head = root while root: ...
6c8aa894c50bc79c86e7f0229762d9db877d58ad
yang4978/LeetCode
/Python3/0333. Largest BST Subtree.py
662
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def countNode(self,root): if not root: return [0,float('inf'),-float('inf')] l = self.countNod...
e22f54173153779b1d010c781a4611e3c67550ec
yang4978/LeetCode
/Python3/0549. Binary Tree Longest Consecutive Sequence II.py
994
3.75
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def traversal(self,root): if not root: return [1,1] neg = 1 pos = 1 if root.left: ...
8e14dba3414955281a929d243d5f2432a9be9935
yang4978/LeetCode
/Python3/0124. Binary Tree Maximum Path Sum.py
1,122
3.609375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: max_value = -float('inf') def PathSum(self,root): if not root: return -float('inf') l = self.PathSum(roo...
a74072cc0077517c67acfd7a4790a8426b79c813
yang4978/LeetCode
/Python3/0099. Recover Binary Search Tree.py
3,434
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # def recoverTree(self, root: TreeNode) -> None: # """ # Do not return anything, modify root in-place instead. # ...