blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
8e82d1712db526307045eb6b0c937739bfd47b0b | aseemchopra25/Integer-Sequences | /Sorting Number/Sorting_Number.py | 354 | 4.03125 | 4 | #importing required libraries
import math
#function to find Sn
def Sn(n):
return math.floor(1 + math.log2(n))
#take input
n = int(input("Enter number of elements you want of sorting number:"))
#print sequence of n sorting numbers
for i in range(1,n+1):
x = i*Sn(i) - pow(2,Sn(i)) + 1 #this is formula for sor... |
3029f326bdfa33a784cd0aead5486ae7603d6a65 | marwahaha/highlight-news | /app/tests/test_source.py | 1,162 | 3.65625 | 4 | import unittest
from app.models import Source
class SourceTest(unittest.TestCase):
'''
Test class to test the behaviour of the Source class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_source = Source('espn','ESPN','ESPN has up-to... |
f7967049695650a0fb7fb78626fa5676cd8bcea7 | kayak0806/pretty-pictures | /pyglet_stuff/hello_music.py | 1,804 | 3.5625 | 4 | import pyglet
from pyglet.window import mouse
window = pyglet.window.Window()
label = pyglet.text.Label('Hello, world',
font_name='Times New Roman',
font_size=36,
x = window.width//2, y=window.height//2,
anchor_x='center',... |
9fb3f7a17af1ed8b85fbd8eb9bfa109bec952e26 | NNishkala/PESU-IO-SUMMER | /coding_assignment_module1/w1q3.py | 542 | 4.0625 | 4 | def binarySearch (arr, l, r, x):
if r >= l:
mid = int((l+r)//2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
arr=list([i... |
d0c04b05badf3d6b4d0efbc561431f0bb137eacf | lilin0414/GitRepo | /test.py | 190 | 3.59375 | 4 | def wordCount(data):
re = {}
for i in data:
re[i] = re.get(i,0) + 1
return re
if __name__ == "__main__":
data = ["ab","cd","ab","d","d"]
print ("The result is %s" % wordCount(data))
|
2c633765c303a588fffadab901984a7791372fe4 | TapaniAlastalo/python_practices | /TiRa/rsa_key_builder.py | 2,489 | 3.546875 | 4 | import random
DEFAULT_P = 229
DEFAULT_Q = 419
DEFAULT_E = 89099
DEFAULT_D = 48443
FAST_P = 17
FAST_Q = 29
FAST_E = 173
FAST_D = 101
# Generate random prime number. Not effective at all.
def generateRandomPrimeNumber(min, max, already_picked = -1):
r = random.randint(min, max)
while (isPrime(r) == False or r ... |
bf87c7d9fd21e078b42c7ee6adc64d2ed068af1e | TapaniAlastalo/python_practices | /ass12.py | 248 | 3.78125 | 4 | vows = [ "a", "e", "o", "u", "y" ]
def vowels(text):
count = 0
for x in text:
if x in vows:
count += 1
return count
print(vowels("aaa")) # prints: 3
print(vowels("aba")) # prints: 2
print(vowels("bca")) # prints: 1 |
e4fdc6c628d1689a131aabb42d2ed6998439ee7c | TapaniAlastalo/python_practices | /ass14.py | 249 | 3.875 | 4 | def division(first, second):
try:
return first / second
except ZeroDivisionError:
print("Divided by zero")
return 0
except:
return 0
print(division(2, 0)) # divided by zero
print(division(6, 2)) # 3.0 |
73231c0bb6d8235c3dc5e3ee8acecf07ea0d28b0 | TapaniAlastalo/python_practices | /ass7.py | 285 | 3.78125 | 4 | def getNumber():
print("Give number")
try:
return int(input())
except:
return getNumber()
def checkNumbers(first, second):
if (first + second) % 2 == 0:
print("Yes it is!")
else:
print("Nope")
checkNumbers(getNumber(), getNumber()) |
706f15a435910b66bf950103dfdeeb14a154546a | vineetmidha/DSA | /In2PostPre.py | 2,480 | 4 | 4 |
# infix to postfix and prefix
def push(stack, symbol):
stack.append(symbol)
def pop(stack):
return stack.pop()
def isOperator(symbol):
return symbol in "+-*/%^"
def isOperand(symbol):
return not isOperator(symbol)
def empty(stack):
return stack == []
def peek(stack):
return stack[-1]
de... |
a0d3de19d978930cc094f5c8115b2f61195bd1f7 | anildhaker/DailyCodingChallenge | /LeetCode/Alternatingbits.py | 806 | 3.984375 | 4 | # Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
# Example 1:
# Input: 5
# Output: True
# Explanation:
# The binary representation of 5 is: 101
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
s1 = set()
... |
70cf22aa536a21edd9329f05a94635d3db4d62b0 | anildhaker/DailyCodingChallenge | /GfG/BinaryTree/deletion.py | 1,269 | 3.953125 | 4 | # delete a given node in binary tree and replace it with the bottom-right node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# inOrder traversal
def inOrder(temp):
if temp is None:
return
inOrder(temp.left)
print(temp.data, end=" ")
inOrde... |
8db27330a51b12c8d84ed2d7edcd91754ff9ba0c | anildhaker/DailyCodingChallenge | /LeetCode/reverseInteger.py | 597 | 4 | 4 | # Given a 32-bit signed integer, reverse digits of an integer.
# Example 1:
# Input: 123
# Output: 321
# Example 2:
# Input: -123
# Output: -321
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s=0
y=abs(x)
while (y!=0):
... |
d9f6c075ab6ef6573aceb8758fddb2b20b7e574e | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/gcdSubset.py | 764 | 3.59375 | 4 | # Given a set of N elements such that N\in [1, 1000], task is to generate an array
# such that the GCD of any subset of the generated array lies in the given set of elements.
# The generated array should not be more than thrice the length of the set of the GCD.
# Input : 3
# 1 2 7
# Output : 1 1 2 1 7
# Ass... |
9262c4432490fb56a8688f09e22d7fedc77277c5 | anildhaker/DailyCodingChallenge | /LeetCode/containDuplicate.py | 395 | 3.921875 | 4 | # Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
# Example 1:
# Input: [1,2,3,1]
# Output: true
class Solution:
def containsDuplicate(self, nums):... |
95e6ae0adf128eac0684ddaed8fbd4a98eeee7b0 | anildhaker/DailyCodingChallenge | /LeetCode/FairCandySwap.py | 935 | 3.859375 | 4 | # Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.
# Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. ... |
0b8cfda80341f33b7ec168156f82dcc2dc32e618 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/fibMultpleEff.py | 695 | 4.21875 | 4 | # Efficient way to check if Nth fibonacci number is multiple of a given number.
# for example multiple of 10.
# num must be multiple of 2 and 5.
# Multiples of 2 in Fibonacci Series :
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 ….
# every 3rd number - is divisible by 2.
# Multiples of 5 in Fibonacci ... |
87e12cbe64f2cfcdf00157e8bc34e39485f64773 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/makePerfectSq.py | 842 | 4.1875 | 4 | # Find minimum number to be divided to make a number a perfect square.
# ex - 50 dividing it by 2 will make it perfect sq. So output will be 2.
# A number is the perfect square if it's prime factors have the even power.
# all the prime factors which has the odd power should be multiplied and returned(take 1 element ... |
28d0479fae062757de4e7f2421a1c1c75914c588 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/fibLastdigit.py | 324 | 3.578125 | 4 | # Fib number unit's place digit repeates after every 60 numbers.
arr = [0 for i in range(100)]
arr[0] = 0
arr[1] = 1
for i in range(2, 99):
arr[i] = arr[i - 1] + arr[i - 2]
for i in range(1, 99):
if (arr[i] % 10 == 0) and (arr[i + 1] % 10 == 1):
break
print("Index after sequence repeats -->", i)
... |
014cad9a68bf6b18ab7d860dff49d1e1393137eb | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/primeFactors.py | 401 | 4.25 | 4 | # for 12 -- print 2,2,3
import math
def primeFactors(n):
while n % 2 == 0 and n > 0:
print(2)
n = n // 2
# n becomes odd after above step.
for i in range(3, int(math.sqrt(n) + 1), 2):
while n % i == 0:
print(i)
n = n // i
# until this stage all the composite numbers ha... |
96f331d15dd9bfe271a97022df381baebc581534 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/gcdFloat.py | 325 | 3.953125 | 4 | # gcd of floating point numbers
import math
def gcd_float(a, b):
if a < b :
return gcd_float(b, a)
if b < 0.001:
return a
else:
return gcd_float(a, (a // b) * b)
#what if we try normal appraoch
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
print(gcd_float(1.20,2... |
21b1eb2786b9e7ccbeffe0de39d37611256b8c7c | anildhaker/DailyCodingChallenge | /LeetCode/divisorGame.py | 727 | 3.578125 | 4 | # Alice and Bob take turns playing a game, with Alice starting first.
# Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
# Choosing any x with 0 < x < N and N % x == 0.
# Replacing the number N on the chalkboard with N - x.
def divisorGame(self, N: in... |
bf4935968595877e714c1a62d3ba48287df92e3a | anildhaker/DailyCodingChallenge | /LeetCode/letCombPhoneNums.py | 730 | 3.859375 | 4 | # Given a string containing digits from 2-9 inclusive, return all possible letter
# combinations that the number could represent.
# A mapping of digit to letters (just like on the telephone buttons) is given below.
# Note that 1 does not map to any letters.
class Solution:
def letterCombinations(self,digits):
... |
c8a65e0a4b17162fc59ec343bbf7fb298c1d4525 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/largestPrimeFac.py | 286 | 4.03125 | 4 | # finding largest prime factor
import math as m
def maxPrime(n):
Max = -1
while n % 2 == 0:
Max = 2
n = int(n // 2)
for i in range(3, int(m.sqrt(n)) + 1):
while n % i == 0:
Max = i
n = int(n // i)
if n > 2:
Max = n
return Max
|
a2f2ce6a0379ef412ea96c0cfbbd47bf1d7345bc | Satendarsingh/pythonlab | /sum.py | 92 | 3.96875 | 4 | l=[3,0,5,2]
sum=0
for i in l:
sum=sum+int(i)
print("the sum of the elements in list=",sum) |
831f7f49228b27b511fa415a53729beb96c0e46d | BenjaminLivingstone/poo-python | /usuariosconcuentasbancarias.py | 4,240 | 4.125 | 4 | # Asociación entre clases
# Objetivos:
# Comprender cómo las diferentes clases pueden relacionarse entre sí
# Practica escribir clases con atributos de un tipo personalizado
# Ahora que tenemos una clase de usuario y una clase de BankAccount, pensemos en la relación entre ellos: un usuario tiene una cuenta bancaria o, ... |
5d63309a8adf00bd59dda8cb83e7b0a1616a87c3 | sinanata/python | /clock/clock.py | 610 | 3.84375 | 4 | #11/23/2019 - I suffered from overthinking here, did a deepdive into time and datetime python libraries instead of just doing basic math.
class Clock(object):
def __init__(self, hour, minute):
self.hour = (hour + minute // 60) % 24
self.minute = minute % 60
def __repr__(self):
return "... |
9cdbe7c11a83bee4fa2df45617e3465f577acece | sinanata/python | /word-count/word_count.py | 227 | 3.71875 | 4 | from collections import *
import re
def count_words(sentence):
sentence = re.sub("_", " ", sentence.lower())
inspected = re.findall(r"([\w]+[']?[\w]+|\d|[a-z])", sentence.lower())
return Counter(inspected)
pass |
c9220458303f6c9bc34e844ad7eec7be3e44b5a2 | dragenet/matura-informatyka-python | /4_algorytm_euklidesa/rekurencyjnie/euklidrek.py | 274 | 3.53125 | 4 | def euklidrek( a, b ):
print(a, " ", b)
if b == 0:
return a
c = a%b
return euklidrek( b, c )
if __name__ == '__main__':
l = int( input("Podaj pierwszą liczbę: ") )
m = int( input("Podaj drugą liczbę: ") )
d = euklidrek( l, m )
print( "Ich NWD to: ", d ) |
8b461bcada10b796b8ac9cc770674f39d94d9ac0 | dragenet/matura-informatyka-python | /5_ciag_fibbonaciego/iteracyjnie/fiboit.py | 521 | 4 | 4 | def fiboit( n ):
#Funkcja iteracyjna zwracająca n-wyrazów ciągu fibonaciego
#Parameters:
# n (int): Liczba wyrazów ciągu fibbonaciego
#
#Returns:
# fib (int): Wartość n-tego wyrazu ciągu fibbonaciego
fib = [0, 1]
if n < 3:
return fib[n-1]
for i in range( 2, n ):
x = fib[i-1] + fib[i-2]
fib.append(... |
b6a2ac2655c81d0ca8958c5b9d498c8ad329ce2e | dragenet/matura-informatyka-python | /1_liczby_pierwsze/czypierwsza.py | 320 | 3.734375 | 4 | import math
def czyPierwsza(n):
if n < 2:
return False
i = 0
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
if __name__ == '__main__':
liczba = int(input("Podaj liczbę: "))
if czyPierwsza(liczba):
print("Liczba jest pierwsza")
else:
print("Liczba nie jest pierwsza") |
1939e2e6864f4274836dc47893746485f4e63bff | alexandertheNotGreat/random-rad | /carro1.py | 195 | 4.03125 | 4 | tempo = int(input('Quantos anos tem o seu carro? '))
if tempo <= 3:
print('Carro novinho ein!')
else:
print('Carro tá velho, Melhor trocar...')#mais que 3 anos
print('--FIM---')
|
c927916e909396dcd9240c44962870026d780436 | zoeShao/ML_Project | /part_a/zoe_knn.py | 5,602 | 3.75 | 4 | from sklearn.impute import KNNImputer
from utils import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def knn_impute_by_user(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
student similarity. Return the accuracy on val... |
e91756f5e6c86136a501b50eec86ff68634a5797 | Takobz/Push_Up | /task7.py | 1,736 | 3.890625 | 4 | import re
def read_dictionary():
dictionary = {}
my_input = str(input())
i = 0;
while (my_input != '###'):
dictionary[i] = my_input
my_input = str(input())
i += 1
return dictionary
def compute_response(target, guess):
my_list = []
response = ''
for i in r... |
bc28541b378f69e1b7ef435cff0f4094c4ca75e2 | PSDivyadarshini/C-97 | /project1.py | 298 | 4.21875 | 4 | myString=input("enter a string:")
characterCount=0
wordCount=1
for i in myString :
characterCount=characterCount+1
if(i==' '):
wordCount=wordCount+1
print("Number of Word in myString: ")
print(wordCount)
print("Number of character in my string:")
print(characterCount)
|
4c69d254139b48ca6ab3086f098fe2ebd30659c5 | Sara-DLC/code-challenges | /leetcode.com/merge_two_sorted_lists.py | 1,168 | 4.0625 | 4 | #!python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list_1: ListNode, list_2: ListNode) -> ListNode:
result_head = ListNode(None)
result_tail = result_h... |
a19dcb4e7c1b86b675a0a3704091e2449c380aaf | abharath309/Bharath_PythonC-_Code | /Python/w1a_limits.py | 700 | 3.703125 | 4 | # AUTHOR BHARATH abharath@bu.edu
from decimal import Decimal,getcontext
import math
i=1
#numbers=1,2,4,8
Table = "{:<6} {:<22} {:<22} {:<22}"
print(Table.format('Bytes','Largest Unsigned Int','Minimum Signed Int','Maximum Signed Int'))
#for x in (1,2,4,8):
for x in range(1,9):
#print ("Entering the for-loop with i v... |
119132fefe6c5cb1a977f2128e39676187b178f4 | suryaprakashgiri01/Mini-Calculator | /calc.py | 1,375 | 4.1875 | 4 |
# This is a Mini calculator
print()
print(' ------------------------------------------------------------------')
print(' | Welcome to the mini calculator |')
print(' | Code By : SP |')
print(' ---------------------------... |
03d2b9d47d3bb71ff95feac95911768f3a7cefdd | GusAV/Megasenagenpy | /megasena generator.pyw | 1,284 | 3.75 | 4 | '''
Sorteio da mega sena
'''
from tkinter import *
app = Tk()
app.title("Mena Sena Generator")
app.geometry('550x250')
l1 = Label(app, width = 30)
l2 = Label(app, width = 30)
n = []
def escolhe():
global n
n.append(int(numero.get()))
numero.delete(0, END)
print(n)
l2['text'] =... |
8aff8f034cb41fa3efa60a2441b29e8cd056d3aa | katteq/data-structures | /P2/problem_1.py | 1,315 | 4.34375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number == 0 or number == 1:
return number
start = 0
end = number
res = 0
i = 0
whil... |
5a6cc4d1982b9a12d2a36a0e433e731016c443ca | jasonn9538/Homework-Sample-Code | /Algorithms/PS9b2.py | 564 | 3.546875 | 4 |
MAX = 100
maxArrEven = [0] * MAX
maxArrOdd = [0] * MAX
def maxPoints(arr):
n = len(arr)
maxArr = [0] * n
maxArr[0] = arr[0]
maxArr[1] = max(arr[0],arr[1])
print(maxArr)
for i in range(2,n):
maxArr[i] = max(maxArr[i-1], maxArr[i-2]+arr[i])
print(i)
print(maxArr)
return maxArr[n-1]
def maxPointsPar... |
817bbea4266194ed44da540b620b47ebcbc1045f | xiaocainiao/ConnectFourServer | /AI/State.py | 4,293 | 3.765625 | 4 | #coding:utf-8
__author__ = 'ear_breakfast'
class State(object):
def __init__(self):
self.board = [[0] * 7 for _ in range(6)]
self.turn = 1
self.moves = []
self.rows = 6
self.cols = 7
def printBoard(self):
"""Print the board."""
for i in range(self.rows):
print ' '.join(str(self.board[i][x]) for x... |
23766aad682eccf45ca95ba6cd539d82568a7192 | blbesinaiz/Python | /displayFormat.py | 286 | 4.125 | 4 | #Program Title: Formatted Display
#Program Description: Program takes in a string, and outputs the text
# with a width of 50
import sys
string = input("Please enter a string: ")
for i in range(10):
sys.stdout.write('['+str(i)+']')
print(string)
|
1ccb2cf9f9ac009692a688de2828be20eaa1a99c | crystaleone/test | /four-threads.py | 737 | 3.671875 | 4 | import threading, _thread
def action(i):
print(i ** 32)
class Mythread(threading.Thread):
def __init__(self, i):
self.i = i
threading.Thread.__init__(self)
def run(self):
print(self.i ** 322)
Mythread(2).start()
thread = threading.Thread(target=(lambda: action(2)))
thread.start()
threading.Thread(target=act... |
42615cffbf7d436a511b3a7e55162271bfe9960e | crystaleone/test | /rev2.py | 195 | 3.9375 | 4 | def reverse(list):
if not list:
return list
else:
return reverse(list[1:]) + list[:1]
def ireverse(list):
res = list[:0]
for i in range(len(list)):
res = list[i:i+1] + res
return res
|
7fd8ec44ca644c22a96f61800d44c23be6f842b1 | crystaleone/test | /parser2.py | 4,513 | 3.5625 | 4 | TraceDefault = False
class UndefinedError(Exception): pass
if __name__ == '__main__':
from scanner import Scanner, SyntaxError, LexicalError
else:
from .scanner import Scanner, SyntaxError, LexicalError
class TreeNode:
def validate(self, dict):
pass
def apply(self, dict):
pass
def trace(self, level):
print... |
32a4235f4fead861976a012621ee17d5929f7d44 | JohnnyXiangyu/CS131-S2020-UCLA | /Project/isc.py | 604 | 3.53125 | 4 | connections = {
'Singleton': ['Campbell', 'Jaquez', 'Smith'],
'Campbell': ['Singleton', 'Smith'],
'Jaquez': ['Singleton', 'Hill'],
'Smith': ['Singleton', 'Hill', 'Campbell'],
'Hill': ['Jaquez', 'Smith']
}
port_numbers = {
'Singleton': 12405,
'Campbell': 12406,
'Jaquez': 12407,
'Smit... |
ac8c2cc371d1c777f67b8c32b7d5c941a296f55d | zcgu/CS760Assign5 | /neural_net/neural_model.py | 2,440 | 3.515625 | 4 | import math
def sigmoid(x):
return 1. / (1. + math.pow(math.e, - x))
class Network:
def __init__(self, input_dimension, class_label, learning_rate):
self.input_dimension = input_dimension
self.class_label = class_label
self.learning_rate = learning_rate
self.weight_list = []... |
3ebe0cc5215b2b3b5ae36fbd668fdea4fe7044a5 | abby501198/Programming-for-Bussiness-Computing | /hw2(2).py | 489 | 3.75 | 4 | # abby chang
kg = int(input()) # 欲買公斤數
kg1 = int(input()) # 級距1公斤數
price1 = int(input())# 級距1價錢
kg2 = int(input()) # 級距2公斤數
price2 = int(input()) # 級距2價錢
kg3 = int(input()) # 級距3公斤數
price3 = int(input()) # 級距3價錢
if kg <= kg1: #total
total = kg * price1
if kg1 < kg <= kg2:
total = kg1 * price1 + (kg - kg1) * price2
... |
d14d70aa58d17ecc863850a69ed415c6e243fee9 | abby501198/Programming-for-Bussiness-Computing | /hw6(2).py | 2,388 | 3.671875 | 4 | # abby chang
# input
strings_list = []
while True:
string = input().strip(" ") # 去除多餘的空白
if string == "INPUT_END": # 若遇到INPUT_END則停止讀取資料
break # 並跳出迴圈
else:
strings_list.append(string) # 將各行字串加入string_list
distance = int(strings_list[0])
key_string_1 = strings_list[1] # 把關鍵字取出來
ke... |
555fda7c9314222a422bf8a6ca361b13f625aa9e | tomcusack1/python-algorithms | /Euler/1.py | 275 | 3.515625 | 4 | def multiples(a0, d, n):
nd = (n / d - 1) if n % d == 0 else n / d
n_n_1 = (nd * (nd - 1)) / 2
return a0 * nd + d * n_n_1
t = int(raw_input())
for a0 in xrange(t):
n = int(raw_input())
print multiples(3, 3, n) + multiples(5, 5, n) - multiples(15, 15, n)
|
e2b69836a22a3feda9a41bdc13c7a7761a276faf | tomcusack1/python-algorithms | /Arrays/anagram.py | 841 | 4.125 | 4 | def anagram(str1, str2):
'''
Anagram function accepts two strings
and returns true/false if they are
valid anagrams of one another
e.g. 'dog' and 'god' = true
:string str1:
:string str2:
:return: boolean
'''
str1 = str1.replace(' ', '').lower()
str2 = str2.replace(' ', '').l... |
7fc92dcd05bb8c654bd03241cf646d450b52ddd3 | tomcusack1/python-algorithms | /Recursion/reserse_string.py | 217 | 3.921875 | 4 | def reverse(s):
# Edge case
if s == "":
return ""
# Base case (only one element left)
if len(s) <= 1:
return s
# Recursion
return reverse(s[1:]) + s[0]
print reverse("tom")
|
7b421121b139d2e8c666b30ca350d83706807883 | tomcusack1/python-algorithms | /Recursion/practice.py | 428 | 3.71875 | 4 | def fib(a, b, n):
# Using memoization we can improve this exponential fib algorithm from O(2^n) to O(N)
# However, even memoization is overkill for this alg, when we only need to store the
# data temporarily
if n == 0:
return 0
i = 2
while i < n:
c = a + (b * b)
a = b
... |
e0740ed790385305e6662da05b743c5868b4036c | tomcusack1/python-algorithms | /Search/sequential_search.py | 611 | 3.78125 | 4 | import unittest
def sequential_search(array: list, element: int) -> bool:
"""
General sequential search. Works on ordered lists only
"""
for item in array:
if item == element:
return True
if item > element:
return False
return False
class TestSearch(unitt... |
de4eeafe3ffec1d589a7fbce3e9d9c7c120a46f5 | tomcusack1/python-algorithms | /Trees/list_tree.py | 735 | 3.84375 | 4 | def binary_tree(root):
return [root, [], []]
def insert_left(root, new_branch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
def insert_right(root, new_branch):
t = root.pop(2)
if len(t) > 1:
... |
d27be2d0a4f46705f503fbea533e4b4c7e06bbe1 | bolodave/pythonTutorial | /pythonFunctions.py | 427 | 3.921875 | 4 | import turtle
"""
Topic Functions:
-Set of statements that take inputs, do something, and produces output
-Functions we create are user-defined functions
"""
qazi_turtle = turtle.Turtle()
def square():
qazi_turtle.forward(100)
qazi_turtle.right(90)
qazi_turtle.forward(100)
qazi_turtle.right(90)
qazi_turtle.f... |
e897167bd48775cb25bf37d59d2871f3f1b19562 | Shanta-Marasini/HackerRankPrograms | /A4_list_operations.py | 573 | 3.90625 | 4 | print('Hello my world')
command = []
listt = []
n = int(input(''))
for i in range(n):
com = input().split(' ')
command.append(com)
print(command)
for com in command:
if com[0] == 'insert':
listt.insert(int(com[1]),int(com[2]))
elif com[0] == 'print':
print(listt)
elif com[0] == 'r... |
d701d178a9a545d75a7cb0b90c85581320d591b1 | Shanta-Marasini/HackerRankPrograms | /A6_substr_in_str.py | 427 | 3.609375 | 4 | #how to mutate a string
#1. use list constructor
string = 'GeeksforGeeks is for Geeks'
sub_string = 'Geeks'
lenSub = len(sub_string)
i = 0
count = 0
while i < len(string):
newStr = ''
if (len(string)-i) >= len(sub_string):
for j in range(i,lenSub):
newStr += string[j]
lenSub += 1
... |
d832b208adf2110495f77848fe5dff29549ab805 | KumarArab/TicTacToe | /TicTacToe.py | 1,760 | 4.0625 | 4 | import random
board = ['-','-','-'
,'-','-','-',
'-','-','-',]
def display_board():
print(board[0]+"|"+board[1]+"|"+board[2])
print(board[3]+"|"+board[4]+"|"+board[5])
print(board[6]+"|"+board[7]+"|"+board[8])
def check_empty_area(board):
l = []
for i in range(len(board)):
... |
0ce2639bb7fa01e6406c8dc2228ea21b9cbb275d | chatenlohani/pythonlearningcode | /prob5-2.py | 515 | 3.71875 | 4 | ##problem5-2
classlist=[]
grade=[]
numclass=int(raw_input("How many classes did you take?"))
counter=numclass
print ""
while counter >0:
cname=raw_input("What was the name of this class?")
marks=int(raw_input("what was your grade?"))
classlist.append(cname)
grade.append(marks)
counter=counter-1
print " "... |
d6b3ca47ab06a3a7448b2053a8ab8da406e0a507 | derpkoch/Bac7 | /src/py/utils.py | 327 | 3.84375 | 4 | #!/usr/bin/python3
# Author: Anja Gumpinger
import time
class timer(object):
"""Timer. """
def __init__(self, name):
self.name = name
def __enter__(self):
self.start = time.time()
def __exit__(self, ty, val, tb):
end = time.time()
print(f'{self.name}: {end - self.s... |
cba8f4e74dd9d818179175d5d7ab6529928b2c79 | veronikadajneko/LeverX_courses_task1 | /parses.py | 461 | 3.734375 | 4 | import json
from abc import ABC, abstractmethod
class Parser(ABC):
""" Class for parses different files
"""
def __init__(self, file_name):
self.file_name = file_name
@abstractmethod
def loader(self, file_name):
pass
class ParserJSON(Parser):
""" Class for parses json files
... |
382099f3f82333b07bc3e1eb321b478b9db84c7a | GrigoriyPL/New.10.04.21 | /py_game5.py | 1,660 | 3.90625 | 4 | # круг двигается по клавишам, существует зона в которой круг двигается быстрее и меняет цвет, при отсутвии
# нажатия на кнопки, то круг возвращается в исхнодное положение
import pygame
x, y = 100, 100
W, H = 500, 500
pygame.init()
sc = pygame.display.set_mode((W,H))
color = (255,255,255)
fps = pygame.time... |
28e99c162d188ba95cd9a6a225ef0405f75b2613 | gillespilon/multiprocessing | /multi_pool_class.py | 588 | 3.953125 | 4 | #!/usr/bin/env python3
'''
With pool class.
'''
import time
import multiprocessing
def basic_function(x):
if x == 0:
return 'zero'
elif x%2 == 0:
return 'even'
else:
return 'odd'
def multiprocessing_function(x):
y = x*x
time.sleep(2)
print('{} squared results in {}... |
edf5d9c0efb584f12fef1ad244dccc1048d2e26a | Sponsoredby/sl-countdown | /countdown.py | 176 | 4.03125 | 4 | #set the variable number
number = 10
#set while loop until variable is 0
while number > 0:
print (number)
number = number - 1
#print when loop is complete
print ('Takeoff') |
81fd37f8a388da63cddc20602160ce7ec11c74fc | xuhongfeng/saturn-rec | /python/structure.py | 419 | 3.734375 | 4 | #!/usr/bin/env python
class FIFOCache(object):
def __init__(self, size = 100):
self.size = size
self._list = []
def put(self, id, data):
self._list.append((id, data))
if (len(self._list) > self.size):
self._list.pop(0)
def get(self, id):
for it... |
9f4965c2cc012145b57398508628499f5f5350ee | hroncok/python-brainfuck | /brainx.py | 8,125 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class BrainFuck:
"""Brainfuck interpreter."""
def __init__(self, data, memory=b'\x00', memory_pointer=0):
"""Brainfuck interpreter initialization."""
# variables init
self.memory = bytearray(memory)
self.memory_p... |
d1f2f953b7c0a7214fa62663423719ea541cf477 | ccorboy/Election_Analysis | /PyPoll.py | 5,931 | 4.125 | 4 | # The data we need to retreive.
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The percentage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote.
# Add our dependencies
import csv
import os... |
79541e664a3f3938ea76e919cb37672930a270f1 | sartim/flask_shop_api | /app/core/helpers/password_helper.py | 522 | 3.59375 | 4 | import bcrypt
def generate_password_hash(password, rounds=14, prefix=b'2b'):
"""Generate password hash
with bcrypt having default prefix being 2b if not parsed.
Also default log rounds is 14.
"""
return bcrypt.hashpw(
password.encode(),
bcrypt.gensalt(rounds=rounds, prefix=prefix))... |
bd7adbd1c886d533a06e7d9b5ac3cc5eaa38e09a | harshareddy832/amfoss-tasks | /Task-2 Programming/amfoss6.py | 223 | 3.59375 | 4 | n=int(input("please enter the number of testcases: "))
for i in range(n):
k=input("please enter you string: ")
if len(k)>=10:
abb=k[0]+str(len(k)-2)+k[-1]
print(abb)
else:
print(k) |
a1119c9179a083391387bc5389d60f4df9c529e6 | corzogac/MSD2020 | /Madelbot.py | 913 | 3.609375 | 4 |
from bokeh.plotting import figure
from bokeh.io import output_notebook,show
from bokeh.layouts import column
#To be able to plot we define first what type of output
output_notebook()
#now we create the figure
f=figure(title="Mandelbot", x_axis_label='x', y_axis_label='y')
#for imaginary
a=(2+3j)
m=np.linspace... |
8c5674898143ec7bf68fb306f2e35d463c8349f1 | MDCGP105-1718/portfolio-mrchooch | /Python/ex8.py | 662 | 3.75 | 4 | portion_deposit = 0.25
total_cost = 1000000
target = total_cost*portion_deposit
epsilon = 100
semi_annual_raise = 0.07
invest_return_rate = 0.04
total_saved = 0
months = 36
saving_rate = 0.5
annual_salary = float(input("Annual Salary: "))
for i in range(months):
if (i % 6 == 0):
annual_salary += semi_annual_raise
... |
01012dba215b32fb9e45487cc64f8191a56e2686 | guilmeister/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py~ | 201 | 4.0625 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
unique_list = []
for element in my_list:
if element not in unique_list:
unique_list.append(element)
return sum(unique_list)
|
fb0a084629cde64317ac93cd5cd8f9b6dacb0ff0 | guilmeister/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 253 | 4.03125 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for x in matrix:
for index_value in x:
print("{:d}".format(index_value), end="")
if index_value != x[-1]:
print("", end=" ")
print("")
|
c4581763b8abbf5180570735dc51d4df2eb23ed3 | guilmeister/holbertonschool-higher_level_programming | /0x03-python-data_structures/9-max_integer.py | 407 | 3.671875 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
limit = len(my_list)
flag = 0
if not my_list:
return None
else:
for numbers in range(0, limit):
flag = flag + 1
if flag == 1:
maximum = my_list[numbers]
continue
if my_list... |
b66019522fe2066decb573e28901a0014f73f41d | guilmeister/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 274 | 4.15625 | 4 | #!/usr/bin/python3
def uppercase(str):
result = ''
for letters in str:
if ord(letters) >= 97 and ord(letters) <= 122:
result = result + chr(ord(letters) - 32)
else:
result = result + letters
print("{:s}".format(result))
|
3e37dcbf82e029a7859650ef90594dd1805f8530 | cloudavail/snippets | /python/jinja2/jinja2_using_file_template/jinja2_basic_file.py | 929 | 3.765625 | 4 | #!/usr/bin/env python
# objective: read in the template in ./tutorial_templates and iterate through
# a dictionary, writing out key (city), value (founding date) pairs, example:
# The city {{city_name}} was founded in {{founding_date}}.
# The city San Francisco was founded in 1776.
# The city Los Angeles was founded i... |
c20e5205d3fe2387f6f9ce003eea43dc26e4d3d7 | cloudavail/snippets | /python/scope/scope_testing/scope_testing.py | 527 | 3.5 | 4 | #!/usr/bin/env python
# http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
def test_function():
print 'test_function called'
variable_in_local_scope = 'red'
print variable_in_local_scope
# the test_function() has access to variables in the global scope
print variable_in_globa... |
7ecfc8fd5acf78e38cf2891fc6ca9d6f05b7d16b | cloudavail/snippets | /python/environ_variables/python_get_environ_variable_try_catch.py | 903 | 3.515625 | 4 | #!/usr/bin/env python
# objective: use try/catch to identify if environment variable exists
import logging
import os
env_variable_not_exist = 'VARIABLE_NOT_EXIST'
env_variable_exists = 'USER'
try:
my_variable = os.environ[env_variable_not_exist]
except KeyError as exception:
logging.critical('Environment Var... |
ed2954bdd2ec5424da580a3dbdf86056e9c9e612 | cloudavail/snippets | /python/functions/arguments_passed_as_dictionary/arguments_passed_as_dictionary.py | 668 | 3.96875 | 4 | #!/usr/bin/env python
# objective: pass arguments as dictionary
# creates the function "argument_catcher" and accepts the following keywords
def argument_catcher(city, population, size, state):
print 'city: {!s}'.format(city)
print 'state: {!s}'.format(state)
print 'population: {!s}'.format(population)
... |
dac58c8d8c1ad1f712734e2d33407c270ba38aae | cloudavail/snippets | /python/closures/closure_example/closure_example.py | 1,039 | 4.375 | 4 | #!/usr/bin/env python
# objective: create and explain closures and free variables
def add_x(x):
def adder(num):
# closure:
# adder is a closure
#
# free variable:
# x is a free variable
# x is not defined within "adder" - if "x" was defined within adder
# if... |
6ef1d06b8db4867862415c6b710973aa49e148c7 | cloudavail/snippets | /python/split_on_string/basic_split_on_string.py | 240 | 3.78125 | 4 | #!/usr/bin/env python3
string = "08 G.O.M.D copy 17.mp3"
string_split_on_period = string.split(".")
string_without_extension = string_split_on_period[0:-1]
# prints '08 G', 'O', 'M', 'D copy 17' with [0:-1]
print(string_without_extension) |
cae50539c58a816ed7a7249d09474a40b38a5cf4 | bitcs231n/nasty | /数据挖掘/作业1/dissimilarity.py | 1,627 | 3.578125 | 4 | from homework1.pre_processing import data_array
import numpy as np
from math import sqrt
import pickle
def num_similarity(array, a, b):
a1 = list(array[a, [4, 5, 6, 16, 19, 20, 22]])
a2 = list(array[b, [4, 5, 6, 16, 19, 20, 22]])
i = len(a1) - 1
while i >= 0:
if a1[i] == '?' or a2[i... |
163abf1d7f1fa861b5fc60b8be1290f70e46afe7 | ayushbindlish/Project-Euler | /multiple.py | 83 | 3.765625 | 4 | sum = 0
for i in range(1000):
if ((i%3==0) or (i%5==0)):
sum+=i
print(sum) |
febe5d696b970cd3cb601948ac696472cb52e9a1 | Vijayroman/vjj1 | /yr.py | 87 | 3.703125 | 4 | v=int(input())
if(v%4==0 or v%400==0 and v%100==0):
print("yes")
else:
print("no")
|
f2f5c4c1f582b6a868f72ae286366fd976692ffa | sabrinawhite4/data-python-lab | /data_presenter.py | 584 | 3.59375 | 4 | # PART 2
# NUMBER 2
open_file = open("CupcakeInvoices.csv")
# NUMBER 3
# for line in open_file:
# print(line)
# NUMBER 4
# for line in open_file:
# line = line.strip()
# values = line.split(',')
# print(values[2])
# NUMBER 5
# for line in open_file:
# line = line.strip()
# values = line.split(',... |
293ae711c7822c3d67b20ae236d6c9d4445b4ee7 | sonalisharma/pythonseminar | /CalCalc.py | 2,514 | 4.3125 | 4 | import argparse
import BeautifulSoup
import urllib2
import re
def calculate(userinput,return_float=False):
"""
This methos is used to read the user input and provide and answer. The answer is computed dircetly
using eval method if its a numerical expression, if not the wolfram api is used to get the appropriate ans... |
e06b35be36c3eed153be97a95a5aa802b9c33008 | khanma1962/Data_Structure_answers_Moe | /100 exercises/day10.py | 2,799 | 4.34375 | 4 | '''
Question 31
Question:
Define a function which can print a dictionary where the keys are numbers between
1 and 20 (both included) and the values are square of keys.
'''
def print_dict(start = 1, end = 20):
d = {}
for i in range(start, end+1):
# print(i)
d[i] = i ** 2
print(d)
# print_d... |
5e5e26f39c94bfd18cbff61f3b8bef9b232512ff | khanma1962/Data_Structure_answers_Moe | /Andrei_exercises/functional_prog.py | 784 | 3.78125 | 4 | # map, filter, zip, and reduce
def multiply_by2(lst):
lst_by2 = []
for i in lst:
lst_by2.append(2 * i)
return lst_by2
# print(multiply_by2([9, 4, 8]))
my_list = [3, 9, 12, 17, 21, 20]
def multiply_by2_new(items):
return 2 * items
# print(list(map(multiply_by2_new, my_list)))
# print(my_l... |
03e6e9c8778164eff2dcf1c2157fa8a83382a8b5 | khanma1962/Data_Structure_answers_Moe | /100 exercises/day8.py | 1,607 | 3.921875 | 4 | '''
Question 22
Question:
Write a program to compute the frequency of the words from the input. The output should
output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output ... |
a8b305294173adf71cbada7bb798520f32454f18 | khanma1962/Data_Structure_answers_Moe | /100 exercises/day21.py | 2,060 | 3.984375 | 4 | '''
Question 85
Question
By using list comprehension, please write a program to print the
list after removing the 0th,4th,5th numbers in
[12,24,35,70,88,120,155].
'''
lst = [12,24,35,70,88,120,155]
lst_new = [ x for (i,x) in enumerate(lst) if not(i==0 or i ==4 or i==5)]
# print(lst_new)
'''
Question 86
Question
By us... |
3e2d96c977f6a6d96aadcacbafdb39c4159e91e9 | JoeGakumo21/Password-Locker | /Users/credential.py | 2,754 | 3.734375 | 4 | from .user import User
import random
import string
from .userDetails import read_from_file, write_to_file
data_file = "credentials.csv"
class Credentials:
'''
This class handles credentials of our user
'''
credentials=[]
def __init__(self,account,username,password):
'''
method that... |
292b33cbc71355951b4f55c967085e309fc8700b | bowei437/UNIX-Systems-ECE-2524 | /PythonCar/Backup/block_car2.py | 7,724 | 3.90625 | 4 | #Import rpi.gpio is raspberry pi specific to get use of the GPIO on it
# It comes pre-installed generally on the full Raspbian image
import RPi.GPIO as GPIO
#setmode BCM is just a general Raspberry pi command telling it to use the BCM manufacturered chip GPIO that the Pi uses.
# These are hard set functions that you ... |
581e3539364625589de5aa19a7640844d7c2c605 | A01377744/SegundoRegistro | /Fibonacci.py | 989 | 3.765625 | 4 | def problema1():
lista = []
for x in range(3, 1000):
if x % 3 == 0 or x % 5 == 0:
lista.append(x)
print(sum(lista))
def crearSecuenciaFibonacci(terminos):
fibonacci = [1, 1, 2]
for x in range(0, terminos):
numero = fibonacci[1+x] + fibonacci[2+x]
fibonacci.append... |
daf1d1e453d80a7cc0bd1ce7606825bcab5a87fb | kalaiviswa022/anandhi | /ela.py | 104 | 3.890625 | 4 | x=input()
x=int(x)
if (x<0):
print("invalid")
else:
if(x%2==0):
print("even")
else:
print("odd")
|
8b554a3eb6d101f6376905a8fc65b7e90170c05b | askiada/MusicPy | /MusicPy/src/__init__.py | 1,222 | 3.625 | 4 | #!/usr/bin/env python
from flask import jsonify
import requests
'''
Send a GET or POST request to a specified URL
Parameters
-----------
url : str
The URL to be reached
auth : pair
The first element represents the user and the other the associated password. To use to authenticate.
headers : str
He... |
cc76c3cc3be91b364a724da8c0a75500d7774907 | pilosoposerio/cs165materials | /01_basic_input_and_output/01_images/write_an_image.py | 503 | 3.828125 | 4 | '''
AUTHOR: ceposerio@up.edu.ph
DESC: a demo of creating image files
'''
import cv2
filename = "lena.jpg"
colorType = 0 # gray scale
image = cv2.imread(filename, colorType)
windowName = "Hello OpenCV"
cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE)
cv2.imshow(windowName, image)
keypressed = cv2.waitKe... |
a3bd3cb76a2cc524290d1d2bff370c02ff9ced5a | Kentzo/dlcourse_ai | /assignments/assignment1/metrics.py | 1,665 | 3.59375 | 4 | def binary_classification_metrics(prediction, ground_truth):
'''
Computes metrics for binary classification
Arguments:
prediction, np array of bool (num_samples) - model predictions
ground_truth, np array of bool (num_samples) - true labels
Returns:
precision, recall, f1, accuracy - classi... |
9a220320aba6762701f3e614849d1b0a72b49e7e | Thomas1981Lang/SmartNinja-SWD1-Homework_9.1-9.3_inkl._Bonus-joining_strings_-_CAPM_Homework | /homework_9-Bonus.py | 486 | 4.0625 | 4 | str_one = 'Happy'
str_two = 'Day'
print(str_one + str_two + ' is the same as {}{}'.format(str_one, str_two))
print('')
print('')
print(str_one + ' ' + str_two + ' is the same as {} {}'.format(str_one, str_two))
print('')
print('')
print('%s %s ' % (str_one, str_two) + 'is the same as {1} {0}'.format(str_two, str_o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.