blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
124a697551764ac140609c607ddb0db747908608 | sahilbatra158/python_hacktoberfest2021 | /sum_of_list.py | 191 | 3.75 | 4 | def _sum(arr):
sum=0
for i in arr:
sum = sum + i
return(sum)
arr=[]
arr = [12, 3, 4, 15]
n = len(arr)
ans = _sum(arr)
print ('Sum of the array is ', ans)
|
7994422872211763e72bb9c923738562654a2a32 | thiaagodev/Curso_Python_Mundo_2 | /PythonExercicios/ex062.py | 373 | 3.859375 | 4 | a = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
termos = 10
while termos != 0:
count = a
while count < a + (termos * r):
print(count, end=', ')
count += r
termos_a_mais = int(input('Quantos termos deseja mostrar a mais? '))
if termos_a_mais == 0:
t... |
4769512ba90a911b73214291fe3d6e69e6133dd7 | thiaagodev/Curso_Python_Mundo_2 | /PythonExercicios/ex067.py | 243 | 3.796875 | 4 | while True:
print('-'*30)
tabuada = int(input('Quer ver a tabuada de qual valor? '))
if tabuada < 0:
break
print('-'*30)
for i in range(0, 10):
print(f'{tabuada} x {i + 1:3} = {tabuada * (i + 1):3}')
|
eb85b9cb3a4b94f5cdfad7d46f55a037d810e9c7 | thiaagodev/Curso_Python_Mundo_2 | /PythonExercicios/ex070.py | 784 | 3.625 | 4 | total = quantidade_produtos_custam_mais_de_mil = 0
nome_produto_mais_barato = ''
produto_mais_barato = 9999999999999999
while True:
nome = input('Qual o nome do produto? ')
preco = float(input(f'Informe o preço de {nome}: '))
total += preco
if preco > 1000:
quantidade_produtos_custam_mais_de_m... |
3535c31fe2ac2ca56c95758045174cef7e30ce2a | thiaagodev/Curso_Python_Mundo_2 | /PythonExercicios/ex042.py | 775 | 4.09375 | 4 | print('Vou te perguntar o comprimento de 3 retas e dizer se é possível formar um triângulo')
reta1 = int(input('Digite a primeira reta: '))
reta2 = int(input('Digite a segunda reta: '))
reta3 = int(input('Digite a terceira reta: '))
if reta1 < reta2 + reta3 and reta2 < reta1 + reta3 and reta3 < reta1 + reta2:
pri... |
aba7a534fc2d59fb25967a801e17bc50539a01e8 | ItsSong/DaydayUp | /DayDayUpQ1.py | 150 | 3.53125 | 4 | #!/usr/bin/env python
#-*- coding = utf-8 -*-
dayup = pow(1.001,365)
daydown = pow(0.999,365)
print("向上{:.2f},向下{:.2f}".format(dayup,daydown)) |
5cccbf74749950ae23aa05c7ba85987396c7f6f8 | lovelj520/ToMyGirlfriend | /love/SimpleLove.py | 1,381 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/11/10 21:04
@Auth : feige-xu
@File :SimpleLove.py
@IDE :PyCharm
@Motto:ABC(Always Be Coding)
"""
import turtle
import time
# 画心形圆弧
def hart_arc():
for i in range(200):
turtle.right(1)
turtle.forward(2)
def move_pen_position(x, y... |
61dd27d6954cea99ce0a0b8f7d8fe56dee63f152 | reshavk/Python-Machine-Learning | /Data Preprocessing/Feature_importance_using_random_forest.py | 1,370 | 3.59375 | 4 | '''
Another useful approach to select relevant features from a dataset is to use random forest, an ensemble technique.
'''
#%%
import pandas as pd
df = pd.read_csv('/home/tenacious/Documents/ML and AI/Pyhton Machine Learning/Data Preprocessing/wine.data', header=None)
df.columns = ['Class label', 'Alcohol', 'Malic Aci... |
a0c451d844700bf1ebb022ec0a11d933bc4f3128 | muralimandula/PC_Java | /Day 1/Multi_Inheritance/Inherit.py | 1,162 | 4.09375 | 4 | class Cycle(object):
def __init__(self,a):
self.a = a
print("Im from Grandfather's, Im ",a)
# Bicycle inherits Cycle(contains: class Cycle[Inherited],
# variable a[from Cycle], using a constructor call Cycle.__init__(self, a)
# ... |
fa6453839ae9aecbe541d8ff94e3a10dbb1f2db6 | etienne-monier/inpystem | /inpystem/tests/tools/test_misc.py | 1,692 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import unittest
from ...tools import misc
class Test_misc(unittest.TestCase):
def test_toslice(self):
"""
"""
# Case 5:
s = misc.toslice('5:')
self.assertEqual(s.start, 5)
self.assertIsNone(s.stop)
self.assertIsNone(s.step)
... |
801600570eda9ad5b961c215cb241da85f7cb4dd | maverick51/game-of-sticks | /game_of_sticks.py | 3,633 | 4.1875 | 4 | class Sticks (object):
"""This class keeps track of the number of sticks and allows access to the number."""
total_sticks = 0
def __init__(self, number_of_sticks):
"""Initializes the object with the number of sticks."""
self.total_sticks = number_of_sticks
def get_number_of_sticks(self... |
3b433f9785c0aaf5cd6c3ca808810dbd9620de23 | wes1350/Dominos | /dominos/classes/Domino.py | 1,670 | 3.890625 | 4 | """A class representing a single domino."""
class Domino:
def __init__(self, big_end, small_end):
if big_end < small_end:
raise ValueError("Must pass in big end of Domino first")
self.ends = (big_end, small_end)
self.coordinates = None
self.is_spinner = False
sel... |
d3e395359dbfeb3583c42dec0b5b0e384c40cbba | IUIUN/The-Best-Time-Is-Now | /1282. Group the People Given the Group Size They Belong To.py | 851 | 3.53125 | 4 |
def groupThePeople(groupSizes):
res = []
for size in range(1, max(groupSizes) + 1 ):
temp = []
for i in range(len(groupSizes)):
if groupSizes[i] == size and len(temp) < size:
temp += [i]
elif groupSizes[i] == size and len(temp)==size:
res ... |
4b7e2a8dac1c08586c0cf2982f371d137287fef5 | IUIUN/The-Best-Time-Is-Now | /230. Kth Smallest Element in a BST.py | 973 | 3.625 | 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 kthSmallest(self, root: TreeNode, k: int) -> int:
self.k = k
self.res = None
self.helper(root)
return... |
23af85ea1d2e28672df43c39c6562bc4d9b9df41 | IUIUN/The-Best-Time-Is-Now | /139. Word Break.py | 379 | 3.875 | 4 |
def wordBreak(s, wordDict):
return dfs(s, wordDict)
def dfs(s, wordDict):
for word in wordDict:
if not s:
return True
elif s.startswith(word):
return dfs(s[len(word):], wordDict)
continue
return False
if __name__ == "__main__":
s = "cars"
wor... |
6f698c5793d4363379520899de37fb4151fc4041 | IUIUN/The-Best-Time-Is-Now | /138. Copy List with Random Pointer.py | 1,538 | 3.671875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return
/... |
261fc50a447035dcaa064b2fdd46c78be8b7ad25 | IUIUN/The-Best-Time-Is-Now | /Nutanix1.py | 574 | 3.53125 | 4 | def countWays(are, n):
pos = [0 for i in range(n)]
p = 0
# for loop for saving the positions
# of all 1s
for i in range(n):
if (arr[i] == 1):
pos[p] = i + 1
p += 1
# If array contains only 0s
if (p == 0):
return 0
ways = 1
for ... |
c451f37b2016ec1ad6b073a5bae922a98c72e270 | RiverEngineer2018/CSEE5590PythonSPring2018 | /Source Code/Lab3 Q3.py | 2,249 | 4.34375 | 4 | #Don Baker
#Comp-Sci 5590
#Lab 3, Question 3
#Take an Input file. Use the simple approach below to summarize a text file:
#- Read the file
#- Using Lemmatization, apply lemmatization on the words
#- Apply the bigram on the text
#- Calculate the word frequency (bi-gram frequency) of the words (bi-grams)
#- Cho... |
6afa503b45287578dc0a98f6110d3d7a2fc72742 | jsomers/project-euler | /pell.py | 1,051 | 3.78125 | 4 | """Compute solutions to the diophantine Pell equation x^2-D*y^2=1."""
import itertools
def pell (D):
"""Return the smallest integer set solving Pell equation
x^2-D*y^2=1 where x, D and y are positive integers. If there are no
solution (D is a square), return None.
>>> pell(3)
(2, 1)"""
a0 = i... |
201f20817f32c407ab4c3b274628e9f55c4e6b47 | jsomers/project-euler | /23.py | 1,375 | 3.796875 | 4 | # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
from math import ceil
from time import time
start = time()
''' Used to build the abundant numbers
def half(n):
return int(ceil(n/2 + 1))
def divisors(n):
div_sum = 0
divisor_count = 0
for i in range(1, half(n)):... |
39e5134c58db23cb3b1b1b148228743970193345 | jsomers/project-euler | /21.py | 477 | 3.65625 | 4 | from time import time
from math import ceil
start = time()
def half(n):
return int(ceil(n/2 + 1))
def divisors(n):
div_sum = 0
divisor_count = 0
for i in range(1, half(n)):
if (float(n)/i) % 1 == 0:
div_sum += i
return div_sum
pairsum = 0
for a in range(2, 10000, 2):
b = divisors(a)
t = divisors(b)
i... |
49007104a978b21ad305c9ae13413da0dccd7e77 | noy20-meet/meet2018y1lab4 | /sorter.py | 228 | 4.375 | 4 | bin1="apples"
bin2="oranges"
bin3="olives"
new_fruit = input('What fruit am I sorting?')
if new_fruit== bin1:
print('bin 1')
elif new_fruit== bin2:
print('bin 2')
else:
print('Error! I do not recognise this fruit!')
|
ccb8959205acfbe224aebdab1dff1c921aaef448 | YSAnirudh/Machine-Learning | /Fuzzy/code1.py | 3,590 | 3.796875 | 4 | ####Implementation of fuzzy logic
#####Finding the range of the inputs
import pandas as pd
import numpy as np
#####There are the fuzzy sets which we have used for this program
vector = [[-1,-0.66,-0.33],[-0.66,-0.33,0],[-0.33,0,0.15],[0,0.15,0.33],[0.15,0.33,0.45],[0.33,0.45,0.75],[0.45,0.75,1]]
FAM = [[-0.75,-0.75... |
489a52968abbde58836596d36cade48229e7fbe4 | fanhk/aizuoj | /pintia/dsa/MaxSubArraySumOnline.py | 338 | 3.6875 | 4 | def max_subarray_sum(array, n):
this_sum = max_sum = 0
for i in range(n):
this_sum += array[i]
if this_sum > max_sum:
max_sum = this_sum
elif this_sum < 0:
this_sum = 0
return max_sum
n = eval(input())
arr = [eval(x) for x in input().split()]
print(max_suba... |
87ff17d9be57a554a8d58919310a29e6d362dc87 | fanhk/aizuoj | /ITP1/Rectangle.py | 126 | 3.65625 | 4 | a, b = input().split()
a = eval(a)
b = eval(b)
area = a * b
perimeter = 2 * (a + b)
print(str(area) + " " + str(perimeter))
|
6f0779320edd18fbc6c19c4d2bfba85c188d1f68 | Cy1614/Dijkstra-Project_1 | /Project_1.py | 9,179 | 3.5 | 4 | import sys
import numpy as np
import math as ma
import csv
def Dijkst(ist,isp,wei):
# Dijkstra algorithm for shortest path in a graph
# ist: index of starting node
# isp: index of stopping node
# wei: weight matrix
# exception handling (start = stop)
if (ist == isp):
shpath = ... |
f722960dfeb6a33c3e0819cf409536a55b853286 | anoukruhaak/TaxCalcNL | /tax_calc.py | 1,251 | 3.859375 | 4 | def taxes_payable(inc):
low_box = 0.36
mid_box = 0.42
high_box = 0.52
limit_low = 19645
limit_high = 56531
income = inc - 2000
taxes = 0
if income >= limit_high:
taxes += (income - limit_high) * high_box + low_box * limit_low + mid_box * (limit_high - limit_low)
elif income ... |
ed6f6da350b48cde11a0e7952aad238c590cca74 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_brute.py | 1,329 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces ar... |
d7830b9e24ae1feeff3e2e7fce5b3db531adab73 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/longest_palin_substring_topDownMemo.py | 1,591 | 4.15625 | 4 |
"""
Given a string, find the length of its Longest Palindromic Substring (LPS).
In a palindromic string, elements read the same backward and forward.
Example 1:
Input: "abdbca"
Output: 3
Explanation: LPS is "bdb".
Example 2:
Input: = "cddpd"
Output: 3
Explanation: LPS is "dpd".
Example 3:
Input: = "pqr"
Out... |
e5d39b3d90a337a44a5fa09fd5107616166d3a2c | mkoryor/Python | /coding patterns/bitwise xor/single_number.py | 401 | 3.9375 | 4 |
"""
[E] In a non-empty array of integers, every number appears twice except for one,
find that single number.
Example 1:
Input: 1, 4, 2, 1, 3, 2, 3
Output: 4
Example 2:
Input: 7, 9, 7
Output: 9
"""
# Time: O(n) Space: O(1)
def find_single_number(arr):
num = 0
for i in arr:
num ^= i
return num
def m... |
a0b41f2d8a2a446a55c1cf9d7a7edb60d370bf56 | mkoryor/Python | /coding patterns/modified binary search/ceiling_number_similar_prob.py | 1,302 | 4 | 4 |
"""
[M] Given an array of numbers sorted in ascending order, find the floor of a given number
‘key’. The floor of the ‘key’ will be the biggest element in the given array smaller
than or equal to the ‘key’
Write a function to return the index of the floor of the ‘key’.
If there isn’t a floor, return -1.
Examp... |
70e986eb5a878af5da52aa207deb0f4fcab29f46 | mkoryor/Python | /coding patterns/top 'k' elements/top_k_frequent_numbers.py | 1,348 | 4 | 4 |
"""
[M] Given an unsorted array of numbers, find the top ‘K’
frequently occurring numbers in it.
Example 1:
Input: [1, 3, 5, 12, 11, 12, 11], K = 2
Output: [12, 11]
Explanation: Both '11' and '12' apeared twice.
Example 2:
Input: [5, 12, 11, 3, 11], K = 2
Output: [11, 5] or [11, 12] or [11, 3]
Explanation: Only ... |
6ae5ceb37e2ac89ec327baee964e560fe8b1c0b4 | mkoryor/Python | /coding patterns/top 'k' elements/k_closest_numbers_two_pointers.py | 1,728 | 3.84375 | 4 |
"""
[M] Given a sorted number array and two integers ‘K’ and ‘X’, find ‘K’
closest numbers to ‘X’ in the array. Return the numbers in the sorted order.
‘X’ is not necessarily present in the array.
Example 1:
Input: [5, 6, 7, 8, 9], K = 3, X = 7
Output: [6, 7, 8]
Example 2:
Input: [2, 4, 5, 6, 9], K = 3, X = 6
... |
027f1de2e737fdc5556c86a83f0e7248c2812934 | mkoryor/Python | /coding patterns/subsets/string_permutation.py | 1,143 | 4.1875 | 4 |
"""
[M] Given a string, find all of its permutations preserving the character
sequence but changing case.
Example 1:
Input: "ad52"
Output: "ad52", "Ad52", "aD52", "AD52"
Example 2:
Input: "ab7c"
Output: "ab7c", "Ab7c", "aB7c", "AB7c", "ab7C", "Ab7C", "aB7C", "AB7C"
"""
# Time: O(N * 2^n) Space: O(N * 2^n)
de... |
2c713bda8945104526d6784acdced81ae0681ad4 | mkoryor/Python | /coding patterns/modified binary search/bitonic_array_maximum.py | 957 | 4.1875 | 4 |
"""
[E] Find the maximum value in a given Bitonic array. An array is
considered bitonic if it is monotonically increasing and then
monotonically decreasing. Monotonically increasing or decreasing means
that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explan... |
2c758b4cfbc3b715578c8df5aa164742061529e3 | mkoryor/Python | /coding patterns/dynamic programming/fibonacci_numbers/house_thief_bottomUpTabu_optimize.py | 693 | 3.953125 | 4 |
"""
Given a number array representing the wealth of ‘n’ houses,
determine the maximum amount of money the thief can steal without alerting
the security system.
Example 1:
Input: {2, 5, 1, 3, 6, 2, 4}
Output: 15
Explanation: The thief should steal from houses 5 + 6 + 4
Input: {2, 10, 14, 8, 1}
Output: 18
Explana... |
c76f2d054fdbc1401a78a040eeb2277a5b226795 | mkoryor/Python | /coding patterns/two pointers/sortedarr_square.py | 652 | 3.71875 | 4 |
"""
[E] Given a sorted array, create a new array containing squares of all the
number of the input array in the sorted order.
Input: [-2, -1, 0, 2, 3]
Output: [0, 1, 4, 4, 9]
"""
# Time: O(N) Space: O(n)
def make_squares(arr):
n = len(arr)
squares = [0 for x in range(n)]
highestSquareIdx = n - 1
left, r... |
83407eac0a8aaa8a71aa1631bbd17f5818dc877c | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/subsequence_pattern_match_bottomUpTabu.py | 1,261 | 4.15625 | 4 |
"""
Given a string and a pattern, write a method to count the number of
times the pattern appears in the string as a subsequence.
Example 1: Input: string: “baxmx”, pattern: “ax”
Output: 2
Explanation: {baxmx, baxmx}.
Example 2:
Input: string: “tomorrow”, pattern: “tor”
Output: 4
Explanation: Following are the fo... |
b2ae19549528e82aaec418c4bb32868ac9272b73 | mkoryor/Python | /binary trees/diameterBT.py | 1,697 | 4.3125 | 4 |
# A binary tree Node
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = self.right = None
# utility class to pass height object
class Height:
def __init(self):
self.h = 0
# Optimised recursive function to find di... |
f6e2485cdea43a0eb8c9b2cf97a26f92f25446a1 | mkoryor/Python | /coding patterns/subsets/structure_unique_BST.py | 1,594 | 3.8125 | 4 |
"""
[H] Structurally Unique Binary Search Trees (hard) #
Given a number ‘n’, write a function to return all structurally unique Binary
Search Trees (BST) that can store values 1 to ‘n’?
Example 1:
Input: 2
Output: List containing root nodes of all structurally unique BSTs.
Explanation: Here are the 2 structurally ... |
d397c69f3ac130a043b80ec03f1b94f52ee5d3d3 | mkoryor/Python | /coding patterns/dynamic programming/unbounded_knapsack/coin_change_topDownMemo.py | 1,436 | 3.859375 | 4 |
"""
Given an infinite supply of ‘n’ coin denominations and a total money amount,
we are asked to find the total number of distinct ways to make up that amount.
Example:
Denominations: {1,2,3}
Total amount: 5
Output: 5
Explanation: There are five ways to make the change for '5', here are those ways:
1. {1,1,1,1,... |
f94bb441ad7d7eb8177296ebafdbad092a96f30a | mkoryor/Python | /backtracking and recursion/power.py | 757 | 4 | 4 |
'''
(Recursion): Power Function: Implement a function to
calculate xn. Both x and n can be positive/negative and overflow doesn't happen.
Try doing it in O(log(n)) time. '''
def positivePower(x, power):
if power == 0:
return 1
if power == 1:
return x
halfpower = positivePower(x... |
e4aaffbaf8eca78790ac16fb5fd93392cd1e77fa | mkoryor/Python | /graph/floyd_warshall.py | 1,483 | 3.921875 | 4 |
from pprint import pprint
INF = float('Inf')
def floyd_warshall(graph):
nodes = graph.keys()
""" distance[][] will be the output matrix that will finally
have the shortest distances between every pair of vertices """
distance = {}
for n in nodes:
distance[n] = {}
for k... |
b6c8c4750c8feca766f8d199428d11f6d5410ec6 | mkoryor/Python | /binary trees/inorder_traversal_iterative.py | 657 | 4.15625 | 4 |
# Iterative function to perform in-order traversal of the tree
def inorderIterative(root):
# create an empty stack
stack = deque()
# start from root node (set current node to root node)
curr = root
# if current node is None and stack is also empty, we're done
while stack or curr:
# if current node is not... |
2f64b0b7b9e2b65d23da392a6d6c1e361e117aa9 | mkoryor/Python | /sorting algorithms/quickSort.py | 1,224 | 3.96875 | 4 |
import random
class Quicksort(object):
def __init__(self, data):
self.__data = data
def sort(self):
self.quicksort(0, len(self.__data) - 1)
return self.__data
def quicksort(self, start, end):
if end == start:
return
data = self.__data
... |
e968385720aebfa80a902d56938b23145a0c7e8c | mkoryor/Python | /coding patterns/dynamic programming/knapsack_and_fib/equal_subset_sum_partition_brute_force.py | 1,460 | 4.03125 | 4 |
"""
Given a set of positive numbers, find if we can partition it into two subsets
such that the sum of elements in both the subsets is equal.
Example 1: #
Input: {1, 2, 3, 4}
Output: True
Explanation: The given set can be partitioned into two subsets with equal sum: {1, 4} & {2, 3}
Example 2: #
Input: {1, 1, 3, ... |
f3bd0efb053cca0be4fbf3454d6ffde63a323d00 | mkoryor/Python | /arrays & strings/rotateMatrixby90.py | 608 | 3.96875 | 4 |
def rotate(mat, start, end):
curr = 0
while curr + start < end:
temp = mat[start][start + curr] # save top
mat[start][start + curr] = mat[end - curr][start] # left to top
mat[end - curr][start] = mat[end][end - curr] # bottom to top
mat[end][end - curr] = mat[start + curr][en... |
40797649346fc0fe98d4cf76ce816f9ad8ff2ce3 | mkoryor/Python | /coding patterns/subsets/unique_generalized_abbreviations.py | 2,035 | 3.78125 | 4 |
"""
[H] Given a word, write a function to generate all of its unique generalized abbreviations.
Generalized abbreviation of a word can be generated by replacing each substring of the word
by the count of characters in the substring. Take the example of “ab” which has four
substrings: “”, “a”, “b”, and “ab”. Afte... |
f870ada9c0aafbad7ad5433a2aaa430a771afe85 | mkoryor/Python | /coding patterns/miscellaneous/k_smallest_number_BF_using_sorting.py | 1,008 | 4.09375 | 4 |
"""
[H] Given an unsorted array of numbers, find Kth smallest number in it.
Please note that it is the Kth smallest number in the sorted order, not the Kth distinct element.
Example 1:
Input: [1, 5, 12, 2, 11, 5], K = 3
Output: 5
Explanation: The 3rd smallest number is '5', as the first two smaller numbers are ... |
a3040c92d37501e9b9e098ff672052b670012c3f | mkoryor/Python | /coding patterns/cyclic sort/missing_number.py | 769 | 3.890625 | 4 |
"""
[E] We are given an array containing 'n' distinct numbers taken from the range 0 to ‘n’.
Since the array has only 'n' numbers out of the total 'n+1' numbers, find the missing number.
Example 1:
Input: [4, 0, 3, 1]
Output: 2
"""
# Time: O(n) + O(n -1) + O(n) -> O(n) Space: O(1)
def find_missing_number(nums):... |
68db251c87295d02c092b7e521524f134b55d0a8 | mkoryor/Python | /coding patterns/dynamic programming/palindromic_subsequence/palindromic_partitioning_bottomUpTabu.py | 1,836 | 4.15625 | 4 |
"""
Given a string, we want to cut it into pieces such that each piece is a palindrome. Write a function to return the minimum number of cuts needed.
Example 1:
Input: "abdbca"
Output: 3
Explanation: Palindrome pieces are "a", "bdb", "c", "a".
Example 2:
Input: = "cddpd"
Output: 2
Explanation: Palindrome pieces ar... |
4610f706e3e3a344bd2c89b5566f5b5c9fa16cf6 | mkoryor/Python | /binary search/findPeak.py | 1,071 | 3.9375 | 4 |
'''
(Binary Special Tricks Find Peaks) Search for a Peak: A peak element in array
A is an A[i] where its adjacent elements are less than A[i]. So, A[i - 1] < A[i]
and A[i + 1] < A[i].Assume there are no duplicates. Also, assume that A[-1] and
A[length] are negative infinity (-inf). So A[0] can be a peak if A[1] ... |
8777c96db874f1a8f37b00492575883f933d4e6f | mkoryor/Python | /binary search/floorSquareRoot.py | 818 | 3.96875 | 4 |
'''(Binary Search Special Trick Square Root [E]): Find the square root of an
integer X. For example, squareRoot(4) = 2. It is ok to find the integer floor
of the square root. So squareRoot(5) or squareRoot(8) can also return 2.
squareRoot(9) will return 3.'''
def square(x):
return x * x
def floorSquareRoot(... |
db3da546c26b6d3c430ca62e18a2fc2127d76e60 | mkoryor/Python | /coding patterns/dynamic programming/knapsack_and_fib/count_subset_sum_bruteforce.py | 1,325 | 4.15625 | 4 |
"""
Given a set of positive numbers, find the total number of subsets whose sum
is equal to a given number ‘S’.
Example 1: #
Input: {1, 1, 2, 3}, S=4
Output: 3
The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3}
Note that we have two similar sets {1, 3}, because we have two '1' in our input.... |
1f567c01031206e9cd45c02f0590a36a0affde12 | mkoryor/Python | /coding patterns/dynamic programming/longest_common_substring/longest_common_substring_topDownMemo.py | 1,204 | 4.125 | 4 |
"""
Given two strings ‘s1’ and ‘s2’, find the length of the longest substring which
is common in both the strings.
Example 1:
Input: s1 = "abdca"
s2 = "cbda"
Output: 2
Explanation: The longest common substring is "bd".
Example 2:
Input: s1 = "passport"
s2 = "ppsspt"
Output: 3
Explanation: The lon... |
93e0bfcf6a17fcbeafca3b7af962534000140c58 | mkoryor/Python | /arrays & strings/unsortedSub.py | 1,227 | 4.09375 | 4 |
''' (Traverse Both Ends [M]): Given an array of integers, find the continuous
subarray, which when sorted, results in the entire array being sorted.For example:
A = [0,2,3,1,8,6,9], result is the subarray [2,3,1,8,6]'''
def unsorted_sub(arr):
start = 0
end = len(arr) - 1
# find start of dip
wh... |
14d7ff92a104c92367c537893d85fbddbf481b73 | mkoryor/Python | /coding patterns/two pointers/remove_instance_of_key.py | 741 | 4 | 4 |
"""
[E] Given an unsorted array of numbers and a target ‘key’, remove all instances of ‘key’
in-place and return the new length of the array.
Input: [3, 2, 3, 6, 3, 10, 9, 3], Key=3
Output: 4
Explanation: The first four elements after removing every 'Key' will be [2, 6, 10, 9].
"""
# Time: O(N) Space: O(1)
def ... |
10866e76593aaa67eeffe481160aa71e002955b6 | mkoryor/Python | /coding patterns/tree Depth First Search/path_with_max_sum.py | 2,477 | 4.09375 | 4 |
"""
Find the path with the maximum sum in a given binary tree.
Write a function that returns the maximum sum. A path can be defined
as a sequence of nodes between any two nodes and doesn’t necessarily pass through the root.
tree:
1
2 3
4 5 6
Output: 16
Explanation: The path with maximum s... |
6dbb44e147405710f942350d732c2ec4c0d12a4f | kukiracle/curso_python | /python1-22/seccion5-7/50DiccionariosPARTE2.py | 900 | 4.15625 | 4 | # UN DICCIONARIO TIENE (KEY, VALUE)como un diccionario
#es como un jason :V
#para entrar a los elementos con la key'IDE'
diccionario={
'IDE':'integrated develoment eviroment',
'OOP':'Object Oriented Programming',
'DBMS':'Database Management System'
}
#RECCORER LOS ELEMENTOS
for termino,valor in dic... |
2276a5f65e020ff5fb2c96720e8a58166f949ead | kukiracle/curso_python | /python1-22/seccion5-7/42continue EN PYTHON.py | 135 | 3.75 | 4 | for i in range(6):
if(i%2==0):print(f'valor: {i}')
for c in range(6):
if c%2!=0:
continue
print(f'valor: {c}') |
39302bbeef2a7fd905c28c74b88e6bd24c3eaa22 | kukiracle/curso_python | /python1-22/seccion1-4/17 ejerciciocalificatudia.py | 81 | 3.796875 | 4 | numero1=int(input("como estuvo tu dia"))
print("mi dia estuvo de : ",numero1)
|
d10a1720f67aaba0d14fbeef032e7b06a87e313a | poltorres7/M-todoRLE | /RLEv1.py | 8,768 | 3.734375 | 4 | #!/usr/bin/python
#importamos la libreria necesaria para usar arreglos
import numpy as np
#variables de nuestros arreglos globales
arr=""
arr2=[]
arr4=[]
#####################################################################
# #
# #
# #
# FUNCION PARA LEER EL ARCHI... |
55ca11b639fcca51fa889ef694e84d0eb61a14bd | yutaka20111005/flask-web2 | /instance/create_booktable.py | 575 | 3.953125 | 4 | import sqlite3
DROP_TABLE = "DROP TABLE IF EXISTS books"
CREATE_TABLE='''CREATE TABLE books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author TEXT,
cover TEXT DEFAULT 'book.png')'''
INSERT_TABLE='''INSERT INTO books(id,title,author,cover)
VALUES(1,'ヤン・フスの宗教改革','佐藤優','book.png')
'''
SELECT_TABLE="SELECT * FR... |
3c460bbf476da3f469991769fc9faf424d530982 | schari98/DataScience | /Numpy.py | 912 | 3.734375 | 4 | import numpy as np
mylist = ['a','b','c']
x = np.array(mylist)
print(mylist,x)
x= np.arange(1,20,2)
print('Array ',x,'Length ',len(x))
y = x.reshape(2,5)
print('Reshaped ',y)
print('Slicing')
print (y[:,3])
print (y[1:2,:])
# increment x by 1
x = x +1
print ('Incremented ',x)
# increment selected indices
x[1:5]... |
e44627da7e4bd3e4d75c55396b8cf6536f7b9461 | adamomfg/lpthw | /ex19ec3.py | 641 | 3.984375 | 4 | #!/usr/bin/python
def pigLatin(word):
vowels = ("a", "e", "i", "o", "u", "y")
if word[0].lower() in vowels or word == "the" or word < 3:
print word
elif word[-1] in ('.', ',', '?', '!'):
print '%s%s' % (word[1:-1], 'ay')
else:
print '%s%s' % (word[1:], 'ay')
pigLatin('Adam')
pigLatin('derp')
s ... |
217567ab61ce376d78ca6c3fe04ac4428f6ad46a | adamomfg/lpthw | /ex15ec4.py | 294 | 4 | 4 | #!/usr/bin/python
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
print "Worked as before, but never asked me for input after giving it the name of the file as the first argument."
|
521bf6681e29f70c8bcf05fa8c01655f33925bfb | adamomfg/lpthw | /ex5ec4.py | 544 | 4.03125 | 4 | units = raw_input('What unit do you want to convert from? ')
if units.startswith('in'):
factor = 0.39
other_unit = 'centimeters'
elif units.startswith('c'):
factor = 2.54
other_unit = 'inches'
elif units.startswith('pou') or units.startswith('lbs'):
factor = 2.20
other_unit = 'kilos. you drug dealer'
elif u... |
adf515163aad1d273839c8c6ed2ca2d8503dfb9b | adamomfg/lpthw | /ex15ec1.py | 1,187 | 4.59375 | 5 | #!/usr/bin/python
# from the sys module, import the argv module
from sys import argv
# Assign the script and filename variables to argv. argv is a list of
# command lne parameters passed to a python script, with argv[0] being the
# script name.
script, filename = argv
# assign the txt variable to the instance of o... |
a37f2b989503964fdb67e50897dbaaec431a8ec0 | nickarad/my-pycrypt | /main.py | 6,992 | 3.703125 | 4 | from Tkinter import *
import os
import method_3
class ADialog:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="What do you want to do?").pack()
b = Button(top, text="Encrypt a file", command=self.encrypt)
b.pack(pady=5)
... |
4c62bb9cb0b54321712d135e82de951aa797d16e | erizocosmico/Project-Euler-Solved-Problems | /Problem 22/euler22.py | 742 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_name_chars_score(name, chars):
score = 0
for char in name:
score += chars[char]
return score
def main():
abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'... |
d2687186d15e492089550a4603376d6324339e47 | DastanB/BF-Django | /week1/hackerrank/easy/01.py | 74 | 3.578125 | 4 | a = int(input())
b = int(input())
print(a+b)
print(float(a-b))
print(a*b) |
d3de8ea37150484370eae5caa98a5a682447de5a | YeisonfabianSantos/Metodo-Hibrido-para-buscar-raices | /metodo_hibrido.py | 864 | 3.53125 | 4 | # Metodo de Brent-Dekker
# autor: Yeison Santos
# codigo para resolver ecuaciones algebraicas
import numpy as np
import matplotlib.pyplot as plt
import math as m
x=np.linspace(0,9,100)
plt.plot(x,np.cos(x)**5+60*np.sin(3*x),x,x**2) # graficamos la funcion ha resolver
# Reescribimos la funcion ... |
6f1bdfd2c180a967f8f6bef2dc2f7f41bc296be7 | cVijay91/PythonVenture | /Dict_inbuit_function.py | 737 | 4.03125 | 4 | d={"pen":"kalam","gold":"sona","diamond":"heera","silver":"chandi","list":[1,2,3,4,6]}
print(d.items()) # item built in fuction// return pair of key and values
print(d.keys()) # .keys built in function //return the list of keys of dictionery
d.update({"mine":"mera"}) # update built in... |
652af34fe3a8ce59b5715e64da8859c430a13910 | ubermelon/Exercise_Restaurant | /restaurant-ratings.py | 734 | 3.875 | 4 | # your code goes here
import sys
filename = sys.argv[1]
ratings_dictionary = {}
for list_of_restaurant in open(filename): # this pulls data from the file
list_of_restaurant = list_of_restaurant.rstrip() # this strips the \n from the end of the line
restaurant_name, ratings = list_of_restaurant.split(":") # this spli... |
b262b83cedd0a59cae8e08a723db5e0e5844ed27 | amZotti/Python-challenges | /Python/11.1.py | 346 | 3.734375 | 4 | l1 = []
for i in range(3):
l1.append([])
for k in range(4):
l1[i].append(int(input("Enter a 3-by-4 matrix row for row %d" %k)))
for column in range(len(l1[0])):
count = 0
for row in range(len(l1[column])):
count += l1[row][column]
print("The sum of row %d is %d" % (row,co... |
2af1ff3a9f6e3bfb120e4b155bb4c6048de1dd64 | amZotti/Python-challenges | /Python/5.15.py | 430 | 3.5625 | 4 | def main():
processing = True
n = 12000
while processing:
if is_Cube_Root(n) == True:
print("Cube root closest to 12,000 is", n)
processing = False
else:
n -= 1
def is_Cube_Root(n):
floatroot = (n ** (1.0 / 3.0))
introot = ... |
58379a40498cd21ffdc195e2fe134d8903789308 | amZotti/Python-challenges | /Python/10.13.py | 303 | 3.734375 | 4 | def eliminateDuplicates(lst):
nums = [i for i in set(lst) if i.isdigit()]
print("The distinct numbers are: ", end = "")
for i in nums:
print(i," ",end = "")
def main():
raw = input("Enter ten numbers: ")
eliminateDuplicates(raw)
if __name__ == "__main__":
main()
|
16e2dbb229a46e20c1c3ad21dbc6c57c5d9e83c2 | amZotti/Python-challenges | /Python/13.1.py | 355 | 4.0625 | 4 | def main():
raw = open('text.txt','r')
text = raw.read()
#read() receives entire text via as a string data type
string_to_remove = input("Enter the string you wish to remove")
new_text = text.replace(string_to_remove, '')
raw = open('text.txt','w')
raw.write(new_text)
raw.close()
if ... |
8b411123ffdc29a2a798e700ed0b3afd5ae806a7 | amZotti/Python-challenges | /Python/sorting algorithim.py | 317 | 3.828125 | 4 | #selection sort
lst = [1,5,3,1,4]
def sort(lst):
for i in range(len(lst)-1):
current = i
for j in range(i + 1, len(lst):
if lst[current] > lst[j]:
current = j
if current != j:
lst[i], lst[current] = lst[current],lst[i]
|
424dc43dd276732e400fc771ec93966d69766dd9 | amZotti/Python-challenges | /Python/6.4.py | 193 | 4.28125 | 4 | def main():
reverse(input("Enter a number you want reversed!"))
def reverse(number):
print("The reversal of %s is %s" % (number, number[::-1]))
if __name__ == "__main__":
main()
|
92be2d072d41e740329b967749d113fb96a40882 | amZotti/Python-challenges | /Python/12.2.py | 993 | 4.15625 | 4 |
class Location:
def __init__(self,row,column,maxValue):
self.row = row
self.column = column
self.maxValue = float(maxValue)
print("The location of the largest element is %d at (%d, %d)"%(self.maxValue,self.row,self.column))
def getValues():
row,column = [int(i) for i in input... |
7ce2cff78853656c0c7bc76c066b283aa2f35055 | amZotti/Python-challenges | /Python/2.13.py | 422 | 3.578125 | 4 | def main():
try:
splitDigits = input("Enter a four-digit integer")
a,b,c,d = splitDigits[0], splitDigits[1], splitDigits[2], splitDigits[3]
print(int(d))
print(int(c))
print(int(b))
print(int(a))
except Exception:
print("Please enter a valid ... |
3dc04fddb990a989139d583b7abdd08e87f6e4bc | amZotti/Python-challenges | /Python/4.3.py | 436 | 3.953125 | 4 | #4.3
def main():
a, b, c, d, e, f = [float(number) for number in input("Enter a, b, c, d, e, f: ").split(',')]
if ((a * d) - (b * c)) == 0:
print("The equation has no solution")
else:
x = ((e * d) - (b * f))/ (
(a * d) - (b * c) )
y = ((a * f) - (e * c)) /... |
61c072b930322b6221012896b013367f81575c26 | amZotti/Python-challenges | /Python/5.11.py | 469 | 3.796875 | 4 | def main():
number_of_students = int(input("How many students? "))
scores = []
max1 = 0
max2 = 0
for i in range(1, number_of_students + 1):
scores.append(int(input("Input score for student number %d: " %i)))
max1 = max(scores)
scores.remove(max(scores))
... |
5f8194955c30f5c80fbb9d7c71aecd59995b98c4 | RichelieuRosa/Python-4-everyone | /ex_07_02.py | 479 | 3.625 | 4 | fname = input('Enter the file name: ')
strcri='X-DSPAM-Confidence:'
try:
fop = open(fname)
except:
print(fname, 'is not a file')
quit()
count =0
total =0 #initialize variables
for lx in fop:
if lx.startswith(strcri):
count = count+1
numpos = lx.find(':')
n... |
951a08bc41a2b0b55c289286d31de1478baf5bec | RichelieuRosa/Python-4-everyone | /09_dict/ex_09_04_countmaxemail.py | 679 | 3.890625 | 4 | fname = input('Enter a file name: ')
try:
fop = open(fname)
except:
print('Not a valid file name')
quit()
addcount = dict()
for line in fop:
line = line.rstrip()
words = line.split()
if len(words)<3 or words[0]!='From':
continue
else:
addcount[words[1... |
bd718d44a46edd52473603dcff29ae5a4050b071 | RichelieuRosa/Python-4-everyone | /10_tuples/ex_10_03_commonword.py | 732 | 3.78125 | 4 | fname = open('mbox.txt')
import string
count = 0
wordlist =dict()
letterlist=list()
print('Computing...')
for line in fname:
line = line.rstrip()
line = line.translate(str.maketrans('','',string.digits))
line = line.translate(str.maketrans('','',string.punctuation))
line = line.lower() #... |
d8c8015f08a9f39a415a72c8536fbe062d0a080e | sepro/CoNekT | /utils/vector.py | 437 | 3.78125 | 4 | from math import sqrt
def dot_prod(a, b):
"""
Calculates the dot product of two lists with values
:param a: first list
:param b: second list
:return: dot product (a . b)
"""
return sum([i * j for (i, j) in zip(a, b)])
def norm(a):
"""
Calculates the Frobenius norm for a list of ... |
6c311c48591efb25f6ab17bb06a906660800ac58 | dchen098/bmi_calc | /bmi_calculator.py | 424 | 4.15625 | 4 | print("\n\t\t\tBMI Calculator\n\t\t\tMade by Daniel Chen\n\n")
bmi=(int(input("What is your weight in pounds? "))*703)/(int(input("What is your height in inches? "))**2)
t="underweight"if bmi<18.5 else"normal"if bmi<25 else"overweight"if bmi<30 else"obese"
print("Your BMI is "+str(bmi)+"\nYou are "+t)
print("Try losi... |
d5c1f8cda079174e12edb8cf3d025c544b13b128 | P0intMaN/artificial-intelligence | /Tic-Tac-Toe/TicTacToe_AI.py | 7,507 | 3.640625 | 4 | import random, os
board=[[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def show_board(board):
print("+---+---+---+")
print("| ", end="")
print(board[0][0], board[0][1], board[0][2], sep=" | ", end="")
print(" | ")
print("+---+---+---+")
print("| ", end="")
print(board[1][0], ... |
a4b3f8dcf932ebd88eab2b8144a5559303a3244d | MjBordalo/ProjectoAsint | /v2.1/api/server/student.py | 704 | 3.609375 | 4 | class Student:
def __init__(self,uname,id):
self.uname=uname
self.id=id
self.room=None
def __str__(self):
if self.room is not None: tmp=self.room
else: tmp="Empty"
return "----- STUDENT: \n" + \
"\t --- Username: " + self.uname + '\n' + \
"\t --- Identifier: " + self.id + '\n' + \
"\t --- Roo... |
88eea8e514c7c67b9d455f85516ea2aa8035c8cd | fernandlira/semana7_sesion3 | /classes/funciones.py | 2,177 | 3.828125 | 4 | from classes.productos import Producto
from classes.categorias import Categoria
class Funciones:
def insertar_producto(cantidad):
categoria = Categoria()
categoria.listar()
i = 1
while True:
if i > cantidad:
break
while True:
... |
63db6383217a6f0baa38b3eb99fb9caf655df817 | wonderfulsteven/GAandBP | /selection.py | 1,271 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 16:05:53 2017
@author: Boheimain
"""
# 0.0 coding:utf-8 0.0
# 选择
import random
def sum(fit_value):
total = 0
for i in range(len(fit_value)):
total += fit_value[i]
return total
def cumsum(fit_value): ... |
b3fbd14eb0439bbb1249fd30112f81f1c72f2d51 | lglang/BIFX502-Python | /PA8.py | 2,065 | 4.21875 | 4 | # Write a program that prompts the user for a DNA sequence and translates the DNA into protein.
def main():
seq = get_valid_sequence("Enter a DNA sequence: ")
codons = get_codons(seq.upper())
new_codons = get_sets_three(codons)
protein = get_protein_sequence(new_codons)
print(protein)
def get_va... |
55e8c743ce6591b6bf62588fded3261abbc6d456 | gidon429/Inventory-Management-App | /app.py | 6,216 | 3.921875 | 4 | import csv
import os
def read_products_from_file(filename="products.csv"):
filepath = os.path.join(os.path.dirname("products_app"), "db", filename)
products = []
with open(filepath, "r") as csv_file:
reader = csv.DictReader(csv_file) # assuming your CSV has headers, otherwise... csv.reader(csv_file... |
3073f3055b66d9d36deb68ec77efd47e48eb11c9 | ademyagmurlu1994/effective_sudoku_puzzle_game | /utils.py | 473 | 3.765625 | 4 | import numpy as np
import random as rnd
def create_random_array(size, range=(0, 8)):
rnd_array = []
index = 0
while index != size:
rnd_number = rnd.randint(range[0], range[1])
if rnd_number not in rnd_array:
rnd_array.append(rnd_number)
index += 1
return rnd_arra... |
783621171a4951f8d6cdbef936a2a275ecc51529 | alonsodaniel1090/autoparts_scraper | /info_parts.py | 486 | 3.625 | 4 | class InfoParts:
'''
The purpose of this class is to create
objects with all the needed information
to create a database to keep
track of all the objects and its information.
'''
def __init__(self, title, price, href):
self.title = title
self.price = price
self.href ... |
329a9d78137768539aa4bb300b3bea1a0fe8500f | nat-sharpe/Python-Exercises | /Day_3/strings_long.py | 298 | 3.71875 | 4 | word = "cheese"
long_word = ''
longs = ['e', 'o', 'a']
new_num = 2
pre_letter = ''
for char in word:
if char == pre_letter and char in longs:
pre_letter = char
long_word += char + char * new_num
else:
pre_letter = char
long_word += char
print long_word
|
c8e00355e8ed05fba844a47f9925b304e9065527 | nat-sharpe/Python-Exercises | /Day_4/wordsummary.py | 1,153 | 4.09375 | 4 | string_input = raw_input('Count words in: ')
# Turn string_input into lowercase with no special characters:
string = ''
lower = " 'abcdefghijklmnopqrstuvwxyz"
upper = " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for char in string_input:
if char in upper:
for j in range(len(upper)):
if char == upper[j]:
... |
1efa65530ee7adfb87f28b485aa621d7bab157ca | nat-sharpe/Python-Exercises | /Day_1/loop2.py | 264 | 4.125 | 4 | start = input("Start from: ")
end = input("End on: ") + 1
if end < start:
print "Sorry, 2nd number must be greater than 1st."
start
end
for i in range(start,end):
if end < start:
print "End must be greater than start"
print i
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.