blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
8d97636d1e094ba6070889cc584ad76b1b2aaf4f
pigmonchu/bzChallenges
/dientes_de_leon/diente_leon_v.2.py
663
3.546875
4
import turtle miT = turtle.Turtle() ''' Ahora vamos a dibujar dos y para ello vamos a utilizar bucles anidados ''' #Limpiar pantalla miT.reset() #Posición vertical miT.left(90) #Diente de leon miT.pd() miT.forward(100) miT.right(90) miT.pu() miT.fd(6) for repes in range (15): #Hacemos 15 repeticiones con un for ...
0bf2950b73b843ae52582a2174486fbc48240eef
draju1980/Hello-World
/string_fun_exe2.py
570
4.3125
4
# Write a function that accepts an input string consisting of alphabetic # characters and removes all the trailing whitespace of the string and returns # it without using any .strip() method. def _remove_trailing_whitespace_sample_(string): my_index = None i = len(string) while i > 0: if stri...
71cfdc85af24f268b5035983b5602214baaad858
markhorsfield/py4e
/other-proj/secure.pass.checker.py
1,117
4.3125
4
#!/usr/bin/python3 while True : password = input("Make up a secure password: ") print("You entered: ", password) # initialize has_capital = False has_digit = False # check length gt_6 = len(password) >= 6 if gt_6 is True : print("Password length check passed") # check alp...
6c837aa721e83b62283cc847f2ec24a1371fc22b
shalini1803/pramp_questions
/questions/sudoku-solver/solution.py
1,315
3.609375
4
def getCandidates(board, row, col): candidates = [] for num in xrange(1,10): num = str(num) collision = False for i in xrange(9): if (board[row][i] == num) or (board[i][col] == num) or (board[row-(row%3)+(i/3)][col-(col%3)+(i%3)] == num): collision = True break if not collisio...
867e1b06b3499c5052203690b50b67f7b70976c1
jiju1234/python-basics
/factorial_number.py
529
3.9375
4
mul=1 a=int(input("enter a number:")) for i in range(1,a+1): mul=mul*i print(mul) #write for checking a palindrome or not u_input=input("enter a string:") if(u_input[::-1]==u_input): print("its a palindrome") else: print("this",u_input,"not a palindrome") """write a program for dice game checking""" import random ...
c0662230474f2683ac45fa4e827fe34e1557c178
ashahrior/DS_Algo
/queue.py
779
3.9375
4
from double_linked_list import DoubleLinkedList class Queue: def __init__(self): self.__list = DoubleLinkedList() def enque(self, value): self.__list.add(value) def deque(self): val = self.__list.pop_front() return val def front(self): return self.__list.f...
f20ea25f3efb953aa90a97d3104f1c7fd89180a4
niranjanh/Machine_Learning_Projects_and_Assignments
/LEARNING and PRACTICE/00_Python_Practice_Questions/Question_03_Squares.py
548
4.28125
4
#Squares #Description #Given a list of positive integers, you have to find numbers divisible by 3 and replace them with their squares. #For example, consider the list below: #Input: [1,2,3,4,5,6] #The output for the above list would be: [1,2,9,4,5,36]. Because 3 and 6 were divisible by 3, these numbers were replaced w...
72348e060e3ba3f1f8d3de0b7c8a57f2e34b9763
Aasthaengg/IBMdataset
/Python_codes/p02720/s615753432.py
486
3.578125
4
def incr_lunlun(num): num[0] += 1 if len(num) == 1: if num[0] == 10: num.append(1) num[0] = 0 elif num[0] > num[1] + 1 or num[0] == 10: suffix = incr_lunlun(num[1:]) digit = max(0, suffix[0] - 1) num = [digit] + list(suffix) return num def ...
e56fdddf5dca231c841f78a6b1a85790f999e603
gpriya/class-5-advanced-collections
/step_1.py
412
3.53125
4
from data import products_string def transform_products_to_list(products_string): split_products = products_string.split('\n') products_list = [] for product_line in split_products: if product_line: product = product_line.split(",") products_list.appe...
bc930d2164cb9f9b94919a10f1b53c96b50bc199
DylanDmitri/BoggleSolver
/WordSearch.py
2,065
3.609375
4
import numpy as np import itertools wordlist = set(open('wordlist', 'r').read().split('\n')) def valid(word): assert word == word.strip().upper() return word in wordlist class Board: def __init__(self, letters): # needs to be a 2D array of letters assert all(( hasattr(l...
466ac5d7a2c2876b7b781c2a215af99a373cd4a8
nishasinha/DataStructures
/src/datastructures/solution1.py
1,272
3.828125
4
def findLargestPower(n): x = 0 while ((1 << x) <= n): x += 1 return x - 1 def countsetbits(n): if (n <= 1): return n x = findLargestPower(n) return (x * pow(2, (x - 1))) + (n - pow(2, x) + 1) + countsetbits(n - pow(2, x)) def solution(X, Y): countsetbits() if __name__ =...
4184a31f91b9f3afc441de01c5d7774d90602f7f
conanlhj/2021_python_study
/jan/06/문제풀이/0106-03.py
450
3.75
4
# Sol 1 n = int(input()) for _ in range(n): for i in range(n): if _ % 2: print(' ', end='*') else: print('*', end=' ') print() # 가장 정석? # Sol 2 n = int(input()) for _ in range(n): print(" "*(_ % 2), "* "*n, sep="") # 현재 줄이 짝수 홀수인지에 따라서, # 맨 처음 한칸 띄우고 시작할지 바로 시작할지 정함....
ba78eaa032e0600cfdc722dd1b315fde3e07aaab
pavanmaganti9/v1
/lists.py
876
4.28125
4
x1 = [1,2,3] print(type(x1)) print(x1[1]) """ Functions of Lists """ #append function : When we add an item to list using append. By default the item will be added to the end of the list new1 = [1,2,3,4,5] new1.append(31) print(new1) #insert function : When we add an item to list using insert function. # insert(i...
9ee054edff75cefcb112e23e3d7c4336be3d6166
daniel-reich/ubiquitous-fiesta
/ysgbRFTPujx8v37yF_15.py
152
3.578125
4
def row_sum(n): cur = 1 row = 0 length = 1 for i in range(n): row = sum(range(cur,cur+length)) cur+=length length+=1 return row
c902cb052bc1a7f3712be72dda965e94aef1d207
MartinYan623/Lint-Code
/Algorithm/Easy/1-500/133LongestWord.py
915
3.6875
4
class Solution: """ @param: dictionary: an array of strings @return: an arraylist of strings """ def longestWords(self, dictionary): # write your code here """ length=len(dictionary) maxlength=0 for i in range(length): a=len(dictionary[i]) ...
f8545a5f3dcd9d9e3fe83e967eee31715bb6a395
jlmedina123/codingforfun
/recursion.py
594
4.0625
4
'''Write a function, for a given number, print out all different ways to make this number, by using addition and any number equal to or smaller than this number and greater than zero. For example, given a 5, we have the following different ways to make up 5: 1st: 1, 1, 1, 1, 1 2nd: 1, 4 3rd : 1, 1, 1, 2 4th : 1,...
dc9f0a43241ea0b7dd627d01eac70a9c1862d857
guilhermetiaki/coding-challenges
/HackerRank/hackerrank-in-a-string.py
218
3.703125
4
q = int(raw_input()) match = "hackerrank" for x in range(0,q): string = raw_input() i = 0 for c in string: if i < len(match) and match[i] == c: i += 1 if i == len(match): print "YES" else: print "NO"
a4120605a3adedfa5326ee09ad504ce8fc50f3ca
forxhunter/ComputingIntro
/solutions/codeforces/617A.py
802
4.09375
4
''' greedy algorithm An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he n...
d94adba583e6e7785293af641f1fe4f483c1646e
lcdlima/python_projects
/month.py
407
4.03125
4
# Read an integer between 1 and 12, inclusive. Corresponding to this value, the month of the year must be presented in full, in English, with the first letter in uppercase. NUMERO = [1,2,3,4,5,6,7,8,9,10,11,12] MES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'No...
9013197d0963ef5a8c740fd4a7bb851de474a32e
LeonildoMuniz/Logica_de_programacao_Python
/Listas/Lista2_Ex02.py
133
4.0625
4
a=int(input('Digite um número: ')) if a>=0: print ("O valor digitado é positivo!") else: print("O valor digitado é negativo")
6c62ffbe70f8ef65d019e9c55a56a4357392ae30
manikandan5/HackerRank-Problems
/Algorithms/Implementation/TheTimeinWords.py
1,151
3.828125
4
#!/bin/python3 import sys units = {1:"one" , 2:"two" , 3:"three" , 4:"four" , 5:"five" , 6: "six" , 7:"seven" , 8:"eight" , 9:"nine", 10:"ten" , 11:"eleven" , 12:"twelve" , 13:"thirteen" , 14:"fourteen" , 15:"fifteen" , 16:"sixteen" , 17:"seventeen" , 18:"eighteen" , 19:"nineteen"} tens = {20:"twenty" , 30:"thirty" ...
534ecafa32488c85ea96f6c7368a68f3903fc0a5
hunse/nengo_spinnaker
/nengo_spinnaker/regions/region.py
1,075
3.546875
4
class Region(object): """Represents a region of memory.""" def sizeof(self, vertex_slice=None): # pragma : no cover """Get the size of the region in bytes.""" raise NotImplementedError def sizeof_padded(self, vertex_slice=None): """Get the size of the region in bytes when padded to...
d6bc4d7b875d10e316da2c8ceecc15266b0e0873
DK2K00/100DaysOfCode
/d28_quick_sort.py
855
4.15625
4
#Function to perform quick sort def quick_sort(arr): sort_help(arr,0,len(arr)-1) def sort_help(arr,first,last): if(first < last): splitpt = partition(arr,first,last) sort_help(arr,first,splitpt-1) sort_help(arr,splitpt+1,last) def partition(arr,first,last): pivot = arr[first] ...
7c9bbef730d063c41711019ad61fb17ceabaa956
sharazul/arthematic_exam_application
/arithmetic.py
2,392
4.28125
4
# write your code here import random import math def simple_operations(number1, number2, sign): if sign == '+': return number1 + number2 elif sign == '-': return number1 - number2 elif sign == '*': return number1 * number2 def calculate_square(number): return number * number ...
998c16791c7185748103efa98cf35cd0b786f906
xhachex/Robopi
/avoid-robot.py
1,341
3.578125
4
from gpiozero import Robot, DistanceSensor, LED from time import sleep # Variables: # Motors RobotLeftPlus = 4 RobotLeftMinus = 14 RobotRightPlus = 17 RobotRightMinus = 18 RobotFullSpeed = 1 # Sensor DistanceECHO = 23 DistanceTRIG = 24 DistanceMAX = 1 #DistanceTHRESHOLD = 0.2 # LEDs # GPIOzero def: robot = Robot(le...
bb2d8598158481675c7c7051f5457af43c2ef816
sourabh90/Udacity-Data-Analyst-Projects
/Project 4 - Data Wrangling with MongoDB/python_project/src/utils/audit_street_names.py
2,739
3.59375
4
import re from collections import defaultdict ### Regular Expression for a street name street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) expected_st_names = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road", "Highway", "Trail", "Parkway", "Commons"] str...
616ebefa6e201add2d7696c3f81a66ac2c52921e
kmsalah/pythonPractice
/knapsack.py
399
3.765625
4
def knapsack(W, wt, val, n): #base case if n ==0 or W==0: return 0 #if weight of nth item is more than knapcack capacity W, t #then item cant be included if wt[n-1] > W: return knapsack(W, wt, val, n-1) else: return max(val[n-1] + knapsack(W-wt[n-1], wt, val, n-1), knapsack(W,wt, val ,n-1)) val = [...
945605547656c6b5003545e75f642f7423a4e36d
githubweng/pythoncode
/py_example_oop_program.py
4,720
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 31 16:21:38 2017 @author: nocman """ #当我们定义一个class的时候,我们实际上就定义了一种数据类型。我们定义的数据类型和Python自带的数据类型 #判断一个变量的类型可以使用isinstance class Student(object): #Student,类名,通常大写开头的单词。object,表示该类是从哪个类继承下来的,通常没有合适的类就使用object类 #创建好Student类,就可以根据Student类创建出Student的实例,如:a=Student() #可以自由地给实例变量绑定...
f37e9e573e66106340c76a1280db38850e32e80d
PedroBernini/ipl-2021
/set_0/p0_2_2.py
450
3.9375
4
# Programa para calcular as raízes da expressão "ax2 + bx + c". a = 1 b = 2 c = 3 def getRoots(equation): delta = equation['b'] ** 2 - (4 * equation['a'] * equation['c']) x1 = (-equation['b'] + (delta) ** 0.5) / (2 * equation['a']) x2 = (-equation['b'] - (delta) ** 0.5) / (2 * equation['a']) if x1 == ...
a0b686e781859fde866d86c5f764314a558489e5
Hashizu/atcoder_work
/abc133/D/main.py
830
3.53125
4
#!/usr/bin/env python3 import sys def solve(N: int, A: "List[int]"): all_sum = sum(A) od_sum =sum([A[i*2] for i in range((N+1)//2)]) a = [] a1 = (od_sum - all_sum//2)*2 pre = a1 a.append(a1) for x in range(0,N-1): t = (A[x] - pre//2)*2 a.append(t) pre = t prin...
70c80dbc549a9ab9409d24ba488e6ff134a4ecf4
xiaoxue11/hank_practice
/Greedy/03_get_mim_cost.py
457
3.671875
4
""" Created on : 11:16 PM Author : Xue Zhang """ from collections import deque def get_minimum_cost(k, c): if len(c) <= k: return sum(c) c.sort() min_cost = 0 count = k j = 1 while c and count: min_cost += j * c.pop() count -= 1 if count == 0: j += ...
9e3fc16581816e18234c73857948fc4b68d68439
vivan-verma/Phython
/string_loops.py
184
3.71875
4
city = "DUBLIN" index_start = 0 index_end = 5 len_city = 6 while (index_start <= index_end ): print(city[index_start]) index_start = index_start + 1
26c81c5dbd79f9586a387edaf6a012d762e0f098
CodecoolMSC2016/python-pair-programming-exercises-2nd-tw-ghost-1
/years_module.py
376
3.875
4
import datetime def years(age): return def main(): name = str(input("Type your entire name: ")) age = int(input("Type your age: ")) now = datetime.datetime.now() yearofhundred = now.year - age + 100 print("Dear {}, ".format(name)) print("you will be 100 years old in {}".format(yearofhund...
f5431c079f2064875903666357d8402e95de9d8b
mmylll/FDSS_Algorithm
/leetcode/everyday/2020.12/1203.py
1,495
3.546875
4
import math class Solution: def countPrimes(self, n: int) -> int: cnt = 0 for i in range(2, n): d = int(math.sqrt(i)) flag = True for j in range(2, d+1): if i % j == 0: flag = False break if flag:...
1b917535d4f34d1a7ad6a8946fbfe89666d27a57
robertggovias/robertgovia.github.io
/python/cs241/w08/team_stretch.py
1,829
3.9375
4
class Time: def __init__(self): self._hours = 0 self._minutes=0 self._seconds=0 @property def hours_simple(self): if self._hours > 12: return self._hours -12 else: return self._hours @property def period(s...
e7720f46acd05c73a77b305d2377571a55eb6dc3
sigorilla/computational-mathematics
/numerical-linear/method-ferma.py
464
4.03125
4
from math import pow eps = 100 POW = 3 MIN = int(10e3) MAX = int(10e6) print("From ", MIN, " to ", MAX, ". Eps = ", eps) for x in list(range(MIN, MAX)): for y in list(range(MIN, MAX)): for z in list(range(MIN, MAX)): if (x != 0 and y != 0 and z != 0 and x < y): if ( abs(pow(x, PO...
f3af6830430c2b6ac708d33219d332d262355314
kumbharswativ/Core2Web
/Python/DailyFlash/01feb2020/MySolutions/program1.py
244
4.125
4
''' Write a Program to that prints series of odd numbers in reverse order from the limiting number entered by user. Input: 100 Output: 99 97 95 93 . . .. 1 ''' n=int(input("Inputs:")) for i in range(n,0,-1): if(i%2==1): print(i,end=" ")
69dac5e1b8fed379c5e37ff862fae4e6159771b7
simplymanas/python-learning
/ReturnTwoValues.py
1,238
4.1875
4
# You have a list. Each value from that list can be either a string or an integer. Your task here is to return two values. # The first one is a concatenation of all strings from the given list. The second one is a sum of all integers from the given list. # # Input: An array of strings ans integers # # Output: A list or...
605494eaf2f9581b56f298ecc19b892f3edd6a62
manpreetSingh1308/Python-programs
/cs even or odd.py
96
4.125
4
n=int(input('enter a no')) if n%2==0: print('it is even') else: print('it is odd')
dffa7b59f34168d5006581449c7e29bc9280992f
Mxt3usz/python_stuff
/Projects/ex_case.py
621
3.890625
4
def to_screaming_snake(s:str): string = "" for chars in s: if chars.islower(): string += chars if chars.isupper(): string += "_" string += chars return string.upper() print(to_screaming_snake("mySuperCoolFunction")) def to_camel(s:str): lower = s...
e167907b7e2d8c8f3171508cd454851f2bf5266f
GustasStankus/College-work
/yoda2.py
5,578
3.609375
4
def yoda(): print (""" |========================| | Good, Day Hmmmm Have | |========================| \ ____ \ _.' : `._ .-.'`. ; .'`.-. __ / : ___ ; /...
e6dc9edc7a4f48ac50906cccb631d6f389264a22
Stevens-Kevin-M/Pre-Work
/Python102PreWorkQuestions.py
1,708
4.46875
4
################################################### # 1 # Write a function to print "hello_USERNAME!" USERNAME # is the input of the function. # The first line of the code has been defined as below. # def hello_name(user_name): def hello_name(user_name): """Display a greeting to the user.""" print("hello_...
503edd2d60590fc3ece3d0cd02012f2fefbcfa46
HareshNasit/LeetCode
/Top Amazon Questions 2020-21/1047. Remove All Adjacent Duplicates In String.py
366
3.53125
4
def removeDuplicates(self, S: str) -> str: # Runtime: O(n) # Space: O(n - d) where d = num. of duplicates stack = [] for s in S: if len(stack) == 0: stack.append(s) elif stack[-1] == s: stack.pop() else: ...
946d569e6c28ee4b4b1c82a90110cb63d9dd6b82
cjh3630508/python_cookbook
/chapter3/s_3_6.py
842
3.6875
4
if __name__ == '__main__': print("-- 负数的数学运算 --") print("-- numpy 模块支持复数 --") print("-- cmath 模块支持复数计算 --") print() print("-- 使用 complex --") num = complex(3, 4) print("num={}".format(num)) print() print("-- 使用 j 表示负数 --") num = 3 + 4j print("num={}".format(num)) print(...
12525b1b86e171c125d75afb3b35ca0add3ae393
JackRossProjects/Computer-Science
/store.py
1,874
4.21875
4
class Store: def __init__(self, name, departments): self.name = name # Departments will be a list of strings self.departments = self.init_departments(departments) def __str__(self): # this will print out the name of the Store # as well as any departments that the Store ...
fd1cd13ce4aa9704738527ad8d25c2542cf83d0f
Gwyd10n/Smart_grid
/classes/house.py
1,059
3.859375
4
#!/usr/bin/env python # Gwydion Oostvogel, Sophie Schubert """ House class for smart grid. """ class House(object): def __init__(self, id, x, y, max_out): """ Initialize object with parameters. :param id: string :param x: int :param y: int :param max_out: float ...
7349d505008d3c04bef6079dfbc7dd8e72ab8d87
cvasani/SparkLearning
/Input/Notes/python_course/numbers/lessons/03.py
137
3.625
4
#!/usr/bin/env python3 sum = 1 + 2 difference = 100 - 1 new_number = sum + difference print(new_number) print(sum / sum) print(sum + 1)
0aaf267184536926f83f1ae8f907904c3eafdf45
ru57y34nn/Wi2018-Classroom
/students/ak-foster/Spring/Lesson02/spotify.py
599
3.640625
4
import pandas as pd # Catch raw song data as music variable music = pd.read_csv("featuresdf.csv") # Get Ed Sheeran songs by looping over list comprehension for track in (song for artist, song in zip(music.artists, music.name) if 'Sheeran' in artist): print(track) # High energy tracks (>0.8) def get_energy(cuttof...
200219595268f08e53f7fc6c7a0fd17b4e336f5f
gan3i/Python_Advanced
/DS_and_AT/GFG/Stack/sortstack.py
278
3.921875
4
from stack import Stack stack = Stack() stack.push(4) stack.push(6) stack.push(1) stack.push(10) stack.push(35) stack.print() print(stack) #stack.sort() #s= stack.sortted() s = sorted(stack)# after implementing the __iter__ print(s) # for i in stack.items(): # print(i)
03f16ae5cbbf29589a163355eb3245fb38313cb0
adrinerandrade/algoritmo-genetico
/cities.py
546
3.5625
4
from random import randint from location import Location # Cria uma matriz de cidades aleatórias class Cities: def __init__(self): self.count = 20 self.x = [] self.y = [] for i in range(self.count): self.x.append(randint(1, 10000) / 10000) self.y.append(randi...
d57a754c38d866d66c895146a292fcb99a499284
nnkkmto/practice-design-pattern-python
/iterator/example-python-2.py
864
4.09375
4
class Book: def __init__(self, name: str): self.name = name def get_name(self): return self.name class BookShelf: """ ConcreteAggregate """ def __init__(self, max_size: int): self.__books = [None for _ in range(max_size)] self.__last = 0 def __iter__(self...
e6c8220af3dd974957de4213dbfcddb8e7dc7811
motleytech/crackCoding
/RecursionAndDyn/powerset.py
870
4.125
4
'find powerset of a given sequence/set' def powerset(a): '''uses bit strings to create powerset''' la = list(a) pset = [] for x in range(2**len(la)): xx = bin(x)[2:] cset = [la[i] for i, y in enumerate(reversed(xx)) if y == '1'] pset.append(cset) return pset def powerset2(a...
28099cb1a2c029e9a2215c0cc1dbda9dd09e120e
bsbz/leetcode
/medium/findRepeatedDnaSequences.py
840
3.796875
4
''' All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. Exa...
5d7f1db6eb128e5de32309df13933ee73d334f4f
joshnankivel/joshnankivel.github.io
/learnpythonthehardway/ex32.py
1,686
4.625
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # ...
350723fce8de84823ac0ed290c862d3d387a2e06
BIGbadEL/Python_lab_2018-2019
/Lab9/task2.py
1,232
3.734375
4
import math class Vec: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __add__(self, other): return Vec(self.x + other.x, self.y + other.y, self.z + other.z) def __iadd__(self, other): return self + other def dot_product(self, other): ...
7935a31a8eb7c336fd5a95cd05ff15c2975f2bfd
nogueral/Full-Stack-Python-Codo-a-Codo
/Python/entrada_salida.py
201
3.78125
4
lado=int(input("Ingrese el lado del cuadrado: ")) superficie = lado*lado #print("La superficie es: " + superficie) #print("La superficie es: " + str(superficie)) print("La superficie es: ", superficie)
5b74a49b304a10a5dc48a6b6f9c84b1c1d4009c3
partho-maple/coding-interview-gym
/algoexpert.io/python/Zigzag_Traverse.py
990
3.5625
4
# Time O(n) | Space O(n) >> where n is the total number of elements in 2D array def zigzagTraverse(array): height = len(array) - 1 width = len(array[0]) - 1 result = [] row, col = 0, 0 goingDown = True while not isOutOfBound(height, width, row, col): result.append(array[row][col]) ...
3b3337898cd9bf34b09ba7752bdb6fcfbbe966f3
HanneWhitt/mancalazero
/mancala.py
9,301
3.84375
4
import numpy as np import warnings class MancalaBoard: ''' An object to represent a game of mancala, implementing board representations, legal moves, game termination/win conditions etc. Also facility for playing a game in console for debugging/fun :) Includes a few options on rules: 1) How ma...
c68f52983e470e49d7503ae654315fa60769cddc
sudeepgaddam/online-coding
/leetcode_python/253_meeting_rooms_ii.py
856
3.859375
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e # Before anything, sort the meeting room intervals based on start time. # Idea is to use min-heap to store ending times of meetings and if a meeting room can be # freed for next ...
2342436e01d420f1eaf8a55898dcb28fe26b76d1
Mekeda/CSCI-1300-Introduction-to-Programming
/Assignment 8/graphics_filters.py
14,338
3.671875
4
''' Graphics Filters By: Spencer Milbrandt Created: 10/25/13 Last Modified: 10/27/13 This program is used to take an image that is decided by the user in the graphics_main.py. From there it filters the image in a graphical window depending on the choice the user determined and will display 2 windows. One of the Or...
5f481ba9d4e89f1e06cbf7ce590b9b146f7465e1
lightbits/euler
/problem47.py
1,142
3.578125
4
# The first two consecutive numbers to have two distinct prime factors are: # 14 = 2 × 7 # 15 = 3 × 5 # The first three consecutive numbers to have three distinct prime factors are: # 644 = 2² × 7 × 23 # 645 = 3 × 5 × 43 # 646 = 2 × 17 × 19. # Find the first four consecutive integers to have four distinct prime fac...
46d4baf09c54e46041df7bc115cdf4c3891eca8a
Oblum1989/phytonTest
/search.py
326
3.6875
4
palabra = input("Ingresa la palabra que deseas encontrar: ").upper() cadena = input("Ingresa la cadena en donde deseas buscar: ").upper() encontrada = True inicio = 0 for ch in palabra: pos = cadena.find(ch, inicio) if pos < 0: encontrada = False break inicio = pos + 1 if encontrada: print("Si") else: print...
ea0af73d513206485e538bcee649f3ff3868abac
princecoker/codelagos-Python-Class-Assignment-2.0
/out of school assignment 3.py
2,448
4.46875
4
#This is a calculator to compute area of certain shapes #Algorithm #Collect name #Display Instruction #input the desired shape to be computed #calculate based on the input #calculation collects desired variable and produces answers #import math library to use pi import math name = str(input('\n what is y...
af7a690389919dbf2344931f629479883948c12d
TapendraBaduwal/Days_To_Hours
/streamlit.py
424
4.03125
4
import streamlit as st st.title("Number of Days to Hours") st.write("Simple calculation to convert days to hours") from days_to_units import days_to_units user_input=int(st.text_input("Enter number of days to convert in number of hours::")) total_hours=days_to_units(user_input) with st.form(key='my_form.'): days_to...
9cfe227837393c7eb276e20aed08a8803b4f5ab8
Anuroop-ag/Image-Processing
/Day4/prog2.py
482
3.515625
4
'''Write a program to detect a.Horizontal line b.vertical line''' import numpy as np import cv2 i1 = cv2.imread('hori_ver.jpg',0) sobelx = cv2.Sobel(i1,cv2.CV_64F,1,0,ksize=5) sobely = cv2.Sobel(i1,cv2.CV_64F,0,1,ksize=5) #########Detecting horizontal lines############### i2 = cv2.addWeighted(sobelx,0,sobely,1,0)...
00857ec9ef2b13c262f92aad9af0f9b9b19c71ad
thanaphon/FundamentalCS
/LAB/Oct12/2.py
2,276
4.65625
5
# -*- coding: utf-8 -*- """ TODO RECURSIVE vs ITERATIVE 1.1) เขียนฟังก์ชั่นจาก program specification ที่กำหนดให้ โดยใช้ iterative หรือ recursive programming styles (Write codes for a given program specification using iterative fn and recursive fn ) a) complete function iter_mul b) c...
f287b1051b667747a071c6fcdf0dc3181562af36
NikiDimov/SoftUni-Python-Basics
/first_steps_in_coding/fruit_market.py
503
3.6875
4
strawberry_price = float(input()) bananas_kg = float(input()) oranges_kg = float(input()) raspberries_kg = float(input()) strawberries_kg = float(input()) raspberries_price = strawberry_price / 2 oranges_price = raspberries_price - (raspberries_price * 0.4) bananas_price = raspberries_price - (raspberries_price * 0.8)...
d2a053ed390b114de922d0e8d50a6914115ec3ea
ogulcangumussoy/Python-Calismalarim
/Iterator-ve-Generatorler/Ornekler/ornek-generator-kullanim.py
324
3.671875
4
""" Generator kullanarak fibonacci serisini yazdırmak """ def fibonacci(): a=1 b=1 yield a #tek kullanımlık a yazıdırıldı. yield b #tek kullanımlık b yazıdırıldı. while True: a,b = b,a+b yield b for sayi in fibonacci(): if(sayi > 100000): break print(sayi)
2b887cd643b04ca7223b27c4c308a162de444bfb
KhAoS182/Programacion
/Primer trimestre/P2/p2ex2.py
181
3.921875
4
print ("Primero numero: ") a = float(input()) print ("Segundo numero: ") b = float(input()) if (a>b): print ("El numero mayor es ",a) else: print ("El numero mayor es ",b)
a843a4ef3956a92defeafeca2cebd6c10d33941b
miradouro/CursoEmVideo-Python
/aula007 - OPERADORES ARITMETICOS/ex010.py
148
3.75
4
n1 = float(input('Quantos reais você tem na carteira? R$ ')) print('Você consegue comprar {:.2f} dolares com seus {} reais!'.format(n1/3.27, n1))
29b85abb3c3a88052187eac05075e8802ed27faa
yuanyuanzijin/Offer-in-Python
/Chapter6_面试中的各项能力/54_二叉搜索树的第k大节点.py
691
3.5
4
## 题目描述:给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。 class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here if not pRoot or not k: return None self.result = [] self.midOrder(pRoot) if k > len(self.result): ...
ab1acd4d75b168d6eacf619cbf73ebf2664e2a70
mundostr/adimra_introprog21_mdq
/sem4/iterar_listas.py
1,607
4.3125
4
# Declaración de una matriz tipo lista, conteniendo números enteros listaEnteros = [10, 20, 50, 15, 12, 80, 33] # Accedemos a los items de una lista mediante un índice que SIEMPRE inicia en 0 print("Primer item:", listaEnteros[0]) # imprimirá 10 print("Tercer item:", listaEnteros[2]) # imprimirá 50 # De similar maner...
404ed688d2326e141c05c01ee000ccc33b60098e
Nudrat-boop/ComputingVCEYr11-SAC
/SACGUI.py
10,893
3.609375
4
#Function: Programming Calculator #Input: bits #Output: The bits' hexadecimal, binary,octadecomal and decimal values from tkinter import* from functools import partial from pathlib import Path window = Tk() window.title("Programming Calculator") window.geometry('1000x600') window.config(bg= "#114B5F") window.ico...
71080ea8f322dc8c05c50b16bac58afc75166b07
evtodorov/aerospace
/SciComputing with Python/lesson_04-24/2-prime.py
349
3.828125
4
import math n=1 primes = [] while len(primes)<10001: i = 2 check = True while (i<=math.sqrt(n)): if(n%i==0): check = False break i +=1 if(check): primes.append(n) n+=1 print primes[-1] #Put a number to check if it is prime: #65845484531 #65845484531 is a pr...
45b1a966bdaabb8c9b528d93f577f1d47b15439e
lucas54neves/python-curso
/ex014.py
111
3.796875
4
c = float(input('Temperatura em Celsius: ')) f = 9 * c / 5.0 + 32 print('{:.1f} C = {:.1f} F'.format(c, f))
695c5c602da97899b68d8d91d9559a7f01af29dc
valoto/python_trainning
/exec/16.py
565
3.8125
4
class Quadrado: __lado = 0 def get_lado(self): return self.__lado def set_lado(self, lado): self.__lado = lado def __init__(self, lado): self.__lado = lado def mudar_lado(self, lado): self.set_lado(lado) def retorna_lado(self): return self.get_lado() ...
98433a736b76f11221b48ab62b6c14b8b95be02c
ferconde87/HackerRank
/Python/textWrap.py
444
3.828125
4
import textwrap def wrap2(string, max_width): i = 0 j = max_width result = "" while i < len(string): result += string[i:j] result += "\n" i += max_width j += max_width return result def wrap(string, max_width): return textwrap.fill(string, width=max_width) if _...
20c3a8b14f21915461e8b531c91eb05e18a50481
P79N6A/python-example
/svm_sklearn.py
1,528
4
4
# -*- coding: utf-8 -*- print(__doc__) ''' 使用scikit-learn 线性SVM对数据两分类,并plot制图 ''' import numpy as np import matplotlib.pyplot as plt from sklearn import svm def loadDataSet(fileName): dataMat = []; labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = line.strip().split('\t') ...
02bcf00011e4f26f7e462c32cb07f9461126a6d3
solka-git/Python-Orion-basic-
/lectures/arguments_serialization/file_parser.py
352
3.546875
4
import argparse parser = argparse.ArgumentParser() parser.add_argument("--file", help="Please write path to file") parser.add_argument("--write", help="You can write something to file") args = parser.parse_args() if args.write: f = open(args.file, 'w') f.write(args.write) else: f = open(args.file, 'r') ...
0fe370b75eaba6a18b165a8060914b9f3777e4dd
hoshen20-meet/meet2018y1final-proj
/final_proj.py
4,331
4.03125
4
import turtle import random turtle.shape('blank') t = turtle.clone() t.shape('blank') words = ('entrepreneurship','meet','nature','global warming','animals','recycle','treehous','plastic', 'pollution', 'water', 'ground','toxic waist','grass','forest','enviornment','earthquake','extinct','climate') underscore_position =...
4e0a2e272cd0f06ffafe14a82429dc80a3764552
AengusDavies/Practicals
/prac_04/quick_picks.py
784
4.25
4
""" CP1404/CP5632 Practical Quick Picks Program """ import random NUMBER_OF_RANDOM_NUMBERS = 6 MINIMUM_NUMBER = 1 MAXIMUM_NUMBER = 45 def main(): """Program that creates a table of random numbers""" number_of_quick_picks = int(input("How many quick picks? ")) for i in range(number_of_quick_picks): ...
ed4a8ba5fee721d4bbf16ff962cf9a0c66e32a0e
lisphacker/leetcode
/python/arrays_and_strings/merge_sorted_array.py
1,071
4.03125
4
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ p1 = m - 1 p2 = n - 1 o = m + n - 1 while p1 >= 0 and p2 >= 0: if n...
f1030c30e6b0b4dfa27637fb1a2150b3c5aa4bea
MukeshLohar/Python
/__pycache__/Exercise File/question30.py
389
4.1875
4
# Define a function that can accept two strings as input and print the string with maximum length in console. # # If two strings have the same length, then the function should print al l strings line by line. def printstr(x,y): if len(x)> len(y): print(x) elif len(x) < len(y): print(y) el...
3ea9d451a50fc934cf680d0589c8157573be7f2f
GeonwooVincentKim/textRPG-2
/textRPG.py
13,249
3.546875
4
import random class Die: """Represents a single die.""" def __init__(self, sides=6): """Set the number of sides (defaults to six).""" self.sides = sides def roll(self): """Roll the die.""" return random.randint(1, self.sides) def roll3D6(): roll1 = Die(6).roll() ...
a2157216e38e1013064d0fe330ef85cb12828078
manisha2412/SimplePythonExercises
/exc3.py
345
4.125
4
""" Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) """ def str_len(s): count = 0 for c in s: count += 1 return count print str_len(u"String...
b2621c9c0430fd518718226a1aa0684d00e1b2b7
jeremyyew/tech-prep-jeremy.io
/code/topics/2-lists-dicts-and-strings/E13-roman-to-integer.py
872
3.859375
4
''' - For each roman numeral, if the current value is less than the next numeral's value, we are at a 'boundary' number e.g. 4, 9, 40, 90, etc. - If so, then instead of adding the value, we simply subtract that value. ''' class Solution: def romanToInt(self, s) -> int: res = 0 r_to_i = { ...
f06072fd3cd40aa5084153e204732abcf0337f4b
caropro/liao_study
/iteration.py
827
3.75
4
#coding=utf-8 l=(1,2,3,4,5,6,7,8,9) for i in l: print(i) l2={'a':1,'b':2,'c':3} for i in l2: print(i) #字典也可以迭代 for i in l2.values(): print(i) #可以直接循环数值 for i in l2.keys(): print(i) #可以直接循环关键字 for i,m in l2.items(): print(i,m) #可以用item来读关键字和数值 print('\n') from collections import Iterable isinstance('abc', Iterabl...
ba7f8f85ee028e58e3598b22bc0e128154d2960a
azizsaad/55-CodeWars-Problems
/codewars/7 kyu/list_filtering.py
162
3.703125
4
def filter_list(l): result = [] for i in l: if type(i) != str: result.append(i) return result print (filter_list([1,2,'a','b']))
6143bf1fbf17ee3c983089d65915df0fb0445170
flourido/python-bootcamp
/Week 2/random_num_game.py
1,069
4.09375
4
#import the random #import random #winning_number= random.randint(0,10) #print(winning_number) #num_guesses = 5 #user_won = False #while num_guesses != 0 and user_won == False: # user_guess = int(input("Enter your guess: ")) # if user_guess == winning_number: # print("Hey, you won!") # user_won = True # else: # ...
24f45a2689b10b5c6c5b0b78060a3d47d8c31f22
MohitHasija/Elevator
/visualiser.py
814
3.734375
4
from time import sleep class Visualizer(object): # Tests the elevator by running it and outputting statistics # This function assumes that floors have already been requested def visualize(self,Controller): # Output initial parameters and state of elevator print('Number of floors: {}'.forma...
a33131490f2b19eaec150287e11f0cc83debb5b3
sanpadhy/GITSOURCE
/src/Concepts/MATHPuzzles/DC248/solution.py
326
3.734375
4
# Find the maximum of two numbers without using any if-else statements, branching, or direct comparisons. def getMaximumOfTwo(a, b): c = a - b # you can have positive or negative k = (c >> 31) & 1 # check for whether the last bit is 1 or 0. return a - (c * k) print(getMaximumOfTwo(10, 15...
426f1fb9861c7873600e605137fa48931ba2cf94
bigdata202005/PythonProject
/Day03/FileIOEx06.py
783
4.0625
4
# 문제 # chunja2.txt 파일을 읽어서 각각의 줄을 파싱하여 # 다음과 같이 변경하여 chunja3.txt로 저장하시오!!! # 1. 天地玄黃(천지현황) : 하늘은 위에 있어 그 빛이 검고 땅은 아래 있어서 그 빛이 누르다. file = open('chunja2.txt', "r", encoding='utf-8') file2 = open('chunja3.txt', "w", encoding='utf-8') chunja_list = file.readlines() file.close() print(str(len(chunja_list)) + "줄 읽음") for...
81603ced0143981ee6540c89ee829ff663547c2f
v-erse/pythonreference
/Science Libraries/Numpy/arraymath.py
1,033
4.34375
4
import numpy as np print("Array Math:") # Basic mathematical functions operate on ndarrays in an elementwise fashion a = np.arange(10).reshape(2, 5) b = np.arange(10).reshape(2, 5) print(a + b) print(a*b) # We can use the dot function to find dot products of vectors and multiply # matrices (the matrixmultiplication.j...
d58aa81f7ba38185605b2c830c24c86886817a38
kriben/flightdata-norway
/flightinfo/position.py
742
3.640625
4
from math import sin, cos, radians, atan2, sqrt, asin class Position(object): def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude def compute_distance_to(self, p): # geometric mean from wikipeda earth_radius = 6371.0 # convert ...
43e490f695e0704010773853a347c0d884a4756d
javigon/bisp
/bif/building/impl/service.py
1,442
3.5
4
''' Service - Abstract representation of a service Created on Jan 18, 2013 @author: Javier Gonzalez ''' import abc class Service(object): __metaclass__ = abc.ABCMeta def __init__(self): self.roomID = 0 #Initialized self. wattage = 60.0 #Watts self.efficiency = 0 #...
c6e5f9c83461477540de30fb626b17f77cf480a7
si21lvi/tallerlogicaprogramacion
/14.py
210
3.765625
4
print("algoritmo que determina el tiempo de caída de un objeto que se suelta desde una altura h") vf=float(input("Digite la velocidad final de la caída")) t=(vf-0)/9.8 print("El tiempo que tarda es",t,"m/s")
fd1bf99761adacff94665319e6f36a27c5897a5b
evejweinberg/detourn
/WEEK2/tb2.py
899
3.5
4
import sys from textblob import TextBlob import codecs from collections import Counter # filedata = codecs.open(sys.argv[1], 'r', 'utf-8') # read or write, and what encoding, use utf-8 filedata = codecs.open('medium.txt', 'r', 'utf-8') text = filedata.read() blob = TextBlob(text) # get all the words blob.words #...
0e13835fb3ff84251111b5bc73220f00d8009d21
Zarwlad/coursera_python_hse
/week2/task35.py
137
3.890625
4
inputs = int(input()) even = 0 while inputs != 0: if inputs % 2 == 0: even = even + 1 inputs = int(input()) print(even)
324084f8a8c164493c8822c1c88289e78ee46e4a
weijchen/16lessonPython
/7-5.py
674
4.03125
4
# -*- coding: utf-8 -*- # PN: 16 lesson python - 9*9 chart, Created Mar, 2017 # Version 1.0 # KW: for, 9*9 # Link: # --------------------------------------------------- python 2 for i in range(1,10,3): for j in range(1,10): print('%d * %d = %d ' %(i, j, i*j), end="") print('%d * %d = %d ' %(i+1, j, (i+1)*j)...
4a415359b80c3db1d103dec068c53bdc8623b568
doan-david/Mechine-Learning
/methods/Newton_Simple.py
1,482
3.859375
4
""" Newton法求二元函数 """ import numpy as np from sympy import symbols, diff # 首先定义二维向量内的元素 x1 = symbols("x1") x2 = symbols("x2") def jacobian(f, x): """ 求函数一阶导 :param f: 原函数 :param x: 初始值 :return: 函数一阶导的值 """ grandient = np.array([diff(f, x1).subs(x1, x[0]).subs(x2, x[1]), diff(f, x2).subs(x...