blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
97cd900d1aca5ba528f3bdcfa27cc0e14dd483af | Vayne-Lover/Intro-to-Programming | /p3/media.py | 601 | 3.9375 | 4 | # -*- coding: utf-8 -*-
#Define class
class Movie():
'''
The class Movie provides a way to store movie related information.
'''
def __init__(self, title, poster, link):
'''
Initialize the class.
:param title:
:param poster:
:param link:
'''
self.t... |
9e23553c1da75dea25946142f3d5aeb598e47a2f | lumy/Simplon-POO | /part1/army.py | 677 | 3.84375 | 4 |
class Army():
"""Army hold all fighter ready to battle."""
def __init__(self):
"""Create an Empty Army"""
self._army = []
def __getitem__(self, item):
"""
:param item: index
:return : the Instance of a fighter.
:raise : IndexError
"""
return self._army[0]
def __len__(self):
... |
52277f14afb6b71e0d246879b63bab8eea6b1cf7 | m-sergio/Projeto_Resolucao_Exercicios_Python | /pacote_download/100/03_operadores aritméticos/ex012.py | 315 | 3.84375 | 4 | #Desafio 012
#Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
prec = float(input('Digite o preco do produto'))
prec_desc = prec - (prec * 0.05)
print('Preço do produto: {:.2f} mts\n'
'Preço do produto com 5% de desconto: {:.2f} mts'.format(prec,prec_desc)) |
babec3bf4a2717695ec5f46ad548f994c6c411a2 | m-sergio/Projeto_Resolucao_Exercicios_Python | /pacote_download/100/01_primeiros comandos/ex002.py | 102 | 3.640625 | 4 |
nome = input('Digite seu nome')
print('Bem-vindo ao mundo de programação python, {}!'.format(nome)) |
1abb70cc4d1e930f651ce5824b279f48dc4f770a | bnn678/Personal-Projects | /ReduceFraction.py | 200 | 3.859375 | 4 | def ReduceFraction(num, denom):
from fractions import gcd
divisor = gcd (num, denom)
num = num / divisor
denom = denom / divisor
print ( str(num) + "/" + str (denom) )
|
b694f33f95f5c2c98ee1d9ea47b9c23762da6506 | bnn678/Personal-Projects | /##BingoGame/Option1.py | 3,907 | 3.625 | 4 | import pygame
from pygame.locals import *
import random
import time
## Type "pygame.display.quit()" in the GUI to exit
## The first center is 87x87
## The second center is 187x187
## The third center is 287x287
## Enter tile info here
mainList = ['I','V','M','C','II','IV','VIII',
'XII','g','h','i','j','9... |
68e7165708af0c3a7099fa15c71d41cf3e067f18 | pucminas-luigidomenico/comp-grafica | /py-paint/pypaint/algorithm/dda.py | 593 | 4 | 4 | def line(p1, p2):
""" Retorna a reta construída a partir de um ponto
inicial e um ponto final.
Tanto p1 quanto p2 devem ser um dicionário contendo
as chaves x e y, referente as coordenadas.
"""
x, y = p1.values()
dx = p2['x'] - x
dy = p2['y'] - y
steps = abs(dx) if ... |
ffb0fe08b35790c9b74c6963ab22ff5a6061f483 | Legion-God/Karasu | /sites/anime_list.py | 1,970 | 3.515625 | 4 | import requests
from bs4 import BeautifulSoup
from collections import namedtuple
'''
Extracts and translates the anime schedule list
'''
def xtractor_list():
"""
Xtracts the anime list schedule and returns the namedtuple
:return: Weekday(['day', Show(['show_name', 'episode', 'time'])])
"""
schedu... |
45c1bb59409c79ad873e7f36bb94798ab2cc4e4d | Mamata-s/Neural-Networks-from-scratch | /Convolutional-Neural-Networks/maxpool.py | 2,319 | 3.53125 | 4 | import numpy as np
class MaxPool2(object):
'''
A Max Pooling layer using stride of 2
'''
def iterate_regions(self, image):
'''
Generate non-overlapping 2x2 image regions to pool over
- image is a 2d numpy array
'''
h, w, _ = image.shape
new_h = h // ... |
ec6c2c23e8ef2021d9bbd388ff44c84c8a09f9ec | tannerblack/evenNumber | /evenNumber.py | 265 | 4.25 | 4 | """
This prints even numbers in a range up to 4
"""
for num in range(5): # range of (0,1,2,3,4)
if num%2 == 0: # mod 2 of a number equal to zero means its even (it has a remainder of zero)
print(num) # prints the numbers that meeet the if statement
|
67eb84ad372663601cf3989c205daa8bc1aa023c | smirnoffs/typing_is_good | /pydantic_example/example_1_dataclass.py | 268 | 3.53125 | 4 | from dataclasses import dataclass
from typing import Dict
@dataclass
class CountryDC:
_id: int
name: str
population: Dict[int, int]
if __name__ == "__main__":
country_dc = CountryDC(_id=1, name="Slovenia", population=2094060)
print(country_dc)
|
2c6f210d32621dcf51bfe92c9c4e55157ec9c532 | SeunghyeunBaek/TIL | /15_python/args_kwargs.py | 795 | 4 | 4 | # 200816
'''
- *args: 변수가 tuple 형태로 입력
- **kwargs: 변수가 dictionary 형태로 입력
- 필수 입력은 지정하고, 선택 입력값을 kwargs로 받음
- References
- https://toughbear.tistory.com/entry/python-args%EC%99%80-kwargs-%EC%9D%98%EB%AF%B8%EC%99%80-%EC%82%AC%EC%9A%A9
'''
def args_func(*args):
print(args)
def kwargs_func(**kwargs):
print(kwargs)
de... |
ee0b3d6b39b1ed34b6b95b860feb50915485b8ba | SeunghyeunBaek/TIL | /07_웹개발/1_python/class.py | 176 | 3.71875 | 4 | class Person:
population = 0
def __init__(self,name):
self.name = name
Person.population = Person.population+1
p1 = Person('a')
print(p1.population)
|
c6767fe483b3947549355d4d24c23046dabdaed8 | aqasaad/smart-flashcard | /second/FlashCardItem.py | 909 | 3.515625 | 4 | #! /usr/bin/env python
#
# Author: Jack Hebert (jhebert@gmail.com)
#
# A signle Flashcard - it has a history of the times
# that it has been asked, how to display itself,
# the question it poses, the answer, and which learning
# sets that it belongs to.
import time
from PosedQuestionSequence import PosedQuestionSeque... |
5f3c9b1c6c43ef52998f715f29a31c9e80eda5ce | shan-shaji/yachalk | /examples/example.py | 868 | 3.5625 | 4 | #!/usr/bin/env python
from yachalk import chalk
print(f"before {chalk.black('Hello World')} after")
print(f"before {chalk.red('Hello World')} after")
print(f"before {chalk.green('Hello World')} after")
print(f"before {chalk.yellow('Hello World')} after")
print(f"before {chalk.blue('Hello World')} after")
print(f"befo... |
21dd3a75c071bed69d762fa7e44ae0c1651ced05 | ayushjaiswal6556/Python-Lab | /string.py | 137 | 3.65625 | 4 | s="python programming"
for i in s:
if i=="p":
print("present")
break
else:
print("not present")
|
ba79255d5a3da449b3a4a1491376b6d61ce8c593 | CodeKratos/LPHW | /PythonCodes/LPHWex6.py | 737 | 3.96875 | 4 | type_of_people = 10
# format string
x = f"there are {type_of_people} type of people in the world."
binary = "binary"
do_not = "don't"
# string inside string 3 and 4
y = f"those who know {binary} and those who {do_not}"
print(x)
print(y)
# format string inside an print statement
print(f"I said : {x}") # str... |
c06eb8e63d8245930caf7c62b69e8b1ee69298fe | CodeKratos/LPHW | /PythonCodes/LPHWex23.py | 1,124 | 4 | 4 | # Page 97 Excercise Strings, Bytes and Character Encoding
import sys #importig sys module to use aya.argv
script, encoding, error = sys.argv # sys.argv is a list that stores command line arguments
def main(language_file, encoding, errors): # 2. defining main function readline() returns one line from language_fil... |
b17b3296ba46f45eea96f2f129026c4e3d2e8bf8 | CodeKratos/LPHW | /PythonCodes/LPHWex11.py | 379 | 4.03125 | 4 | #getting input from user
print("Enter your age boy", end ='>>>')
age=input()
print("enter your height boy", end='>>>')
height=input()
print("enter your weight boy", end='>>>')
weight=input()
print(f"you might be wondering how do I know all this that but \n your age is {age} \n your height is {height} \n and yo... |
d99a810ddc422e8af614fd199f167f71ff5d7703 | CodeKratos/LPHW | /PythonCodes/LPHWex31.py | 1,696 | 3.84375 | 4 | #Excercise 31 Making Decison
print(""" You enter a dark room two doors.
Do you go through the door #1 or door #2""")
door = input(">>>")
if door =="1":
print("There is a giant bear here eating a cheese cake.")
print("what do you do ?")
print("1. Take the cake")
print("2. Scream at the bea... |
cb48c6ecd32755d1bec0a988e57ec3963e4d8502 | NapoleaoHerculano/Introducao-a-Programacao-P1 | /Comando Condicional - IF and ELSE/Comando Condicional - 01.py | 310 | 4.15625 | 4 | #1. Escreva um programa que receba como entrada um número e
#exiba uma mensagem informando se ele é positivo, negativo ou neutro.
numero=int(input("Digite um número:"))
if numero > 0:
print("Número Positivo")
elif numero < 0:
print("Número Negativo")
else:
print("Número Neutro")
|
1e87e631c935afbb2911a642caaa0ce1ec311571 | NapoleaoHerculano/Introducao-a-Programacao-P1 | /Comando For/Comando For - Lista 02 - EX 02.py | 731 | 3.5625 | 4 | valor = 0
seco = 0
total = 0
exe= int(input("Quantos pedidos deseja verificar:"))
for i in range(1,exe+1):
tipo=str.lower(input("Digite o tipo de cobrança - Peça ou Quilo:"))
if tipo == "peça":
quant=int(input("Digite a quantidade de peças:"))
valor = 7 * quant
elif tipo == "quilo... |
a8982c5068ad56106e15cb2794d3b94767cc9f6f | NapoleaoHerculano/Introducao-a-Programacao-P1 | /Listas/Função Listas - Lista 01 - EX 02.py | 111 | 3.90625 | 4 | lista = []
for i in range(8):
num=int(input())
if num %3 == 0:
lista.append(num)
print(lista)
|
0bcde7985da7e98c7e4a308d67089dc2d74ab655 | Prakarsh-Kaushik/100-Days-of-Code | /Project 18 (Higher Lower Game)/main.py | 1,507 | 3.875 | 4 | import random
from art import logo, vs
from game_data import data
from replit import clear
def printData(account):
"""Format game data into readble form"""
accountName = account["name"]
accountDescription = account["description"]
accountCountry = account["country"]
return f"{accountName} is a {accountDescr... |
3ebf10dad891bb48a3b361cf9be0aaf3aca15d2a | Prakarsh-Kaushik/100-Days-of-Code | /Project 10 (Rock Paper Scissors)/main.py | 1,069 | 4.15625 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
... |
d2c82169da5eece18be4af40c7040f0a6757cfbd | bafulton/prime-days | /primes.py | 4,901 | 3.84375 | 4 | from math import sqrt, ceil, floor
from calendar import Calendar
def getPrimeBirthdays(birthday):
p = PrimesGenerator()
primeYears = []
for i in range(0, 100):
date = birthday + i
if (p.checkPrime(date)):
primeYears.append(int(date-10000*floor(date/10000)))
return primeYe... |
f28274e94718385662864376ba370bc3cbeff879 | choucoder/competitive-programming | /practice/dynamic-programming/coin_change.py | 572 | 3.5 | 4 | def minChange(money, coins, dp={}):
if money in dp: return dp[money]
if money == 0: return []
if money < 0: return None
minCoins = None
for c in coins:
remainder = money - c
remainderCoins = minChange(remainder, coins)
if remainderCoins != None:
_coins = remaind... |
5c832afcf1d94a01b68aec9dc06082c0fd015b41 | a-carrasquillo/Blackjack-Game | /games/board/cards/blackjack/player.py | 2,950 | 3.71875 | 4 | '''
The script that contains the Player Class
'''
# import the hand class
from .hand import Hand
# import the error classes
from .errors import NotEnoughCardsToPrint
from .errors import NotEnoughFunds
class Player:
'''Class that simulates a player of blackjack
Attributes:
name -- player n... |
f81b3a16ef4a266bebd8cfa6d038b94c6cb39c28 | a-carrasquillo/Blackjack-Game | /games/board/cards/card.py | 878 | 4.09375 | 4 | '''
The script that contains the Card Class
'''
class Card:
'''Class that simulates a general card
Class that simulates a general card
that contains suit, rank, and
an associated value to the rank
Attributes:
suit -- suit of the card
rank -- rank of the card
va... |
d4d5af76324739412cbf3ba15d3034e781430451 | Nisar-1234/Data-structures-and-algorithms-1 | /Disjoint Set/(IMP) path compression in Find operation.py | 289 | 3.875 | 4 | def find(i, parentList):
if parentList[i] == -1:
return i
parentList[i] = find(parentList[i], parentList)
return parentList[i]
parentList = [-1, 7, 1, 2, 7, 4, 5, -1]
#[-1, 7, 7, 7, 7, 4, 5, -1]
print(find(3, parentList))
print(parentList)
|
7fa7d713f54cc9f709f69e48cbe5280cbbe51d3f | Nisar-1234/Data-structures-and-algorithms-1 | /Mathematical/Check if point lies inside a triangle.py | 909 | 3.96875 | 4 | """
B(10,30)
/ \
/ \
/ \
/ P \ P'
/ \
A(0,0) ----------- C(20,0)
area of triangle = abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)) / 2
"""
def check(triangleArray,P) -> bool:
x1 = triangleArray... |
8ba23bfc318d1684e4fec9c69f7e25e3760859ac | Nisar-1234/Data-structures-and-algorithms-1 | /Trees/Deepest Node BT.py | 864 | 3.984375 | 4 | # FINDING DEEPEST ELEMENT IN BT
# LOGIC -> The last element in level order traversal is always the deepest element
class BinaryTree():
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def deepestNode(node):
# using level order traversal
queue ... |
0308cf397ef2f4f5f2c741ceea039e4953c834e5 | Nisar-1234/Data-structures-and-algorithms-1 | /Recursion/Fractional knapsack (Greedy).py | 1,347 | 3.703125 | 4 | # ratio = value/weight
import operator
# we are importing operator so that we can sort the list by one element(ratio)
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
capacity = 50
n = len(wt)
# making list of [value, weight, value/weight]
list1 = []
for i in range(len(val)):
list1.append ([val[i],wt[i],va... |
f7528192527a02f8143a294a6506ee3ba0fb3210 | Nisar-1234/Data-structures-and-algorithms-1 | /Binary Search/Index of First 1 in a Binary Sorted Infinite Array.py | 1,343 | 3.953125 | 4 | """
ALGORITHM
>> Get index of any 1 in the array by growing the left and right and using binary search, name it indexOfAny1
>> Now find first occurence of 1 in with left = 0 and right = indexOfAny1
"""
def firstOccurence(left,right,arr,indexOfAny1,ans):
if left <= right:
mid = (left + right) // 2
if arr[... |
b635c7d10ce55d846402e374b422053c3d68b9cb | Nisar-1234/Data-structures-and-algorithms-1 | /Heaps (or Priority Queue)/merge k sorted Linked List.py | 1,458 | 3.734375 | 4 | import heapq
class Item:
def __init__(self, data, nextNode):
self.data = data
self.nextNode = nextNode
def __lt__(self, otherObject):
return self.data < otherObject.data
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
minHeap = [... |
1c29dc1ecfe316faa78fb563f818acb64a7520f9 | Nisar-1234/Data-structures-and-algorithms-1 | /Arrays/Merge overlapping ranges.py | 341 | 3.671875 | 4 | def merge(ranges):
ranges.sort()
stack = []
stack.append(ranges[0])
for i in range(1,len(ranges)):
if ranges[i][0] <= stack[-1][1]:
stack[-1][1] = max(stack[-1][1],ranges[i][1])
else:
stack.append(ranges[i])
return stack
ranges = [[2,13],[8,20]]
... |
ac6720f54ec7de206c9f73c48d20bb15b961b2ca | Nisar-1234/Data-structures-and-algorithms-1 | /Sorting/Shell Sorting.py | 1,244 | 4.09375 | 4 | """
==== ALGORITHM FOR SHELL SORT ====
>> First we find the initial gap by len(arr) // 2
>> While gap > 0:
# check the array in from left to right
=>while j < len(arr):
>> check elements from left to right. i=0 and j = gap. Increment i and j by once and swap if arr[i] >arr[j]
# check the ... |
39bf93e188d55ee29b593e230d70344a7dd99cfb | Nisar-1234/Data-structures-and-algorithms-1 | /Graphs/Dijkstra on matrix (grid).py | 1,241 | 3.5 | 4 | global INT_MAX
global n
n = 4
INT_MAX = 3 ** 38
class Solution:
# <- this returns the minVertex's co-orinates ->
def minimumVertex(self, distMat, visited):
minVertexi = 0
minVertexj = 0
max1 = INT_MAX
for i in range(n):
for j in range(n):
... |
53e7791ab57914b32111d76c407550897a015935 | Nisar-1234/Data-structures-and-algorithms-1 | /Greedy Programming/Indian Coin Change by greedy.py | 1,097 | 3.9375 | 4 | # Please note that greedy should not be used as it may FAIL!
# Use dyanamic programming to solve coin change as greedy fails for some test cases
def binarySearch(left,right,coinList,currAmount,ans):
if left <= right:
mid =(left + right) // 2
if coinList[mid] <= currAmount:
ans[0]... |
4bbe9b30a5d993c41983376a5c43d08d9da505fb | Nisar-1234/Data-structures-and-algorithms-1 | /Graphs/Alien DIctionary.py | 1,232 | 3.515625 | 4 | from collections import defaultdict
class Solution:
def __init__(self):
self.vertList = defaultdict(list)
def addEdge(self, u, v):
self.vertList[u].append(v)
def topologicalSortDFS(self, givenV, visited, stack):
visited.add(givenV)
for nbr in self.vertList... |
b658a92cdd72921b7cceec00a10a0d07031baa85 | Nisar-1234/Data-structures-and-algorithms-1 | /Stacks/Questions/PrefixToPostfix.py | 889 | 3.859375 | 4 | class Stack():
# defining the attributes
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
if not(self.isEmpty()):
return self.items.pop()
else:
return "UNDERFLOW"
def peek(self):
... |
0be1ef09f678cceb1095dc762713df5d3fa81e40 | Nisar-1234/Data-structures-and-algorithms-1 | /Binary Search/count occurence.py | 1,519 | 3.890625 | 4 | """
Algo to count occurence
-> find the first occurence
-> find the last occurence
-> return (last occurence - first occurence) + 1
"""
def firstOccurence(left,right,arr,key,firstAns):
if left <= right:
mid = (left + right) // 2
if key == arr[mid]:
# save the index
firstAns[0] = mid
# m... |
33974a401b3d0822fd1abe7ab03f7928176dfe84 | Nisar-1234/Data-structures-and-algorithms-1 | /Heaps (or Priority Queue)/heap of class objects.py | 752 | 4.0625 | 4 | """
overload __lt__ (called as rich comparator) this is used by the heapq.heapify to compare them and generate the heap
NOTE: after overloading rich comparator list of objects of this class can be sorted also
"""
import heapq
class Person:
def __init__(self, name, age):
self.name = name
... |
6636a12ccde01a43b0b4011d0153838137d3e316 | Nisar-1234/Data-structures-and-algorithms-1 | /Trees/Height (or depth) of BT.py | 422 | 3.78125 | 4 | class BinaryTree():
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def heightBT(node):
if node is None:
return 0
return (max(heightBT(node.left),heightBT(node.right))+1)
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = B... |
0c1a600863d93919a29b892ec4b68a148281e742 | Nisar-1234/Data-structures-and-algorithms-1 | /Heaps (or Priority Queue)/convert array to heap o(nlogn).py | 1,270 | 3.9375 | 4 | """
ALGORITHM TO CONVERT ARRAY TO HEAP IN O(N*LOGN)
->Compare the current index with its parent
->While the heap condition is not true or curr is not equal to 0, swap the elements and change the indices for next iteration
"""
class Heap:
def __init__(self, type1=False):
self.type1 = type1
... |
15451ca0bedba346ba2366934aba746b16f38a04 | Nisar-1234/Data-structures-and-algorithms-1 | /Mathematical/Count perfect squares.py | 340 | 3.875 | 4 | """
search space consists of all perfect squares i.e. [1, 4, 9............]
given integer N, find all the number of perfect squares before N
"""
import math
class Solution:
def countSquares(self, N):
x = int(math.sqrt(N))
if x*x == N:
return x-1
else:
... |
8d873f0ccba178ffac36bc01c01214be96186155 | Nisar-1234/Data-structures-and-algorithms-1 | /Bit Magic/count set bits.py | 309 | 4.21875 | 4 | """
Count the number of set bits
This can count the number of set bits even in negative numbers
"""
def countSetBits(num):
i = 31
ans = 0
while i >= 0:
k = num >> i
if k & 1 > 0:
ans += 1
i -= 1
return ans
print(countSetBits(-5))
|
72fa11d6ee94e603952bb373c59a6dd16e2befe1 | Nisar-1234/Data-structures-and-algorithms-1 | /LinkedList/Singly LL/Questions/nth node from the end of singly LL.py | 1,561 | 3.890625 | 4 | #Logic to get nth item from the back:
# index from the back starts from 1 (actually -1), so just print the data of (len - n)th node.
# pointer is already on the head node so we dont' have to worry ki range() aakhiri include nhi karega (len-n) me
class Node():
def __init__(self,data):
self.data = data
... |
43882c9db2a517f91a2edc327b2dd829ff21f746 | Nisar-1234/Data-structures-and-algorithms-1 | /Sorting/Quick Sort.py | 1,120 | 4.28125 | 4 | """
==== ALGORITHM FOR QUICK SORT ====
The main logic is that in each recursive call we bring the pivot element i.e. left most element to its correct postion and then recursively
call the function for its left and right side.
We do this till we have atleast two elements
Time Complexity: Worst case => O(n2)|... |
1e13a1fb9a006cbf83843d8eccedc83da2b92a85 | Nisar-1234/Data-structures-and-algorithms-1 | /Arrays/Kth smallest number again.py | 840 | 3.609375 | 4 | def merge(ranges):
stack = []
stack.append(ranges[0])
for i in range(1,len(ranges)):
if ranges[i][0] <= stack[-1][1]:
stack[-1][1] = max(stack[-1][1],ranges[i][1])
else:
stack.append(ranges[i])
return stack
def kthNumber(ranges,k):
for list1 in r... |
c1c962b1708753d6dfc0fa2b64e93d8c321a4e3c | Nisar-1234/Data-structures-and-algorithms-1 | /Graphs/Cycle check in graph using Disjoint Set.py | 1,164 | 3.546875 | 4 | class Graph:
def __init__(self,numofVertices):
self.numofVertices = numofVertices
self.edgeList = []
def addEdgePair(self,u,v):
pair = (u,v)
self.edgeList.append(pair)
def find(self,i,parentList):
if parentList[i] == -1:
return i
re... |
70877ba4f0cd6b47301c67bdbf6a236800c5ae44 | Nisar-1234/Data-structures-and-algorithms-1 | /Graphs/BFS - Snake Ladder Problem.py | 1,478 | 3.546875 | 4 | from collections import defaultdict
global INT_MAX
INT_MAX = 3 ** 38
class Graph:
def __init__(self):
self.vertList = defaultdict(list)
def addEdge(self, u, v):
self.vertList[u].append(v)
def distanceBFS(self, src, target):
queue = [src]
distanceDict = {}
... |
0005bf45473d48f7e6483ffb626620af916059f7 | Nisar-1234/Data-structures-and-algorithms-1 | /LinkedList/Circular LL/Implementation and other basic stuff/Insertion (beg,end,after) in circular LinkedList.py | 2,638 | 4.09375 | 4 | #NOTE: In circular LinkedList, inserting at the beg and end are exactly same with just one difference. For insertion at the beg of the list we need to make it the
# head however for inserting at the end we need not to make it the head.
# 11->22->33->44->55->66->head
class Node():
def __init__(self,data):
... |
6d481bb764d3cf7306539ecaf5b10bdf001d2871 | Nisar-1234/Data-structures-and-algorithms-1 | /Greedy Programming/Choose and Swap.py | 1,003 | 3.765625 | 4 | """
swap two chars in a string such that we get lexicographically smaller string
input = "abcabcpop"
output = "abcabcopo"
"""
class Solution:
def LexicographicallyMinimum(self, str):
temp = sorted(str)
ch1 = '$'
ch2 = '$'
flag = False
for i in range(len(str)):
... |
cda8414c0291e10b829ebae87439376e9a2fd2aa | Nisar-1234/Data-structures-and-algorithms-1 | /Stacks/Questions/PrefixToInfix.py | 971 | 4 | 4 | ## Prefix to infix is like prefix to postfix only with a difference ki beech me operator lga ke push krna h stack me
class Stack():
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
if not(self.isEmpty()):
return self.... |
dacd1632200a14059d847f3e81cec2f2e6b2fef3 | Nisar-1234/Data-structures-and-algorithms-1 | /Trees/Implementation BT.py | 984 | 3.796875 | 4 | class BinaryTree():
def __init__(self,data):
self.data = data
self.leftChild = None
self.rightChild = None
def insertLeft(self,newData):
if self.left == None:
self.left = BinaryTree(newData)
else:
t = BinaryTree(newData)
t.lef... |
d8fe6c1bd210fcb7945c249dc709aa95d3d5a817 | Nisar-1234/Data-structures-and-algorithms-1 | /Binary Search/EKO - Spoj.py | 863 | 4.03125 | 4 | """
we need to find a valid maximum height
a valid height is where we can cut >= M metres
"""
def isValid(currHeight,treeArray,target):
cuttkiya = 0
for tree in treeArray:
if tree - currHeight > 0:
cuttkiya += tree-currHeight
return cuttkiya >= target
def findMaxHeight... |
951f00a8a7a184ee266e8536111ff3f7dc9f714c | Nisar-1234/Data-structures-and-algorithms-1 | /Graphs/Bipartite Check.py | 1,221 | 3.578125 | 4 | class Graph:
def __init__(self, numofVertices):
self.numofVertices = numofVertices
self.adjacencyMatrix = [[0 for i in range(self.numofVertices)] for j in range(self.numofVertices)]
def isBipartite(self, src):
colorArr = [-1] * self.numofVertices
colorArr[src] = 0
... |
3115863a10067cda6c98d02ce1e3864ca9f1e599 | Nisar-1234/Data-structures-and-algorithms-1 | /Heaps (or Priority Queue)/Reorganize String such that no adjacent chars are same.py | 1,509 | 3.546875 | 4 | """
Link: https://leetcode.com/problems/reorganize-string/
Time complexity = O(NlogN)
"""
import heapq
class Item:
def __init__(self, char, count):
self.char = char
self.count = count
def __lt__(self, otherObject):
return self.count > otherObject.count
class Solution... |
1f5db848934398e683196e97a68ca74e907ed6f9 | Nisar-1234/Data-structures-and-algorithms-1 | /Backtracking/Partition array to K subsets with equal sum.py | 1,416 | 3.640625 | 4 | def isPossible(start,currSum,k,targetSum,visited,arr):
if k == 1: # main function checked that sum(arr) % k == 0, hence if all subsets are formed and just one is left, it will obviously be formed
return True # rest by of the elements
if currSum > targetSum:
return
if currSum... |
aa2b5b77f42a30986909f7af5c1beeaa9ae49f7d | Nisar-1234/Data-structures-and-algorithms-1 | /Dynamic Programming/Optimal Game Strategy Top Down DP.py | 687 | 3.78125 | 4 | # TIME COMPLEXITY = O(N^2) | SPACE COMPLEXITY = = O(N^2)
def optimalStrategy(i,j,arr,memory):
if i > j:
return 0
if memory[i][j] != -1:
return memory[i][j]
op1 = arr[i] + min(optimalStrategy(i+2,j,arr,memory),optimalStrategy(i+1,j-1,arr,memory))
op2 = arr[j] + min(optimalStrategy(i+1,j-1,arr,memory... |
c6a3ef2c31083ee8fc1a165095e9a5928ade94aa | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 04 - Trees and Graphs/q4.py | 659 | 3.828125 | 4 | class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def balancedAndHeight(node):
if (node is None):
return True, 0
leftBalanced, leftHeight = balancedAndHeight(node.left)
rightBalanced, rightHeight = balancedAndHeight(node.right)
if (not lef... |
d574f745354b0f33326a0ac708439dd63bed3fbd | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 01 - Arrays and Strings/q4.py | 547 | 3.90625 | 4 | def getCharacterFrequency(s):
d = {}
for c in s:
if (c == " "):
continue
c = c.lower()
d[c] = 1 if c not in d else d[c] + 1
return d
def palindromePermutation(s):
frequency = getCharacterFrequency(s)
oddFrequencyCount = 0
for character in frequency:
if (frequency[character] % 2 != 0):
oddFrequencyC... |
023053d994e0260ad3522cecbf69fa8148371202 | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 03 - Stacks and Queues/stack.py | 661 | 4 | 4 | class StackNode:
def __init__(self, value, next):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.head = None
def pop(self):
if self.head is None:
print("Empty stack")
return
value = self.head.value
self.head = self.head.next
return value
def push(self, value):
sel... |
983ffaba2a8efaf12167eece2c2776975b4ac35f | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 08 - Recursion and Dynamic Programming/q5.py | 854 | 3.875 | 4 | def recursiveMultiply(a, b):
if (a == 0 or b == 0):
return 0
if (a < 0 and b < 0):
return recursiveMultiply(-a, -b)
if ((a > 0) != (b > 0)):
return -recursiveMultiply(abs(a), abs(b))
if (a < b):
return recursiveMultiply(b, a)
return a + recursiveMultiply(a, b-1)
print(recursiveMultiply(1, 2))
print(recurs... |
2c9d1c0da4d329620c2a337140437e844bf55191 | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 04 - Trees and Graphs/q10.py | 798 | 3.890625 | 4 | class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def equalTrees(t1, t2):
# True if t2 is identical to t1
if (t1 is None and t2 is None):
return True
if ((t1 is None) != (t2 is None)):
return False
if (t1.value != t2.value):
return Fal... |
a9ccd16ccf04fb16526fadad8539862733b2b528 | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 16 - Moderate/q21.py | 223 | 3.609375 | 4 | def sumSwap(l1, l2):
diff = sum(l1) - sum(l2)
s1, s2 = set(l1), set(l2)
for element in s2:
searched = element + diff/2
if searched in s1:
return element, searched
print(sumSwap([4, 1, 2, 1, 1, 2], [3, 6, 3, 3]))
|
8c466c706abb19f8921a0d961e8f1f8d0e7c83bc | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 02 - Linked Lists/q3.py | 444 | 3.859375 | 4 | class Node:
def __init__(self, value, next):
self.value = value
self.next = next
def deleteMiddleNode(node):
node.value = node.next.value
node.next = node.next.next
def printLinkedList(head):
trav = head
while (trav):
print(trav.value, end=" ")
trav = trav.next
print("")
node = Node(4, Node(5, Node(6, ... |
82836e7599304a919e39bbc7109f68821fb3542e | GokulSoman/scripts | /Codevita/samples/question3.py | 1,974 | 3.671875 | 4 | '''
Answer:
Problem Description
War between Republic and Separatist is escalating. The Separatist are on a new offensive. They have started blocking the path between the republic planets (represented by integers), so that these planets surrender due to the shortage of food and supplies. The Jedi council has taken a n... |
415b881d5f590713d92c77de91b68b08ee5429bd | GokulSoman/scripts | /InterviewBit/insertionSort.py | 455 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 10:20:10 2020
@author: gokul
"""
def insertionSort(arr: List[int]):
n = len(arr)
if n == 0:
return "Empty List"
for i in range(1,n):
elem = arr[i]
j = i-1
while j >= 0 and arr[j]>elem:
arr[j+1] = arr[j]
... |
210911a173738613bc325295e62cf92af1a3e7c0 | GokulSoman/scripts | /Codevita/samples/question1.py | 1,591 | 3.828125 | 4 | '''
Some of the keys of Ajith's Laptop's Keyboard are damaged and he is not able to type those keys. He has to complete his assignment and submit it the next day and since it is midnight he will not be able to give his laptop for repair. So he decides to make a character sequence of all the damaged keys in a sequence t... |
992a06fb0156373b42d88cdc66bf3e686723095e | minias/Essay-small-simulation | /WCRT+TECDSA.py | 15,934 | 3.640625 | 4 | import math
import fractions
import bitcoin
# 判断是否为素数
def isPrime(num):
if num <= 1:
return False
for i in range(2, int(math.sqrt(num) + 1)):
if num % i == 0:
return False
return True
# 筛选一个区间范围内的所有素数并将素数结果存到一个列表中
def listPrimes(begin, end):
COLUMN = 10
... |
6847cf0bdb59b6cc422d25c5c1ceb2030f786d3e | baliao/202012tkinter | /test_event.py | 638 | 3.5 | 4 | #coding:utf-8
import tkinter
win= tkinter.Tk()
win.title('Event 事件')
win.geometry('300x200')
label1 = tkinter.Label(win,text='确认',bg='green')
label1.pack()
def buttonClicked(event):
label1.config(text='产生了事件,{},{}'.format(event.x,event.y))
label1.bind('<Button-1>',buttonClicked)
def enter(event):
text.set(... |
16fe52aa3e97b3da69595ca88c4ada35730cdba8 | stephensamonte/Python-Paste-Timestamp-Shortcut | /typeTimestamp.py | 397 | 3.640625 | 4 |
# For printing to cursor
import pyautogui as ag
# For retrieving the current date
import datetime
# ag.typewrite("hello Geeks !")
# Retrieve the current date time
time = datetime.datetime.now()
# formate the current date time and convert it into a sstring
timeStamp = time.strftime("%Y.%m.%d %H.%M.%S")
# type the cu... |
f6bd9c5928e17e6dbb11d4a4c96726872e85cbc4 | kirchhoff/my_work_py2 | /leetcode_py/461. Hamming Distance.py | 1,056 | 4.09375 | 4 | #coding=utf-8
'''
题目中解释的很清楚了,两个数字之间的汉明距离就是其二进制数对应位不同的个数,那么最直接了当的做法就是按位分别取出两个数对应位上的数并异或,
我们知道异或的性质上相同的为0,不同的为1,我们只要把为1的情况累加起来就是汉明距离了
'''
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
s = bin(x^y)[2:]
coun... |
4a1d7441392ee8f2f7a7895d1c391742c1346305 | jessuraura/CS50 | /pset6/dna/dna.py | 1,250 | 3.640625 | 4 | from sys import argv, exit
from csv import DictReader
if len(argv) != 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(1)
STRs = []
data = open(argv[1], "r")
reader = DictReader(data)
for row in reader:
for key in row.keys():
if (key == 'name') or (key in STRs):
continue
... |
fe6dc32699e6ad5173ed6864530732c5fb690c97 | rho621/test | /functions.py | 226 | 3.9375 | 4 | def avg(arg1):
count = len(arg1)
sum = 0
for item in arg1:
sum = sum + item
result = sum/count
return result
input_1 = [1,2,3]
input_2 = [7, 8, 9, 10, 11]
print(avg(input_1))
print(avg(input_2)) |
64baccb9b070c30c3b65aec0349c910e0ef427d5 | rho621/test | /candy.py | 402 | 3.96875 | 4 | candy_cart = ["snickers", "kit kat", "coffee candy", "gummy bear", "cookies"]
"""
for candy in candy_cart:
print(candy_cart.index(candy))
"""
for candy in candy_cart:
print("[" + str(candy_cart.index(candy)) + "] " + candy)
allowance = 3
cart = []
for count in range(allowance):
candy_choice = int(input(... |
4d63d14788d800a35ca194bd441e42d504b79386 | trehman65/2020fa-section-code | /section - caching/lru_caching.py | 1,368 | 4.09375 | 4 | from timeit import repeat
from functools import lru_cache
@lru_cache(maxsize=128)
def steps_to(step):
if step == 1:
# You can reach the first step with only a single step
# from the floor.
return 1
elif step == 2:
# You can reach the second step by jumping from the
# f... |
3f486046829ead819ac85ffb44769b674a3e0aab | trehman65/2020fa-section-code | /Section 5/A_inheritance.py | 1,310 | 4.59375 | 5 | # Examples from "Learn Python 3 the Hard Way" by Zed A Shaw
class Parent(object):
def __init__(self):
self.phone_type = "iphone"
# self.mood = "sleepy" # if I change this attribute here, it won't get inherited!
def implicit(self):
print("I am a person!")
def override(self):
... |
2f143eb0e5cf62b4643983bf4624e6d5afaee3c9 | kasperhelweg/thesis | /scripts/magic_heap_proto/one_class/stack.py | 1,678 | 3.9375 | 4 | class stack_node( object ):
def __init__( self, node ):
self.node = node
self.next = None
class stack( object ):
def __init__( self ):
self.head = None
self.next = None
def push( self, node ):
n = stack_node( node )
if not self.head:
self.head = n
else:
n.next = self... |
27c1fec6fd59b95c7cb53179bff013ce9f7432b0 | Subhadarsini-10/100daysofcode | /13.py | 1,041 | 3.890625 | 4 | #password check
import re
p = input('Enter a password')
x = True
while x:
if (len(p)<6 or len(p)>16):
break
elif not re.search('[a-z]', p):
break
elif not re.search('[0-9]', p):
break
elif not re.search('[A-Z]', p):
break
elif not re.search('[#$@]', p):... |
1e71930b28470ced7191e75df530e2421e2622db | Subhadarsini-10/100daysofcode | /9.py | 481 | 4.15625 | 4 | from array import *
array_num = {'i', [1,3,4,6]}
for i in array_num:
print(i)
print('access the first three items')
print(array_num[0])
print(array_num[1])
print(array_num[2])
print('starting array', array_num)
array_num.append(11)
print('new array', array_num)
print(array_num[::-1])
print(array_n... |
a648c5285788dfa641fb067f53ca09cdc198b10e | nkhaldi/Python | /chess_horse.py | 1,019 | 3.71875 | 4 | #!/usr/bin/env python3
"""
Ходы коня
На шахматной доске 8×8 стоит конь.
Напишите программу, которая отмечает положение коня на доске и все клетки.
которые бьет конь.
Клетку, где стоит конь, отметьте английской буквой N,
клетки, которые бьет конь, отметьте символами *,
остальные клетки заполните точками.
На вход програ... |
07dcdfba623de2ef8159587043445881671dca9e | nkhaldi/Python | /length_translator.py | 1,513 | 3.75 | 4 | #!/usr/bin/env python3
"""
Требуется написать программу, осуществляющую преобразование
из одних единиц измерения длины в другие.
Должны поддерживаться
мили (1 mile = 1609 m),
ярды (1 yard = 0.9144 m),
футы (1 foot = 30.48 cm),
дюймы (1 inch = 2.54 cm),
километры (1 km = 1000 m),
метры (m),
сантиметры (1 ... |
e185a4270d7cb5bb9178e6ca7d5b87e4cf55ff14 | nkhaldi/Python | /superannotate_task/task2.py | 704 | 4.28125 | 4 | #!/usr/bin/env python3
def caesar_encpypt(line, shift):
encrypted = str()
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
for char in line:
if char in upper:
encrypted += upper[(upper.index(char) + shift) % len(upper)]
elif char in lower:
... |
36b22b21080ac1a983b86be64c624e17a4259525 | nkhaldi/Python | /card_counter.py | 611 | 3.65625 | 4 | def get_card_count(n, k, cards) -> int:
def rec(deque, value, steps):
if steps == 0:
return value
if steps == 1:
return max(value + deque[0], value + deque[-1])
val1 = rec(deque[1:], value + deque[0], steps - 1)
val2 = rec(deque[:-1], value + deque[-1], steps... |
5a8f7e9b06caa05e617f7c458ffb6b9b7667f561 | nkhaldi/Python | /triangle.py | 1,327 | 3.9375 | 4 | #!/usr/bin/env python3
"""
Описать класс треугольник и реализовать для него следующие методы:
+ Периметр
+ Площадь
+ Визуализация
"""
import matplotlib.pyplot as plt
import numpy as np
class Point:
def __init__(self, x_, y_):
self.x = x_
self.y = y_
print("Point", self.x, self.y)
class... |
2e3fef54cf7072e31458266169645eb559631f0e | nkhaldi/Python | /brackets.py | 621 | 3.96875 | 4 | #!/usr/bin/env python3
"""
Программа проверяющая правильность расстановки скобок в строке
"""
def brackets(brac):
stack = []
for el in brac:
if el in ["[", "(", "{", "<"]:
stack.append(el)
elif el in ["]", ")", "}", ">"]:
if len(stack) > 0:
top = stack... |
df9eabb23b719feb793785fd199704e830d0be30 | tdieff/solver | /helpers.py | 2,664 | 4.03125 | 4 | import re
# used to allow user-input freedom, but still wind up with consistent formatting later
def remove_whitespace(string):
return re.sub(r'\s+', '', string)
# used to rule out user input with unsupported symbols
def invalid_chars(string):
unsupported_chars = []
for char in string:
if not isnumber(char) an... |
c031b98cdf49ab13ce06807c9901958202c19d27 | chenlinwang/LeetCodeSolution | /5.longest-palindromic-substring.py | 2,727 | 3.734375 | 4 | #
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# https://leetcode.com/problems/longest-palindromic-substring/description/
#
# algorithms
# Medium (27.71%)
# Likes: 4069
# Dislikes: 377
# Total Accepted: 619.9K
# Total Submissions: 2.2M
# Testcase Example: '"babad"'
#
# Given a str... |
ef2dc9f2fc722818f51bcd6c0aa3d5fedcd72489 | foster99/LP-FIB | /Python/Lab1/P45231.py | 1,089 | 3.703125 | 4 | def fibs():
yield 0
a,b = 0,1
while True:
a,b = b, a+b
yield a
# TESTING
# fib = fibs()
# print([next(fib) for n in range(10)])
def roots(n):
curr = n
yield curr
while True:
prev = curr
curr = 0.5 * (prev + (n/prev))
yield curr
# TESTING
# g2 = roots(4... |
07b5e43061492b198954f41e24a42264ed692b36 | Anti-Distinctlyminty/orgextended | /orgparse/inline.py | 926 | 3.625 | 4 | """
Org-mode inline markup parser.
"""
import re
def to_plain_text(org_text):
"""
Convert an org-mode text into a plain text.
>>> to_plain_text('there is a [[link]] in text')
'there is a link in text'
>>> to_plain_text('some [[link][more complex link]] here')
'some more complex link here'
... |
2a7ca5d6ddb9dff3785daa8fc7bb67a30cfc3e1f | troykiim/Python | /lpthw/ex08.py | 517 | 4.09375 | 4 | #This program is lesson 8 from "Learn Python the Hard Way"
formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
... |
8a969e99fb5a2c03ddd47a27f36427f631cdfe9b | psmith586/py_file_manage | /pSmith_coffee_records.py | 677 | 4.0625 | 4 | #Phillip Smith
#Hmwrk 6
#this module adds coffee inventory records
def add_coffee():
another = 'y'
#open file
coffee_file = open('coffee.txt','a')
#add records to file
while another == 'y' or another == 'Y':
print('Enter the following coffee data: ')
descr = input('Description: ')
qty = fl... |
2d95dfe85063696bc421e1c52ba3cf4046a2b74e | SuhasKulkarni5180/Python | /Palindrome.py | 421 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 13:04:21 2020
@author: Suhas Kulkarni
"""
# This function identify if provided string/number is palindrome or not
string=input("Enter any name or number:")
length=len(string)
rev=""
for i in range(0,length):
rev=rev+string[length-1]
length=length-1
if(string... |
2ba5c9f3b27920426e8b518bf073cec3c7397298 | sivaram5403/pythondataStructures | /selectionsorting.py | 315 | 3.78125 | 4 | def sort(nums):
for i in range(len(nums)-1):
minpos = i
for j in range(i,6):
if nums[j] < nums[minpos]:
minpos = j
temp = nums[i]
nums[i] = nums[minpos]
nums[minpos] = temp
print(nums)
nums = [5,2,6,8,7,3]
sort(nums)
print(nums) |
b3d55dd11885467755179a66448053cab28485a5 | sivaram5403/pythondataStructures | /filehandling.py | 259 | 3.90625 | 4 |
#Reading a file
f = open('mydata','r')
# print(f.read())
# print(f.readline())
#Writing a file
# f1 = open('abc','w')
#
# f1.write("this is new file 1")
#appending
f1 = open('abc','a')
# f1.write("this is new file 2")
for data in f:
f1.write(data) |
4f523cc76239a0f9733c9eb66ac4c1cd7f549109 | mHamzaArain/Alien-Invasion | /Alien Project v1.4/alien_invasion/button.py | 1,898 | 3.890625 | 4 | import pygame.font # to write on game screen
class Button():
def __init__(self, ai_settings, screen, msg):
"""Initialize button attributes."""
self.screen = screen
self.screen_rect = screen.get_rect()
# Set the dimensions and properties of the button.
sel... |
36e3554a02fcf286dd5a1920b9bd5627172d1425 | emreustaa/PythonProgramming | /Exercise_9/.idea/questions/Q1.py | 98 | 3.609375 | 4 | list_a = [1, 5, 3, 6, 2, 4]
list_b = [6, 4, 6, 1, 2, 2, 9, 8, 11]
print(list(zip(list_a,list_b))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.