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 |
|---|---|---|---|---|---|---|
12f878060df0f95feb1718aaefd2871bd62bb779 | ettoreiovine/labPy | /coniche/retta.py | 1,735 | 3.78125 | 4 | # La classe retta
class retta:
def __init__(self,a,b,c):
# un attributo privato si dichiara con il doppio underscore ( __ )
self.__a = a
self.__b = b
self.__c = c
self.__punti = []
def __init__(self, p1, p2):
'''
questo costruttore deve generare u... |
95bf38eccb1a70731cc9cc4602a440fdb98043dd | ranjanlamsal/Python_Revision | /file_handling_write.py | 1,891 | 4.625 | 5 | '''In write mode we have attributes such as :
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a f... |
f3b3097f27139da6dee72e92922ca3a554f33894 | ranjanlamsal/Python_Revision | /file_handling_read.py | 3,240 | 4.3125 | 4 | """Basics of file handling in python"""
'''The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
open("filename", "mode")'''
'''
Modes
"r" - open file for reading, error if file doesnot exist
"w" - open file for writing, create... |
3867392dee2e78d71c9a8bf99e1372a46a0eb726 | beyondvalence/thinkpython | /tp.05.py | 1,537 | 4.15625 | 4 | #! Thinking Python, Chp05, conditionals and recursion
#5.1 modulus operator
print("5.1")
print("156%100=")
print(156%100)
#5.9 E2 stack diagrams for recursive functions
print("5.9 E2")
def do_n(f,n):
if n<=0:
return
f()
do_n(f, n-1)
def print_now(s='now'):
print(s)
do_n(print_now,6)
#5.11 keyboard input
prin... |
2f17d45567bc42522fb3ee263376e3824397daaf | alimahatma/latihan_oop | /Main2_CIV.py | 683 | 3.796875 | 4 | class Hero: #template
#class variabel
jumlah = 0
def __init__(self, inputName, inputHealth, inputPower, inputArmor):
#instance variabel
self.name = inputName
self.health = inputHealth
self.power = inputPower
self.armor = inputArmor
Hero.jumlah +... |
1abed0e8ec5f286d20e94024c6864f5cfe6d315a | minigar/minigar | /lib/ball.py | 1,498 | 3.8125 | 4 | import math
from tkinter import Canvas
#создаем класс для мяча
class Ball:
def __init__(self, canvas, x, y, r, color):
self.pos_x = x
self.pos_y = y
self.radius = r
self.speed = 10
self.canvas = canvas
self.ball = canvas.create_oval(
x - self.radius,
... |
d59b573a9bc93897e130ad223c08f0b22b99bf0b | ankarn/groupIII_twintrons | /groupIII_3'_motif_search.py | 2,605 | 4.125 | 4 | ################################################################################
#
# Search for Group III twinton 3' motifs
# ______________________________________
#
# A program to to find 3' motifs for group III twintrons, given the external
# intron in FASTA format.
#
# ** Prog... |
b819f06e33319f8924adbcd3fc7c9670c2f8cc2d | jhcb007/Estruturas-de-Dados-I | /G1/FilaE.py | 721 | 3.59375 | 4 | class FilaE():
def __init__(self):
self.__lista = [None, None, None, None, None]
self.__quant = 0
def inserir(self, valor):
self.__lista[self.__quant] = valor
self.__quant += 1
def remover(self):
i = 0
while i < self.__quant - 1:
self.__lista[i] ... |
c293242e46a1fd375cf2e6c7538694bbd6d26130 | jhcb007/Estruturas-de-Dados-I | /G2/CurvaHilbert.py | 1,668 | 3.5625 | 4 | import turtle, math
class CurvaHilbert(turtle.Pen):
def curva(self, size, level, parity):
if level == 0:
return
self.left(parity * 90)
self.curva(size, level - 1, -parity)
self.forward(size)
self.right(parity * 90)
self.curva(size, level - 1, parity)
... |
73adfabacfd33fe459cd50ab1ec8705011bbfa5b | treppomj27/Blackjack | /player.py | 785 | 3.5 | 4 |
class Player:
def __init__(self, name, balance):
self.name = name
self.hand = []
self.balance = balance
self.bet = 0
# noinspection DuplicatedCode
def print(self):
string = ' '
for i in range(0, len(self.hand)):
string += self.hand[i].name + ' '... |
ca55b480b5735b4bc0bcb9feb1bb810de93a1007 | andrewrisse/Exercises | /ArrayAndStringProblems/URLify.py | 1,727 | 4.1875 | 4 | """
URLify.py
Creator: Andrew Risse
Drew heavily from example 1.3 in "Cracking the Coding Interview" in attempt to understand and
write their Java version in Python.
This program replaces spaces in a string with '%20'.
Assumptions: the string has sufficient space at the end to hold the additional characters and ... |
473bd30b5daa7d8d0335840ea14aacff66c661df | Bhvay/My_even_number_program | /even_num.py | 92 | 3.859375 | 4 | num=[1,2,3,4,5]
for i in num:
if i%2 != 0:
print(i)
else:
print(i)
|
125aee19d713f5af5e602059394b8b03adaa817c | P4Kubz/no_quiero_otro_repositorio_aaaaaaaaaa | /for/Introfor.py | 293 | 3.75 | 4 | vocales = ["a", "e", "i", "o", "u"]
frase = "Hola, estoy aprendiendo python"
vocalesnum: int = 0
for letra in frase:
print(letra)
if letra in vocales:
print("he encontrado una '{}'".format(letra))
vocalesnum += 1
print("\n Vocales encontradas: {}".format(vocalesnum)) |
a194e92701501b778fcd38568b573d7a8b554adb | P4Kubz/no_quiero_otro_repositorio_aaaaaaaaaa | /for/ex3.py | 154 | 4.03125 | 4 | tabla = int(input("Ingrese el número de la tabla que quiere: "))
print("La tabla del {} es: ".format(tabla))
for n in range(1, 13):
print(tabla * n,) |
4f127311328e648f7c379ab667f7c704b05c6e28 | P4Kubz/no_quiero_otro_repositorio_aaaaaaaaaa | /Listas/listacompra.py | 500 | 3.875 | 4 | listadecompra =[]
userin = None
print("Programa lista de la compra\n ")
while userin !='Q':
userin = input("¿Qué desea añadir a la lista?(Q) para salir: ")
if userin == 'Q':
break
elif userin in listadecompra:
print("{} ya está en la lista de la compra".format(userin))
else:
if ... |
736639fee57a2ab9e2473e2f4ef67b83dffd2267 | sharapy/py | /Practise/Oct21/big_scratchCode.py | 648 | 3.9375 | 4 | # age = 25
# name = 'Sharad'
# print('{0} was {1} year old when he read this book'.format(name, age))
# print(f'{name} was {age} year old when he read this book')
# print('Why is {0} playing with that python?'.format(name))
# print("{0:_^11}".format('Hello'))
# print("a", end="")
# print("b", end="")
# For Regular ex... |
611124c37947300c19a666c720441e8605a101fc | sharapy/py | /reg_exp4.py | 617 | 3.65625 | 4 | #!/usr/bin/python
#Author: Sharad Talekar
#Date: 5thFeb2015
#Purpose: Practice Regular Expressions
import re
#reg1 = re.compile('hello', re.IGNORECASE) #Matches Verbatim
#reg1 = re.compile('\d+4', re.IGNORECASE) #Matches Verbatim
#reg1 = re.compile('\d+\s+\w+', re.IGNORECASE) #Matches digit/space/words
reg1 = re.com... |
bf224b02942fad9804256c5f0956b7af441b7152 | sharapy/py | /Practise/sep21/q7.py | 857 | 4 | 4 | # unicodeString = u"hello world!"
# print(unicodeString)
# Q64
# _______________________________
# n = int(input())
# sum = 0.0
# for i in range(1,n+1):
# sum+=float(float(i)/(i+1))
# print(sum)
# Q65
# _______________________________
# def f(n):
# if n==0:
# return 0
# else:
# return f(n-... |
11f9399b48273f9ff297dc6fbd052f6eb5738bc8 | malavikalakshmi/Reservation_System | /Customer.py | 1,419 | 3.5625 | 4 | class Customer(object):
__id = 0
def __init__(self, first_name, last_name, airline_class_preference, hotel_class_preference,budget):
Customer.__id += 1
self.__id = Customer.__id
self.__first_name = first_name
self.__last_name = last_name
self.__airline_class_preference =... |
d94f38c829dfbba17b01391e44b10c56a2b7a521 | sagarverma/Wikipedia-Dataset-Processing | /tokenizer.py | 135 | 3.609375 | 4 | import re
while True:
inp = str(raw_input())
out = re.findall("[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\'\w\-]+", inp)
print out |
e903f849bda44a855a36cd6fa0d5dde6a9004241 | ClaudioBorges/Master | /PEL202_fundamentos_da_inteligencia_artificial/BFS_DFS/ia-exercise-1.py | 7,386 | 3.765625 | 4 | from __future__ import print_function
from collections import deque
import random
class ImmutableJar:
""" Jar contains units limited to the capacity and can carry liquids.
"""
def __init__(self, capacity, units=0):
""" Jar contains liquid units limited to a capacity.
:param capacity: Maxi... |
e6d47914f0dbb83a1d0dd6175e6e17fef9129dd3 | GhostDovahkiin/Chinese-Checkers | /Logica.py | 15,009 | 3.640625 | 4 | letras = ["A","B","C","D","E","F"]
def letra ():
ovo = letras
return ovo
def adicionarPecas(tabuleiro,numJogadores):
contador = 0
if numJogadores == 2:
for q in range(4):
for w in range(q+1):
tabuleiro[q][w] = letras[0]
contador = 3
for q in range(13,1... |
d34447e596da9bb30697c679ab690245afe8f8d2 | lennonrar/courses | /coursera/python/week7/exe1.py | 189 | 3.953125 | 4 | b = int(input("digite a largura: "))
a = int(input("digite a altura: "))
i, j = 0, 0
while i < a:
while j < b:
print("#", end = "")
j+=1
print()
j = 0
i+=1 |
bcc951e58e78e95e56eff259c0011ee96f45ab89 | muodov/pymoticon | /pymoticons.py | 932 | 3.546875 | 4 | class BaseEmo(object):
def __repr__(self):
return 'hmm...'
class Damn(BaseEmo):
def __repr__(self):
return 'doh!'
class Cool(BaseEmo):
def __repr__(self):
return 'Awesome!'
class Indeed(BaseEmo):
def __repr__(self):
return 'You are so right!'
class Lol(BaseEmo):
d... |
ac4be20f003f5e94d72f2251cc53f7ef384d02f0 | chunhuayu/Python | /Crash Course/06. Operators.py | 616 | 4.3125 | 4 | # Multiply 10 with 5, and print the result.
>>> print(10*5)
# Divide 10 by 2, and print the result.
>>> print(10/2)
# Use the correct membership operator to check if "apple" is present in the fruits object.
>>> fruits = ["apple", "banana"]
>>> if "apple" in fruits:
print("Yes, apple is a fruit!")
# ... |
0d303b898e689b0460aecb8d16248106d3a0073e | chunhuayu/Python | /Crash Course/0702. Tuple.py | 2,436 | 4.78125 | 5 | # Tuple is immutable
# A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
# Access Tuple Items: You can access tuple items by referring to the ind... |
02e253bfd5d3cd75b926eb259b8bbad14126e14b | chunhuayu/Python | /01. Numpy/09. Splitting.py | 1,037 | 3.796875 | 4 | # Splitting one array into several smaller ones
# Using hsplit, you can split an array along its horizontal axis,
# either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur:
>>>
>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ ... |
8b927e4232d797be279c235d4a02e0ff922c5f24 | momentum-cohort-2020-01/word-frequency-DeeMeyers | /word_frequency.py | 2,338 | 4.09375 | 4 | STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
# """Read in `file` and print out the frequency of words in that file."""
# pass
def print_word_freq(file):
with... |
c1d484e097060f174fa6dc8435972ef74dabdbe6 | tptracker/tptracker | /test_CSV.py | 901 | 3.59375 | 4 | # This is the code for connecting to the serial port of Arduino.
# adaped from https://www.learnrobotics.org/blog/arduino-data-logger-csv/'s version
import serial
arduino_port = "COM5" #serial port of Arduino
baud = 9600 #arduino uno runs at 9600 baud
fileName="Output_CSV_from_Arduino.csv" #name of the CSV file genera... |
909606bcce11782b89b5a861e4b089453a1a44d8 | Changkyuuu/Chapter3 | /condition.py | 653 | 4.03125 | 4 | # if -elso
a = 1
if a > 5:
print('big')
a = 1
if a < 5:
print('big') # 요고만 출략
a = 3
if a > 5:
print('big')
else:
print('small')
# a가 5보다 크면 big를 출력하고 아니면 small을 출력해라
# if - elif -
n = -1
if n > 0:
print('양수')
elif n < 0:
print('음수')
else:
print('0')
# spam : 100
# egg : 500
# spagetti :... |
2f59e1f224aeeab57e9e336d4ae4004f8fb29801 | Harinarayan14/p103 | /p103.py | 247 | 3.515625 | 4 | import pandas as pd
import plotly.express as px
df = pd.read_csv("data.csv")
scatterChart = px.scatter(df,x="Date",y="Number of Cases",color="Country",title="Number of Covid Cases in different Countries on different Dates")
scatterChart.show() |
852504421ea9d18a3636053bc66ff4d5c6058c82 | shrutibhanderi/exampleScripts | /vehicules-en-circulation/readData.py | 302 | 3.640625 | 4 | #vehicules-circulation-2016 dataset
#import pandas for reading csv file into dataframe
import pandas as pd
#read_csv from pandas will read the csv file into dataframe(which is table like format)
df = pd.read_csv('vehicules-circulation-2016.csv')
#prints first 5 row of the dataframe
print(df.head(5))
|
83737baf0095cba0d483b3c7f69d3fe95af14cee | kimhs1876/python-oop | /encapsulation/bmi_calculator.py | 282 | 3.5 | 4 | class Bmi_Calculator:
def setdata(self, weight, height):
self.weight = weight
self.height = height
def bmi(self):
return b.weight / (b.height * b.height)
if __name__ == '__main__':
b = Bmi_Calculator()
b.setdata(97, 1.87)
print(b.bmi()) |
5d6e0e52607c1299afd67a97ac524569c681a54e | arhandreu/ADV_PY | /HW4/Generator.py | 244 | 3.6875 | 4 | import hashlib
def convert_md5(path='iterator.txt'):
with open(path, 'r', encoding='utf-8') as file:
for text in file:
yield hashlib.md5(text.strip().encode('utf-8')).hexdigest()
for i in convert_md5():
print(i)
|
7863c25ec169455a4f1cf787992e7b582fa42336 | AdityaJsr/cosmosDB | /cosmosDB/mongoDb/CRUD.py | 4,376 | 3.609375 | 4 | """
Title - Write a Python program to to perform CRUD operations on the mongodb api (azure).
Author name - Aditya Kumar
Ceation time - 23 April 2021
Modified time - 29 April 2021
"""
#All the imports required to run the script.
import pymongo
from decouple import config
'''
Connection to azure mongodb API.
Cr... |
80b085924929cdfc54be0dcf6030312216b5056e | MrHuxu/leetcode150 | /python/13.py | 1,179 | 3.78125 | 4 | import unittest
from typing import Dict
map_sym_to_num: Dict[str, int] = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
class Solution:
def romanToInt(self, s: str) -> int:
ret = 0
for i in range(len(s)):
if s[i] == 'V' or s[i] == 'X'... |
f82dff7e5d3f1ffc37dedd920e4968d5cd82e4c0 | MrHuxu/leetcode150 | /python/5.py | 839 | 3.75 | 4 | import unittest
from typing import List
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return s
dp: List[List[bool]] = list(
list(False for _ in range(len(s))) for _ in range(len(s)))
resultL = 0
resultR = 0
for l in range(1,... |
539a15d7e4c4e1862a47161037ee370cb5decd05 | MrHuxu/leetcode150 | /python/35.py | 714 | 4 | 4 | import unittest
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target <= nums[0]:
return 0
if target > nums[-1]:
return len(nums)
left, right = 0, len(nums) - 1
while left < right:
mid = (... |
b6ee1ff0c521b4c1fcb6afc875639e68a1aebf73 | MrHuxu/leetcode150 | /python/20.py | 658 | 3.796875 | 4 | import unittest
from typing import Dict, List
class Solution:
mapRightToLeft: Dict[str, str] = dict(zip(')]}', '([{'))
def isValid(self, s: str) -> bool:
stack: List[str] = []
for char in s:
if not stack:
stack.append(char)
continue
if ... |
3b76bf4b27d94c845110d5de9bcd258687f6f421 | MrHuxu/leetcode150 | /python/67.py | 797 | 3.609375 | 4 | import unittest
from typing import List
class Solution:
def addBinary(self, a: str, b: str) -> str:
l = max(len(a), len(b))
sum: List[str] = ['0'] * (l + 1)
carry = 0
for i in range(l):
if i < len(a):
carry += ord(a[len(a) - i - 1]) - ord('0')
... |
c094ca71ac8acbb27b62c50135807d895aab862e | MrHuxu/leetcode150 | /python/74.py | 1,109 | 3.796875 | 4 | import unittest
from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
left, right = 0, len(matrix) - 1
row_idx = 0
while left <= right:
mid = (left + right) // 2
... |
0ca0317ff1f686cde6287455673ac882642ea91a | makurek/leetcode | /1309-decrypt-string-from-alphabet-to-integer-mapping.py | 780 | 4 | 4 | '''
Given a string s formed by digits ('0' - '9') and '#' .
We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.
It's guarante... |
58415f2059a2052ff548576e4170cc142156c1e0 | duoduo3369/exercise | /algorithm/data_structure/linked_list.py | 1,337 | 3.578125 | 4 | # coding=UTF8
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
class ListException(Exception):
message = "列表元素为空"
class List(object):
def __init__(self):
self.head = None
self.tail = None
def push(sel... |
b4f30a8dd730c80e2da41cf00f50bc2624ed2e71 | duoduo3369/exercise | /algorithm/Divide_and_Conquer/二分搜索.py | 405 | 3.71875 | 4 | def binary_search(L,key):
low,high = 0,len(L)
while low <= high:
mid = (low + high)/ 2
if L[mid] is key:
return mid
elif L[mid] < key:
low = mid + 1
else:
high = mid - 1
return None
L = range(500)
print L
for i in xrange(100)... |
09575841e6bb979f91a6aa63513de9bcb42cd8a6 | duoduo3369/exercise | /algorithm/最大公约数/gcd.py | 203 | 3.640625 | 4 | # coding=UTF8
def gcd(a,b):
"""欧几里得算法"""
def remainder(x,y):
return x % y
if remainder(a,b) is 0:
return b
else:
return gcd(b,remainder(a,b))
|
2a4d241b1a274ddc88855f5c4c16d96bba9546e4 | duoduo3369/exercise | /pyqt/stack/linked_list.py | 911 | 3.796875 | 4 | class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
class ListException(Exception):
pass
class List(object):
def __init__(self):
self.head = None
self.tail = None
def push(self, value):
if ... |
e0d8c27e314b1b0eac2c1f1629268dbce350373a | goncaloalbino/fibonacci | /api/fibonacci.py | 2,634 | 3.75 | 4 | from typing import Dict, List, Tuple, Iterator, Union
import paginate
BLACKLIST = set()
def fibonacci() -> Iterator[int]:
"""
Generates an iterator with the fibonacci sequence values
:return: Iterator with fibonacci value
"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
... |
89bbb456d2361621c7cefe4d98f5e209e05f30f6 | everestocean/design_pattern | /python/design_pattern/behavioral_pattern/visitor_pattern.py | 1,528 | 3.671875 | 4 | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
# base implementation of vistor pattern, this code only work on python 3 or more higher python version
def _qualname(obj):
"""Get the fully-qualified name of an object (including module)."""
return obj.__module_... |
9fc1e19c88ccb94049cae0eaccb676e2190f0cda | rajatpachauri/Python_Workspace | /Print_function_and_string/Print_ways.py | 161 | 3.8125 | 4 | a = 12
b = 13
c = a+b
print('the sum of',a,'and',b,'is',c)
print('The sum of %d and %d is %d'%(a,b,c))
print('The sum of {} and {} is {}'.format(a,b,c))
|
57c29ce26289441922f017c49a645f8cbe9ce17f | rajatpachauri/Python_Workspace | /While_loop/__init__.py | 260 | 4.25 | 4 | # while loop is mostly used for counting
condition = 1
while condition < 10:
print(condition)
condition += 1
# condition -= 1
# to create out own infinite loop
while True:
print('doing stuff')
# for breaking use control+c |
911079fd58789407a192638c50726f27a3f9c5f2 | rajatpachauri/Python_Workspace | /Classes/__init__.py | 532 | 3.515625 | 4 | # classes is somewhat simlar to modules
# way of binding attributes
class calculator:
def __init__(self):
pass
def addition(x,y):
added = x+y
print(added)
def subtraction(x,y):
sub = x-y
print(sub)
def multiplication(a,... |
c55c8329fa37490c18c8fabf18a30f1859276b95 | Dufert/VariousAttempts | /numpy_exercise.py | 278 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 17:37:13 2018
@author: Administrator
"""
import numpy as np
#a = [1,2,3,4,7,8]
#print(np.where(a == np.max(a)))
a = 1
b = 2
c = 3
if ((a ==0) & (b>1) & (c ==3)):
print('ok')
print(a ==1 and b>1)
elif c ==3:
print(3) |
152988ffaf42fe23efccdeb8a730afb161600b6d | triibal/workspace | /python/arrays.py | 2,079 | 4.0625 | 4 | #!/bin/env/python
# import any required libraries
# none required
### Working with Arrays
xaa = [1,1,2,3,2,2,4,5,7]
xab = [1,2,3,4,5,6]
# Find the only element in an array that only occurs once.
def uniqueCount():
""" Find the elements in an array that occur once"""
for f in xaa:
count = xaa.count(f... |
09eec26832a145c2c914e4c34621c94c09d9347a | naveentrtumkur/Basic-Python | /string_formatting.py | 315 | 3.78125 | 4 | #You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.
data = ("John", "Doe", 53.44)
#print(data)
format_string = "Hello"
name= data[0] +" "+ data[1]
print(" %s %s. Your Current balance is $%d" %(format_string ,name, data[2]))
|
645fa33f0810f3f461a7f3fa05d14fe4b3e6b048 | harry1180/python_basics | /Project/Plagiarism/02_LongestCommonString_Algorithm - Copy/libraries/algos/lcs_v1.py | 3,387 | 3.59375 | 4 | def genArraysList(a,b,defaultValue=0):
"""
returns an matrix of zeroes,size aXb kind of object using lists within a list
"""
try:
assert a>0,b>0
temp=[]
for i in range(a):
temp.append([defaultValue]*b)
return temp
except AssertionError:
... |
2d0d71924024f7ac58578566ae996782f4c57b02 | shreyansh-kabir/Covid-19-Detector | /Covid-19 detector.py | 15,768 | 4.09375 | 4 | '''
1. User information.
2. All required data.
3. calculation.
4. probability.
5. class.
6. symtoms confirmation.
7. How prevent COVID-19.
8. Some information about how this COVID-19 generated.
9. Some information about the vaccine.
'''
def AskUserinfo():
# getting the user info
print('HELLO!\n... |
dea3ca416f2a30a5938052a1ccae70261fec1980 | Aminaba123/LeetCode | /071 Sqrt(x).py | 637 | 4.09375 | 4 | """
Implement int sqrt(int x).
Compute and return the square root of x.
"""
__author__ = 'Danyang'
class Solution:
def sqrt(self, x):
"""
Newton's method
x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} \
http://en.wikipedia.org/wiki/Newton's_method
:param x: Integer
... |
44c208a563b5e080fe8a82824a8ec91bab919180 | Aminaba123/LeetCode | /150 Evaluate Reverse Polish Notation.py | 1,493 | 3.515625 | 4 | __author__ = 'Danyang'
class Solution(object):
def evalRPN(self, tokens):
"""
stack
basic in bytecode operation
basic in compiler technique
:param tokens:
:return:
"""
ops = ["+", "-", "*", "/"]
def arith(a, b, op):
... |
cd192a4ea1d267c842ef5b1d693124b9869f1e9a | Aminaba123/LeetCode | /453 Minimum Moves to Equal Array Elements.py | 626 | 3.78125 | 4 | #!/usr/bin/python3
"""
Given a non-empty integer array of size n, find the minimum number of moves
required to make all array elements equal, where a move is incrementing n - 1
elements by 1.
"""
class Solution:
def minMoves(self, nums):
"""
List out, find the pattern
for every operation, ... |
1aa840435f3eaabb240f81d193c62b3381f52110 | Aminaba123/LeetCode | /477 Total Hamming Distance.py | 1,306 | 4.1875 | 4 | #!/usr/bin/python3
"""
The Hamming distance between two integers is the number of positions at which
the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the
given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 010... |
05a8f71fc5e7b421ee098845806cc55f6460df06 | Aminaba123/LeetCode | /086 Scramble String.py | 2,347 | 4.09375 | 4 | """
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any ... |
2548a641b724b6f7233119cbaf964e0d0f38524e | Aminaba123/LeetCode | /026 Remove Duplicates from Sorted Array.py | 1,993 | 3.953125 | 4 | """
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A ... |
0674b8d7de1b0a1f417b11be2eac016d459c8be5 | Aminaba123/LeetCode | /063 Unique Paths II.py | 1,948 | 4.1875 | 4 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0... |
a8e56295e5b3d81fc6b63eb549d4a4d4f51dd7ea | Aminaba123/LeetCode | /433 Minimum Genetic Mutation.py | 2,041 | 4.15625 | 4 | #!/usr/bin/python3
"""
A gene string can be represented by an 8-character long string, with choices
from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to
"end"), where ONE mutation is defined as ONE single character changed in the
gene string.
For example, "AACCGGTT" -> "A... |
290e0583e680f669ce53fcc8fd8bb79e3b7c8ada | Aminaba123/LeetCode | /341 Flatten Nested List Iterator.py | 4,245 | 4.59375 | 5 | """
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next shoul... |
5c64ed55f1b30d9a656f5855458dcea9ff0c4d0c | Aminaba123/LeetCode | /049 Anagrams.py | 1,993 | 4.0625 | 4 | """
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
"""
__author__ = 'Danyang'
class Solution:
def anagrams_complicated(self, strs):
"""
sorting
:param strs: a list of strings
:return: a list of strings
... |
5b2e240df75725af7b6dec5e42544e1ced88e7a6 | Aminaba123/LeetCode | /309 Best Time to Buy and Sell Stock with Cooldown.py | 1,776 | 3.875 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell
one share of the stock multiple times) with the following restrictions:
You may not engage in multiple tra... |
6488e82df4b18fc4b52b2be04ff50db7fdb9c36b | Aminaba123/LeetCode | /462 Minimum Moves to Equal Array Elements II.py | 2,229 | 4.03125 | 4 | #!/usr/bin/python3
"""
Given a non-empty integer array, find the minimum number of moves required to
make all array elements equal, where a move is incrementing a selected element
by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Ex... |
64ebeedfbf3d242316451493e0407916896c2f77 | Aminaba123/LeetCode | /403 Frog Jump.py | 2,164 | 4.28125 | 4 | """
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The
frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river
by landing o... |
14dcb0729ca849355b387604547c468e01411695 | Aminaba123/LeetCode | /050 N-Queens.py | 3,981 | 4.125 | 4 | """
The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a
... |
c0c20727afc5effa9329c73557d8b8596ce3c0a1 | Aminaba123/LeetCode | /219 Contains Duplicate II.py | 802 | 3.5625 | 4 | """
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array
such that nums[i] = nums[j] and the difference between i and j is at most k.
"""
__author__ = 'Daniel'
import heapq
from collections import defaultdict
class Solution:
def containsNearbyDupl... |
24ba1fb74133913ff4642b3168f44b775cf64b7c | Aminaba123/LeetCode | /384 Shuffle an Array.py | 1,372 | 4.28125 | 4 | """
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array ba... |
3fa97143863d937d9907713bf1f3d6ca90197497 | Aminaba123/LeetCode | /451 Sort Characters By Frequency.py | 898 | 4.03125 | 4 | #!/usr/bin/python3
"""
Given a string, sort it in decreasing order based on the frequency of characters.
"""
from collections import defaultdict
class Solution(object):
def frequencySort(self, s):
"""
Brute force: counter, sort O(n log n)
There is a uppper limit of the counter, thus bucke... |
88e20b905002d5a64956f68cb80acbd7477fd820 | Aminaba123/LeetCode | /128 Longest Consecutive Sequence.py | 2,472 | 4.03125 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
__author__ = 'Danyang'
class So... |
5a5333ae12496d1ff99033ec928eb96fd66cf6bc | Aminaba123/LeetCode | /097 Interleaving String.py | 2,718 | 3.828125 | 4 | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
def isInterleave(self, s1, s2, s3):
... |
1f74424865e12a7a5881a723a18462cd130e6aca | Aminaba123/LeetCode | /054 Jump Game.py | 2,848 | 3.78125 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return f... |
c3b2607b4f0b9bd94c6f3c752494e5789be9f17d | Aminaba123/LeetCode | /290 Word Pattern.py | 2,332 | 3.953125 | 4 | """
Given a pattern and a string str, find if str follows the same pattern.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" sh... |
86fcbe4e8ef1f0e2d229bd1765101090b2cf39e3 | Aminaba123/LeetCode | /247 Strobogrammatic Number II.py | 3,454 | 3.5 | 4 | """
Premium Question
Generation
https://leetcode.com/problems/strobogrammatic-number-ii/
"""
from collections import deque
__author__ = 'Daniel'
class Solution(object):
def __init__(self):
self.lst = ["11", "69", "88", "96", "00"] # use list rather than map since no need to look up
self.middle = ... |
11eb1db94086cfe2581eb2aee651972c7403cc56 | Aminaba123/LeetCode | /397 Integer Replacement.py | 1,391 | 3.859375 | 4 | """
Given a positive integer n and you can do operations as follow:
If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Input:
7
Out... |
13684394a6e93a3c95c3c7916fcb88113a22e7a0 | Aminaba123/LeetCode | /088 Merge Sorted Array.py | 1,122 | 4.125 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ = 'Danyang'
class... |
36bd7b053f22dbde6145ee948b168bb114a1bcfe | Aminaba123/LeetCode | /225 Implement Stack using Queues.py | 1,673 | 4.28125 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, p... |
b92d845c95719ce666dbd1b3b33ac3c38696f947 | Aminaba123/LeetCode | /160 Intersection of Two Linked Lists.py | 1,521 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
N... |
202b121e811198b5c9a55d8209d1a9fff43f5759 | Aminaba123/LeetCode | /491 Increasing Subsequences.py | 1,922 | 4 | 4 | #!/usr/bin/python3
"""
Given an integer array, your task is to find all the different possible
increasing subsequences of the given array, and the length of an increasing
subsequence should be at least 2 .
Example:
Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7],
[4,7,7]]... |
7885fb14e8d07b3e6ee48edcb12b467fb96b7195 | Aminaba123/LeetCode | /427 Construct Quad Tree.py | 1,947 | 3.765625 | 4 | #!/usr/bin/python3
"""
We want to use quad trees to store an N x N boolean grid. Each cell in the grid
can only be true or false. The root node represents the whole grid. For each
node, it will be subdivided into four children nodes until the values in the
region it represents are all the same.
Each node has another t... |
cdb87aa34052b988b1b4b4a97333c8121809e7fe | Aminaba123/LeetCode | /330 Patching Array.py | 2,519 | 3.734375 | 4 | """
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in
range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches
required.
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1],... |
d9e0e9eeb9cb466d68b6e577b242799227918af3 | Aminaba123/LeetCode | /328 Odd Even Linked List.py | 1,977 | 4 | 4 | """
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking
about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->N... |
bc7aef2e02170ac4af072cca339ddf71f6e128cf | Aminaba123/LeetCode | /261 Graph Valid Tree.py | 1,033 | 3.578125 | 4 | """
Premium Question
"""
from collections import defaultdict
__author__ = 'Daniel'
class Solution(object):
def validTree(self, n, edges):
"""
A graph is a tree:
1. no cycle
2. all connected
:type n: int
:type edges: List[List[int]
:rtype: bool
"... |
5c9c097ca50814b99215e1490952a5f86c51b137 | Aminaba123/LeetCode | /123 Best Time to Buy and Sell Stock III.py | 3,035 | 3.703125 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
__au... |
e1f8418c619387080a7022d1d6a4c1434bc7885f | Aminaba123/LeetCode | /291 Word Pattern II.py | 1,265 | 3.578125 | 4 | """
Premium Question
"""
__author__ = 'Daniel'
class Solution(object):
def wordPatternMatch(self, pattern, s):
"""
Backtracking with prune
:type pattern: str
:type s: str
:rtype: bool
"""
return self.dfs(pattern, s, {}, set())
def dfs(self, pattern, s, ... |
91b1af0b14a19ef05546b36010c23e6d3d45b9ba | Aminaba123/LeetCode | /187 Repeated DNA Sequences.py | 1,871 | 3.859375 | 4 | """
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying
DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
For ... |
2bdfc5dc0dea17c1221e708eb253fd386546ae9c | Aminaba123/LeetCode | /516 Longest Palindromic Subsequence.py | 1,246 | 3.859375 | 4 | #!/usr/bin/python3
"""
Given a string s, find the longest palindromic subsequence's length in s. You
may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequ... |
85068b845fc62bc3ca6b9307072225de0f5d380f | Aminaba123/LeetCode | /353 Design Snake Game.py | 2,043 | 4.4375 | 4 | """
Design a Snake game that is played on a device with screen size = width x height.
"""
from collections import deque
__author__ = 'Daniel'
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@par... |
683d76c9c33929407a4d8707b24e793daeefe1cc | Aminaba123/LeetCode | /446 Arithmetic Slices II - Subsequence.py | 1,999 | 4 | 4 | #!/usr/bin/python3
"""
A sequence of number is called arithmetic if it consists of at least three
elements and if the difference between any two consecutive elements is the same.
The function should return the number of arithmetic subsequence slices in the
array A. (Subsequence rather than slide)
"""
from collections ... |
2b1f310577c60d215a2c22ced20a611320431d33 | Aminaba123/LeetCode | /138 Copy List with Random Pointer.py | 1,690 | 3.984375 | 4 | """
A linked list is given such that each node contains an additional random pointer which could point to any node in the
list or null.
Return a deep copy of the list.
"""
__author__ = 'Danyang'
# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
... |
d51b291eddd251869ee107deba47d4d98ae94623 | Aminaba123/LeetCode | /198 House Robber.py | 1,129 | 3.75 | 4 | """
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it
will automatically contact the police if two adjacent houses were broken int... |
bc29683d52bc8fc5a889a13f61388b539214e349 | mys5209/test | /untitled/room.py | 35,561 | 3.734375 | 4 | #! /usr/bin/python
# -*-coding:utf-8 -*-
#a = 4
#print(a)
#a= input ("请输入密码:")
#print(a)
#a,b,c,d,= 1,2,3,"hello"
#print(a,b,c,d)
#a='hell 我叫{},今年{}岁'
#b='缪'
#c=a.format(b)
#print(c)
#a='hello 我叫%s,今年%d岁'
#b=input('请输入你的名字')
#f=input('请输入你的年纪')
#t=int(f)
#c=a %(b,t)
#print(c)
#a=' qwer '
#b=a.strip()
#print(b)
#a='ewq... |
fffcddf17a4e77094d5a8a311517da690a7a1e20 | Chonwai/CISC7201 | /Inclass Exercise/Exercise 01/exercise01.py | 251 | 3.75 | 4 | import datetime
flag = True
while flag:
name = input("Give me your name: ")
age = input("Give me your age: ")
now = datetime.datetime.now()
temp = 100 - int(age)
ans = now.year + temp
print("100 years old at " + str(ans))
pass
|
81e034a1b21232a4030a9546e0cd6f033814a2ce | OUfuke/MakeCalender | /print_cal.py | 1,676 | 3.6875 | 4 | import calendar
def print_title(title, year, month, is_month_num, month_abbreviation):
title = title.replace("Year", str(year))
if is_month_num:
title = title.replace("Month", str(month))
else:
if month_abbreviation:
title = title.replace("Month", calendar.month_abbr[month])
... |
4497459039fd1819dfa4e2934f031784d5f87eb6 | owaiskazi19/Practice-Problems | /Tree/vertical_level_order.py | 834 | 3.671875 | 4 | from collections import defaultdict
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return
queue = []
res = defaultdict(list)
hd = 0
... |
fc2bd21bba35d9c8c426897ae30ae0c966be5bcc | owaiskazi19/Practice-Problems | /Tree/bfs.py | 790 | 3.75 | 4 | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printLevelOrder(root):
h = height(root)
for i in range(0, h+1):
printGivenOrder(root, i)
def printGivenOrder(root, level):
if root is None:
return
if level == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.