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 |
|---|---|---|---|---|---|---|
1474002269e9bf284b20131b9620e4bc1c3309ca | airakesh/CompSci | /ProblemSolving/find_a_number_in_sorted_rotated_array.py | 803 | 3.9375 | 4 | # Search an element in sorted and rotated Array
def search(A, low, high, B):
if low > high:
return -1
mid = (low + high) // 2
if A[mid] == B:
return mid
# If A[left...mid] is sorted
if A[low] <= A[mid]:
# As this subArray is sorted, we can quickly check if B lies in half o... |
aad324917eb47a2ec5d187ed099f10d1976fee2e | airakesh/CompSci | /ProblemSolving/stock_buy_sell_max_profit.py | 985 | 3.828125 | 4 | '''Python program to maximize the profit by doing at most k transactions given stock prices for n days'''
# Function to get maximum profit by buying & selling a share atmost k times for the given stock prices of n days.
def get_max_profit(stock_prices, n, k):
# Bottom-up DP approach
profit = [[0 for i in ran... |
46f0ad27a4266513dd4a91aa911dce55edfcccaa | airakesh/CompSci | /ProblemSolving/merge_trees.py | 938 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.left = self.right = None
self.data = data
def inorder(self):
if self.left:
self.left.inorder()
print(self.data, end=" ")
if self.right:
self.right.inorder()
def merge_tree(A, B):
if ... |
cd45184fb2c45cb505969e02122525623fdd939f | llenfan/hackerrank | /new_year_chaos.py | 1,189 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumBribes function below.
def minimumBribes(q):
bribes = 0
# Makes an iteration of the list until it is in order again (undoing all bribes to count them)
while q != list(range(1, len(q) + 1)):
for i, n i... |
c481f8ff8ef73eb2e2f1234826bd791a37f7f39d | Sas2k/Calculator | /advanced calculator.py | 640 | 3.953125 | 4 | run = True
def calculate(num1, sign, num2):
num1 = int(num1)
num2 = int(num2)
sign = str(sign)
if sign == '+':
print(num1 + num2)
if sign == '/':
print(num1 / num2)
if sign == '*':
print(num1 * num2)
if sign == '-':
print(num1 - num2)
print('to ... |
98b33e58b1ca9709c694dcdd8e39c52e8a4a4083 | xiaoruiguo/lab | /brdcast/mysqltest/showtable2.py | 633 | 3.828125 | 4 | #!/usr/bin/python
import MySQLdb
# Open database connection
#db = MySQLdb.connect("localhost","root","hello")
db = MySQLdb.connect("localhost","root","hello")
# prepare a cursor object using cursor() method
cursor = db.cursor()
try:
cursor.execute('CREATE DATABASE hostdb')
except:
print 'data bases existed'... |
d42d04b25861190fa06c0d09dc055437bf4cb532 | xiaoruiguo/lab | /fordict/test.py | 71 | 3.8125 | 4 | a = {'aaa':'aaaa','bbb':'bbbb'}
for i in a:
print i
print a[i]
|
3e506e2cc461c6fbcd3cb1a2643c00e4d9b3366d | xiaoruiguo/lab | /brdcast/mysqltest/inserttable1.py | 999 | 3.890625 | 4 | #!/usr/bin/python
import MySQLdb
# Open database connection
#db = MySQLdb.connect("localhost","root","hello")
db = MySQLdb.connect("localhost","root","hello", "hostdb")
# prepare a cursor object using cursor() method
cursor = db.cursor()
try:
cursor.execute('CREATE DATABASE hostdb')
except:
print 'data base... |
c3403af3130a1d17a2430390934955391650670d | abdulaziz661/python3progamming-coursera | /course_2_assessment_6.py | 2,235 | 4 | 4 | #Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5).
def sublist(lst):
i = 0
wh... |
5843ac6d892d271b31efafd28ce43cf07177c3cc | ondrno/tomatobot | /tomatobot/waterpump.py | 5,230 | 3.625 | 4 | from tomatobot import Relais, RelaisStatus, NoWaterExc
class WaterPump(Relais):
"""Implements a water pump controlled by a relay which is controlled by a gpio pin of a raspberry pi"""
def __init__(self, device, buck_size: float, min_level: float = 0):
super().__init__(device)
self._bucket_siz... |
3fe31446e797516c9173bda768ad2d7d71699422 | Achamoth/CITS4403_Project_Stock-Exchange-Model | /SocialSphere.py | 4,848 | 3.640625 | 4 | import Graph
import random
class SocialSphere(object):
g = None
def __init__(self, n=100, model='ba', k=2, p=0.15):
"""Creates a new SocialSphere
n: number of nodes/people (must be at least 3)
model: model used for network construction. Should be 'ba' for Barabase-Albert, or 'ws' fo... |
d79c4ee1a5c85a2015e11859ecccd1845b99557a | shomah4a/continuation-slide | /cps2_.py | 330 | 3.546875 | 4 | #-*- coding: utf-8 -*-
def fact(n, cont):
u'''
継続渡しスタイルでの階乗計算
'''
def n1_cont(m):
u'''
結果を受け取って次に渡す
'''
cont(n*m)
if n <= 0:
cont(1)
else:
fact_cont(n-1, n1_cont)
def p(x):
print x
fact_cont(5, p)
|
5dc55e68d64ec50e01eb22d276c853fd9a11747e | MBeshkov/maze-adventure | /rpsGame.py | 1,594 | 3.890625 | 4 | from getch1 import *
import sys
import random
def playRTS():
"""function for rock paper scissors duel with the gamer goblin and gamer monster"""
rps_array = ['rock', 'paper', 'scissors'] # possible choices
comp_choice = ''
user_choice = ''
gameOver = False
while not gameOver:
... |
49f152d7d63137b86e8beb4afc4a44344b35bf25 | shyamu-ar/python_programs | /divisor.py | 128 | 4.125 | 4 | def user_input(num):
return num%2==0
number = int(input("Enter a number to check even or odd: "))
print(user_input(number))
|
2ef28a01e29b586c8200d8ca7db948c89e5a0afc | senapati-deepak/titanic-dataset-prob | /Prediction.py | 9,993 | 3.59375 | 4 |
# coding: utf-8
# # **_Titanic Dataset Solution_**
# ***
# <br><br><br>To solve the titanic dataset we need to follow the following steps:-
# * Import the required Libraries.
# * Load the the training and test datasets.
# * Visualise the data with the help of graphs.
# * Carry out data analysis and d... |
95104dd69446673ab525431421d784c6cbf0e541 | krasch/smart-assistants | /recsys/classifiers/randomc.py | 1,326 | 3.5625 | 4 | # -*- coding: UTF-8 -*-
import random
import pandas
from base import BaseClassifier
class RandomClassifier(BaseClassifier):
"""
A classifier that gives random service recommendations, used as baseline in the experiments.
"""
name = "Random"
def __init__(self, features, target_names):
B... |
12abd510bd551ccafd2101bb6392c35357bdbe47 | mtmccarthy/langlearn | /bottomupcs/Types.py | 1,530 | 4.71875 | 5 | from typing import NewType, Dict
"""
In Chapter 1, we learned that 'Everything is a File!'. Here we've created a new type, 'FileType' which models a file
as its path in the filesystem.
"""
FileType = NewType('FileType', str)
"""
In Chapter 1, we learned about FileDescriptors, which are essentially integer indexes int... |
6bb5fbe258c60e039c2380dcbbf50dc6b8e5d803 | mtmccarthy/langlearn | /dailyredditor/easy/imgurlinks_352.py | 1,574 | 4.25 | 4 | from common import *
from typing import Union
"""
Finds the greatest exponent of n that is less than or equal to another number m
Example: if n = 2 and m = 17 return 4
"""
def get_base62_character(index: int) -> Union[str, None]:
capital_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower_case = 'abcdefghijklmnopqr... |
e9e2888aadd078af0b900974c2a951787184c658 | realayo/mentorship-py | /week-2/diceroll.py | 439 | 4.09375 | 4 | import random
print(random.randint(1, 6))
while True:
roll = random.randint(1, 6)
roll_again = input("To roll again, enter (y/n): ")
while roll_again != "y":
if roll_again == "n":
print("Game Over")
quit()
else:
print("Invalid input")
roll_agai... |
8db82e12f0cfa5f5863973711198b502f3acc666 | whywontitwork/PythonAdvanced | /07. Repetitive Statement/Ex_09.py | 203 | 3.53125 | 4 | ### 중첩 for 문 ###
'''
- 반복문안의 명령어에 또 반복문이 들어가있는 형태
'''
for i in range(10):
for j in range(10):
print("*")
print()
|
0f2a30acfc6ae4bcffa7a56e71c50e0ce75c3c6d | whywontitwork/PythonAdvanced | /03. Data Type/Ex_01.py | 3,983 | 4.125 | 4 | ### 자료형 ( Data Type ) ###
'''
1) 일반 자료형
1-1) 부울 ( bool )
1-2) 정수 ( int )
1-3) 실수 ( float )
1-4) 문자 ( str )
1-5) 문자열 ( str )
2) 고수준의 자료형
2-1) 리스트 ( list )
2-2) 튜플 ( tuple )
2-3) 딕셔너리 ( dict )
2-4) 집합 ( s... |
6c3da58c83d35c563ac5fc9c63d07cd95017ad56 | whywontitwork/PythonAdvanced | /07. Repetitive Statement/Ex_08.py | 452 | 4.0625 | 4 | ### 리스트 안 for문 ###
'''
- for문을 기준으로 오른쪽 부분은 데이터 생성 부분
- 왼쪽부분은 리스트에 저장되는 데이터 부분
'''
datas = []
for i in range(1,51):
datas.append(i)
print(datas)
datas2 = [i for i in range(1,51)]
print(datas2)
datas = []
for i in range(1,51):
datas.append(i*10)
print(datas)
datas3 = [i... |
95f304bc2c5bfaf664412d9b868ab08f40d01a52 | whywontitwork/PythonAdvanced | /07. Repetitive Statement/Ex_07.py | 474 | 4.09375 | 4 | ### enumerate ###
'''
- for문 안에서 데이터와 인덱스를 동시에 얻을수 있는 구문
[형식]
for 인덱스변수, 데이터변수 in enumerate(반복가능객체):
명령어
'''
datas = ["data1","data2","data3","data4"]
for i,j in enumerate(datas):
print(i,j)
print()
# 예제 1
datas = [-3,1,5,-5,7,-7,9,10,-343]
for i,j in enumerate(datas):... |
29844ceaccc4c0990982337b216e01a5547f81c3 | whywontitwork/PythonAdvanced | /09. Function/Practice_07.py | 313 | 3.59375 | 4 | # count 함수를 구현해보세요.
def my_count(datas,value):
cnt = 0
for i in datas:
if i == value:
cnt += 1
return cnt
lis1 = [1,2,3,1,1,1,1,2,3,4,5,2]
print(lis1.count(1))
print(lis1.count(2))
print()
print(my_count(lis1,1))
print(my_count(lis1,2)) |
c6899f6b076acde08c43ecfc5c51ee6456df684c | taytam/crystaldefense | /build/lib/projectile.py | 3,653 | 3.859375 | 4 | import pygame
from math import *
from graphics import *
from copy import deepcopy
class Projectile(pygame.sprite.Sprite):
def __init__(self, x, y, type, currTarget, enemiesInRange, damage):
pygame.sprite.Sprite.__init__(self)
self.type = type
self.damage = damage #inherited damage from Tower
self.xVel = 0 #st... |
082227f1f3c533bf39dfad8f0ef2d2aaef19e2b0 | Aniruddha008/computer-vision | /CNN-examples/example5.py | 1,307 | 3.5625 | 4 | from keras.layers import Conv2D
from keras.models import Sequential
from keras.optimizers import SGD
from keras.layers import MaxPooling2D
#image size = 28 x 28, colored , 3 channels
"""
2 convolutional layers:
32 and 64 filters respectively
kernel initializer = 'he_uniform'
kernel_size / filter_size = (3,... |
3d724abfe03b4e5f6a762906e0a62bea55e316af | captainalan/linked-list-problem | /add_two_numbers.py | 1,155 | 3.984375 | 4 | # Definition for singly linked list
# This was given with the problem
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# This is the function we were asked to write in the problem
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
... |
ce49437c13008c328087e2eacdf537850eddc807 | pkrysiak/decision-support-systems-lab | /ui.py | 1,045 | 3.515625 | 4 |
class UserInterface:
def __init__(self):
self.filePath = None
def fileMode(self):
mode = raw_input("File mode ? [Y/N]: ")
if mode in ["y", "Y"]:
defaultMode = raw_input("Default file mode ? [Y/N]: ")
if defaultMode in ["y", "Y"]:
... |
17ce6e5c354abe914abb538356201ed5cfc55a25 | lamyai-norn/algorithsm-week11 | /week11/thursday1.py | 279 | 4.15625 | 4 | def sumFromTo(start,end):
result=0
if start>end:
return 0
else:
for index in range(start,end+1):
result=result+index
return result
startValue=int(input("Start value : "))
endValue=int(input("End value : "))
print(sumFromTo(startValue,endValue)) |
3f1e14977a748c4eb83c0371005704343f35a6d0 | max-moazzam/pythonBible | /for.py | 518 | 3.828125 | 4 | vowels = 0
consonants = 0
for letter in "supercalifragilisticexpialidocious":
if letter.lower() in "aeiou":
vowels = vowels + 1
elif letter == " ":
pass
else:
consonants = consonants + 1
print("There are {} vowels and {} consonants".format(vowels, consonants))
students = {
... |
f4a810e817c4d6cc1fb545be4705e9d867dcd9ca | xwc1019/big-data-spring2018 | /week-01/scripts/first-script.py | 5,025 | 3.640625 | 4 | msg = "Python is printing me!"
print(msg)
import math
print(math.pi)
from math import pi
print(pi)
import pandas as pd
# I really feel disappointed by this windows system
"""
this is a
multiline
comment
"""
print("comments worked!")
x = 4.0
print(x)
print(x*2)
text = "this is the text we're storing"
print(text)
... |
4be84e1220b509a41ef9ef3b06ae4e62e84840f9 | yndevelop/healthcheck | /health.py | 365 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 22:43:00 2021
@author: user
"""
#import random
import random
#user health
health = 50
#diffculty levels
diffculty = 1
#convert float into a int()
check_health = int(random.randint(25,50) / diffculty)
health = health + check_health
#print... |
3ce463b0b5860ae48129db242597bb45d7620ecc | NikolasSchildberg/guesser | /guesser_simple.py | 1,218 | 4.21875 | 4 | """
Welcome to the number guesser in python!
The logic is to use the bissection method to find a number chosen by the user, only
providing guesses and asking to try a bigger or smaller one next time.
"""
# Initial message
print("Welcome to the number guesser!\nThink of a number between 1 and 1000 (including them).I'll... |
3b09918e700af24ac3dd1f1aa41064e71e8f8708 | ShengjieXu667/modeling-master | /code by chapter/Chapter 4/ch4_tf2_image_classif.py | 2,348 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 14:49:49 2020
@author: tom verguts
written for TensorFlow 2
image classification; could a two-layer network solve this task...?
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# images dataset
#(x_train, y_train)... |
a0c3b7797864185d567f0a9622595f9b2fd410b6 | carolyn1ee/carbox | /threeWayIntersec.py | 16,803 | 3.875 | 4 | #acts same as intersection but when it has cars, if there is no destination road,
#it sends the cars to one of the other roads.
#######only works with three way!! need to implement the check in intersections to make sure the light is green or yellow if it is not movable
#create a way to see how many cars have been b... |
6e56adfb71792ef5630cc1e02e1993b3573fb30e | AhmedElsayed201097/network-programming-task2 | /server.py | 1,459 | 3.890625 | 4 | """
server :
1- handle clients (accept connection ) =======> main process do that
2- handle send/recieve for each client =======>create 2 threads for each client """
# import socket lib used for client_server
from socket import *
#import threading libraries
from _thread import *
import threading
# to send and ... |
423b5d6ade51c67ca12aa62565cb31d3c78b7c10 | akkinasrikar/Data-structures-and-algorithms | /python/soring algorithms/selecionsort.py | 337 | 3.859375 | 4 | import numpy as np
numbers=[]
for i in range(10):
n=np.random.randint(1,100)
numbers.append(n)
print("Unsorted array: ",numbers)
l=len(numbers)
for i in range(l):
index=i
for j in range(i+1,l):
if numbers[index]>numbers[j]:
index=j
numbers[i],numbers[index]=numbers[index],numbers[i]
print(f"iteration ... |
1d343cbf79cb7c08b27d729c6e1deb475534cfdb | Roshan98b/DSA | /Algorithms/FibonacciSeries-DP1.py | 257 | 4.09375 | 4 | # Fibonacci Series using Dynamic Programming
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
f = [0, 1]
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return (f)
# Main function
if __name__ == "__main__":
print(fibonacci(5))
|
1c19631aec8bc1c77cacfa80d5e98ddbcb169648 | Roshan98b/DSA | /Algorithms/GCDarray-Math.py | 313 | 3.65625 | 4 | def gcd_pair(A,B):
if B==0:
return A
else:
return gcd_pair(B,A%B)
def gcd(n, arr):
if n==1:
return arr[0]
A = arr[0]
B = arr[1]
g = gcd_pair(A,B)
for i in range(2,n):
g = gcd_pair(g,arr[i])
return g
arr = [8,22,15]
n = len(arr)
print (gcd(n,arr)) |
4d17c91e6b734c0c7e3a2222fcac27b3a1d0d2a8 | Roshan98b/DSA | /Algorithms/AllConstruct-DP2.py | 654 | 3.75 | 4 | def all_construct(target_word: str, word_bank: list):
table = [[] for i in range(len(target_word) + 1)]
table[0].append([])
for i in range(len(table)):
if table[i] != []:
for word in word_bank:
if target_word[i:].startswith(word):
target_construct = [c... |
7803d567e5d033f3698f45b0837465025e7e4e01 | SHawkeye77/ttt | /ttt.py | 4,140 | 3.640625 | 4 | """
Unbeatable Tic-Tac-Toe AI
Samuel Hohenshell
Notes:
Minimizer = AI = -10
Maximizer = Human = 10
"""
import pygame
import make_board
import minimax
import game_start
import time
import sys
def main():
""" Variables used in our game """
keep_going = True
# Character representing the player
pl... |
6150528fcd6ecb0f9a68655746318a2f680ee546 | Antonio24ch/BEDU-281120 | /01_tabla_multiplicar.py | 485 | 4.15625 | 4 | #Preguntar el numero que el usuario quiere multiplicar
numero = int(input('Que número quieres multiplicar?\t'))
print(f'A continuacion se muestra la tabla del {numero}')
print('------------------------------------------------')
#Esta función hace esto:
# n * 1 = n
# n * 2 = n
# n * 3 = n
# ...
for n in range(10):
... |
bcce2fb06af5259cd1b29caf4e50392a1972056f | browngirlangie/Lesson7 | /Lesson 7/problem2/problem2.py | 139 | 3.8125 | 4 | x = input (' Pick a number: ')
x = int (x)
y = input (' Pick another number: ')
y = int (y)
total = x * y
total = str(total)
print (total) |
48959e2ae230e696fa9cd6e7ac96bdc50b9f6743 | topher235/python_scripts | /raining_code.py | 983 | 3.703125 | 4 | #NOTE TO USER:
#TO ESCAPE THE SCRIPT PRESS CTRL+C
import random
import threading
#Hexadecimal range: 21 - 79
#Add all symbols to an array based on their hexadecimal values
initial = '!'
hexa = ord(initial)
symbols = [initial]
space = []
for i in range(89):
hexa += 1
char = chr(hexa)
symbols.append(char)
#Gets a r... |
826f03f9f1dc41fe4aca2c70b505d7381ba091bf | EagleRock1313/Python | /circle.py | 523 | 4.40625 | 4 | # Load the Math Library (giving us access to math.pi and other values)
import math
# Ask for the radius of a circle that will be entered as a decimal number
radius = eval(input(("Enter the radius of the circle: ")))
# Computer circumference and area of this circle
circumference = 2 * math.pi * radius
area = math.pi ... |
1b6810dbc5adf1024b73a9dc2e19b5073ced1165 | abhijitdalavi3/AI | /python/practice/testpython/source/date_time.py | 164 | 3.8125 | 4 | from datetime import date
now = date.today()
print(now)
birthday = date(1994, 3, 15)
age = now - birthday
age = age.days / 360
print("AGE: ", age)
|
68ea79bfeec5ba4e4af849934a177308cff0c378 | marks828/front-end | /hamburger/app.py | 1,168 | 3.921875 | 4 | # PALINDROME
# def pal():
# word = raw_input('> ')
# word = word.replace(' ', '')
#
# rev = word[::-1]
#
# if word == rev:
# print "Correct"
# else:
# print "Incorrect"
# pal()
#
# pal()
# def pal(word):
# word.replace(' ', '')
# rev = word[::-1]
# if rev == word:
# ... |
8b5e21b4a7513d779881ae593e609c208a9019d6 | Jorden-Quast/shopping-list-cmd | /mainCMD.py | 1,699 | 3.703125 | 4 | import json
running = True
myList = []
try:
with open('myList.json', 'r') as f:
myList = json.load(f)
except FileNotFoundError:
pass
print("Welcome to my shopping list")
while running:
shopList = ", ".join(myList)
print("\nYour options at any time are to (a)dd an item, (d)elete an item, (c)a... |
f7267cacc276bc363dd7120f81275082bfc0b09f | jdevey/Euler-1-100-Solutions | /Problem_030/main.py | 209 | 3.53125 | 4 | BIG = 6*9**5
def isGood(nn):
n = nn
sm = 0
while (not n == 0):
sm += (n % 10)**5
n //= 10
return sm == nn
sm = 0
for i in range (10, BIG):
if (isGood(i)): sm += i
print(sm)
|
5d676fe8a1866f6ecc740a63fdc123a23283ed0d | Introduction-to-Programming-OSOWSKI/2-1-addition-checker-JacobVaerst23 | /main.py | 178 | 3.546875 | 4 | #WRITE YOUR CODE HERE
#define addCheck
def addCheck(x, y, z):
if x + y == z:
return True
else:
return False
#print the fuction
print(addCheck(2, 2, 4)) |
c5dd7cf0096128d8b60c9b70c5527d37a4fa302a | GargiGuptagd/June2020-Leetcode-Challenge | /June 8/Solution.py | 277 | 3.71875 | 4 | import math
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
i=0
while True:
num=math.pow(2,i)
if n==num:
return True
if num>n:
return False
i+=1
|
5d877374d2cd9863f73c2a2262953f55c1ab5318 | chandru-shane/DataStructuresAndAlgorithms | /Recursion/python/nested_recursion.py | 215 | 3.90625 | 4 |
"""
nested recursion function call will pass function call as argument
"""
def func(n):
if n > 100:
return n - 10
return func(func(n+11))
if __name__ == "__main__":
x = 98
print(func(x)) |
eb31423934f87effa6a27b0f0693c0319900c9b8 | chandru-shane/DataStructuresAndAlgorithms | /Recursion/python/indirect_recusion.py | 244 | 3.921875 | 4 |
"""
Indirect recursion is call one from another one
"""
def funcA(n):
if (n > 0):
print(n)
funcB(n-1)
def funcB(n):
if (n > 1):
print(n)
funcB(int(n/2))
if __name__ == "__main__":
funcA(25) |
ad79e77f208ea4c6a4abbc1d34b4ec0902da83cc | petemulholland/learning | /mazes/tests/celltests.py | 3,130 | 3.515625 | 4 | from mazes.cell import Cell
class CellTests:
def test_cell_create(self):
c = Cell(0, 0)
#print("testing Cell was created.")
assert c, "Failed to create cell"
#print("testing row was set correctly")
assert c.row == 0, "Incorrect row value on cell {0}".format(c.row)
#print("testing column was set correct... |
d15ef45e23c74f2a5c7678c9f728fbedac077422 | petemulholland/learning | /Python/ThinkPython/Chapter04/testmypolygon.py | 773 | 3.828125 | 4 | from swampy.TurtleWorld import *
from mypolygon import *
def test_square(turtle, count, length):
for i in range(count):
square(turtle, length * (i + 1))
def test_polygon(turtle, count, length, sides):
for i in range(count):
polygon(turtle, length + (i * 10), sides + i)
def test_circle(turtle,... |
60cc7f6a1517ad28ffeb757d94682705229ca4ce | petemulholland/learning | /Python/ThinkPython/Chapter18/Deck.py | 1,421 | 3.90625 | 4 | from Card import Card
import random
class Deck(object):
"""Represents a deck of playing cards"""
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
def... |
d7cc09f7881b7788bf00fd89308747597d84b0f1 | petemulholland/learning | /Python/ThinkPython/Chapter10/Chapter10.py | 6,893 | 3.765625 | 4 | import random
import time
# exercise 10-1
def nested_sum(ints):
""" takes a nested list of integers and add up the elements from all of the nested lists.
assuming on 1 level of nesting
"""
total = 0
for i in range(len(ints)):
total += sum(ints[i])
return total
def te... |
ebcf7ae783f11ff6e8908df29b9c0c46cd0b54af | petemulholland/learning | /Python/ThinkPython/Chapter18/MyCard.py | 1,364 | 4.15625 | 4 | class Card(object):
""" Represents a playing card"""
#suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
#rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
# '8', '9', '10', 'Jack', 'Queen', 'King']
suit_names = ('C', 'D', 'H', 'S')
rank_names = (None, 'A', '2', '... |
ae32faabd57669e986b80fbdc56c1db130031612 | PythonNagendra/22royalmechd12018 | /axis graph.py | 415 | 3.875 | 4 | import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1,2,3,4,5]
# heights of bars
height = [10,24,36,40,5]
# labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']
#plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])
... |
8551503350fc13546f013609da65dac73b9f0bda | rajatgupta310198/DSA-Python | /DSA-python/Hash/hash.py | 1,026 | 3.71875 | 4 | import os
os.system("clear")
class hashNode:
def __init__(self,data,key):
self.data = data;
self.key = key
self.next = None
class HashTable:
def __init__(self):
self.max_table_size = 20
self.hashtable = []*self.max_table_size
for i in range(0,self.max_table_si... |
3628e73f47e6e32eb8d9b4719d7dcac55f3d9e65 | laneenget/wake-the-sheeple | /back/datastore.py | 2,782 | 3.59375 | 4 | """
datastore.py
This file handles everything having to do with the database
"""
import sqlite3
import os
# database variable
db = os.path.join('conspiracystore.db')
class Connection:
# Create a new Connection Object
def __init__(self, latitude, longitude, magnitude, air, date, id):
self.lat... |
a45ed182c0d836da3f29ac4e8d9ecb918d0ee144 | shaitan1985/homeworks | /task_exception_free_land.py | 911 | 3.5 | 4 | from math import sqrt
errs = {
'bad_full': "Не задана площадь участка",
'bad_bed' : "Не задана площадь грядки",
'bad_larger': "Размер грядки больше размера участка"
}
def get_sides(full_area):
ratio = full_area[1].strip()
a, b = map(int, ratio.split(":"))
x = int(sqrt(full_area[0] * 100 / (a... |
fdeecfeec4bbea1b1c5bd1738bbadf905dcb3772 | Kapilmundra/Complete-Python-for-Lerner | /4 set.py | 691 | 4.21875 | 4 | #Create set
print("Create set")
s={"teena","meena","reena"}
print(s) # it can print in unorder way
#pop the element from the set
print("\npop the element from the set")
s.pop() # it can pop the element in unorder way
print(s)
#Add element in the set
print("\nAdd element in the set")
s.add("priya") # i... |
6993c4c414706551a69a16d0faa3001fcf8d22bd | alclass/YtIdsGenPySwDv | /generateYtidsForSqliteS.py | 1,375 | 3.6875 | 4 | #!/usr/bin/env python3
'''
From the page below:
http://www.learningaboutelectronics.com/Articles/How-to-generate-a-random-video-id-like-youtube-in-Python.php
We learnt two things:
1) a ytid is a 64-base 11-character string
2) this 64-base is composed of 26 Uppercase letters, 26 lowercase ones, 10 digits... |
e83f978346516017aa8e773117e4a41422e2ca84 | alclass/YtIdsGenPySwDv | /lib/functions/test_str_adjust_functions.py | 3,241 | 3.78125 | 4 | #!/usr/bin/env python3
'''
test_str_adjust_functions.py
Test of Functions for checking or adjusting strings.
'''
import unittest
import lib.functions.str_adjust_functions as adjfuns
class AdjustTest(unittest.TestCase):
def test_isItAllNumbers(self):
'''
Check whether a word is composed o... |
1d453b84bd50d7870acaaa8e070aa669515d3888 | nvoronin1337/Random-Walk-From-Point-to-Point | /rw_visual.py | 1,692 | 3.546875 | 4 | import matplotlib.pyplot as plt
from random_walk import RandomWalk
def paint_spatter(x_vals, y_vals):
colors = []
for i in range (0, len(x_vals)):
hex_strawberry = '#f82a2a'
hex_light_green = '#8ef82a'
hex_blue = '#2e2af8'
hex_yellow = '#f8e72a'
"""choose a color bas... |
3b754d56098641bc0604393f6fec4a7ed246b301 | marrecs/TR_Ho2 | /Codi_TR_Ho2.py | 5,363 | 3.59375 | 4 | #Treball Recerca H2o
#13-12-2018
#Importem llibreries
import time
import Adafruit_CharLCD as LCD
import sys
import RPi.GPIO as GPIO
from picamera import PiCamera
from time import sleep
import datetime
camera = PiCamera()
date_string = datetime.datetime.now().strftime("%Y-%m-&d-%H:%M")
#GPIO.setmode(GPIO.BOARD)
GPIO... |
b9e134e1eff552326aa1757ae61ac5e70695ce4f | Omkar-97/gTTS_example | /gTTS_example.py | 1,529 | 3.609375 | 4 | """
Sample representation of google text to speech (gTTS) library
"""
def get_candy():
import os
from gtts import gTTS
import sys
with open("chat.txt", "w+") as f:
sys.stdout = f
print("me: I want candies")
print("shopkeeper: How many candies do you want?")
n = int(inpu... |
751750bcd78114063d542e9297f743b5bace7b3e | amitkrdotmandal/Python-coding | /multiprocessin1.py | 652 | 3.625 | 4 | import os
from multiprocessing import Process, current_process
import time
import threading
def cube(i):
print("calculating cube.....")
for n in i:
result = n * n * n
time.sleep(.2)
print(f"the cube of {n} is {result}")
def square(i):
print("calculating square.....")... |
a0504680f7487baf0c42d67ac080225373df0e1d | BEUTControls/hello-world | /hello.py | 773 | 4.03125 | 4 | from time import sleep #This will allow us to use a pause in program
#
# If you are totally new to programming.
# the # allows you to enter a comment in python.
#
# Just so we are clear. I have absolutely no musical talent.
# Just wanted to spice up the hello-world.
# Play around with the timing.
def hellofunc(): # Th... |
3c6899bf2bd9bb4768cb26185de7631c4e18a0eb | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/maximum-swap.py | 987 | 3.953125 | 4 | """
# MAXIMUM SWAP
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Not... |
623f27b835c642e7b6f2bfddc1964eee56874f41 | das-jishu/data-structures-basics-leetcode | /Leetcode/easy/implement-stacks-using-queues.py | 2,507 | 4.03125 | 4 | """
# IMPLEMENT STACKS USING QUEUES
Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the el... |
cbd1a50edaf082a20f334de22ab0d889e5fb9833 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/divide-two-integers.py | 1,661 | 3.859375 | 4 | """
# DIVIDE 2 INTEGERS
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345... |
8a186f57d45dc3a64ad678e86eab317feb582f02 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/postorder-traversal.py | 1,166 | 4.0625 | 4 | """
# POSTORDER TRAVERSAL
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
Input:... |
1e55df9c946fe16d9ced35d6238e0c108d9ac858 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/perfect-squares.py | 1,330 | 3.71875 | 4 | """
# PERFECT SQUARES
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
"""
class Solution:
def numSquares(se... |
bcf99b8e4dbeee3581d4b8af385e8dc9fe333683 | das-jishu/data-structures-basics-leetcode | /Leetcode/easy/single-number.py | 683 | 3.90625 | 4 | """
# SINGLE NUMBER
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1... |
52075090a64382bedb3e66db716cf8233d9cef0a | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/search-2D-matrix.py | 1,384 | 4 | 4 | """
# SEARCH 2D MATRIX
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [[1,3,5,7],[... |
d86d7fdc1e4fb8c3e6c328b2d4141f5b2e078f66 | das-jishu/data-structures-basics-leetcode | /Leetcode/hard/regular-expression-matching.py | 2,506 | 4.28125 | 4 | """
# REGULAR EXPRESSION MATCHING
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Exampl... |
bd683cca8a3548140236243afa0b832135e7169c | das-jishu/data-structures-basics-leetcode | /Searching-and-sorting/binary-search.py | 877 | 4 | 4 |
def binary_search_iter(arr, target):
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] == target:
return True
elif arr[mid] > target:
right = mid - 1
else:
left = mid + 1
return False
def binary_sea... |
98c75eea12af28fb53c4a24f72ec9433f350a53b | das-jishu/data-structures-basics-leetcode | /Searching-and-sorting/insertion-sort.py | 375 | 4.09375 | 4 |
def insertion_sort(arr):
for i in range(1, len(arr)):
el = arr[i]
x = i - 1
while x >= 0 and arr[x] > el:
arr[x + 1] = arr[x]
x -= 1
arr[x + 1] = el
if __name__ == "__main__":
arr = [7, 3, 5, 6, 3, 1, 0, 8, 3]
arr2 = [3, 1]
insertion_sort(arr)
... |
e67c4ca45fef3f62b0448490c40d04d7bb3ff34e | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/count-numbers-with-unique-digits.py | 833 | 4 | 4 | """
# COUNT NUMBERS WITH UNIQUE DIGITS
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
excluding 11,22,33,44,55,66,77,88,99
Constraints:
0 <= n... |
eaef0c32b53970349a14c69f53df8b143eb29b97 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/coin-change.py | 1,634 | 4.03125 | 4 | """
# COIN CHANGE
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infin... |
120e13fe91549556d227be14f9bf9cfbea2e0723 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/4sum.py | 1,550 | 3.640625 | 4 | """ # 4 SUM
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Notice that the solution set must not contain duplicate quadruplets.
Example 1:
Input: nums = [1,0,... |
7f9fec33a56b941ed5b581cc29289e53e0e91495 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/design-add-and-search-words-data-structure.py | 2,810 | 3.765625 | 4 | """
# DESIGN ADD AND SEARCH WORDS DATA STRUCTURE
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched late... |
c1491f839d69356b250443087239523408c74e42 | das-jishu/data-structures-basics-leetcode | /Leetcode/easy/two-sum-II-input-array-sorted.py | 1,182 | 3.984375 | 4 | """
# TWO SUM II INPUT ARRAY SORTED
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:... |
6990ecdaea6992270b7dbcfb92c813a7004f596c | das-jishu/data-structures-basics-leetcode | /Searching-and-sorting/quick-sort.py | 835 | 3.921875 | 4 |
def q_s(arr):
quick_sort(arr, 0, len(arr) - 1)
def quick_sort(arr, first, last):
if first < last:
pos = split(arr, first, last)
quick_sort(arr, first, pos - 1)
quick_sort(arr, pos + 1, last)
def split(arr, first, last):
pivot = arr[first]
left = first + 1
right = last
... |
fad79a850863fa59320236acfa57ec00bda2a5da | das-jishu/data-structures-basics-leetcode | /Recursion/coin-change.py | 823 | 3.78125 | 4 |
def rec(target, coins, known):
min_coins = target
if target in coins:
known[target] = 1
return 1
# condition if there isn't a way to make the desired target
elif target < min(coins):
return 0
elif known[target] > 0:
return known[target]
else:
for i in ... |
3799878d6f7aeddc643150e44af9fb633985bc76 | das-jishu/data-structures-basics-leetcode | /Leetcode/easy/minimum-depth-of-binary-tree.py | 1,192 | 4 | 4 | """
# MINIMUM DEPTH OF BINARY TREE
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input:... |
ccc0a511f5ae0ec0ec660d5ea293b97b28ada6e1 | das-jishu/data-structures-basics-leetcode | /Trees/implement-with-OOP.py | 867 | 3.65625 | 4 |
class BinaryTree(object):
def __init__(self, value):
self.key = value
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
... |
ecdb8fca0b74cff5aaf023c87aed6a61f6395e12 | das-jishu/data-structures-basics-leetcode | /Arrays/string-compression.py | 387 | 3.859375 | 4 |
def compress(st):
result = ""
i = 0
length = len(st)
while i < length:
temp = st[i]
count = 1
i += 1
while i < length and st[i] == st[i-1]:
i += 1
count += 1
result += temp + str(count)
return result
if __name__ == "__main__":
pr... |
59d4865c48cf12bac99b751cec480b1aa52b59c5 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/simplify-path.py | 2,163 | 4.5 | 4 | """
# SIMPLIFY PATH
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period '.' refers to the current directory. Furthermore, a double period '..' moves the directory up a level.
Note that the returned canonical path mus... |
5d3dd6075ef521b68241107e55c4b40d02cf1300 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/number-of-islands.py | 1,420 | 4.09375 | 4 | """
# NUMBER OF ISLANDS
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [... |
9044e0ce47b199ce2194538113f0484d4bd081c2 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/decode-ways.py | 1,784 | 4.0625 | 4 | """
# DECODE WAYS
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: ... |
947cadcbb658e3cfd062d4346b816001b5e45fde | das-jishu/data-structures-basics-leetcode | /Searching-and-sorting/selection-sort.py | 400 | 4 | 4 |
def selection_sort(arr):
for i in range(len(arr)):
pos = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[pos]:
pos = j
t = arr[pos]
arr[pos] = arr[i]
arr[i] = t
if __name__ == "__main__":
arr = [2, 6, 4, 6, 7, 1, 0]
arr2 = [3, 1]
... |
5d91df9ba7a60245d0e0a4c158e3527000fdd33d | das-jishu/data-structures-basics-leetcode | /Trees/validate-bst.py | 612 | 3.734375 | 4 |
class Node(object):
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def validateBST(node, min, max):
if not node:
return True
if node.val < min or node.val > max:
return False
return validateBST(node.left, min, node.val) and valida... |
7028074d72039afc722149007fbae5fda2bba392 | SPARSHAGGARWAL17/DSA | /Linked List/linked_ques_4.py | 1,325 | 4.28125 | 4 | # reverse of a linked list
class Node():
def __init__(self,data):
self.data = data
self.nextNode = None
class LinkedList():
def __init__(self):
self.head = None
self.size = 0
def insertAtStart(self,data):
self.size += 1
node = Node(data)
... |
272bca0ac2aa4971420b2a157f85404837173de7 | atulj968/Python3-Basics | /lambda.py | 412 | 3.921875 | 4 | #(i)making a square fuction
square = lambda num: num**2
square(10)
#(ii)checking if number is even
even = lambda num: num%2 == 0
even(4)
even(7)
#(iii)grab the first number of string
first = lambda s: s[0]
first('Hello')
#(iv)reversing the string
rev = lambda s: s[::-1]
rev('Hello')
#(v) adder
adder = lambda x,y :x... |
707959dfcbf1e66fd544e96a706172066fb63d8e | Unknown-Flyin-Wayfarer/pycodes | /LIST/Q6.py | 168 | 3.515625 | 4 | li=['ssss',10,'kkkk','ddd',30,'a']
n=len(li)
count=0
for i in range(n):
if type(li[i]) is str:
if len(li[i])>=2:
count+=1
print (count)
|
d9402c751d352b002fff94a55c3d4f322e231e8d | Unknown-Flyin-Wayfarer/pycodes | /9/testFor.py | 307 | 4.15625 | 4 | # i starts from 0, will increment by +1 stop at the range
for i in range(3):
print("My name is Amit, value of i = ",i)
for j in range(6,10):
print ("Value of j = ",j)
for z in range(10,50,5):
print("Value of z = ",z)
for y in range(100,10,-10):
print("value of y = ",y)
|
50dfd4b377425832e0a75179c16433e00d68ffda | Unknown-Flyin-Wayfarer/pycodes | /7/test_if4.py | 658 | 4.25 | 4 | a = int(input("enter first number"))
b = int(input("Enter second number"))
if a > b:
print("a is larger")
if a > 100:
print("a is also greater than 100")
if a > 1000:
print ("a is greater than 1000 also")
print("a is only greater than and not 1000")
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.