blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
17a77522c49ec45a5a60e9d7e6fc1eb1ba94f774
HDShaw/Runaway-Reservation-System-BST-
/binary_search_tree.py
4,376
4.03125
4
class tree_node(object): def __init__(self,key = None, left = None, right = None): self.key=key self.left=left self.right=right class binary_search_tree(object): def __init__(self,root=None): self.root=root def insert(self,key): """recursion way""" self.root=...
eb79f7e79b9a79eeb8ebfb6d12b580516066b4da
elizabeth19-meet/yl1-201718
/Project/ball.py
1,213
3.859375
4
from turtle import * class Ball(Turtle): def __init__(self, x, y, dx, dy, r, color): Turtle.__init__(self) self.penup() self.x=x self.y=y self.dx = dx self.dy = dy self.r = r self.color(color) self.shape('circle') self.goto(x, y) ...
be4dd527e96636ee178b150e160cbec28ac55082
chowdhurynawaf/URI-SOLVE
/1154.py
142
3.65625
4
X = 0 Y = 0 Z = 0 while True: Z = int(input()) if Z>0: X = X+Z Y = Y+1 else: break print("%.2f"%(X/Y))
6b58bc74a4169347f4c079516be12e6da439e8e0
ArshanKhanifar/eopi_solutions
/src/vlad/problem_8_p_6_vlad.py
1,831
3.8125
4
from protocol.problem_8_p_6 import Problem8P6 from collections import deque """ THINGS TO NOTE ABOUT THIS PROBLEM Problem 8.6var1 was trivial so was not explicitly done. You do exactly same thing as in this solution except every other level you just pop instead of popleft (use a stack instead of queue) Problem 8.6var...
9c29eba38ae71213ccb6956476153b61c8f1415f
baieric/hackerRank
/leetcode/battleship_in_a_board.py
641
3.515625
4
# https://leetcode.com/problems/battleships-in-a-board/description/ class Solution(object): def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ ships = 0 for x in range(len(board)): row = board[x] for y in range(...
d7d2bf72d838557c0071f5760932312f501e6be1
HariharanNandagopal/guviphy
/greatest of three number.py
147
3.75
4
a=input() b=input() c=input() if(a>b) and (a>c): print("1 st is big") elif(b>a) and (b>c): print("2nd one is big") else: print("third is big")
c72d56dc5144e3b87fca9bee754ad93705724752
Palash51/Python-Programs
/Data Structures/xample/cpy_prime.py
268
3.734375
4
def selsort(a): for i in range(len(a)): m = min(a) swap(a, i, m) return a def swap(arr, x, y): #temp = 0 temp = arr[x] arr[x] = arr[y] arr[y] = temp #return arr, x , y a = [7, 5, 4, 2] print selsort(a)
417642488986077f665b70df6e0ea6693a0a78e8
goodgoodliving/3d-vision-semantic-localization
/code/images.py
2,030
3.59375
4
""" Module for loading the content from directory containing a sequence of timestamped images. """ import glob import re import numpy as np from os.path import join, basename def get_image_path_list(image_dir_path): """ Get a sorted list of paths of all images (files with file name pattern '*.jpg') in a given...
267f4deabb05214c0bd236f1abcbaf261bf4ccb0
lucasbruscato/StretchingTimer
/helper.py
993
3.609375
4
import os import time import datetime ######### change here ######### time_in_seconds = 35 ############################### exercises = [ 'push up', 'lengthen the trunk down', 'lengthen the trunk to the right', 'lengthen the trunk to the left', 'stretch the right fist down', 'stretch the left ...
b4591976d6bb1186dc8e2c3a71d03346aa9be598
Yuvv/LeetCode
/0001-0100/0049-group-anagrams.py
808
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @File : 0049-group-anagrams.py # @Date : 2019/08/17 # @Author : Yuvv <yuvv_th@outlook.com> from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = dict() for s in strs: sorted_s = ''...
c72fae0c88fc3a896108cd5632463c5247c8b173
betty29/code-1
/recipes/Python/205126_Variant_property_allowing_one_functibe_used/recipe-205126.py
2,356
3.53125
4
class CommonProperty(object): """A more flexible version of property() Saves the name of the managed attribute and uses the saved name in calls to the getter, setter, or destructor. This allows the same function to be used for more than one managed variable. As a convenience, the default function...
60bd8139b3f279b9b3c8b0e3d8b37241c5e2a596
KKosukeee/CodingQuestions
/LeetCode/199_binary_tree_right_side_view.py
2,274
4.15625
4
""" Solution for 199. Binary Tree Right Side View https://leetcode.com/problems/binary-tree-right-side-view/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: """ Runtime: 40 ms...
8239401a10c5471ba46d239a79409f83caa32050
MengnanZoeZhou/LearnToProgramFundamentals
/Assignments/grade.py
844
4.0625
4
def read_grades(gradefile): '''(file open for reading) -> list of float Read and return the list of grades in the file. Precondition: gradefile starts with a header that contains no blank lines, then has a blank line, and then lines containing a student number and a grade. ''' # Skip over...
d4732957153731bb76ae6d2881fb68ce5c52441c
Serendipity0618/python-practice
/zero_number_end2.py
351
4.03125
4
def factorial(n) : product = 1 while n > 0: product = product * n n = n - 1 return product n = input("Please input x:") product = factorial(int(n)) print(product) str = list(str(product)) #print(str) i = -1 counter = 0 while int(str[i]) == 0: counter = counter + 1 ...
418d9bce6e41fa47c99bf714be2baf2f0ae40b33
kantel/nodebox-pyobjc
/examples/Extended Application/sklearn/examples/ensemble/plot_forest_importances.py
2,601
4.25
4
""" ========================================= Feature importances with forests of trees ========================================= This examples shows the use of forests of trees to evaluate the importance of features on an artificial classification task. The red bars are the feature importances of the forest, along wi...
b49394ba3f4ce97fe89d500355ed70c50df49549
SemieZX/InterviewBook
/代码/LinkedList/removeValue.py
677
3.84375
4
# method 1 def removeValue1(head,num): if head == None: return None stack = [] while head != None: if head.val != num: stack.append(head) head = head.next while stack: stack[-1].next = head head = stack.pop() return head # method 2 def removeVal...
c35d1bb018941a0e34663a3a6e32964b7101187c
parastuffs/INFOH410
/TP_C/tp_c_template.py
1,367
3.6875
4
#!/usr/bin/python3 import matplotlib.pyplot as plt import matplotlib.patches as patches import math # You should install matplotlib for this code to work # e.g. pip install matplotlib # or https://matplotlib.org/users/installing.html def q4(): """ Q4 (c) In this function, we initialize the positive and n...
91288067ef5b7f53739f3bf929a5a592192e836d
senel-study/kosmo-3rd
/s.yoon/job interview/google_specialSort_answer.py
166
3.921875
4
def special_sort(s_list): return [x for x in s_list if x < 0 ] + [x for x in s_list if x is 0] + [x for x in s_list if x > 0] print(special_sort([-1,1,3,-2,2]))
9308fc861d4b6c041e58a8f7a684f9b33166cead
reemahs0pr0/Daily-Coding-Problem
/Problem50 - Largest Set Consisiting of Multiples.py
934
3.96875
4
# Given a set of distinct positive integers, find the largest subset such that every pair of elements in the subset (i, j) satisfies either i % j = 0 or j % i = 0. # For example, given the set [3, 5, 10, 20, 21], you should return [5, 10, 20]. Given [1, 3, 6, 24], return [1, 3, 6, 24]. def largest_set(l): final_l ...
d9253fcd3d8275c340e665e74b6afcfe7fbf590b
shetty-shithil/python_code
/queue.py
597
4.03125
4
queue=list([]) n=1 while(n>=0): print('1.Enter elements in queue') print('2.Remove an element') print('3.Print queue') print('4.Print first element') print('5.Print last elemnt') print('6.Enter your choice:') n=int(input()) if(n==1): queue.append(input()) elif(n==2): ...
a0c1e73177c16d2b9f2ed0d39e4aea88f2f2838d
danRobot/ProyectoDise
/trayectoria.py
5,614
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 12 19:52:53 2018 @author: mahou """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from numpy import pi from scipy.interpolate import interp1d from scipy import integrate class T...
5ba5c5b5ab9d1e4e41da3611b75d9e226ab51d65
arpithappu/python
/assignment1/q4.py
117
3.734375
4
n=int(input("enter anumber")) sum=0 if n>0: for i in range(1,n+1): sum+=1/(i*i*i) print(f"result:{sum}")
314a4d115dd1b9d339038ed44269b50f2083cc4a
pranav-kural/Python-Practice
/example_logical_op.py
276
3.921875
4
# A = number of people living in the building # B = eldest person living in the building A = 10 B = "Simon" eldestPerson = A and B if eldestPerson != 0: print("Name of the eldest person living in the building is", B) else: print("No one living in the building")
4a293d8ff792467334e8616d9fd250127c22a5a9
devinchugh/MS_Word-Functions
/main.py
11,826
4.4375
4
# CODES FOR VARIOUS PROGRAMS FOR STRINGS print('Enter the string on which you wish to execute all the programs:') print('At last press enter keeping the last line empty') string = '' temp = 'run' while(temp == 'run'): line = input() string += line+' ' if line == '': temp = 'stop' lis = string.spl...
6815b68ebf82d0dfa1221d89acb092f4cadbb93f
vaibhav20325/school_practical
/Class11/q7.py
167
3.578125
4
h=int(input("Enter number of heads ")) l=int(input("Enter number of legs ")) a=int((l-2*h)/2) b=h-a print ("Number of rabbits is", a, "Number of chickens is", b)
276a25ef9628b579bdcc4c5148a5c2dbfb6b1029
daniel-reich/ubiquitous-fiesta
/rSa8y4gxJtBqbMrPW_14.py
94
3.609375
4
def lcm(n1, n2): num = max(n1,n2) while num%n1!=0 or num%n2!=0: num+=1 return num
e8a09ad36b45339d5a4b3f0e35e1b447d603f48b
Arnold329/Game
/dice.py
771
3.53125
4
import random, pygame, time pygame.init() screen_width, screen_height = 100, 100 screen = pygame.display.set_mode((screen_width, screen_height)) def display_die(nums, x, y): random_num = int(random.choice(nums)) die_face_to_display = pygame.image.load("./images/dice/die_" +str(random_num...
0b7b1d5fedc080022cd9caf3e07eed87559248ab
zhanxinl/self-teaching
/185apple_plan/mit-introduction to Computer Science and Programming in Python/hw/coursa/test.py
426
3.5
4
s = 'abcbcd' max_len=0 max_str="" if len(s)==0 or len(s)==1: max_len=len(s) max_str=s else: n=1 start=0 end=1 while end<len(s): if s[end-1]<=s[end]: n+=1 end+=1 if n>=max_len: max_str=s[start:end] max_len=n ...
c6bccec19209ed6c9e2d1f812b70a6457dc3c1b6
supvolume/codewars_solution
/5kyu/pack_bagpack.py
491
3.796875
4
""" solution for Packing your backpack challenge find maximum score to fit in bagpack with given capacity""" # NOT FINISH def pack_bagpack(scores, weights, capacity): bagpack_list = list(zip(scores, weights)) bagpack_list.sort(reverse = True) max_score = 0 total_cap = 0 for i in range(len(bagpack_...
adca92958262cc3e25f99541be42eeebe51c5225
anfernee84/Learning
/python/func2.py
227
3.953125
4
def positive(): print('Positive') def negative(): print('Negative') def test (): a = int(input('Enter a digit:' )) if a < 0: negative() else: positive() test ()
2df038ee4cd9471a94fbb8e86318ce31342966e8
bhuvankaruturi/Python-Programs
/Python Regex/filter2.py
1,247
3.546875
4
import re def RemoveDuplicates(matches): uniqueList = [] duplicate = False for i in range(0, len(matches)): for j in range(0, len(uniqueList)): if matches[i] == uniqueList[j]: duplicate = True if not duplicate: uniqueList.append(matches[i]) duplicate = False return uniqueList def ReplaceStrings(un...
0b6c9d4a75c9953ab7a30bcf07b9dea14be08943
ggchappell/AdventOfCode2020
/day15/solve-15b.py
1,346
3.546875
4
#!/usr/bin/env python3 # Advent of Code 2020 # Glenn G. Chappell import sys # .stdin import itertools # .count # ====================================================================== # HELPER FUNCTIONS # ====================================================================== def generate_numbers(start_...
c17262d53028457e9900bfa6b8142c25ede24fea
leannef/SENG265-Software-Development-Methods
/assignment_02/import math.py
3,637
3.78125
4
import math ''' Purpose Provide an exception class for Point and Line. Exceptions None Preconditions Message is a string. ''' class Error(Exception): def __init__(self, message): self.message = message ''' Purpose Store a point as an x, y pair. Provide functions to rotate, scale and translate the point. Preco...
9e58f1338774738e438c683de67334e21c42f90d
wxiea/CS2302Lab4
/main.py
5,759
3.8125
4
class BTree(object): # Constructor def __init__(self,item=[],child=[],isLeaf=True,max_items=5): self.item = item self.child = child self.isLeaf = isLeaf if max_items <3: #max_items must be odd and greater or equal to 3 max_items = 3 if max_items%2 =...
a4e0fa9ca5f0fda5817b02889346b848d47240d2
b-ark/lesson_5
/Task1.py
399
4.34375
4
# Write a Python program to get the largest number from a list of random numbers with the length of 10 # Constraints: use only while loop and random module to generate numbers from random import randint random_list = [] counter = 0 while counter != 10: random_list += [randint(0, 10)] counter += 1 print(rand...
a61881ea17bd5331463bf4f551787b254383290c
eronekogin/leetcode
/2021/minimum_number_of_refueling_stops.py
1,048
3.765625
4
""" https://leetcode.com/problems/minimum-number-of-refueling-stops/ """ from heapq import heappop, heappush class Solution: def minRefuelStops( self, target: int, startFuel: int, stations: list[list[int]]) -> int: """ Keep driving until no fuel le...
4f314b32a45fc1e1acc2e5f1b1adca304b9c7ec8
kaalachor/Python-OOPS
/General_Decorator.py
358
3.75
4
# This decorator can decorate any function # args will be the tuple of positional arguments. # kwargs will be the dictionary of keyword arguments. def works_for_all(func): def inner(*args, **kwargs): print("I can decorate any function") return func(*args, **kwargs) return inner @works_for_all...
86e6af527928f9d91539f47d81ec653c0eae8bec
diegohsales/EstudoSobrePython
/List Comprehensions.py
568
4.25
4
""" Set Comprehension Lista = [1, 2, 3, 4, 5] Set = {1, 2, 3, 4, 5} #Exemplos numeros = {num for num in range(1, 7)} print(numeros) #Outro exemplo numeros = {x ** 2 for x in range(10)} print(numeros) #DESAFIO! O que pode ser feito para alterar na estrutura abaixo para gerar um dicionário ao invés de Set? numero...
f577dc5bb8ceb984c52a4c6269b98800d0f46320
maniraja1/Python
/proj1/Python-Test1/CodingInterview/stacks_queues/stacks_queues.py
518
4.09375
4
# Stacks Using list print("#"*20+"Stacks"+"#"*20) stack = ["Amar", "Akbar", "Anthony"] stack.append("Ram") stack.append("Iqbal") print(stack) # Removes the last item print(stack.pop()) print(stack) # Removes the last item print(stack.pop()) print(stack) #Queues using list print("#"*20+"Queues"+"#"*20) stack = ["Ama...
12631ccd1c9ac579d030121c5eee69fed4002b51
DawnSeeker99/Uni-Stuff
/Hello World.py
771
4.1875
4
from math import ceil while True: try: students = int(input('How many students are there? ')) if students > 0: break else: print('Please enter a positive number.') except ValueError: print('Please enter a positive number') while True: try: co...
98bdee7605dbf1b09df3dd0b446d0a0f6e1eff7d
dicao425/algorithmExercise
/LintCode/miniTwitter.py
2,486
3.96875
4
#!/usr/bin/python import sys ''' Definition of Tweet: class Tweet: @classmethod def create(cls, user_id, tweet_text): # This will create a new tweet object, # and auto fill id ''' class MiniTwitter: def __init__(self): # do intialization if necessary self.order = 0 ...
67fdb7b386f622cad9e0cf7cdebaf3500cbb5255
daniela-mejia/Python-Net-idf19-
/PhythonAssig/5-15-19 Assigment 12/pi.py
729
3.578125
4
import sys from math import pi def calcPi(): q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 while True: if 4*q+r-t < n*t: yield n nr = 10*(r-n*t) n = ((10*(3*q+r))//t)-10*n q *= 10 r = nr else: nr = (2*q+r)*l ...
cbbe30cb2d381086d6a619de9c2a2651f7b11d7f
gireevash/giree
/varshu.py
108
3.75
4
guvi = int(input(' ')) if(guvi % 4==0 and guvi % 100!=0 or guvi % 400==0): print('yes') else: print('no')
59aef11625c67edeb838dae91c0e3328e9447601
christopher-burke/warmups
/python/misc/partially_hidden_string.py
1,311
4.53125
5
#!/usr/bin/env python3 """Partially Hidden String. Create a function that takes a phrase and transforms each word using the following rules: * Keep first and last character the same. * Transform middle characters into a dash -. Source: https://edabit.com/challenge/h9hp2vGKbHJBzN87i """ def hide_word(word, replace...
0580d8335ffcd9a6b6f8e77fb22ecb7eb97608ff
josephsurin/cp-practice
/ANZAC/2019/ANZAC Round 1 2019/j.py
127
3.78125
4
n = int(input()) print('1 2 b') print('1 2 c') for i in range(3, n+1): print('b', i, 'c') print('c', i, 'b') print('b c a')
49165b593f67df4d46984ba0aa76eec577262ca4
gabriellaec/desoft-analise-exercicios
/backup/user_386/ch149_2020_04_13_20_02_10_955520.py
818
3.78125
4
salario=float(input('salario? :')) dep=float(input('dependentes?: ')) if salario <= 1045: INSS = 0.075*salario if salario > 1045 and salario <= 2089.6: INSS = 0.09*salario if salario > 2089.6 and salario <= 3134.4: INSS = 0.12*salario if salario > 3134.4 and salario<= 6101.06: INSS = 0.14*salario if sa...
47baeaf789ea3af71615976f722f4c2aec797eb5
MuralidharanGanapathy/Hackerrank
/Swapcase.py
100
4
4
def swap_case(s): s = "".join(c.lower() if c.isupper() else c.upper() for c in s) return s
3bb189261e6c46a32cd61177027642fe93fc88b5
coderTa/sets
/sets/sets_sum.py
225
3.5
4
array = [5, 7, 2, 3, 1, 0] checked_set = set([]) for i in range(len(array)): num = array[i] complement = 7 - num checked_set.add(complement) if num in checked_set: print(num, complement)
4c57c692d3405a35b2b3784cbc94bbeefa0f1445
Lanfear22/sqlite_emp
/Employees Table.py
602
4.21875
4
import sqlite3 conn = sqlite3.connect('employee.db') c=conn.cursor() c.execute("""CREATE TABLE Employees ( EMPLOYEE_ID INTEGER PRIMARY KEY, FIRST_NAME STR, LAST_NAME STR, CURRENT_CONTRACT STR )""") c.execute("""INSERT INTO Employees (FIRST_NAME, LAST_NAME, CURRENT_CONTRAC...
2cc4ae22ed55c44aaf7fa5521a093ef8e1757af4
mendoza/hotcake
/Btree.py
7,964
3.625
4
from Node import Node import bisect import itertools import operator class BTree(object): BRANCH = LEAF = Node """ Orden: como su palabra lo dice, el orden en el que basamos el arbol """ def __init__(self, order): self.order = order self._root = self._bottom = self.LEAF(self) ...
2353c72d946d288d288eaa9806cb106df09e4649
jasonpea/DAD-PROJECT
/test/prob 1 bitch.py
205
3.765625
4
# NUMBER 1 s = int(input("please input number: ")) m = int(input("please input number: ")) l = int(input("please input number: ")) if 1 * s + 2 * m + 3 * l > 10: print("Happy") else: print("Sad")
9c46d2ba4151ca3f906f486ba9091809f255fe8c
apag101/is210_lesson_06
/task_01.py
709
4.34375
4
#!usr/bin/env python# # -*- coding: utf-8 -*- """Even and Odds Function.""" import data def evens_and_odds(numbers, show_evens = True): """Returns even or odd numbers. Args: numbers(numeric). show_even(boolean, Default = True). Returns: Number: Returns a new list object. Examples: ...
244d0f7b41acc7c25502ff38ce683259a784ecc5
young8179/pythonClass
/python102/7-number-positive.py
212
3.78125
4
## positive number numbers = [10, 20, 30, -99, 50, -12, 87, 90, 1, 101, 9182691, 12, -11, 42] positive_num = [] for number in numbers: if number > 0: positive_num.append(number) print(positive_num)
169e1942a7d2b96e7eccadb5aabf2c40ed7bfca7
acarter881/exercismExercises
/grains/grains.py
210
3.734375
4
def square(number): if number < 1 or number > 64: raise ValueError('Please enter a number greater than or equal to 1.') return 2 ** (number - 1) def total(): return sum((2 ** i for i in range(64)))
134331caef5f33664b7147322ef2d39d9c349e63
somanie1/Practicing-Python
/datetime.py
3,071
4.21875
4
""" days in month """ def days_in_month(year, month): """ days in month """ import datetime if ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0)) and (month == 2): return 29 elif (month == 2): return 28 elif (month == 4) or (month == 6) or (month == 9)...
46981ad4de6e8a408302f80921a8290999cc512b
markstali/atividade-terminal-git
/code13.05.py
2,854
4.25
4
#01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: # a) tamanho da lista. # b) maior valor da lista. # c) menor valor da lista. # d) soma de todos os elementos da lista. # e) lista em ordem crescente. # f) lista em ordem decrescente. """ L = [5, 7, 2, 9, 4, 1, 3] ...
735400d97ebbda97e93e60d66aff8d7545572418
RafaelMuniz94/AjudandoBruninho
/Questao7.py
924
4.03125
4
# 7-Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. # Após isto, calcule a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram # (mostrar o mês por extenso: 1 – janeiro, 2 – fevereiro, . . .). temperatura = [] mese...
ebc85a13de078710c7b6b15bda0bd646bf9887cd
Villager-B/Default-Algorithm-Python
/Radix/decimal_to_binary.py
309
3.796875
4
def main(): decimal = int(input("decimal : ")) q_list = [] while True: r = decimal // 2 q = decimal % 2 q_list.append(str(q)) if r == 0: break decimal = r print("binary : ", "".join(q_list[::-1])) if __name__ == '__main__': main()
ff92e0d54569282b11d916928c4770763f9e44ea
lpchambers/aoc19
/day06/p1.py
1,222
3.53125
4
class Space: def __init__(self, name): self.name = name self.children = [] self.parent = None def set_parent(self, parent): self.parent = parent self.parent.children.append(self) def cost(self): if self.name == "COM": return 0 if self.parent is None: print(self.name) return self.parent.cost()...
ff0ca3e93238f9aa5297d0466e46ddead96a76b3
jimjshields/python_learning
/think_python/other/most_common.py
2,336
4.28125
4
### modules ### import string # module that has string operations below ### functions ### def process_file(filename): # function to build dictionary of words and frequencies for a file hist = dict() # hist is the empty dictionary fp = open(filename) # fp is the opened file for line in fp: # running ...
f5b85a5ee8bbdb010056af893f548367bf74e733
DevKheder/PythonCrashCourse
/introducing-lists/3-1 names.py
199
4.3125
4
# making a list of friends' names friends = ["kheder", "modar", "sandy", "amani"] # now printing each name indvidually print(friends[0].upper()) print(friends[1]) print(friends[2]) print(friends[3])
346aed3c0e2893acd565f89fe767cc06604f8fbb
sukant16/Leeter
/medium/remove_duplicates_from_sorted_array.py
1,237
3.75
4
''' Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Approach: 1. Use Deque 2. iterator over the length, check if ...
d51e08d55057c6816e1dabe9a3230cf13c848dc6
StuartCowley/PythonExercises
/areacalculator.py
595
4.28125
4
# This program is for calculating the area of a given shape inputted by the user print("The calculator is running") name = input("Enter C for Circle or T for Triangle: ") option = name if option in "Cc": radius = float(input("Input radius: ")) area = radius**2 * 3.141592 print("Area of circle is %.2f " % a...
b39dd060dfef90dbb5a2168236ac04fbe92528aa
smart8612/KMU_Python
/algorithm/Doomsday_Algorithm.py
2,773
3.828125
4
def isLeapYear(year): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return True else: return False def closer(target1, target2, value): return target1 if abs(target1 - value) < abs(target2 - value) else target2 def closerSearch(sorted_ary, value): try: maxidx =...
d0c7ed468562a89cf06db007ce851316331cf613
fredcodee/get_emails
/scrapy2.py
1,752
3.734375
4
'''a simple python script to scrape emails from any website and other website linked to then prints out on terminal emails found and website it was gotten from and also option to download and save as csv file ''' import requests from bs4 import BeautifulSoup import re import csv from time import sleep print...
d452255fc7008ca6274747c8ecae7d2779908a60
Timothy-py/Python-Design-Patterns
/structural_design_patterns/flyweight_pattern.py
2,907
3.53125
4
import json class Flyweight: """ The Flyweight stores a common portion of the state(intrinsic) that belongs to multiple real business entities. The Flyweight accepts the rest of the state(extrinsic) via its method parameters. """ def __init__(self, intrinsic=''): self._intrinsic = int...
a5b8eda8d550a03319eb9202ff2885270ced78ac
muttakin-ahmed/leetcode
/PascalsTriangle.py
1,183
3.96875
4
def generate(self, numRows: int) -> List[List[int]]: # The outer list arr_out = [] for i in range(1, numRows+1): # The inner list, initialized with 0 arr_in = [0] * i # putting 1 to the either ends of this inner list arr_in[0] = 1 ...
0ad0637af3d0dd74d2e942beb4ddf726f40a438a
jamestaylormath/MachineLearning
/Python/logistic_regression.py
3,901
4.15625
4
import numpy as np # linear algebra import pandas as pd import math #Sticks a column of ones to the front of X def insert_ones(X): return np.c_[np.ones(X.shape[0]), X] #Returns f_beta(X) (discussed in "Logistic Regression Explained" in Math folder) def f(beta, X): return 1/(1+np.exp(-np.sum(X*beta, axis=1))) ...
100bf4fda4a528cb3129506398b110e8c934bca7
vad2der/Python_examples
/brakets_validating.py
1,319
3.859375
4
""" Tiny app to check if a string has properly closed brakets or not. """ sample11 = "({[]})" sample12 = "({}[])" sample13 = "({})[]" sample14 = "(){}[]" sample21 = "({}[)]" sample22 = "({}([]" brakets = [["(",")"],["{","}"],["[","]"]] def determine_opening_braket_type(opening_braket): """ returns closing br...
7de765906585d25dfb1d5895e5931993c18d4f31
marciooferraz/TestesPython
/TestesPython/TestesPython.py
590
4.40625
4
#Testes com variaveis e Inputs #nome = input("Nome: ") #print(nome.upper()) #Testes com metodos nos prints mensagem = "o grande teste" print(mensagem.find("t")) #Conta o número de caracteres até o valor parametizado print(mensagem.count('a')) #Conta quantos caracteres = ao valor parametizado existem na string pr...
9b585bf8796a14a973b4445971c2cf6ed0c2f3db
FaridWaid/sms2-praktikum-strukturdata
/Modul 5/2.py
1,843
3.78125
4
def binsearch(listData,key): for a in range (1,len(listData)): x = listData[a] b=a-1 while b>=0 and x<=listData[b]: listData[b+1]=listData[b] b-=1 listData[b+1]=x print(listData) found=False first= 0 last=len(listData)-1 more=[] ten...
a143f24a8eb40ad3858c87595ec7784ebf09ce31
trowa88/python_machine_learning
/src/books/ch6/ngram-test.py
679
3.578125
4
def n_gram(s, num): res = [] s_len = len(s) - num + 1 for i in range(s_len): ss = s[i:i+num] res.append(ss) return res def diff_n_gram(sa, sb, num): a = n_gram(sa, num) b = n_gram(sb, num) r = [] cnt = 0 for i in a: for j in b: if i == j: ...
a64b32ea2aa6df03cd2c6c34856a40229b27bbda
haotwo/pythonS3
/day22/input_output.py
263
3.734375
4
# -*- coding:utf-8 -*- #作者 :Lyle.Li #时间 :2019/10/19 9:52 #文件 :input_output.py # s ='Hello,Runoob' # print(str(s)) # # print(str(1/7)) for x in range(1,11): print(repr(x).rjust(2),repr(x*x).rjust(3),end='') print(repr(x*x*x).rjust(4))
89d635dee7df164288ed7035e04348e1da0200da
zioul123/VocalPitchModulator
/Utils.py
10,430
4.21875
4
import numpy as np import librosa import librosa.display import matplotlib.pyplot as plt from enum import IntEnum ################################################################# # 3D to flattened array utilities ################################################################# def flatten_3d_array(arr, i_lim, j_lim...
3bdd97e86dbe63b385faa73d0f4b42ca00a79340
wzqwsrf/Leetcode
/Python/098 Validate Binary Search Tree.py
1,954
3.96875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # Validate Binary Search Tree 308ms """ /** * Given a binary tree, determine if it is a valid binary search tree (BST). * Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys less than the node's key. * The right subtree of a ...
1e7263eb2e7be9b28401ce829d0dc4da2dce3936
scMarth/Learning
/Leetcode/35_search_insert_position.py
1,784
3.765625
4
import math def binary_search_call(arr, target): l = 0 r = len(arr) - 1 while l < r: mid = math.floor((l + r)/2) print("l: {} ; m: {} ; r: {}".format(l, mid, r)) if arr[mid] == target: return mid elif arr[mid] < target: l = mid + 1 el...
e0aedef4f1ef9578ff59bc9a706779790c64de24
Brodie-Pirovich/FOP_CovidTest
/FOP/FOP/personClass.py
757
3.71875
4
class person(): myClass = "Person" def __init__(self, name, weight, dimensions, temp, cough, throat, resp): self.name = name self.weight = weight self.dimensions = dimensions self.temp = temp self.cough = cough self.throat = throat self.resp = resp ...
e424fdaf1fc2f8f39129bfff3411cb2f4298ef41
agyenes/greenfox-exercises
/08a recursive_python/5.py
344
4.28125
4
# 5. We have a number of bunnies and each bunny has two big floppy ears. # We want to compute the total number of ears across all the bunnies # recursively (without loops or multiplication). def bunny_ear_calculator(n): if n <= 2: return n * 2 else: return 2 + bunny_ear_calculator(n-1) print(b...
68373247630435f99c172347aa28e27b0a5e1c6c
Syed-Azam/Challenges_of_the_day
/alphabet_dictionary.py
250
3.828125
4
# Challenge of the day # Alphabet Dictionary in single line of code # i.e. {1 = 'A', 2 = 'B'.................26 = 'Z'} print(dict(zip([n for n in range(1,27)], [chr(c) for c in range(65,91)]))) # or print({i+1:chr(i+65) for i in range(26)}) input()
80a5b5cd615cd3aa98a65428cd54a34b1f7cbf9e
Vlados2810/DMI
/PYTHON/if.py
426
3.875
4
#!/usr/bin/python # -*- coding: utf-8 -*- a=input("Lietotāj, lūdzu, ievadi vienu skaitli: ") if a > 0: print "Tu esi ievadījis pozitīvu skaitli" elif a == 0: print "Tu esi ievadījis nulli" else: print "Tu esi ievadījis negatīvu skaitli" ''' a=input("Lietotāj, lūdzu, ievadi vienu skaitli: ") if a > 0: print ...
d47c3977d779ad5eac4b7876c88d71773bb1f4b5
sasiarivukalanjiam/python-learning
/fundamental/doc_strings.py
607
3.59375
4
# Add two values and print the result class doc_strings(object): def add_it(self, a, b): """ Adds two value and returns the result :param a: :param b: :return: """ c = a+b return c def print_message(self, value): """ gets a va...
523e1a4d8e0a41a2438b48fe66649ffe6970c1b7
asdra1v/python_homework
/homework01/Exercize03.py
163
3.53125
4
user_number = int(input("Введите число n: ")) un1 = int(f"{user_number}{user_number}") un2 = int(f"{user_number}{un1}") print(user_number + un1 + un2)
acd34f81e686830723714cc487a9b4def96f1180
AJ3907/mergecsvs
/merge.py
2,676
3.609375
4
import csv import os import sys def readCSV(csvFile): res =[] csvReader = csv.reader(csvFile) for row in csvReader: res.append(row) return res def getCommonColumnIndex(read,commonColumn): commonColumnIndex = -1 l = len(read[0]) for i in range(0,l): if (read[0][i] == commonColumn): commonColumnIndex = i ...
78de255e59cd5b5f14de2562820ebfe9099cf5b1
DreamerKing/learn-python
/sum-average.py
254
4.0625
4
#!/usr/bin/env python3 N = 10 sum = 0 count = 0 print("please input %d numbers:"% N) while count < N: number = float(input()) sum += number count += 1 average = sum / count print("N={} Sum={:.2f} Average={:.2f}".format(count, sum, average))
283bed7bc8a6d7c45462130a6b48633076c619f7
SafonovMikhail/python_000577
/000403StepPyThin/000403_02_02_Task_01_BreakContinue_other_02_20200105.py
95
3.71875
4
while True: a = int(input()) if (a < 10): continue if (a > 100): break print(a)
f1cc8f8f31c09dbd134e836d12a43399d5d035f9
Jatin666/calculator
/cal.py
588
4
4
def add(): a=int(input("enter the first number: ")) b=int(input("enter the second number: ")) c=a+b print(c) return c def subtract(): a = int(input("enter the first number: ")) b = int(input("enter the second number: ")) c = a - b print(c) return c def multiply(): a = int(inp...
95e81e2b912866c0f24ab78b588b2769374c9071
ashishiit/workspace
/LovePython/DecimaltoBinary.py
653
3.640625
4
''' Created on Oct 26, 2016 @author: s528358 ''' # import string class StackPython: def __init__(self): self.a = [] def Push(self,item): self.a.append(item) def Pop(self): return self.a.pop() def Peek(self): return self.a[len(self.a)-1] def IsEmpty(self): ret...
5795c53a22d0a4baaeb20c66153c0a8109afa77a
UncleBob2/MyPythonCookBook
/for loop types.py
1,438
4.625
5
colors = ["red", "green", "blue", "purple"] for color in colors: print(color) print(colors,"\n") for i in colors: print(i) # For example, let’s say we’re printing out president names along with their numbers (based on list indexes). # range of length print("\nrange len indexes example") presidents = ["Wa...
f0c3be8043c5974ac224d85c948478e9c772c723
shuyirt/Leetcode
/0509_fibonacci_number.py
461
3.5
4
class Solution(object): def fib(self, N): """ :type N: int :rtype: int """ if N == 0 or N == 1: return N # list based # l = [0, 1] # for i in range(2, N+1): # l.append(l[i-1] + l[i-2]) # return l[-1] # variable...
92ca38cc9a5635a114a1535224c4cdc4918f06c5
otisscott/1114-Stuff
/Lab 5/binaryconverter.py
411
3.875
4
# Otis Scott # CS - UY 1114 # 4 Oct 2018 # Homework 4 num = int(input("Enter a decimal number: ")) number = num orig = num count = 0 bin = "" while num != 0: num = num // 2 count += 1 for each in range(count - 1, -1, -1): if (number - 2 ** each) >= 0: bin += "1" number -= 2 ** each el...
54d1b3bb4547132be9da6f100f71a0595efbbd45
causelovem/4-course
/python 2017/dz5/task3_misha.py
398
3.609375
4
def comp(a, b): if len(a) != len(b): return 0 for i in range(len(a)): if not((b[i] == a[i]) or (b[i] == "@")): return 0 return 1 inp = input() mask = input() res = -1 for i in range(len(inp)): if ((mask[0] == inp[i]) or (mask[0] == "@")) and (comp(inp[i:len(mask) + i], m...
29d66486ab9e0fffe88cc28d533e7e999adf5c96
Manoji97/Data-Structures-Algorithms-Complete
/InterviewQuestions/Python/1_Arrays/2_ArrayPairSum.py
449
3.828125
4
''' ex: pairSum([1, 3, 2, 2], 4) output: (1, 3) and (2,2) sum of Output should be equal to the number in input ''' # For this method the Time Complexity is O(n) def ArrayPairSum(lst, num): length = len(lst) if length < 2: return False seen = set() output = set() for i in lst: diff = num - i if diff no...
d790776bd4bf0cc42da837dd894a252d97e45bfd
anaerobeth/dev-sprint2
/palindrome.py
1,040
4.25
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] #print first('biology') #print last('biology') #print middle('biology') #print middle('hit') #print middle('hi') #print middle('a') #print middle('') #Type these functions into a file named palindrome.py and...
5324d423564c7de10ba3f2bb922cfb1061543851
zgao92/STAT628_Module2_Group5
/code/LSTM/LSTM_clean_data.py
1,808
3.5625
4
#python script to transform the test data into the matrix #load the package import sys import pandas as pd import numpy as np import re pd.options.mode.chained_assignment = None test_data = pd.read_csv(sys.argv[1]) test_text = test_data.iloc[:,2] from nltk.stem.wordnet import WordNetLemmatizer lem = W...
345b75e60ba0c0c775a013e826e4b37d1a2abc32
j42j/foundations
/pig_latin.py
707
3.71875
4
'''Pig Latin Translator rules: if word begins with vowel, add "way" to the end of the word. if word begins with consenant, removes all consenants until reach first vowel, then add those consenants to the end of word, then add "ay."''' while True: s = input('Enter word: ') if s.isalpha(): ...
383daeb888ab0748ebc5e9df45a983b998d1977f
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4138/codes/1637_2446.py
372
3.71875
4
s = int(input(" insira a senha: ")) a = s // 100000 b = s //10000 - (a * 10) c = s // 1000 - ((a * 100) + (b * 10)) d = s // 100 - ((a * 1000) + (b *100) + (c * 10)) e = s // 10 - ((a * 10000) + (b *1000) + (c * 100) + (d * 10)) f = s % 10 sp = b + d + f si = a + c + e if (sp % si != 0): mensagem = "senha invalida" ...
3b6eae090733e889c597c2ce4d7159d65feaa0ac
minccia/python
/python3/cursoguanabara/bhaskara.py
626
3.59375
4
# Progama para resolver a fórmula de Bhaskara e encontrar as raízes possíveis coa = (int(input("Qual é o valor do coeficiente A?"))) # Coeficiente A cob = (int(input("Qual é o valor do coeficiente B?"))) # Coeficiente B coc = (int(input("Qual é o valor do coeficiente C?"))) # Coeficiente C delta = ((cob**2)-4*coa*c...
459f867fd7c82b44f6bb052c3a4180a643513773
MrJay10/Image-Processing
/Flash Light Detector.py
2,177
3.6875
4
from SimpleCV import * cam = Camera() # Initialize Camera img = cam.getImage() # get a sample image to know the screen size display = Display() # Creates an object of Display Class width, height = img.width, img.height # Gets width and height of the Image captured screensize = width*height # initiali...
5972a40d079d603bea44a2f631b6bd3a146c30e9
viszi/codes
/CodeWars/7kyu/Python/018-get-the-middle-character.py
708
4.15625
4
# https://www.codewars.com/kata/56747fd5cb988479af000028 # You are going to be given a word. Your job is to return the middle character of the word. # If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. # Kata.getMiddle("test") should return "es" # Kat...
069b1e495218ed00a66b4638afcec5170ac15f99
samrizky28/Manual-K-Fold-Cross-Validation
/KFoldCV_Manually.py
1,473
3.53125
4
import pandas as pd import math from sklearn.model_selection KFold #X is the independent variable in the dataset #y is the target variable #n is the number of observations in the dataset n=len(X) #Let say we want to make 5-fold CV. It means, we are equivalent to doing a 20% separation of test data, then: kf = KFold(...