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 |
|---|---|---|---|---|---|---|
3bed65c073160ed00382d22455a18fa09654fd3f | elechigeorge/python_basic | /problemThree.py | 895 | 4.03125 | 4 | # String
# Quotes in string
course = "Python's Course for Beginners"
# Double quote in string
course2 = 'Python for "Beginners"'
# Tripple quote in string
course3 = '''
Hi John,
Here is our first email to you.
Regards.
The support team
'''
# String Index
string = "Python String"
# print(string[-2... |
3d72585149bfb33abf41871d94e3e9832a83123c | satheeshalathiyur/python-lab | /shift_array.py | 373 | 3.90625 | 4 | '''
Program to accept an array and shift by a particular number of positions
array: input array
no_postions: shift by a particular number
'''
array = raw_input('enter values seperated by commas')
no_positions = int(raw_input('number of position'))
array = map(int,array.split(','))
head = array[0:no_positions]
array.... |
209ac630bf8a15bbbc93dba2d0a9cbeaa81e1ee0 | zaki-lknr/python-samples | /class/sample.py | 1,254 | 3.546875 | 4 | class Animal:
def __init__(self, a):
self.__nakigoe = a
def naku(self, arg=None):
if arg:
print(arg)
else:
print(self.__nakigoe)
@property
def nakigoe(self):
return self.__nakigoe
@nakigoe.setter
def nakigoe(self, value):
self.__n... |
5d92ecd74ad7923249b3a43b121c5ace40575f27 | dwkula/data-structures | /exercises/hash-table-ex.py | 3,289 | 4.09375 | 4 | """
1. nyc_weather.csv contains new york city weather for first few days in the month of January.
Write a program that can answer following,
1. What was the average temperature in first week of Jan
2. What was the maximum temperature in first 10 days of Jan
Figure out data structure that is best for t... |
c0e32988331e72474e7b50ea59ac3891627ebd6b | georgeescobra/algorithmPractice | /quickSort.py | 1,408 | 4.25 | 4 | # this version of quicksort will use the last element of the array as a pivot
import random
import copy
def quickSort(array, low, high):
if(low < high):
partitionIndex = partition(array, low, high)
quickSort(array, low, partitionIndex - 1)
quickSort(array, partitionIndex + 1, high)
# don't necessarily have to ... |
e18f0f34927a7aa2398152077a7f88a811466f11 | klandon94/python3_fundamentals | /lambda.py | 820 | 4.1875 | 4 | def square(num):
return num*num
square(3)
#Lambda is used to specify an anonymous (nameless) function, useful where function only needs to be used once and convenient as arguments to functions that require functions as parameters
#Lambda can be an element in a list:
y = ['test_string', 99, lambda x: x ** 2]
print... |
6d500948ce0e44b83eb7739921c7f37fadf9c226 | bui1/cmput404lab2 | /echo_server.py | 628 | 3.59375 | 4 | import socket
# Make a file called echo_server.py that listens for incoming connections and echos any received data
# Stolen from https://docs.python.org/3/library/socket.html#example
# Python3 socket docs to listen to connections and print data afterwards
HOST = 'localhost'
PORT = 8001
with socket.socket(socket.AF_IN... |
de2c7cb47bc6f721978033b1f04f0376f21333b3 | msemjan/coding_interview_questions | /src/editDistance.py | 1,058 | 4.09375 | 4 | '''
# Edit Distance (AirBnB)
Given two strings, determine the edit distance between them. The edit distance is defined as the minimum number of edits (insertion, deletion, or substitution) needed to change one string to the other.
For example, "biting" and "sitting" have an edit distance of 2 (substitute b for s, and ... |
ba933eaf5bc57fa61cc5b74acef3cf49849644e9 | msemjan/coding_interview_questions | /src/simple_calculator.py | 2,541 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
# Create a simple calculator (Google)
Given a mathematical expression with just single digits, plus signs, negative
signs, and brackets, evaluate the expression. Assume the expression is properly
formed.
Example:
Input: - ( 3 + ( 2 - 1 ) )
Output: -4
@author: ms
"""
import ... |
dedb3ae48ec057f7cb002d98695e237e97b3b0f8 | msemjan/coding_interview_questions | /src/pi_estimate.py | 340 | 4 | 4 | from random import random # perform this import outside the function
def find_pi(n):
"""
Function to estimate the value of Pi
"""
inside=0
for i in range(0,n):
x=random()
y=random()
if (x*x+y*y)**(0.5)<=1: # if i falls inside the circle
inside+=1
pi=4*ins... |
96a5711b2d05f6a28605e5ee5a5f9a2c385bb49f | msemjan/coding_interview_questions | /src/pythagoreanTriplets.py | 665 | 4.28125 | 4 | '''
# Find Pythagorean Triplets (Uber)
Given a list of numbers, find if there exists a pythagorean triplet in that list. A pythagorean triplet is 3 variables a, b, c where a^2 + b^2 = c^2
Example:
> Input: [3, 5, 12, 5, 13]
>
> Output: True
Here, 5^2 + 12^2 = 13^2.
'''
def findPythagoreanTriplets(nums):
nums_s... |
85fe37cc2fd459a3bfd9faa78eef5dfe0f4d03c6 | Yuvrender-Gill/French-Translator | /log_prob.py | 2,407 | 3.6875 | 4 | from preprocess import *
from lm_train import *
from math import log
def log_prob(sentence, LM, smoothing=False, delta=0, vocabSize=0):
"""
Compute the LOG probability of a sentence, given a language model and whether or not to
apply add-delta smoothing
INPUTS:
sentence : (string) The PROCESSED ... |
f5287962c86a4ba490671539709e55387b65182e | WinnyTroy/python_assesment-1 | /key_press/key_press.py | 1,976 | 4 | 4 | import unittest
class KeyPress(object):
"""
Create the dictionary to store the numbers as keys and the list of strings as values
Create a counter variable to store counts whenever a letter is found in the key-value pairing.
Convert the input string to uppercase for easier dictionary 'parsing'
loop... |
096a9cb6e5b381f54dd6961c8b923991365a9889 | UP-RS-ESP/GEW-DAP05-2018 | /Session_01/spiral.py | 415 | 3.578125 | 4 | import sys
import numpy as np
from matplotlib import pyplot as pl
def spiral(x, y, rho, phi):
xn, yn = x + rho * np.cos(phi), y + rho * np.sin(phi)
pl.plot([x, xn], [y, yn])
try:
spiral(xn, yn, 0.7 * rho, phi + np.pi / 4)
except Exception:
# ignore the RuntimeError: maximum recursion de... |
b6890d57a0af14bcfa499b97094f2c04877cd61f | shri9098/Pythoin_list | /fun/demo2.py | 157 | 3.625 | 4 | def missing_nu(l):
missing_l = []
return [x for x in range(l[0], l[-1]) if x not in missing_l]
l = [1, 2, 3, 4, 5, 8, 9, 101]
print(missing_nu(l))
|
95d1436e703a6aa687476e1614a4331b19485d2e | vpshastry/Artificial_Intelligence | /Project 4/question3_solver.py | 1,893 | 3.546875 | 4 | from math import sqrt
class Question3_Solver:
def __init__(self):
self.initCentroids = [(30, 30), (150, 30), (90, 130)]
return;
def getDistance(self, pointA, pointB):
X1, Y1 = pointA
X2, Y2 = pointB
return sqrt(((X1 -X2) **2) + ((Y1 -Y2) **2))
def getMinD... |
173ac7194b186c297295ebf9f75b3d48230603a8 | samirettali/ctf-scripts | /Cryptography/Analysis/word_frequencies.py | 640 | 3.65625 | 4 | from sys import argv
def frequencies(text, separator=' '):
d = dict()
strip = ['.', ',', '!']
for char in strip:
text = text.replace(char, '')
text = text.replace('\n', ' ')
for word in text.split(' '):
if word in d:
d[word] = d[word] + 1
else:
... |
6c28c84200655c2939e723a61361b355a065fe04 | samirettali/ctf-scripts | /Misc/translate.py | 794 | 3.890625 | 4 | #!/usr/bin/env python3
# Translates a string into another one for an entire file
from sys import argv
table = dict()
def load_table(filename):
with open(filename, 'r') as f:
for line in f:
symbol, translation = line.replace('\n', '').split('\t')
table[symbol] = translation
def t... |
ec424c88251432c7ce2898e513deecd199707a9a | CS-UTEC/tarea1-github-Joaquin-Caceres | /primo.py | 336 | 3.84375 | 4 | num = int(input("Ingrese un numero: "))
def nPrimo(num):
if num < 1:
return False
elif num == 2:
return True
else:
for i in range (2, num):
if num % i == 0:
return False
return True
resultado = nPrimo(num)
if resultado is True:
print("El numero es primo")
else:
print("El numer... |
ab101ca6166f419e8b190898e760aa06d74488cf | fwangboulder/DailyCodePractice | /BirthdayValidateApp/main.py | 3,579 | 3.5625 | 4 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
107fa70fc1d1525a6f2b78cd0dfd228f3b8d1ad1 | Shantti-Y/Algorithm_Python | /chap02/prac13.py | 2,456 | 4.25 | 4 | # coding: utf-8
# 日付を表す構造体が次のように与えられているとする。
#
# typedef struct {
# int y;
# int m;
# int d;
# } Date;
#
# 以下に示す関数を作成せよ。
# ・y年m月d日を表す構造体を返却する関数DateOf
# Date DateOf(int, y, int m, int d);
# ・日付xのn日後の日付を返す関数After
# Date After(Date x, int n);
# ・日付xのn日前の日付を返す関数Before
# Date Before(Date x, int n);
... |
636f6ae606adda12c038864c5e37baaa754835dd | Shantti-Y/Algorithm_Python | /chap01/prac18.py | 620 | 3.796875 | 4 | # coding: utf-8
# 下を向いたn段の数字ピラミッドを表示する関数を作成せよ。
# void nrpira(int n);
# 第i行目に表示する数字は、i % 10によって求めること
def nrpira(n):
i = n
while(i > 0):
l = (i - 1) * 2 + 1
a = []
for j in range(n - i):
a.append(" ")
for k in range(l):
a.append(str(n - i + 1))
a =... |
8ca721b206d5f7b3ed3e975248d2397cfeb2fbf7 | Shantti-Y/Algorithm_Python | /chap01/prac11.py | 495 | 4.09375 | 4 | # coding: utf-8
# 正の整数値を読み込んで、その値の桁数を表示するプログラムを作成せよ。
# たとえば、135を読み込んだら『その数は3桁です。』と表示し、1314を読み込んだら『その数は4桁です。』と表示すること。
# Main function
print("Indicate the number of digits you input")
print("Number :")
num = int(input())
n = 1
i = 0
while(num - n > 0):
n *= 10
i += 1
print("This number has {0} digits".format(i... |
9aa90a2df1734f12f98a22e925575be47ccbb0f8 | Shantti-Y/Algorithm_Python | /chap02/prac04.py | 778 | 4.1875 | 4 | from random import randint as rand
#coding: utf-8
# List2-6(参考書参照)は身長を乱数で生成した上で身長の最大値を求めるプログラムであった。
# 身長だけでなく人数も乱数で生成するように書き換えたプログラムを作成せよ。
# 人数は、5以上20以下の乱数とすること。
def maxof(a, n):
max = a[0]
for i in range(n - 1):
if(max < a[i + 1]):
max = a[i + 1]
return max
#Main function
print("C... |
310a3f8748aa537f06014bd9258e889d0102095f | Shantti-Y/Algorithm_Python | /chap03/prac07.py | 930 | 3.859375 | 4 | # Searching a number from a lang class array program with 'bsearch' function in a descending order
def int_cmp(a, b):
if(a < b):
return -1
elif(a > b):
return 1
else:
return 0
def seqbsearch(key, base, size):
base.append(key)
ans = size
for i in range(size):
res... |
677757b62e888cb005d647708a63b1f89f16d987 | kashishh2/CodeWars-Kata-Practice | /strlen.py | 161 | 3.546875 | 4 | def s(num):
offset = len(num)%2==0
return num[len(num)//2-offset:round(len(num)/2)+offset]
if __name__ == '__main__':
print(s("hello"))
|
05aaf503fa651f97d153d80c6a281fae922bd056 | klarify-tech/sudoku-solver | /sudoku.py | 4,542 | 3.984375 | 4 | #Klarify.tech
#We will build a console based sudoku solver
class sudokuBoard:
box = []
rowValues = []
columnValues = []
subValues = []
value = " "
def __init__(self,value):
for x in range(81):
self.box.append(value[x])
def drawBoard(self):
count=0
... |
6a9178888251b1e30eac4076a6428cf4874ae641 | RoseCabbage/Leetcode_Solutions | /Solutions/23.合并k个排序链表.py | 1,593 | 3.796875 | 4 | #
# @lc app=leetcode.cn id=23 lang=python3
#
# [23] 合并K个排序链表
#
# https://leetcode-cn.com/problems/merge-k-sorted-lists/description/
#
# algorithms
# Hard (51.76%)
# Likes: 780
# Dislikes: 0
# Total Accepted: 139.6K
# Total Submissions: 267.5K
# Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'
#
# 合并 k 个排序链表,返回合并后的排序链... |
f515b0ffff6839d5511b6fc9063feb1bc1b22ce3 | jmunro4/polynomial-classes | /quadratictest.py | 3,271 | 4.0625 | 4 | #####################################
# quadratictest.py
# Jonathan Munro
#####################################
'''Prints statements that tests every aspect of the Quadratic class and aspects from the Polynomial class for the user to review.'''
from quadratic import *
from polynomial import *
def main():
'''print... |
640a387a08a022c98fdb7b8b5ae6a1f0e44d4ced | 603lzy/LeetCode | /543. Diameter of Binary Tree/543. Diameter of Binary Tree.py | 1,124 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getHeight(self, root):
"""
:type root : TreeNode
:rtype: int
"""
# Base Case:... |
02be3193941d7cb5523baf3c1bcba84f14bba3d4 | 603lzy/LeetCode | /557. Reverse Words in a String III/557.ReverseWordsinStringIII.py | 371 | 3.75 | 4 | class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
if s == "" or s == " ":
return s
wordsList = s.split(" ") # words list splited by blank
invstr = ""
for words in wordsList:
invstr += words[::-1]
... |
0cf26ce3fa88bf2534def982a1a0449d4fc0d003 | 603lzy/LeetCode | /107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II.py | 1,143 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
e668ff0bd8ba26409a88650c6c6a376467d5348b | 603lzy/LeetCode | /589. N-ary Tree Preorder Traversal/589. N-ary Tree Preorder Traversal.py | 585 | 3.609375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
Alogrithm preorder()
"""
value ... |
51a863cf4c2d28097ef6961202e1a5204e91a22c | 603lzy/LeetCode | /342. Power of Four/342. Power of Four.py | 289 | 3.78125 | 4 | class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
i = 0
while (4 ** i) < num:
i += 1
if (4 ** i) == num:
return True
else:
return False
|
67a173b6b55c3a59c3ba32f8e578ffa8b4e6bace | 603lzy/LeetCode | /520. Detect Capital/520. Detect Capital.py | 256 | 3.5625 | 4 | class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word.capitalize() is word or word.upper() == word or word.lower() == word # first big or all big or all small
|
e72e64f3ed4e0f13255c2e5c69f5761d182d4044 | hideman1231/OOP-python | /hw5/classes.py | 3,819 | 3.578125 | 4 | import csv
class Record:
def __init__(self, phone_number, address=None):
self.phone_number = phone_number # this should be unique
self.address = address
def __str__(self):
return f"{self.phone_number} {self.address}"
@classmethod
def from_csv(cls, fp):
with open(fp,... |
530a8a0ef7a36ef90eb632b95d8af6108a94aae7 | Bionkis/Bionkis | /Script4.py | 125 | 3.59375 | 4 | with open(filename, 'r') as fp:
lines = fp.readlines()
for i in range(len(lines)):
print("Line "+str(i)+":"+line) |
d58149aba50c100c9edd2feb6275279ae35889d2 | cassiefn/radial-basis-function-neural-network | /Backprop.py | 3,261 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 15:17:06 2019
@author: asadc
"""
'''
Backprop class takes a network model and data point to calculate
the gradient descent based on the error in each layer. It starts calculating
the error for the output layer first and then goes backwords for each layer.
'''... |
08233d0c1f5e7f78f4c483959f0596925d5d61e1 | amdmak2020/square | /bonusplz.py | 210 | 3.71875 | 4 | list = [1,2,3,4,5,6,7,8,9,10]
def square(l, x, y):
values = []
for i in l:
if i*i > y:
values.append(i*i)
else:
pass
return values
print(square(list,1, 10)) |
7fdb49f4df5473807bc8024f5770323a4b67d20e | Josekeitor/Top-Down-Parser | /main.py | 9,527 | 3.640625 | 4 | ''' Top Down parser (non-recursive)
This is a script to generate strings from a grammar that is represented as a dictionary, using productions.
The script builds a tree as it tries to construct the string, it keeps the tree properly pruned
in order to save memory and it takes in a maximum depth value to prevent infin... |
f32e5e22729b97f4a5f003e56109cd0d2b06ad7b | YMyajima/CodilityLessonPython | /lesson3-1/solution.py | 1,123 | 3.625 | 4 |
class TestValue:
def __init__(self, X, Y, D, expect):
self.X = X
self.Y = Y
self.D = D
self.expect = expect
class Solution:
def __init__(self):
self.test_values = [
TestValue(10, 85, 30, 3),
TestValue(10, 10, 30, 0),
TestValue(10, 1... |
9b42569f1322093475322a771f6f78c41c83ffb0 | RonanChang/Data_Structures | /week1_Python_review/Assignment[1]/Problem_4.py | 353 | 3.84375 | 4 |
def add_one(num_list):
#convert the string to a list and convert the list into an int
#int + 1
new_num = int(''.join(str(x) for x in num_list)) + 1
#convert the new int back to str
#and then convert the new string to a new list
new_list = [int(x) for x in str(new_num)]
return new_list
tes... |
25a2054b60e36b2458303f0b4be16ec3cdbb8a7e | RonanChang/Data_Structures | /week3_recursion/Assignment[3]/problem_3.py | 454 | 3.9375 | 4 | #The first method is provided, a recursive function
def recur(n):
if (n < 0):
return -1
elif (n < 10):
return 1
else:
return (1 + recur(n // 10))
print(recur(1000))
#This is the method using iteration as required
def recur_iteration(n):
result = 0
if n < 0:
... |
bc3daab19eff25fc4fc4a76886f667b635a90563 | RonanChang/Data_Structures | /week3_recursion/Assignment[3]/problem_6.py | 580 | 3.578125 | 4 | #This method is for getting all the possible combinations from a list
import copy
def generateBillboards(names, size, result_list, position):
if len(result_list) == size:
print(result_list)
elif position != len(names):
copy_list = copy.deepcopy(result_list)
result_list.append(names[posi... |
a603ed83eb1c61d7bae490401133f97a9a1452f4 | RonanChang/Data_Structures | /week2_runtime/recitation_exercise/question_2_time.py | 1,812 | 3.75 | 4 | import timeit
import matplotlib.pyplot as plt
import random
def timeFunction(f,n,repeat=1):
return timeit.timeit(f.__name__+'('+str(n)+')',setup="from __main__ import "+f.__name__,number=repeat)/repeat
def prefix_average1(S):
n = len(S)
A = [0] * n
for j in range(n):
total = 0
for i in ra... |
1769e7ee9a9dad0296ef5fd1e189ac4f8ac1e6c6 | ayush94/Python-Guide-for-Beginners | /FactorialAlgorithms/factorial.py | 1,290 | 4.1875 | 4 | from functools import reduce
'''
Recursively multiply Integer with its previous integer (one less than current number) until the number reaches 0, in which case 1 is returned
'''
def recursive_factorial(n):
# Base Case: return 1 when n reaches 0
if n == 0 :
return 1
# recursive call to function with the integer ... |
29472be57b07f8cb6d7790db0d2a52c1aefc7238 | lmquan1609/Pytorch_Tutorial | /06_data_loading/pyimagesearch/nn/conv/lenet.py | 1,705 | 3.5 | 4 | from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Activation, Flatten, Dense
from keras import backend as K
class LeNet:
@staticmethod
def build(width, height, depth, classes):
# initialize the model
model = Sequential()
input_shape = (height, w... |
9f3d81269c9d8c53cc9cd7719f398e93a91ef704 | lmquan1609/Pytorch_Tutorial | /12_finetuning_torchvision/custompytorch/nn/dynamicnet.py | 1,114 | 3.609375 | 4 | import torch
from torch import nn
import numpy as np
class DynamicNet(nn.Module):
def __init__(self, depth_in, hidden_layer, depth_out):
super().__init__()
self.input_linear = nn.Linear(depth_in, hidden_layer)
self.middle_linear = nn.Linear(hidden_layer, hidden_layer)
self.... |
f9ec8b68390d98b1f9f2928c3345883f0474478e | RaphaelCoelhof3/Python-.coursera. | /Semana3/Opcional/Exerc1_sem3_opc.py | 406 | 3.953125 | 4 | print("Digite os valores de coordenadas x e y dos pontos A e B respectivamente:")
xa = int(input("Coordenda x do ponto A: "))
ya = int(input("Coordenda y do ponto A: "))
xb = int(input("Coordenda x do ponto B: "))
yb = int(input("Coordenda y do ponto B: "))
import math
Hipotenusa = math.sqrt((xb - xa)**2 + ... |
df39e064ef580e1a2361d468159b9fb9b0b6bd4b | RaphaelCoelhof3/Python-.coursera. | /Semana5/Opcional/Exerc1_Sem5_OPC.py | 548 | 4 | 4 | def fizzbuzz(numero):
#'FizzBuzz' se o número for divisível por 3 e por 5;
if numero % 5 == 0 and numero % 3 == 0:
return 'FizzBuzz'
#'Fizz' se o número for divisível por 3 e não for divisível por 5;
elif numero % 3 == 0:
return 'Fizz'
#'Buzz' se o número for divisível por 5 e... |
e8c65e63fa412ad59041b1c033d02508a64fa81c | RaphaelCoelhof3/Python-.coursera. | /Semana3/Exerc1_sem3.py | 300 | 4.0625 | 4 | número = int(input("Entre com um número inteiro:"))
if (número % 2 == 0): #um número é par quando o resto da divisão por 2 é semelhante a 0.
print("par")
else: #Caso contrário, se o reto da divisão por 2 não for igual a 0 significa que ele é um número impar.
print("ímpar")
|
b8d4d3a26ac844ded84fe6150a26dd6ae56366d7 | KatarzynaKuich/modul4.3-lista-zakupow | /sklep.py | 528 | 3.78125 | 4 | def shopping(items, payment='card', shop='local shop'):
result = ""
result = result + "Idę na zakupy do %s.\n" % shop
result = result + "Kupię następujące rzeczy:\n"
for item in items:
result = result + " - %s\n" % item
result = result + "By zapłacić, używam %s." % payment
return result
... |
e224a34ec37f50014e7dde73993710b560d54606 | FilipM13/design_patterns101 | /pattern_bridge.py | 2,431 | 4.28125 | 4 | """
Bridge. Structure simplifying code by deviding one object type into 2 hierarchies.
It helps solving cartesian product problem.
Example:
In this case if I want to create one class for every combination of plane and ownership i'd need 16 classes (4 planes x 4 ownerships)
Thanks to bridge pattern I only have 8 cl... |
47d36bece3f27fbc20175ed62cfddb8d4beb016d | FilipM13/design_patterns101 | /pattern_command.py | 1,260 | 3.546875 | 4 | """
Command. Allows passing request as an object to commands.
here:
Receiver - request object
Command, Print, Verification - command classes that can execute a method
Invoker - command caller
"""
from abc import ABC, abstractmethod
class Receiver:
def __init__(self, name, age):
self.name = name
self.a... |
1a7bde719c2731aed129c9d141abfe40693ceb7d | FilipM13/design_patterns101 | /pattern_observer.py | 1,501 | 3.796875 | 4 | """
Observer. Pattern that allows notifying other objects about taken action.
here:
Subscriber - class which instances are to be notified
Channel - class which instances are to notify Subscribers
"""
class Subscriber:
def __init__(self, name):
self.name = name
def get_notification(self):
print(f'I, {... |
5a8cef7222dc2cf61e58a594183c742ace27e10f | mylons/changemaker | /change/util.py | 3,136 | 3.9375 | 4 | __author__ = 'mylons'
class ChangeMaker:
def __init__(self, coins):
"""
requires a list of integers as input
:param coins: list of integers
:return: ChangeMaker object
"""
assert isinstance(coins, list) and len(coins) > 0
# sort coins into ascending order s... |
71fe2bebf9925514d668e008e024477fe98d4894 | Rikharms1972/py4neteng | /Python-Files/py-gen/files-01-read-write-time.py | 987 | 3.59375 | 4 | import os
import time
# open with read access
input_file = open('test.txt', 'r')
# open and overwrite
output_file = open('results.txt','w')
# read all the lines into a list of lines
line_list = input_file.readlines()
# walk the list of lines taking each line
for line in line_list:
# find the local time
time_n... |
9b3e9fd005bb5e222d3927ac26631ead88c531ea | jg00/w201_objects_classes | /assn1_bankaccount.py | 1,117 | 3.5625 | 4 |
class BankAccount:
def __init__(self, first_name, last_name, middle_name, account_type, balance):
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.account_type = account_type
self.balance = balance
if (self.balance >= 100):... |
93423877a5264fa60fd133bc08f8bc39cc2e9f03 | samuelluo/practice | /taxicab_number/taxicab_number.py | 935 | 3.546875 | 4 | # Build list of sorted sum of cubes
cubes = [i**3 for i in range(1, 1000)]
soc_list = [] # [(soc, num_i, num_j)]
for j in range(len(cubes)):
for i in range(j+1):
num_i, num_j = cubes[i], cubes[j]
soc = num_i + num_j
soc_list.append((soc, num_i, num_j))
soc_list = sorted(soc_list, key=lamb... |
78b5b3a4e8076f804716015f9ea3d8bcb419ea2f | samuelluo/practice | /bst_second_largest/bst_second_largest.py | 2,041 | 4.125 | 4 | """
Given the root to a binary search tree, find the second largest node in the tree.
"""
# ----------------------------------------
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def bst_insert(root, val):
if root is None... |
96de67691c3b6ae5a0708e792c4346e786fce4fe | samuelluo/practice | /prime_factorization/prime_factorization.py | 473 | 3.875 | 4 | import math
def prime_factorization(n):
factors = []
while n % 2 == 0:
factors.append(2)
n = int(n/2)
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
factors.append(i)
n = int(n/i)
if n != 1:
factors.append(n)
return factors
n = ... |
8ac16563cee211e7c1113b4f1d1b3c48a9bfa826 | samuelluo/practice | /reverse_linked_list/reverse_linked_list.py | 1,395 | 4.125 | 4 | """
Given the head of a singly linked list, reverse it in-place.
"""
# ---------------------------------------------------------
class Node:
def __init__(self, val, next_=None):
self.val = val
self.next_ = next_
def build_linked_list(vals):
head = Node(vals[0])
curr_ = head.next_
prev_... |
b68006b4212bd981e735b358af91c72e51f38b5c | samuelluo/practice | /balance_travel/balance_travel.py | 1,621 | 4 | 4 | """
Suppose there are interviewing N job candidates for roles in New York and
San Francisco.
There are two costs associated with each candidate, one for sending him/her to
each city.
Split the candidates into two equal-sized groups while also minimizing travel
cost.
"""
# ----------------------------------------------... |
34a2729829a7ffc87cd7e4bf4e496801cae4fd4b | PatrickPuente/Curso-Python-CEC-EPN | /Clase 15-11-2019/dfdsfdfd.py | 402 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 19:29:29 2019
@author: CEC
"""
a = int (input("Ingrese un numero entre -10 a 10: "))
v=[]
for i in range(-11, 10):
i+=1
v.append(i)
print(v[4][1])
''' if a <= i:
print("No es mayor que", i)
elif a>= i:
print("Si es ma... |
d4969bea8dac65696ca28b28b9139436ec67b36d | PatrickPuente/Curso-Python-CEC-EPN | /Clase 1/Condicionales.py | 529 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 19 12:21:55 2019
@author: 1-26-PB-L2-13
"""
nativeVLAN=1
dataVLAN=100
if nativeVLAN==dataVLAN:
print("The native VLAN and the data VLAN are the same")
else:
print("The native VLAN and the data VLAN are different")
a=int(input("Cual es el nu... |
cd767e65120b4e2e4d17db36f13f1fdcf8f9c366 | motaz-hejaze/Python-Algorithms-and-Problem-Solving | /BinaryGap.py | 2,904 | 3.875 | 4 | """
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contai... |
2acd5d3c1bb903f6a066090355ef4fd27b9f7bfb | unabl4/AoC | /2018/day11/part2/chronal_charge.py | 2,838 | 3.6875 | 4 | # https://adventofcode.com/2018/day/11
def power_level(x,y,serial):
rack_id = x+10
power_level = rack_id * y
power_level += serial
power_level *= rack_id
num = str(power_level)[-3]
return int(num)-5
def generate_table(serial):
return [[power_level(x+1,y+1,serial) for x in range(300)] for y... |
a5d5d307af372400708e979446f0b40281c8c89b | wilding/Playground | /practice/date/jsontest.py | 401 | 3.53125 | 4 | import json
json_object = {
"instructions": [
{
"text": 1,
"image": 2,
"video": 3,
"gif": 4,
"note": 5
}
]
}
print json_object # is a dict
print '\n'
json_string = json.dumps(json_object) # is a string representation of dict
prin... |
63965cc467e6db33c27864319609e584cfc55cbc | wilding/Playground | /practice/date/datetest.py | 1,154 | 3.6875 | 4 | from datetime import date
print date.min
print date.max
print date.resolution
print '\n'
birthday = date(1990, 11, 12)
today = date.today()
christmas = date.fromordinal(359)
# from timestamp
print birthday
print today
print christmas
print '\n'
print today.year
print today.month
print today.day
print '\n'
print... |
282d53431333b2a69504a68f6027b1bea2b50a2d | hubbabubbagump/Python_Text_Game | /projectrevised.py | 15,891 | 3.671875 | 4 | import random
#############################################################################################
def read_string_list_from_file(the_file):
fileRef = open(the_file,"r") # opening file to be read
localList=[]
for line in fileRef:
string = line[0:len(line)-1] # eliminates trailing '\n'
... |
3a3b120f031bd68e268513975d62aea18dc9dab4 | clintonboys/py-ton | /player.py | 2,431 | 3.609375 | 4 | class Player(object):
def __init__(self, batsman, bowler):
self._batsman = batsman
self._bowler = bowler
def bowler(self):
return self._bowler
def batsman(self):
return self._batsman
## a player is just a pair of a batsman and bowler
## print condition joins
# batsman_stats = {"name": Don Bradman,... |
e09d158467ebaa214429ce04b0c9bff68daf6e72 | mohammadmusawer/udpfiletransfer | /ServerSide/server.py | 1,439 | 3.609375 | 4 | #This is the server side of a client/server pair. It receives an image from the client in 1024kb packets
#Network Design. Prof Vokkarane
#Due 9/30/20
#Submitted 9/30/20
#By: Julie Dawley, Mohammad Musawer, and Ricardo Candanedo
import socket
# initializes the socket obj, hostname and port and binds it to the server
s... |
ae9973f853a110f61828cc9302089d194db527ba | lynnemunini/TurtleCrossingGame | /player.py | 788 | 4.1875 | 4 | from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
UP = 90
# Create a turtle player that starts out at the bottom of the screen and listen for the "Up" keypress to move the
# turtle north
class Player(Turtle):
def __init__(self):
super().__init__()
sel... |
8d1542adf3beb607803ede9ab1b76849486a6a15 | mizrael63/learning | /lesson5/task1.py | 1,344 | 3.6875 | 4 | from collections import defaultdict
i = 0
a = int(input("Введите количество предприятий: "))
dictionary = defaultdict()
print("Вводимые наименования и данные разделяются с помощью enter")
while i < a:
name, quart1, quart2, quart3, quart4 = (input("Введите название предприятия и его прибыль за 4 квартала: ") for _ ... |
fe84166843d6a6dba7bb21e47c3a61153e8aa08c | mizrael63/learning | /lesson2/task7.py | 914 | 3.875 | 4 | #7. Написать программу, доказывающую или проверяющую, что для множества натуральных чисел
#выполняется равенство 1+2+...+n = n * (n+1) / 2, где n - любое натуральное число
#Проверяющую
n = int(input("Введите любое натуральное число "))
i = 0
b = 0
while i <= n:
b = b + i
i += 1
y = int(n*(n+1)/2)
if b == y:
... |
66376e65a9d44209d72c3dfbf8b57fbf3c80152c | NivardoX/engComp.PO | /trie_tree/trie.py | 2,964 | 3.953125 | 4 | from trie_tree.node import Node
class Trie():
nodes = []
def __init__(self):
self.last_char = False
def delete(self,string):
print("Deletando a palavra {} da árvore".format(string))
string = string.lower()
string = list(string)
for node in self.nodes:
... |
4b3dec60067443cf7a7a069c5435e00b3e7d14d7 | escramer/minecraft-bot | /singleton.py | 631 | 3.765625 | 4 | """Module for the singleton decorator"""
def singleton(func_or_class):
"""
Decorator for the Singleton pattern for functions or classes
Example uses:
@singleton
def foo(x, y):
# Your code here
@singleton
class A:
def __init__(self, x, y):
... |
64c1acbb3b2b50ebf4d666a50740c55c8a700418 | HakuG/AlgorithmStuff | /Movies Probability DPProblem.py | 1,747 | 3.75 | 4 | import sys
# Given a sequence of Movies Ratings of two people, what is the probability that
# Alice picks "split" amount of movies and has more than or equal to
# twice the cumulative rating of Bob, who also picks "split" amount of movies.
def main():
size, split, maxnum = map(int, raw_input().split())
Ali... |
b93e897e8333021301f525a4dc721337107da27c | theGreenJedi/pyprojects | /NumPywalkthru.py/venv/main.py | 663 | 3.640625 | 4 | import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(np.__version__)
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
... |
7539709f50a5456e19db0746273734d264ff97cd | dodo1210/tcc_code | /resultado/pca.py | 728 | 3.65625 | 4 | import numpy as np
from sklearn.decomposition import PCA
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale
#Load data set
data = pd.read_csv('/home/douglas/Documentos/tcc_code/resultados/selecao/Planilha sem título - Página1.csv')
#convert it to numpy arrays
X=data.values
#S... |
14b42a9d467355fe8648bb3270d465ad39ac4c76 | 0xBADCA7/easyctf-iv-problems | /flagtime/server.py | 449 | 3.609375 | 4 | #!/usr/bin/env python3
import time
flag = "easyctf{ez_t1m1ng_4ttack!}"
def check(s):
for c in range(min(len(s), len(flag))):
if c < 3 and flag[c] == s[c]:
time.sleep(1)
if flag[c] == s[c]:
time.sleep(0.3)
else:
print("no")
return
if len(s)... |
2cfd9d012c7a5a116ffbf90fbbbee74dba0f710b | msznajder/allen_downey_think_python | /ch6.py | 6,778 | 4.53125 | 5 | ## Chapter 6 Fruitful functions
## 6.1 Return values
# We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.”
def area(radius):
a = math.pi ... |
620369233f7cb25553ec58246c922b11cca6bbd4 | msznajder/allen_downey_think_python | /ch3_ex.py | 2,743 | 4.6875 | 5 | """
Exercise 1
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
"""
def right_justify(s):
print((70 - len(s)) * " " + s)
right_justify("abba")
"""
Exercise 2
A fu... |
81180ac30f423ee7c8139c24f2fb9fdf86a285af | msznajder/allen_downey_think_python | /ch3.py | 8,894 | 4.5625 | 5 | ## Chapter 3 Functions
# A function is a named sequence of statements that performs a computation.
## 3.1 Function calls
# We have already seen one example of a function call.
type(42)
# The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this... |
3caeababf01bd2130596febdaada1b1cbfd861db | jazzathoth/DS3-Unit2-Sprint3 | /demo_data.py | 871 | 3.765625 | 4 |
import sqlite3
def make_demo():
conn = sqlite3.connect('demo_data.sqlite3')
curr = conn.cursor()
curr.execute('DROP TABLE IF EXISTS demo')
curr.execute('CREATE TABLE demo(s TEXT, x INTEGER, y INTEGER)')
curr.execute('INSERT INTO demo(s, x, y) VALUES ("g", 3, 9)')
curr.execute('INSERT INTO ... |
3eeb1e6de050f71bc4ddbfb76b9c4e111f917c8c | adekunleayodele/test | /venv/Scratch2.py | 503 | 4.15625 | 4 | # num1 = float(input("Enter first number: "))
# oper = input("Enter operation: ")
# num2 = float(input("Enter second number: "))
inport pexpert
num1 = input("Enter first number: ")
oper = input("Enter operation: ")
num2 = input("Enter second number: ")
import re
import pexpect
if oper == "+":
print(num1 + num2)
... |
4e0e84a549480f1579737bc3f3f70763bd51f1da | Prat9501/geektrust-python-traffic | /get_vehicles.py | 428 | 3.5 | 4 | def get_vehicle(climate):
if climate == "SUNNY":
data = {
"vehicle": ["CAR", "BIKE", "TUKTUK"],
"crater_constant": 0.8
}
elif climate == "RAINY":
data = {
"vehicle": ["CAR", "TUKTUK"],
"crater_constant": 1.2
}
else:
data... |
e5f3bab44c44f05bf25e5068d1b98be55506cfca | imazan00/Assigment_II_DSA | /not_unique_heap.py | 771 | 3.765625 | 4 | def get_parent(index):
return (index - 1) // 2 if index > 0 else 0
def insert_value(heap, value):
heap.append(value)
if len(heap) > 1:
index = len(heap) - 1
parent = get_parent(index)
while value < heap[parent]:
heap[index], heap[parent] = heap[parent], heap[index]
... |
3a3401a6501823d9c321d8ec2d32ac2cd02f4f42 | salil98/mario_game | /person.py | 1,571 | 3.5 | 4 | from controllers import *
class Person(object):
''' Definition For Person '''
def __init__(self, length, width, person_type):
''' Initializing Person '''
self.length = length
self.width = width
self.person_type = person_type
self.x = None
self.y = None
self.matrix = []
def setNewPosition(self,board... |
a0794e5436c8562491dd6d1f939ac018fce39806 | aayc/code-contest-problems | /algorithms/maximum-subarray.py | 242 | 3.640625 | 4 |
def bfmaxSubarray (arr):
m = 0
for i in range(0, len(arr)):
for j in range(i, len(arr)):
print "summing ", arr[i:j + 1]
v = sum(arr[i:j + 1])
m = max(v, m)
return m
print "bf max: ", bfmaxSubarray([-1, -2, 0, 1, -1, 2, -2])
|
1ba41dbe3934bcfb8c6abc1fff8b73e7b2b5181f | aayc/code-contest-problems | /kickstart/ra-2017-patterns/patterns-overlap.py | 523 | 3.546875 | 4 | T = int(input())
for tc in range(0, T):
boxA = list(input())
boxB = list(input())
boxI = boxA if len(boxA) > len(boxB) else boxB
boxJ = boxB if len(boxA) > len(boxB) else boxA
possible = True
for i in range(0, len(boxI)):
if i >= len(boxJ):
if boxI[i] != "*":
print("Ouch")
possible = False
bre... |
a03ba06467b03e4a842588ad355fff4407640c6b | cyberrunk/algorithm | /recursion.py | 498 | 3.953125 | 4 | def recursion_multiply(a, b):
if b == 1:
return a
return a + recursion_multiply(a, b - 1)
def recursion_factorial(n):
if n == 1:
return 1
return n * recursion_factorial(n - 1)
def towers(n, fr, to, spare, k):
if n == 1:
print_move(fr, to, k)
else:
towers(n - 1... |
381bb58a0f76724624e4063eef54d5f8d6752fc7 | xarenwo/crypto | /CaesarCipher.py | 890 | 3.796875 | 4 | import string
def caesarEncrypt(plaintext:str,key:int):
alphabet = string.ascii_lowercase
plaintext = plaintext.lower()
shifted_alph = alphabet[key:] + alphabet[:key]
table = str.maketrans(alphabet,shifted_alph)
endtext = plaintext.translate(table)
return endtext
def caesarDecrypt(plaintext:s... |
6e0020f8a5a1e1c861bab4e85f18dd5ff5ede756 | Sumedh31/algos | /python/InterviewProblems/singleElements.py | 581 | 3.953125 | 4 | '''
Created on 07-Aug-2019
@author: Sumedh.Tambe
/ Given a non-empty array of integers, every element appears twice except for one. Find that single one.
//Example 1:
//Input: [2,2,1]
//Output: 1
//Example 2:
//Input: [4,1,2,1,2]
//Output: 4
'''
if __name__=='__main__':
#givenArr=[4,1,2,1,2]
givenArr=[-1,0... |
8b5742c0de44f2a7c2e1a0615f619a68c88581b8 | Sumedh31/algos | /python/Misc/palindrome.py | 486 | 3.953125 | 4 | '''
Created on 10-Jul-2019
@author: Sumedh.Tambe
list=[11,23,45,32] 32,45,23,11
'''
#
# inputList=[11,23,45,32]
def reverseTheList(List):
length=len(List)
reversed=[]
for I in range(length-1,-1,-1):
reversed.append(List[I])
return reversed
str1='Mathematics'
str2='malayalam'... |
1587e3d486de3b2db068723637f3e55e8a20482b | Sumedh31/algos | /python/Misc/MaxOccurredCharInString.py | 948 | 3.875 | 4 | '''
Created on 18-Jan-2021
@author: sumedh
Given a string, find max occurred character in it. If found multiple character with same number of
occurrence then return the first occurred character from string
E.g if str="abbcc" then return b =2 occurrence
'''
#Brute force
str="hello world"
# Max=0
# MaxChar=""
#
# for... |
32a06e2e3e127db4fb2c012ec3703a7d9607cb1f | Sumedh31/algos | /python/Misc/fib.py | 283 | 3.71875 | 4 | '''
Created on 11-Jun-2019
@author: Sumedh.Tambe
'''
numberFib=int(input("Give number = "))
a=0
b=1
for I in range(numberFib):
if(I==0):
print(0,end=' ')
elif(I==1):
print(1,end=' ')
else:
c=a+b
a=b
b=c
print(b,end=' ') |
55bb2c5c7a8fa2d44fa77dc4b9e053a4f67a263f | Sumedh31/algos | /python/Codelity/maxNoOfWordsInGivenSentenses.py | 753 | 3.984375 | 4 | '''
Created on 12-May-2019
@author: Sumedh.Tambe
'''
# import re
#
# print(re.split('\.|\?|!',"We test coders. Give us a try?"))#
# res = len("We test coders".split())
# print(res)
# COunt no of max words from given a string of sentenses.
import re
def solution(S):
# write your code in Python 3.6
List... |
cecb6007da096bf14b1c6795d56f1899e8529648 | june07/packagecontrol.io | /app/templates/helpers/eq.py | 603 | 3.609375 | 4 | def eq(this, options, val1, val2, *values):
"""
Pybars helper for seeing if a value is equal the other
"""
# Allow comparing two lists
if val2 and values:
values = list(values)
values.append(val2)
val2 = sorted(values)
if val1:
val1 = sorted(val1)
if... |
3282b392544a632095655ed19bef9dee84c2cc6a | june07/packagecontrol.io | /app/templates/helpers/split.py | 455 | 3.78125 | 4 | import math
def split(this, options, values, groups):
"""
Pybars helper for splitting an array of values
"""
groups = int(groups)
per_group = math.ceil(len(values) / groups)
output = []
for group in range(0, groups):
start = group * per_group
end = (group + 1) * per_group... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.