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 |
|---|---|---|---|---|---|---|
b643e9a0d72242ed831b4e20b8edcc08258d50ad | summergirl21/Advent-of-Code-2016 | /Day03/Day3.py | 1,209 | 3.90625 | 4 | def main():
print("Hello")
input = open("Day3_input.txt", "r")
#input = open("Day3_input_test.txt", "r")
newinput = {0:[], 1:[], 2:[]}
for line in input:
line = [int(x) for x in line.split()]
for i in range(0, 3):
newinput[i].append(line[i])
print(newinput[0])
pri... |
f85f89d07de9f394d7f95646c0a490232bc3b7bc | whoismaruf/usermanager | /app.py | 2,605 | 4.15625 | 4 | from scripts.user import User
print('\nWelcome to user management CLI application')
user_list = {}
def create_account():
name = input('\nSay your name: ')
while True:
email = input('\nEnter email: ')
if '@' in email:
temp = [i for i in email[email.find('@'):]]
if... |
59406c79354db2ff825e18a503fa35a4883ca51d | avadesh02/fml-project | /srcpy/robot_env/two_dof_manipulator.py | 10,894 | 3.96875 | 4 | ## This is the implementation of a 2 degree of manipulator
## Author: Avadesh Meduri
## Date : 9/11/2020
import numpy as np
from matplotlib import pyplot as plt
# these packages for animating the robot env
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAn... |
f7691a737227df28f71e8c9d647858bf020523e7 | sidduGIT/Files_examples | /count_capitals.py | 163 | 3.671875 | 4 | with open('content.txt','r') as fh:
count=0
for line in fh:
for char in line:
if char.isupper():
count+=1
print(count)
|
ec458e18c02717868cd756367b3c7c1f7eb8b241 | pavdemesh/stepik_67 | /stepik_67_ex_2_6_spiral_v1.py | 512 | 3.703125 | 4 | number = int(input())
matrix = [[0] * number for h in range(number)]
row, col = 0, 0
for num in range(1, number * number + 1):
matrix[row][col] = num
if num == number * number:
break
if row <= col + 1 and row + col < number - 1:
col += 1
elif row < col and row+col >= number-1:
... |
d9247e91833eb5a66e7388dc3f8e4e1ea99de9d3 | pavdemesh/stepik_67 | /stepik_67_ex_2_6_4.py | 827 | 3.8125 | 4 | # Create empty list
matrix = list()
# Get input from user
while True:
line = input()
# Check if input == "end", break
if line == "end":
break
# Else convert input to a list of ints and append to the matrix list
else:
matrix.append([int(i) for i in line.split()])
# Create variables ... |
23051e5670e7af0274ea6226d679cf8bed225244 | cnguyen-uk/Blockchain | /block.py | 1,420 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
This is our Block class for transaction storage.
Note that although every block has a timestamp, a proper
implementation should have a timestamp which is static from when a
block is finally placed into the blockchain. In our implementation
this timestamp changes every time the code ... |
aab62b602367c12b4ebbf827a5b79ff4f1de84b9 | 18lkent/AFPwork | /GC-content.py | 682 | 3.53125 | 4 | dnaSequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" #The sequence being counted from
print("This program will display the gc content of a DNA sequence")
seqLen = len(dnaSequence) #Length of the sequence
gAmount = dnaSequence.count('G') #Amount of G's in the sequence
cAmount = dnaSequence.count('C') #... |
0ea8e85c1cc8eee1846c38d7adf6dcbb8de16aa5 | cmniccum/Exploring-BikeShare-Data | /bikeshare.py | 10,201 | 3.78125 | 4 | import time
import pandas as pd
import sys
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
fname = ""
separate = False
def log():
"""
This is a logging function which will determine whether to log the information
t... |
7e43010151fd990c1962e1c5847230315ff80d5c | kaka0525/data-strutctures-partII | /merge_sort.py | 1,792 | 3.703125 | 4 | from __future__ import unicode_literals
from time import time
from random import shuffle
def merge_sort(init_list):
if len(init_list) <= 1:
return init_list
list_left = init_list[:len(init_list) // 2]
list_right = init_list[len(init_list) // 2:]
left = merge_sort(list_left)
right = merge_s... |
d827875540a6004a7680a82649bdb58dc6f3431a | Aaron-Ramos/parcial-python | /py-parcial-q3-2020/clave_B/clave_b.py | 2,257 | 4.0625 | 4 | from math import pi
"""
***************************************************************
@@ ejercicio 1 @@
un metodo python que haga la suma de 3 numeros
2+4+6 = 12
"""
# start-->
def suma(numero1,numero2,numero3):
result = numero1 + numero2 + numero3
return result
"""
*************************... |
590e8b488d96bf5961cd747a44386b563a34b76f | richnamk/python_nov_2017 | /richardN/pythFundamentals/multSumAve/multSumAve.py | 248 | 3.5 | 4 | #Mult
#part 1
for x in range (0,1000):
if (x % 2 == 1):
print x
#part 2
for x in range (5,1000000):
if (x % 5 == 0):
print x
#Sum
a = [1, 2, 5, 10, 255, 3]
print sum (a)
#Ave
a = [1, 2, 5, 10, 255, 3]
print sum (a) / (len(a))
|
a5bb79e5269dfb2ac5076f11585d078e404202f5 | zazaho/SimImg | /simimg/dialogs/infowindow.py | 994 | 3.765625 | 4 | from tkinter import messagebox as tkmessagebox
def showInfoDialog():
""" show basic info about this program """
msg = """
SiMilar ImaGe finder:
This program is designed to display groups of pictures that are similar.
In particular, it aims to group together pictures that show the same scene.
The use case is t... |
b9f24efdbaffa1d8c8968c95cafe3025fc01d7e7 | nithinp300/texteditor | /texteditor.py | 1,377 | 3.578125 | 4 | from Tkinter import *
import tkFileDialog
root = Tk("Text Editor")
text = Text(root)
text.grid()
savelocation = "none"
# creates a new file and writes to it
def saveas():
global text
global savelocation
t = text.get("1.0", "end-1c")
savelocation = tkFileDialog.asksaveasfilename()
file1 = open(savelocation, "w")
... |
d76be366cdc01b27a2071c7e88a63fa5b8cbb1e5 | attainu/python-project-Shiva-dwivedi-au9 | /Saanp_Seedhi/Saanp_Seedhi.py | 11,487 | 3.671875 | 4 | import random
import time
import sys
class Saanp_Seedhi:
def __init__(self):
self.DELAY_IN_ACTIONS = 1
self.DESTINATION = 100
self.DICE_FACE = 6
self.text = [
"Your move.",
"Go on.",
"Let's GO .",
"You can win this."
]
... |
c1ba8dbefafd9ea87f4fe74c93e76afa47766fd4 | yrachkov/Python_2_online | /lesson9/hw3.py | 83 | 3.609375 | 4 | s = {'n':2,'d':6,'h':4,'u':11}
for y,l in s.items():
if l ==2:
print(y) |
0ab6be587b51f02f0db4f53534281be61c664c01 | GuiBritoPy/SimplesPySimples | /Jogo.py | 2,323 | 3.84375 | 4 | # -*- coding: utf-8 -*-
while True:
ok = "Ok, vamos continuar"
nome = str(input("Olá, qual o seu nome? "))
idade = str(input("Quantos anos você tem? "))
sexo = str(input("Qual o seu sexo? (M - Masculino e S - Feminino) ")).upper()
if sexo == "F":
sexo = Feminino
if sexo == "S":
s... |
33d262c8ef0f4f7de82ecab4a9fa9783c511e3ec | Italodias32/Python-Repository | /Animal.py | 1,486 | 3.6875 | 4 | class Animal():
def __init__(self, aux_nome, aux_peso):
self.__nome = aux_nome
self.__peso = aux_peso
#Getter e Setters do Nome
def get_nome(self):
return self.__nome
def set_nome(self, aux_nome):
if isinstance(aux_nome, str):
self.__nome = aux_nome
... |
411a14d6899d35beeab715b621d75d8052b288c5 | Italodias32/Python-Repository | /campeonato.py | 1,335 | 3.65625 | 4 | def vencedor(lista):
maior = -1
for i in lista:
if i.get_pontos() >= maior:
maior = i.get_pontos()
campeao = i.get_nome()
return campeao
class Participante():
def __init__(self, nome, index):
self.__nome = nome
self.__pontos = 0
self.__in... |
c4eff3bd9244d150afd43170f9d11e910237e416 | Alparse/artificial_intelligence | /tic_tac_toe.py | 7,445 | 3.765625 | 4 | """
Classic tic tac toe system implemented by Serhat Alpar.
Copied from Xxxxxxxxxxxxxxxxx
permalink: Xxxxxxxxxxxxxx
"""
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
class TicTacToeEnv():
"""
Description:
A game of classical tic tac toe is play... |
7f0d06254acda9ae0f22b35ddefa6f5d9bf53487 | league-python-student/level0-module1-samus114 | /_04_int/_2_simple_number_adder/simple_adder.py | 523 | 4.0625 | 4 | """
* Write a Python program that asks the user for two numbers.
* Display the sum of the two numbers to the user
"""
import tkinter as tk
from tkinter import messagebox, simpledialog, Tk
if __name__ == '__main__':
window = tk.Tk()
window.withdraw()
num1 = simpledialog.askinteger('', 'what is... |
19ed2bdb0d0e8098568d9cb987ddb8997124082b | Samson26/code | /minmax.py | 146 | 3.546875 | 4 | a=int(input())
arr=[int(i) for i in input().split()]
mini=min(arr)
mini1=int(mini)
maxi=max(arr)
maxi1=int(maxi)
print(str(mini1)+' '+str(maxi1))
|
15e7518c82297499f59d448a23822ee7c8859a8c | Samson26/code | /yesorno.py | 74 | 3.65625 | 4 | b=int(input())
if(b<=10 and b>=1):
print("yes")
else:
print("no")
|
525d87507fad34cf9a6ae9a4afa5c0f97b9af1aa | Samson26/code | /alpha.py | 97 | 3.75 | 4 | user=raw_input()
check=str(user.isalpha())
if check=='True':
print "Alphabet"
else:
print "No"
|
7190442863bed270614b64bd3e8e6055ec1f4960 | akansal1/statsintro_python | /Code/S10_normCheck.py | 930 | 3.515625 | 4 | '''Solution for Exercise "Normality Check"
'''
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.formula.api as sm
import seaborn as sns
# We don't need to invent the wheel twice ;)
from S12_correlation import getModelData
if __name__== '__main__':
# get the data
data = getModel... |
63e81f354f4ecbb4d2689d70815dfbec926c2013 | drashti2210/180_Interview_Questions | /merge_sorted_array.py | 1,444 | 3.84375 | 4 | import sys
sys.stdout = open('d:/Coding/output.txt','w')
sys.stdin = open('d:/Coding/input.txt','r')
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Example
# INPUT
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
# OUTPUT
# [1,2,2,3,5,6]
nums1=list(map(i... |
45ba4bf16bf612a0b2c9be396a77290ba419215a | drashti2210/180_Interview_Questions | /Mid_of_Linked_List.py | 932 | 3.921875 | 4 | import sys
#Day 5
# 2. Middle of Linked List
# INPUT:-
# 1->2->3->4->5->NULL
# OUTPUT: -
# 3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def middleNode(head):
# solution 1
# find the length of linked list
# iterate upto mi... |
b929e51eb223e63930330838af02d7d9fd37c9b7 | drashti2210/180_Interview_Questions | /Add_numbers_Linked_List.py | 1,159 | 3.875 | 4 | import sys
# Add two numbers as LinkedLis
# INPUT:-
# 2 linked list
# 1->2->3->->NULL
# 1->2->3->->NULL
# OUTPUT: -
# addition
# 2->4->6->NULL
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(self, l1: ListNode, l2: ListNo... |
4e4019378a59f2b0eb3668cc4c4fbb0abcfa2139 | drashti2210/180_Interview_Questions | /merge_sorted_LL.py | 973 | 4.03125 | 4 | import sys
# Day 1
# 4. Merge Sorted Linked List
#Example:-
#INPUT:-
# 2 sorted linked list
# 1->2->4, 1->3->4
#OUTPUT:-
# Merged Linked List
# 1->1->2->3->4->4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge(self, nums1: List[int], m: int, nums2: ... |
5eb0dc3ddab738e7e7d60960ce8e49142ab87a1f | mbaybay/cs686-2018-01 | /knn.py | 2,023 | 3.671875 | 4 | from classifier import classifier
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
class KNN(classifier):
def __init__(self, k=3):
self.x = None
self.y = None
self.k = k
def fit(self, x, y):
"""
:param X: pandas data frame, w... |
bd5d648e9f62bc9ba12ade748eddcaf9aba03474 | cmdavis4/senior-thesis | /spherical_geo.py | 3,242 | 3.65625 | 4 | #+++++++++++++++++++++++++++++++++++++++
#
# Spherical Geometry
#
# Description:
# This file contains the functions for
# spherical geometry calcuations
# including rotations, coordinate transformations
# and angular separations
#
#---------------------------------------
import numpy as np
import numpy.linalg as LA
... |
dd50743885e2a849652cef7243486196ce364b33 | vikramdayal/RaspberryMotors | /example_simple_servo.py | 2,287 | 4.0625 | 4 | #!/usr/bin/env python3
'''
simple example of how to use the servos interface.
In this example, we are connecting a sinle servo control
to GPIO pin 11 (RaspberryPi 4 and 3 are good with it)
Wiring diagram
servo-1 (referred to S1 in the example code)
---------------------------------------------
| servo wi... |
13a7cd02724849f25e7775b0fd1045364f3a5b98 | Dan609/code_learn | /ipython_log1.py | 3,943 | 3.75 | 4 | # IPython log file
get_ipython().run_line_magic('logstart', '')
class Car:
speed = 5
car1 = Car()
car2 = Car()
car1.engine
car2.engine
car1.engine = 'V8 Turbo'
car1.engine
car2.engine
Car.wheels = 'Wagon wheels ('
c1.wheels
car1.wheels
Car = Car()
Car
new_car = Car()
Car.speed
car1.speed
... |
ecb3c2aa29cc645e011d5e599a0ed24eb1f983b2 | PraneshASP/LeetCode-Solutions-2 | /69 - Sqrt(x).py | 817 | 3.9375 | 4 | # Solution 1: Brute force
# Runtime: O(sqrt(n))
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
sqrt = 1
while sqrt*sqrt <= x:
sqrt += 1
return sqrt-1
# Solution 2: Use Newton's iterative method to repeatively "guess"... |
3785a9becaf8fad4904ea2ec560aec3e6da7de03 | PraneshASP/LeetCode-Solutions-2 | /277 - Find the Celebrity.py | 1,748 | 3.796875 | 4 | # Solution 1: This problem is the same as finding a "universal sink" in a graph.
# A universal sink in the graph => there is no other sink in the graph, so
# we can just iterate through the nodes until we find a sink. Then check if it's universal.
# O(n) runtime, O(n) space
class Solution(object):
def findCelebri... |
b535625fb73b96be2ba8156e9f77c789b9b6e29a | PraneshASP/LeetCode-Solutions-2 | /90 - Subsets II.py | 2,191 | 3.78125 | 4 | # Solution 1: It is sufficient to just do a lookup to see if we
# have already made an existing subset. Runtime = O(nlogn * (2^n))
# You may see the sort in the loop and say it's O(nlogn * (2^n)), which
# isn't wrong, but note that there is actually only one subset of length n.
# There are exponentially more subsets ... |
d68997dde4826ce9781322db961198d8ac537173 | PraneshASP/LeetCode-Solutions-2 | /300 - Longest Increasing Subsequence.py | 5,129 | 3.828125 | 4 | # Solution 1: An O(n^2) algorithm is to start from the back of the array.
# Observe that the last element creates an LIS of size 1. Move to the
# next element, this will either create an LIS of size 2 (if it is smaller
# than the last element), or a new LIS of size 1.
# Repeat this process by moving backwards through t... |
4da19128caf20616ecbd36b297022b1d3ccb92ce | PraneshASP/LeetCode-Solutions-2 | /234 - Palindrome Linked List.py | 1,548 | 4.1875 | 4 | # Solution: The idea is that we can reverse the first half of the LinkedList, and then
# compare the first half with the second half to see if it's a palindrome.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution... |
9fa0f80646fcba2e31f4d42327304c335459cf81 | indefinitelee/Interview-Stuff | /numbers.py | 918 | 3.703125 | 4 | def main():
f("12365212354", 26)
def f(numbers, target):
for i in range(1, len(numbers)):
current = int(numbers[0:i])
to_end = numbers[i:-1]
evaluate(0, current, to_end, target, current)
def evaluate(sum, previous, numbers, target, out):
if len(numbers) == 0:
if sum + previ... |
e1557d11a69c703d33d90b123f65d8b34d0c69d2 | iainhemstock/Katas | /BinarySearch/python/BinarySearch.py | 468 | 3.78125 | 4 | def find_index_of(value, list):
index = -1
if len(list) == 0: index = -1
else:
lowpoint = 0
highpoint = len(list)
while lowpoint < highpoint:
midpoint = int((lowpoint + highpoint) / 2)
if value == list[midpoint]:
index = midpoint
... |
9598e90194eb277fd04ea04f0bb09b10083ab33d | iainhemstock/Katas | /LcdDisplay/python/main.py | 1,000 | 3.703125 | 4 | from lcd_digits import one, two, three, four, five, six, seven, eight, nine, zero
def parse(input):
switcher = {
"1" : one,
"2" : two,
"3" : three,
"4" : four,
"5" : five,
"6" : six,
"7" : seven,
"8" : eight,
"9" : nine,
"0" : zero
... |
ac95a08e0f92a66b9d1df15cddf154c33bc1befa | iainhemstock/Katas | /PrimeFactors/python/main.py | 916 | 3.828125 | 4 | import unittest
class PrimeFactors():
def of(n):
list = []
divisor = 2
while n >= 2:
while n % divisor == 0:
list.append(divisor)
n /= divisor
divisor += 1
return list
class PrimeFactororizerShould(unittest.TestCase):
def ... |
b551eb195b0f3f912eb56fbb774f6054488ee8bd | jigarshah2811/Python-Programming | /6-DS-Graph/test_graph.py | 1,804 | 3.796875 | 4 | from Graph import Graph
"""
TEST CASES
"""
print("\n============ Directed Graph ==============\n")
g = Graph()
edges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 15),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("F... |
869edf4c975e41ccdee0eacfbda1a636576578fc | jigarshah2811/Python-Programming | /Matrix_Print_Spiral.py | 1,741 | 4.6875 | 5 | """
http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
Print a given matrix in spiral form
Given a 2D array, print it in spiral form. See the following examples.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 1... |
4d07e9f7c2199352a664077c93d640d55304e84a | jigarshah2811/Python-Programming | /Interviews/Meta/SlidingWindow-PartitionArray.py | 1,479 | 3.859375 | 4 | """ Q: Partition Array so that Sum of all partitions are SAME
Given an array of integers greater than zero, find if there is a way to
split the array in two (without reordering any elements) such that the
numbers before the split add up to the numbers after the split. If so,
print the two resulting arrays.
=== Test c... |
5ea6b05ac7cd8c380f3e58b0f667c3ee021a0214 | jigarshah2811/Python-Programming | /4-DS-LinkedList/LinkedList.py | 1,839 | 3.953125 | 4 | class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, val=0):
self.head = None
def __append__(self, val):
if self.head is None:
self.head = self.Node(val)
return
# Append at the ... |
0fdb0ee310f777deb4a7de34085615bfe3d5802b | jigarshah2811/Python-Programming | /1-DS-Array-String/CarParking.py | 1,080 | 3.734375 | 4 | class Solution:
def parkingCars(self, parking):
freeSlot = len(parking)-1
for i, car in enumerate(parking):
if car == i: # If Car#K is already at ParkingSlot#K then no movement required
continue
# For car#i find target slot#i
targe... |
1c89bf03246ff0284b01255ec5827ff2866c8041 | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/BinarySearch.py | 1,014 | 4.09375 | 4 | from typing import List
class Solution:
def BinarySearch(self, nums: List[int], target: int) -> int:
# Binary search works only for sorted array, so make sure array is sorted
# Setup indexes, low and high and move them around low++ or high-- based on mid value
low, high = 0, len(nums)-1... |
3a369371f4bfaf5ebade5192a371a1d3e0214101 | jigarshah2811/Python-Programming | /1-DS-Array-String/Array-Misc-Easy.py | 3,101 | 4 | 4 | from typing import List, Tuple
"""
STRATEGY: Map, Modify as you go...
"""
class Solution:
def insertionSort(nums):
for i, num in enumerate(nums):
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
... |
8d68737c1826c508a060af1873b139fa083af8f5 | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/BS-RandomPickUniformDistribution.py | 1,736 | 3.5625 | 4 | import random
class Solution:
def __init__(self, w: List[int]):
# Generate [1/8, 3/8, 4/8]
totalWeight = sum(w)
for i, weight in enumerate(w):
w[i] = weight / totalWeight
# Generate on number line for uniform distribtion betwee 0%-100%
# [1/8, 4/8, 1]... |
dddd4ff528366a9bde62d630ef80f23abaeaa390 | jigarshah2811/Python-Programming | /5-DS-Tree/LL.py | 14,608 | 3.984375 | 4 | from TREE import TreeNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class DLLNode(object):
def __init__(self, item):
self.val = item
self.next = None
self.prev = None
# Definition for a Node.
class RandomListNode:
... |
b766eddd7865f3735da5cc59e44c22225c8cf644 | jigarshah2811/Python-Programming | /Algo-DP/Longest_SubString_Without_Repeat.py | 1,555 | 4.03125 | 4 | """
Longest Substring Without Repeating Characters
https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/
https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/
"""
def longestUniqueSubStr(str):
# HashMap {Char --> IndexLastSeen... |
56a53a69ddeb8f267a9ff221c3e91a7433af985a | jigarshah2811/Python-Programming | /8-DS-Design/HashMap.py | 2,321 | 3.859375 | 4 | """
https://leetcode.com/problems/design-hashmap/discuss/185347/Hash-with-Chaining-Python
"""
class ListNode:
def __init__(self, key, val):
self.pair = (key, val)
self.next = None
class HashMap:
def __init__(self):
"""
Initialize DS here: A HashMap is List of 1000 nodes, Each... |
4a5fc85b209138408683797ef784cbd59dd978fe | jigarshah2811/Python-Programming | /LL_MergeSort.py | 2,556 | 4.625 | 5 | # Python3 program merge two sorted linked
# in third linked list using recursive.
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Constructor to initialize the node object
class LinkedList:
# Function to initialize head
def __init__(self):
s... |
34860ea98e636d64ada5e34e3d025dcc898a23b1 | jigarshah2811/Python-Programming | /Algo-Greedy/timePlanner.py | 1,814 | 3.578125 | 4 | class Solution(object):
def planner(self, slotsA, slotsB, targetDuration):
res = []
a, b = 0, 0
start, end = 0, 1
while a < len(slotsA) and b < len(slotsB):
A = slotsA[a]
B = slotsB[b]
if self.overlaps(A, B):
print(("Overlapping... |
ea993d762ecccbaf00c838eecd5530604263057e | jigarshah2811/Python-Programming | /Algo-Backtracking-Recurssion/5_GraphColor.py | 1,598 | 3.90625 | 4 | class Solution:
def graphColor(self, graph, V, numColors):
def isSafe(curV, c):
# Check if this color is not applied to any connection of V.
for i in range(V):
print(("Checking vertex: [0]".format(curV)))
if graph[curV][i] and c == color[i]: # Ther... |
483184733d370d27c5b02dbaf2d578cac47f8701 | jigarshah2811/Python-Programming | /7-DS-Heap/TopKFreq.py | 1,699 | 3.78125 | 4 | from typing import List
import collections
import heapq
class Solution:
""" DS: Freq Map Algorithm: Bucket Sort
FreqMap {num: times}
Bucket {times: [num1, num2, num3]}
"""
def topKFrequent(self, nums: List[str], k: int) -> List[str]:
# Create Freq Map # {num: times}
freqMap = coll... |
f9e0bf6998f5ee9065ca8b27e56baa95907cb486 | jigarshah2811/Python-Programming | /Advance-OOP-Threading/OOP/ClassObject.py | 1,422 | 4.53125 | 5 | """
This is valid, self takes up the arg!
"""
# class Robot:
# def introduce(self):
# print("My name is {}".format(self.name))
#
# r1 = Robot()
# r1.name = "Krups"
# #r1.namee = "Krups" # Error: Because now self.name wouldn't be defined!
# r1.introduce()
#
# r2 = Robot()
# r2.name = "Pasi"
# r2.intr... |
082fb020db06e9d58f4ff9d06abe8fd3db745131 | jigarshah2811/Python-Programming | /Algo-Backtracking-Recurssion/Recur_BackTracking_WordSearch_Matrix.py | 1,733 | 3.734375 | 4 | class Solution(object):
def exist(self, board, word):
###### BACKTRACKING ##########
# 1) Breath -->: Go through all cells in matrix
for i in range(len(board)):
for j in range(len(board[0])):
# 2) isSafe --> Constraint: Word char match
# 3) Depth... |
30947d19e31e5d58137168d179d797d3f9c2a333 | jigarshah2811/Python-Programming | /3-DS-Stack-Queue/IncreasingStack-LargestAreaRectangle.py | 1,666 | 3.90625 | 4 | def largestRect(hist):
stack = list()
maxArea = 0
# Go through the hist once
i = 0
while i < len(hist):
if (not stack) or (hist[i] >= hist[stack[-1]]):
# Increasing sequence so keep adding indexes on stack
stack.append(i)
print(("Push index: {0}, curren... |
f8290f38eb41af185b5ae229ea1fe60c9b887fc5 | jigarshah2811/Python-Programming | /Pattern_BitManipulation_Sets/Bit_Manipulation.py | 1,578 | 3.578125 | 4 | class Solution(object):
def countBits(self, value):
count = 0
while value != 0:
if value & 1:
count = count + 1
value = value >> 1
return count
def setBit(self, value, bitNum):
value = value | (1 << bitNum)
return value
def r... |
da82f9c03c227499e5f72a758513c8e71a1f43cd | jigarshah2811/Python-Programming | /Algo-Sorting-Searching/Array_BinarySearch.py | 5,031 | 3.875 | 4 | import collections
import sys
"""
Regular Binday Search
"""
class Solution(object):
def binsearch(self, nums, target):
low, high = 0, len(nums)-1
while low < high:
mid = (low + high) >> 1
if target == nums[mid]: # Check if target is HERE
return mid ... |
aef347e759278a90472b16dc638a64282aabb574 | jigarshah2811/Python-Programming | /Stack_LargestRectangleInHistogram.py | 3,616 | 3.640625 | 4 | from STACK import Stack
"""
http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
"""
def LargestRectangleInHistogram(hist):
s = Stack()
i = 0
max_area = 0
# Scan through Histogram
while i < len(hist):
# Increasing ---> Current Hist > Prev Hist
if s.isEmpty() or hist[i... |
67c3f537284076c7a52854c5d1dc7a58d99d908d | jigarshah2811/Python-Programming | /Algo-DP/DP_LCS.py | 607 | 3.546875 | 4 | """
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
"""
def LCS(str1, str2):
m = len(str1)
n = len(str2)
L = [[0]*50]*50
for i in range(len(str1)+1):
for j in range(len(str2)+1):
if i == 0 or j == 0:
L[i][j] = 0
elif s... |
8fe0bcd0540ab6b12b3db8f6fa0619f218f0d89b | jigarshah2811/Python-Programming | /Hash_Last2ShortestStrings.py | 670 | 3.828125 | 4 | k = 3
mydict = {}
def insert(str):
global k
global mydict
try:
mydict[len(str)] = mydict[len(str)].append(str)
except KeyError:
mydict[len(str)] = [str]
sortedKeys = sorted(mydict.iterkeys())
# mydict = sorted(mydict, key=lambda item: item[0], reverse=True)
inserted = 0
... |
923c91352c1941344adada6d21014b06ce7add3d | jigarshah2811/Python-Programming | /8-DS-Design/DS_bloom_filter.py | 960 | 3.71875 | 4 | """
Space efficient probablistic DS for membership testing
Google uses it before Map Reduce
"""
from random import seed, sample
class BloomFilter(object):
def __init__(self, iterable=(), population=56, probes=6):
self.population = range(population)
self.probes = probes
self.data = set()
... |
2949f87f4092c51a398b8a3081bb45a42b010432 | jigarshah2811/Python-Programming | /Pattern-2-Pointers/2.MultiPassPattern-ProductExceptSelf.py | 2,519 | 3.734375 | 4 | from math import prod
from typing import List
"""
Pattern: Multi-Pass L -----> & <------- R
L = Prefix L Running Multiplier
R = Suffix R Running Multiplier
Result = Multiplier of (Prefix L * Suffix R)
Next Q: Trapping Rain Water!
"""
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
... |
6bbd0b28467b15d9d3d5103b41375d6c79999f6c | brunda4/Trees-1 | /solution41.py | 1,036 | 3.59375 | 4 | class Solution:
prev=None #initializing the global variabe prev to hold the previous node
def isValidBST(self, root: TreeNode) -> bool:
return self.inorder(root) #caling the inorder function for root
def inor... |
b510a87a4c15901bfb22b5568623d78be1a35d6d | EFulmer/sorts_of_sorts | /merge_sort.py | 895 | 4.0625 | 4 | # Standard merge sort, done in Python as an exercise.
from math import floor
from random import shuffle
def merge_sort(ls):
if len(ls) <= 1:
return ls
# in smaller arrays, it'd be better to do insertion sort to reduce overhead
mid = int(floor(len(ls)/2))
left = merge_sort(ls[0:mid])
right ... |
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65 | sabeeh99/Batch-2 | /fathima_ashref.py | 289 | 4.28125 | 4 | # FathimaAshref-2-HelloWorldAnimation
import time
def animation(word):
"""this function takes the input and displays it
character by character with a delay of 1 second"""
for i in word:
time.sleep(1)
print(i, end="")
animation("Hello World")
|
7fa5ac027e065348e292847aa7b03933fc57bef0 | Andriy-Hladkiy/ITEA_Python_Basic | /topic_1/task_4.py | 213 | 3.828125 | 4 | # Напишите программу, которая сортирует заданный список из чисел
list = ['topic_1', '23', '435', '143', 'topic_2', 'topic_1']
print(sorted(list, key = int))
|
56a57411d7f44b8a7c15b69fcbf11ac3001f3ab4 | hanucane/dojo | /Bootcamp/bootcamp-python/python_algorithm/lambda.py | 245 | 3.96875 | 4 | def map(list, function):
for i in range(len(list)):
list[i] = function(list[i])
return list
print( map([1,2,3,4], (lambda num: num*num) ))
print( map([1,2,3,4], (lambda num: num*3) ))
print( map([1,2,3,4], (lambda num: num%2) )) |
1fda8b3fd2d9f8aa385c9f365ae983fde0bc711a | hanucane/dojo | /Bootcamp/bootcamp-algorithms/linked-lists/SLists.py | 1,353 | 3.625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class SList:
def __init__(self, value):
node = Node(value)
self.head = node
def printAllValues(self):
runner = self.head
while runner.next != None:
... |
d2f96447565c188fcc5fb24a24254dc68a2f5b60 | hanucane/dojo | /Online_Academy/python-intro/datatypes.py | 763 | 4.3125 | 4 | # 4 basic data types
# print "hello world" # Strings
# print 4 - 3 # Integers
# print True, False # Booleans
# print 4.2 # Floats
# print type("hello world") # Identify data type
# print type(1)
# print type(True)
# print type(4.2)
# Variables
name = "eric"
# print name
myFavoriteInt = 8
myBool = True
myFloat = 4.2
... |
cdb6fb12e74cffd7dce421a4edd389d02d2b4523 | haalogen/hash_table | /func.py | 2,197 | 3.703125 | 4 | """Basic functionality of the project "Hash_Table"."""
def float2hash(f):
"""Float value to hash (int)"""
s = str(f)
n_hash = 0
for ch in s:
if ch.isdigit():
n_hash = (n_hash << 5) + n_hash + ord(ch)
# print ch, n_hash
return n_hash
class HashTable(ob... |
eb392b54023303e56d23b76a464539b70f8ee6e8 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/guessinggame6.py | 507 | 4.1875 | 4 | #!/usr/bin/env python
import random
highest = 10
answer = random.randint(1, highest)
is_done = False
while not is_done:
# obtain user input
guess = int(input("Please enter a number between 1 and {}: ".format(highest)))
if guess == answer:
is_done = True
print("Well done! The correct ans... |
7a3191f98809ba4587415bae2f7f638446c5d8c6 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/condcomp1.py | 1,472 | 3.8125 | 4 | #!/usr/bin/env python
menu = [
["egg", "spam", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
["spam", "egg", "sausage", "spam"... |
3d1946247a3518c4bd2128786609946be2ae768c | shamim-ahmed/udemy-python-masterclass | /section-4/exercises/exercise11.py | 638 | 4.21875 | 4 | #!/usr/bin/env python3
def print_option_menu(options):
print("Please choose your option from the list below:\n")
for i, option in enumerate(options):
print("{}. {}".format(i, option))
print()
if __name__ == "__main__":
options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have di... |
f9610b35b3785f1cd0b5a7ae4f00e2cd9856034a | shamim-ahmed/udemy-python-masterclass | /section-4/examples/strings3.py | 279 | 4.0625 | 4 | #!/usr/bin/env python
number = "9,223;372:036 854,775;807"
separators = ""
for c in number:
if not c.isnumeric():
separators += c
print(separators)
values = "".join([c if c not in separators else " " for c in number]).split()
print([int(val) for val in values])
|
75f04b946796c071f7913bf308f0bf1c40a4c441 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/conditions.py | 135 | 4.15625 | 4 | #!/usr/bin/env python3
age = int(input("Please enter your age: "))
if age >= 16 and age <= 65:
print("Have a good day at work!")
|
bcd6ddba72d2fe2c22112c11f6dbea95fe536d37 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/example_kwargs.py | 323 | 4.3125 | 4 | #!/usr/bin/env python
def print_keyworded_arguments(arg1, **kwargs):
print("arg1 = {}".format(arg1))
for key, value in kwargs.items():
print("{} = {}".format(key, value))
# you can mix keyworded args with non-keyworded args
print_keyworded_arguments("Hello", fruit="Apple", number=10, planet="Jupiter... |
43836b3fe753f9a651cd9f6cbc636c462cd63c81 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/guessinggame4.py | 416 | 4.0625 | 4 | #!/usr/bin/env python
import random
done = False
while done == False:
answer = random.randrange(1, 11)
guess = int(input("Please enter a number between 1 and 10: "))
if guess == answer:
print("Your guess is correct. The answer is {}".format(answer))
done = True
else:
print("S... |
f6008700b5aafa0c7f732e3d5e701832554017a7 | alihaiderrizvi/Leetcode-Practice | /all/29-Divide Two Integers/solution.py | 634 | 3.5625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend > 0:
div_sign = 0
else:
div_sign = 1
if divisor > 0:
dvs_sign = 0
else:
dvs_sign = 1
dividend = abs(dividend)
divisor = abs(div... |
4ec2bd94203ef8db68cd0039227d84bc4ea4c62e | alihaiderrizvi/Leetcode-Practice | /all/20-Valid Parenthesis/solution.py | 457 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stk = []
for i in s:
if i == "(" or i == "[" or i == "{":
stk.append(i)
elif stk and ((i == ")" and stk[-1] == "(") or (i == "]" and stk[-1] == "[")... |
7cae510cb7d7080ad784927bf19c07b3220aa64e | alihaiderrizvi/Leetcode-Practice | /all/720- Longest Word in Dictionary/720- Longest Word in Dictionary.py | 728 | 3.515625 | 4 | class Solution:
def longestWord(self, words: List[str]) -> str:
s = set(words)
good = set()
for word in words:
n = len(word)
flag = True
while n >= 1:
if word[:n] not in s:
flag = False
... |
ffb117397ed8532cd62567473b9fea61de0e3ee6 | Frankyyoung24/SequencingDataScientist | /Algrithms/week2/bm_algorithm.py | 1,283 | 3.5 | 4 | def boyer_moore(p, p_bm, t):
"""
Do Boyer-Moore matching.
p = pattern, t = text, p_bm = Boyer-Moore object for p (index)
"""
i = 0 # track where we are in the text
occurrences = [] # the index that p match t
while i < len(t) - len(p) + 1:
# loop though all the positions in t where ... |
617cd19401efd048959af80295b6a2fef88a15b6 | Amo123456/Assignment-submission | /project assignment/Project 1.py | 755 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Develop a cryptography app using python?
# In[9]:
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("Secret.key","wb")as key_file:
key_file.write(key)
... |
e6f7d7097cd80230a9374bfa5067e0759030ba45 | setu-parekh/Interactive-Programming-in-Python-Coursera | /Project 4: Arcade game - Pong/pong_game.py | 4,341 | 3.84375 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_HEIGHT = HEIGHT / 2
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [W... |
94dea85884bca08feccbf1c68e3bcc3388af668e | JosephLimWeiJie/algoExpert | /prompt/medium/MinHeightBST.py | 2,135 | 3.59375 | 4 | import unittest
def minHeightBst(array):
return constructMinHeightBST(array, 0, len(array) - 1)
def constructMinHeightBST(array, startIdx, endIdx):
if (startIdx > endIdx):
return None
midIdx = (startIdx + endIdx) // 2
bst = BST(array[midIdx])
bst.left = constructMinHeightBST(array, st... |
047b6808f400db0906409e22fb7e3897f9bda51a | kirillrssu/pythonintask | /PMIa/2014/Samovarov/task_3_17.py | 810 | 4.1875 | 4 | #Задача №3, Вариант 7
#Напишите программу, которая выводит имя "Симона Руссель", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Samovarov K.
#25.05.2016
print("Герой нашей сегодняшней программы - Симона Руссель")
ps... |
b40e51de38b2a5a3721f823e707b4bf526e1aefc | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv1.py | 208 | 4.0625 | 4 | # 1 Faça um Programa que peça o raio de um círculo, calcule e
# mostre sua área.
raio = 0
print("Digite o Raio do circulo")
raio = int(input())
area = 3.14 * raio**2
print("Área do circulo: %s" %(area)) |
34a43cd286f6018aee4d23a683ee1e6211db43f1 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv18.py | 268 | 3.65625 | 4 | # 18. A série de Fibonacci é formada pela seqüência
# 1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar a série
# até o n−ésimo termo.
a = 0
b = 1
n = int(input("Quantidade: "))
for i in range(n):
print(a)
aux = b
b = a + b
a = aux |
6820cd52316dc5bca7f89c75c7e7a1a6972981dd | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv12.py | 1,154 | 4.09375 | 4 | # 12. Uma fruteira está vendendo frutas com a seguinte tabela de
# # preços:
# # Até 5 Kg Acima de 5 Kg
# # Morango R$ 2,50 por Kg R$ 2,20 por Kg
# # Maçã R$ 1,80 por Kg R$ 1,50 por Kg
# # Se o cliente comprar mais de 8 Kg em frutas ou o valor total da
# # compra ultrapassar R$ 25,00, receberá ainda um desconto de 10%... |
5b577b07f4542809d54f9b64631cf258fcfcce8a | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv7.py | 961 | 3.65625 | 4 | # João Papo-de-Pescador, homem de bem, comprou um
# microcomputador para controlar o rendimento diário de seu
# trabalho. Toda vez que ele traz um peso de peixes maior que o
# estabelecido pelo regulamento de pesca do estado de São Paulo (50
# quilos8 deve pagar uma multa de R$ 4,00 por quilo excedente. João
# precisa ... |
33377065d8e963885d95fa94d891b11720bb44e9 | tioguil/LingProg | /-Primeira Entrega/Exercicio02 2018_08_21/atv05.py | 321 | 4.0625 | 4 | # 5 Escreva um programa que conta a quantidade de vogais em uma
# string e armazena tal quantidade em um dicionário, onde a chave é
# a vogal considerada.
print("entre com a frase")
frase = input()
frase = frase.lower()
vogais = 'aeiou'
dicionario = {i: frase.count(i) for i in vogais if i in frase}
print(dicionario) |
5d35beb083b9d0eff0c68ee9d8575431b5d6fb70 | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv11.py | 574 | 3.78125 | 4 | # 11 Faça um programa que solicite a data de nascimento
# (dd/mm/aaaa8 do usuário e imprima a data com o nome do mês por
# extenso.
# Data de Nascimento: 29/10/1973
# Você nasceu em 29 de Outubro de 1973.
# Obs.: Não use desvio condicional nem loops.
import datetime
print("Informe sua data de nascimento ex: 01/01/201... |
b16820e8981e0acd4bb8d117ee31925e97f29dc2 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv11.py | 1,018 | 4.09375 | 4 | # 11. Faça um programa que faça 5 perguntas para uma pessoa
# sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no fnal emitir uma classifcação sobre a
# participação da pessoa ... |
9f73c064597a294823c10d6e511d4ddaacb55790 | dcassells/Rumour-Animation | /animated_rumour.py | 4,940 | 3.6875 | 4 | """
==================
Animated histogram
==================
Use a path patch to draw a bunch of rectangles for an animated histogram.
from terminal write:
python animated_rumour.py #number_of_nodes #number_of_initial_infective
"""
import sys
#import argparse
#parser = argparse.ArgumentParser(
# description = 'Sim... |
7e848517d2ba88ba39d23220858eb341a601d66d | Sullivannichols/classes | /csc321/hw/hw4/parse.py | 2,055 | 3.59375 | 4 | #!/usr/bin/env python3
import csv
import socket
import pygraphviz as pgv
def domains():
''' This function extracts domain names from a .tsv file, performs a
forward DNS lookup on each domain, performs a reverse DNS lookup on
each returned IP, then adds all of the info to a graph.
'''
g = p... |
e53f2538cd20c70b5a7a04de4f714f2077194c65 | cyrusv/Birthday-Problems | /puzzle2.py | 386 | 3.53125 | 4 | # Puzzle 2
# Do Men or Women take longer Hubway rides in Boston?
# By how many seconds? Round the answer DOWN to the nearest integer.
# Use the Hubway data from 2001-2013 at http://hubwaydatachallenge.org/
import pandas as pd
df = pd.DataFrame(pd.read_csv('hubway_trips.csv'))
mean = df.groupby('gender')['duration'].m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.