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 |
|---|---|---|---|---|---|---|
ed8ce5ee6f148e1f31e3cbec554f3942455486c1 | beginner-lrk/test_python | /listandtuple.py | 1,782 | 4.4375 | 4 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# 变量classmates就是一个list,x=[ ]
print(1)
classmates = ['tom', 'Bob', '流川']
print(classmates)
print(len(classmates))
# 用索引来访问list中每一个位置的元素,记得索引是从0开始的,最后一个元素的索引是len(classmates) - 1。
print(classmates[0], classmates[1], classmates[len(classmates) - 1])
# 取最后一个元素,倒数第二个,倒数第三个
print(cla... |
cf39bf3bc61936188e995b44b6ca9ec5d9a079d4 | noevazz/learning_python | /041_parametrized_functions.py | 310 | 3.734375 | 4 | # functions can have arguments with default values
# it means that if you invoke the function without providing that argument the function will ise the default value:
def greeting(first_name, last_name="Vazquez"):
print("hi mi name is", first_name, last_name)
greeting("Noe")
greeting("Andy", "Contreras") |
9a707d82601e9d9624b52f04884606cfe8d81e53 | noevazz/learning_python | /035_list_comprehension.py | 681 | 4.46875 | 4 | #A list comprehension is actually a list, but created on-the-fly during program execution,
# and is not described statically.
# sintax = [ value for value in expression1 if expression2]
# it will generate a list with the values if the optional expression is True
my_list = [number for number in range(1, 11)] # this wil... |
e09e60bf03324e754a246d9ef71870103a86ee3a | noevazz/learning_python | /082__init__method.py | 811 | 4.3125 | 4 | # classes have an implicit method (that you can customize) to initialize your class with some values or etc.
# the __init__ method is called constructor
# __init__ cannot return a value!!!!!!!! as it is designed to return a newly created object and nothing else;
class MyNiceClass():
# whenever you see "self" it is us... |
1ac5d30ca8eb886ca9e3c293d490ca97d314024d | noevazz/learning_python | /072_ord_chr.py | 708 | 4.59375 | 5 | print("------ ord ------")
# if you want to know a specific character's ASCII/UNICODE code point value,
# you can use a function named ord() (as in ordinal).
print(ord("A")) # 65
print(ord("a")) # 97
print(ord(" ")) # 32 (a-A)
print(ord("ę"))
# The function needs a >strong>one-character string as its argument
# breachi... |
7ed9c724bf11e137822aad2205b2ba4425de4f5d | noevazz/learning_python | /094_inheritance.py | 693 | 3.984375 | 4 | """
inheritance allows us to grant children (sub class) with all the features of a parent class (super class)
"""
class SuperOne:
def hello_1(self):
print("Hello 1")
class SuperTwo:
def hello_2(self):
print("Hello 2")
class Sub(SuperOne, SuperTwo): # note that a class can have more than one p... |
1e78bed77a7b9c6d2c986581073098305e0fb66b | noevazz/learning_python | /010_basic_operations.py | 676 | 4.59375 | 5 | # +, -, *, /, //, %, **
print("BINARY operators require 2 parts, e.g. 3+2:")
print("addition", 23+20)
print("addition", 23+20.) # if at least one number is float the result will be a float
print("subtraction", 1.-23)
print("multiplication", 2*9)
print("division", 5/2)
print("floor division", 5//2) # floor division (IT ... |
f45f0ea56e2ab05a60c1b897cf1dc2076a13fd09 | noevazz/learning_python | /027_negative_indeces.py | 477 | 4.375 | 4 | # Negative indexes are legal
my_list = [4, 7, 10, 6]
print("List=", my_list)
# An element with an index equal to -1 is the last one in the list
print("[-1] index=", my_list[-1])
# The element with an index equal to -2 is the one before last in the list
print("[-2] index=", my_list[-2])
# We can also use the "del" i... |
0d5eaf303605eeec6370c7a1b1caf06ef909a248 | noevazz/learning_python | /105_polymorphism_and_virtual_methods.py | 434 | 4.375 | 4 | """
The situation in which the subclass is able to modify its superclass behavior
(just like in the example) is called polymorphism.
"""
class One:
def doit(self):
print("doit from One")
def doanything(self):
self.doit()
class Two(One):
def doit(self): # overrides the partent's: doit() is... |
1263ccc26c964ff4190e955eec3632b9d59ab49b | noevazz/learning_python | /019_comparasion_operators.py | 295 | 4.09375 | 4 | pepsi = 200
fanta = 120
print("pepsi=", pepsi, "fanta=", fanta)
# greater than
print(pepsi > fanta)
# greater than or equal
print(pepsi >= fanta)
# less than
print(pepsi < fanta)
# less than or equal
print(pepsi <= fanta)
# you can store the result:
res = pepsi == fanta
print("res=", res)
|
6116132b63fe41387440472cd5846af34a8ab792 | noevazz/learning_python | /045_recursion.py | 468 | 4.375 | 4 | # recursion is when you invoke a function inside the same function:
def factorialFun(n): # Factorial of N number is equal to N*(N-1)*(N-2) ... *(1)
if n < 0:
return None
if n < 2:
return 1
return n * factorialFun(n - 1)
print(factorialFun(3))
# Yes, there is a little risk indeed. If you fo... |
6a022528eb1b7cd8400e72293bc12805dcd6aaef | noevazz/learning_python | /021_while_loop.py | 1,988 | 4.25 | 4 | # loops allow us to execute code several times while a boolean expression is True or while we do not break the loop explicit
# while loop:
money = 0
fanta = 43
while money < fanta:
#save 11 dollar each day to buy a fanta
money += 11
print("I have", money, "dollars")
# there is also inifinite loops:
mone... |
58311959e0e85debd79c0aecdd11058d3ac97566 | noevazz/learning_python | /037_you_first_function.py | 903 | 4.4375 | 4 | # in order to use our own function we first need to define them:
def my_first_function():
print("Hello world, this is my first function")
# Now we can call (INVOCATION) our function:
my_first_function()
# remember the "pass" keyword that we saw when we were learning about loops, it can be used if you don't know w... |
080a28565bf27cd40c8541b2c880522b653a9619 | noevazz/learning_python | /012_operators_and_their_bindings.py | 343 | 4.0625 | 4 | # The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression.
print(9 % 6 % 2)
# This operator has left-sided binding
# 9%6=3, then 3%2=1, result=1
print("example with right-sided binding:")
print(2 ** 2 ** 3)
# first 2**3=8, the... |
2124475661e15275a16886dbb68fc430120db14b | shwetati199/Python-Beginner | /8_for_loop.py | 1,158 | 4.59375 | 5 | #For loop- it is used mostly to loop over a sequence
#It works more like iterator method
namelist=["Shweta","Riya", "Priya", "Supriya"]
print("Namelist: ")
for name in namelist:
print(name)
#For loop don't require indexing variable to get set.
#For loop over String
print("For loop for string")
for i in... |
4b485597028b06accec5822a128ba9b94bf65adc | varunvd/Random-Dumps | /lngpalinstr.py | 631 | 3.984375 | 4 | def palindrome(str)
list=[]
a=0
result=""
str=str.replace(" ", "")
def add_substring(list, str, i):
for j in range(0, len(str)-i):
list.append(str[j:j+i+1])
def palindrome(string):
for i in range(0, len(string)/2):
if string[i]!=string[-(i+1)]:
return 0;
return len(string)
#This for loop create... |
3c70daaafd0bc81c418f81a23529ceb9f0cb5a97 | varunvd/Random-Dumps | /check.py | 355 | 3.90625 | 4 | #!/usr/bin/python
N = int(raw_input("Enter the value of N"))
newans=[]
def isprime(a):
for i in range(2, (a/2)+1):
if a%i==0:
print "False"
return
print "True"
def varun(n,N):
for i in range(2, n+1):
if n%i==0 and N%i==0:
return False
return True
for j in range(2, N):
a=varun(j,N)
if a==True:
newan... |
1915badb39cfe28512f89260ce7fd3c8198e10e6 | varunvd/Random-Dumps | /leader.py | 282 | 3.703125 | 4 | a=int(raw_input("Enter the number of people in the country"))
name=[]
for i in range(0,a):
name.append(raw_input())
check=[]
for i in range(0,a):
v=name[i]
v=set(v)
check.append(len(v))
number=max(check)
for i in range(0,a):
if number == int(check[i]):
print name[i]
break
|
dff25f78f15b37bf71408f43655f9e97176550f8 | ayueha/python-class-assignment | /untitled/assignment2/objectoriented.py | 1,407 | 4.09375 | 4 | class Cookies:
def __init__(self, flavor, topping):
self.cookie_flavor = flavor
self.cookie_topping = topping
def get_cookie(self):
return print("Cookie is " + self.cookie_flavor + " and " + self.cookie_topping)
def __set_name__(self, flavor, topping):
while True:
... |
d2bfb582e28f444727b40bdc7869b9d585450325 | Squidjigg/pythonProjects | /wordCount.py | 318 | 4.125 | 4 | userInput = input(f"What is on your mind today? ")
# split each word into a list
wordList = userInput.split()
#print(wordList) # this is here for debugging only
# count the number of items in the list
wordCount = len(wordList)
print(f"That's great! You told me what is on your mind in {wordCount} words!") |
5d648813aa4c424c34eb59788d8bcb94eb3975bd | arutishauser/lede-notes | /importdateutilparser.py | 3,174 | 3.59375 | 4 | import dateutil.parser
# or import parser from dateutil
import datetime
import csv
import urllib2
import os
# 1 cup = 16 tablespoons
def to_cups(amount, unit):
if unit == "tablespoons":
return float(amount/16.0), "cups"
if unit == "teaspoons":
return float(amount/48.0), "cups"
elif unit == "cups":
return amou... |
f2ad273f470accf625eab53467173590e43f3d40 | talitore/99-projects | /5/python.py | 211 | 4.03125 | 4 | length = float(input("Enter length of floor: "))
width = float(input("Enter width of floor: "))
cost = float(input("Enter cost of tile per sqft: "))
print("Total cost: " + '$%.2f' % (length * width * cost)) |
fbd41abaad06e7808482feca2e60dd4e146dfd5d | Rachanahande/python_ws | /M2_Q/filtervowel.py | 142 | 3.671875 | 4 | name=input("enter your name:")
lst = ['a','e','i','o','u']
lst.append("python")
print((len(list(filter(lambda x: x in lst,name)))))
print(lst) |
e06f9a1269f939e6e5850410886f0bb189e58178 | javasmuse/mycode | /tuesday/playground.py | 120 | 3.6875 | 4 | #!/usr/bin/env python3
def orange():
ans = input("What's your sign? ")
print(f"You're a {ans}!")
orange()
|
feeedf36a3f2ae4630b2eb85bb3623176854a632 | minddal/School-stuff | /myprojects/src/Countdown.py | 259 | 3.9375 | 4 | '''
Created on 01/11/2012
@author: Andreas M
'''
def countdown(n):
if n<=0:
print ("Boom!!")
else:
print (n)
import time
time.sleep(1)
countdown(n-1)
countdown(5)
|
120c25b2aa19af0bb271502061f37e560bde57b6 | ar2126/Ngram-Viewer | /N Gram Viewer/trending.py | 1,979 | 4.0625 | 4 | """
Finds the top 10 and bottom trending words based on a given start and end year
author: Aidan Rubenstein
"""
from wordData import *
import operator
class WordTrend(struct):
_slots = ((str, 'word'), (float, 'trend'))
def trending(words, startYr, endYr):
"""
Iterates through the words dic... |
4b5d6378165bf91c01788357a803c0d3caa7f077 | tjkabambe/pythonBeginnerTutorial | /Turtle.py | 851 | 4.28125 | 4 | # Let's draw some drawings with the package turtle
# Import turtle
import turtle
# Lets get a setup in turtle
# 'bgcolor' is 'background color'
turtle.bgcolor("black")
turtle.pensize(2)
turtle.color("red")
turtle.speed(15)
# # Draw a square
# turtle.forward(50)
# turtle.left(90)
# turtle.forward(50)
# turtle.left(90... |
4f81440511b981bb636bf62c7d24afc3aed9172b | tjkabambe/pythonBeginnerTutorial | /Quiz.py | 2,027 | 4.5 | 4 | # Quiz time
# Question 1: Assigning variables
# create 2 variables x and y where any number you want
# find sum of x and y, x divided by y, x minus y, x multiplied by y
x = 4
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
# Question 2: Lists
# Create a list of all even numbers from 0 to 100
# Print first 1... |
31204c24e28fd4e3d85f5c957a5b2b162d0da5ca | Frank-Lochtenberg/Blok-2-Praktijktoets---Frank-Lochtenberg | /Blok 2 Praktijktoets - Frank Lochtenberg.py | 26,663 | 3.65625 | 4 | # Made by Frank Lochtenberg
# Version 8
import re
import matplotlib.pyplot as plt
import tkinter
from tkinter import messagebox
def read_fasta():
""" Reads the fasta file and puts the lines from the file in a list.
:return: list of lines from the fasta file.
"""
try:
f... |
40c7cb44652b3157ed46d148ccec296159a78c00 | katsumeshi/leetcode | /00100. Same Tree/solution.py | 1,171 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
... |
36a8e72624d7380063203906b24f9d4ab4904381 | katsumeshi/leetcode | /01022. Sum of Root To Leaf Binary Numbers/solution.py | 613 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumRootToLeaf(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return se... |
e06708059cca9b975f6a2e1e13adc9d25e51a764 | katsumeshi/leetcode | /00700. Search in a Binary Search Tree/solution.py | 656 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
... |
93958ba3dcec1ffe3209db9896ac297ff6c476c3 | hazalgvnky/metuceng-1 | /pthagorean triplets.py | 318 | 3.828125 | 4 | def triplets(n):
m = []
for a in range(1, n):
for b in range(1, n):
w = a**2 + b**2
s = w ** 0.5
c = int(s)
z = tuple(sorted([a, b, c]))
if c < n and s == c and z not in m:
m.append(tuple(z))
return m
print(triplets(100)) |
15ddbc7c2cfa3091b1264e388bd5822aa1134650 | voidJuneau/learning_DataStructuresAndAlgorithmsInPython_Udacity | /Lesson3QuickSort.py | 948 | 4.0625 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(a):
pibotIndex = len(a)-1
compareIndex = 0
if len(a) <= 1:
return a
while compareIndex < pibotIndex-1:
# print(a, ' c ', compareIndex, a[compareIndex], ' p ', pibotIndex, a[pibotIndex])
... |
775543eda42a4fbe31cb82e6460f8403d715c92b | frclasso/Python_tutorial_by_Corey_Schafer | /01_Beginners/47_json.py | 725 | 3.703125 | 4 | #!/usr/bin/env python 3
import json
people_string = '''
{
"people":[
{
"name": "John Smith",
"phone": "555-615-88888",
"emails": ["johnsmith@email.com","john.smith@company.com"],
"has_license": false
},
{
"name": "Jane Doe",
... |
40c1e9fee656afa8edde97d4cf8e85e8354debe9 | Gessika/python-lessons | /King action.py | 886 | 4.0625 | 4 | # King action
x1 = int(input('Input 1-8 figure: '))
y1 = int(input('Input 1-8 figure: '))
kletka1 = x1, y1
print 'Place of the first cell is: ', kletka1
x2 = int(input('Input 1-8 figure: '))
y2 = int(input('Input 1-8 figure: '))
kletka2 = x2, y2
print 'Place of the second cell is: ', kletka2
if x2 == x1: #Search for... |
03463f5345de0bcd3f22f6e2285715e264c80474 | park-junha/Leetcode | /00xx/000x/0002-AddTwoNumbers/Solution.py | 933 | 3.90625 | 4 | # Solution: Elementary Math
# Time Complexity: O(n+1)
# Space Complexity: O(n+1)
#
# Note: n is the length of the larger list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(s... |
a391328172c67662ef0c6586ccdd8ce22503e250 | park-junha/Leetcode | /00xx/000x/0007-ReverseInteger/Solution.py | 504 | 3.6875 | 4 | # Solution: Pop and push digits
# Time Complexity: O(n) (or O(log_10(x))
# Space Complexity: O(1)
#
# Note: n is the number of digits in x
class Solution:
def reverse(self, x: int) -> int:
MIN = -2 ** 31
MAX = 2 ** 31 - 1
r = 0
isNeg = x < 0
while abs(x) > 0:
r = r * 10 + abs... |
5f98434bf76b5e44d1cce1de5ae6484592edf0e8 | tcq1/taxonomy_generation | /src/text_extraction/csv_manager.py | 1,550 | 3.8125 | 4 | def export_docs(documents, output_path):
""" Exports a list of dictionaries to a single csv file
:param documents: list of dictionaries
:param output_path: file path to csv file
"""
for doc in documents:
export_dict(doc, output_path)
def export_dict(dictionary, output_path):
""" Expo... |
5472c2b42dcde138dd491ff8d910a8ae51cebc71 | LeQuynhAnh/Linux | /SV.py | 547 | 3.6875 | 4 | class SinhVien:
Hoten = ""
Namsinh = ""
Khoa = ""
def __init__(self,Hoten,Namsinh,Khoa):
self.Hoten=Hoten
self.Namsinh=Namsinh
self.Khoa=Khoa
def setHoten(self,Hoten):
self.Hoten=Hoten
def setNamsinh(self,Namsinh):
self.Namsinh=Namsinh
def setKhoa(self,Khoa):
self.Khoa... |
ff6fb6ce4d7c07ffc3b0c48ecbef9a0d9644112c | tiware23/treehouseNe | /wordcount.py | 632 | 4.09375 | 4 | # Make a function called word_count
# It should be accept a single argument which will be a string
# the function needs to return a dictionary
# the keys in the dic will be each of the words in the string, lower.
# the values will be how many times that particular word appears in the string
def word_count(single_arg):... |
a400ea69f49c0ac9d931b9de0de01c23361a49e6 | acallah1/acallah1.github.io | /cherrypy/_movie_database.py | 3,474 | 3.5 | 4 |
#Andrew Callahan
#python primer
class _movie_database:
def __init__(self):
self.movies = dict()
self.users = dict()
self.ratings = dict()
def load_movies(self, movie_file):
self.movies=dict()
#open fileobject
with open(movie_file ,'r') as file:
#read each line
... |
dbbc715f7e8ba6df6a912646dd796b4f8850627d | ISPC2020/tscdprog2020_g1-tscdprog2020_g1 | /Programacion-I/16vaSemana/Eje5.py | 2,482 | 3.75 | 4 | class Agenda:
l = []
def __init__(self, nombre, telefono, email):
self.nombre = nombre
self.telefono = telefono
self.email = email
def añadir_contacto(self):
Agenda.l.append(self.nombre)
Agenda.l.append(self.telefono)
Agenda.l.append(self.email)
... |
3bc2ad9dbd3b8ca611cc7408d99fb1da8aea22af | ISPC2020/tscdprog2020_g1-tscdprog2020_g1 | /Programacion-I/16vaSemana/Eje6.py | 547 | 3.546875 | 4 | class Cliente:
#Definomos los atributos
nombre = ""
__cantidad = 0
#Inicializamos el metodo
def __init__(self):
pass
#Metodo depositar
def depositar(self, dep):
self.dep = dep
Cliente.__cantidad += self.dep
#Metodo extraer
def extraer(self,ext)... |
3d595b15d88d0e05bad1b86a5d21c9875aceced0 | gehoon/fun | /birthday.py | 1,138 | 4.25 | 4 | #!~/bin/python
## Simulation of the birthday paradox (https://en.wikipedia.org/wiki/Birthday_problem)
import random
## Each Birthdays class comprises n number of birthdays
class Birthdays:
def __init__(self, n=23): # initialization
self.birthday = []
for x in range(n):
self.birthday.app... |
9bfcdf34c08cfc0791f704fd9b232c81c8de2c72 | RyanKHawkins/Football_PyAndyYT | /player.py | 1,149 | 3.765625 | 4 | # Name: player.py
import random
class Player:
"""
player is on a single team, with many other players
players play in a game for a team
"""
def __init__(self, name, skill):
self.name = name
# player skill ranking
self.skill = skill
def salary(self):
return ... |
22e4526e4d941b8447e7d1a958ef9a72e13e48cf | lemonadern/auto_response_script | /package/weekday.py | 121 | 3.640625 | 4 | import datetime
def is_weekend(d :datetime.date):
weekday: int = d.weekday()
return weekday == 5 or weekday == 6
|
4af967a240043b6de4b3747860497b3355af5676 | CarlosHenrique/CRUD | /PRINCIPAL.py | 704 | 3.65625 | 4 | import profs
import turmas
import disciplinas
import alunos
def main():
while True:
print('{} BEM VINDO AO MENU PRINCIPAL {}\n1-Menu de Professores\n2-Menu de Alunos\n3-Menu de Disciplinas\n4-Menu de Turmas\n0-PARAR PROGRAMA'.format(10*'-',10*'-'))
opcao = int(input('Qual menu deseja acessar: '))
... |
c3b68ea50f81f81152dd3e224401dd293072e613 | crir08/MessageSecret | /MessageSecret.py | 1,184 | 3.953125 | 4 | #2019-02-28
#Christophe Roux
alphabet = 'abcdefghijklmnopqrstuvwxyz'
newMessage = ''
fonction = input('Encrypter ou décrypter un message?[E/d]: ')
if fonction.lower() == 'e':
key = input('Veuillez entrer une clé de cryptage: ')
key = int(key)
message = input('Veuillez entrer un message: ')
for cha... |
069e3bd8d1d5af7d8e1a0cd65c6f2be180be6495 | KatherineSandys/Python | /Image Changer/blackNwhite.py | 599 | 3.765625 | 4 | from PIL import Image
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
print("\nblack and white conversion of images")
#get the file name from the user
#file_name = input("Enter the file name and or path to the image: ")
file_name = "Image Changer/flowers.PNG"
#open the file
img = Image.open(fi... |
2ab3d9b85ae521dfaa445037cd720fb0b42f1d33 | nickfurk/book-manager | /test_book.py | 1,161 | 3.546875 | 4 | from unittest import TestCase
from book import Book
class TestBook(TestCase):
def setUp(self):
self.book_one = Book("123", "April C", "Hacking with April", "Chris", 9, "science", "computer")
self.book_two = Book("456", "Lipra", "Coding with April", "Johnson", 10, "math", "matrix")
def test__... |
b09821dd11d164a611cdaaecdc8b4ced5b8275b7 | LiuL0703/algorithm | /LeetCode/Python/#167 Two Sum II.py | 1,409 | 3.671875 | 4 | # two-pointer
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
l,r = 0,len(numbers)-1
while l<r:
s = numbers[l]+numbers[r]
if s==target :
... |
8363ed63db5857e806f84dc892a2609bb2d11ce0 | LiuL0703/algorithm | /LeetCode/Python/#530 Minimum Absolute Diff in BFS.py | 1,161 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
""... |
9e83f09279a84bdbbd93cea756f129b1a599d9c7 | LiuL0703/algorithm | /LeetCode/Python/#20 Valid Parenttheses.py | 781 | 3.65625 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
alls = {")":"(","}":"{","]":"["}
res = []
for i in s:
if i in alls.values():
res.append(i)
else:
if not res or... |
45cf86a7ee58e79e04ed657402a3b419409c9195 | LiuL0703/algorithm | /LeetCode/Python/#70 Climbing Stairs.py | 245 | 3.59375 | 4 | class Solution(object):
def climbStairs(self,n):
"""
:type n: int
:rtype: int
"""
res = list(range(n+1))
for i in range(3,n+1):
res[i] = res[i-1] + res[i-2]
print(res[n])
return res[n]
|
9fffb220f2a0d959895fe47f4e99baaab9521498 | Drosenwinkel/rubiks_cube | /solver.py | 2,919 | 3.734375 | 4 | import rubik
def shortest_path(start, end):
"""
Using 2-way BFS, finds the shortest path from start_position to
end_position. Returns a list of moves.
Assumes the rubik.quarter_twists move set.
"""
if start ==end:
return []
else:
numTwists =0;
found = False
... |
50453b4e12fffc1c42f096449ee79a7fe048de55 | Manib92/Codewars | /4 Kyu/Human readable duration format.py | 3,246 | 4.65625 | 5 | """Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.
The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minut... |
984530a63d3b13900e34e8e31be4b2b1b931940e | NollHyury/pythonStudies | /dataScience/firstGraph.py | 186 | 3.75 | 4 | import matplotlib.pyplot as plt
x =[1 ,2, 5]
y =[2, 3, 7]
#TÍTULO
plt.title("My first graph with Python")
#EIXOS
plt.xlabel("EIXO X")
plt.ylabel("EIXO Y")
plt.plot(x, y)
plt.show() |
74a4c8832d979354df62e5e89d02dbb79a33d57f | NollHyury/pythonStudies | /basico/exemplos/listsOne.py | 576 | 3.984375 | 4 | myList = ['abacaxi','melancia','tomate']
myList2 = [1,2,3,4,5]
myList3 = [1,4.3,'Laranja',False]
print(myList)
print(myList2)
print(myList3[3])
#varrer uma lista
for item in myList:
print(item)
#descobrir o tamanho de uma lista
print(len(myList2))
# adiciona um item a lista
myList.append("limao")
#remove um it... |
903aa0e96b97ceccddca8fd95c85305740457609 | NollHyury/pythonStudies | /basico/exemplos/stringAdvanced.py | 524 | 4.1875 | 4 | seq = "Hyury Luis Da Silva Noll " + "\n"
print(seq)
# deixa a string em letra minuscula
print(seq.lower())
# remove os caractéris especiais
print(seq.strip())
# deixa a string em letra maiuscula
seq = seq.upper()
print(seq)
# converte uma string em uma lista
x = seq.split("Y")
print(x)
# busca o indice onde esta... |
bd305ac0463130fa89aecdb87f136a1f701fc610 | AracelizGomes/LeetCode | /AddTwoNumbers.py | 2,069 | 3.828125 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
... |
68d7ebc5ed7089c0f55bbf9e0c6dd869a24c87ab | Nurlis98/Exersices-from-Eric-Metiz-book | /For7.py | 256 | 4.03125 | 4 | favorite_fruits = ['Apple','Watermelon','Melon']
if 'Apple' in favorite_fruits:
print("You really love Apple.")
if 'Melon' in favorite_fruits:
print("You really Melon.")
if 'Watermelon' in favorite_fruits:
print("You really love Watermelon.")
|
187fa6361d76c8782a0c6876b82ea37d80619f42 | Nurlis98/Exersices-from-Eric-Metiz-book | /while9.py | 357 | 3.640625 | 4 | sandwich_orders = ['Tuna','Cheese','Pastromi','Panini','Pastromi','with Ham','Pastromi']
finished_sandwiches = []
for finished_sandwiches in sandwich_orders:
print('I made your '+finished_sandwiches+' sandwich!')
while 'Pastromi' in sandwich_orders:
sandwich_orders.remove('Pastromi')
print()
print(sandwich_... |
1137380f042b683a20576b104749754fbff9c9dc | Nurlis98/Exersices-from-Eric-Metiz-book | /Словари8.py | 310 | 3.640625 | 4 | pets_1 = {
'pet name': 'Tobi',
'Age': '11',
'proprietor': 'Kate',
}
pets_2 = {
'pet name': 'Alex',
'Age': '4',
'proprietor': 'Amanda ',
}
pets_3 = {
'pet name': 'Alaska',
'Age': '3',
'proprietor': 'Andrew',
}
pets = [pets_1, pets_2,pets_3]
for pet in pets:
print(pet) |
eb42b57e886d7d76c8a50bf1e391809badebfa6e | adil017/GUI | /entry.py | 849 | 4 | 4 | from tkinter import*
class xyz:
def __init__(self,root):
self.f=Frame(root,height=500,width=350)
self.f.propagate(0)
self.f.pack()
self.l1=Label(text="Enter your name:")
self.l2=Label(text="Enter password:")
self.e1=Entry(self.f,width=20,font=('Arial',16))
... |
f7733a39e0e11f1236c55f3411e7dda4f41bb92c | xz1082/assignment5 | /mer567/assignment5.py | 5,060 | 3.515625 | 4 | #include packages:
import itertools
import numpy as np
####################### Classes ##########################
class Myexception(Exception):
def __str__(self):
return "Boundry notation Error"
class Interval:
def __init__(self, string1):
string2 = string1.replace(" ", "")
parts = string2.split(",")
... |
98f122c4e4d12954e54b9344757e94116c47a5b6 | xz1082/assignment5 | /hz990/Assignment5.py | 2,616 | 3.59375 | 4 | class interval:
def __init__(self, string):
self.string = string
self.lb_type = string[0]
self.ub_tpye = string[-1]
self.lb, self.ub = map(int, string.strip('()[]').split(','))
self.lb_new = []
self.ub_new = []
if self.lb_type == '(':
self... |
bc5559a1bc290be5e955e226699ab8856998f97e | xz1082/assignment5 | /wl1207/assignment5.py | 2,934 | 3.828125 | 4 | #Q1
class interval():
def __init__(self, string):
self.string = string
self.lbd = string[0]
self.ubd = string[-1]
self.index = string.find(',')
self.value1 = int(string[1:self.index])
self.value2 = int(string[self.index+1:-1])
if self.lbd == '[' and self.ubd =... |
ab8b7dda6b2784be505359b0f26f273bb2838b94 | xz1082/assignment5 | /ssz225/my_package/assignment5.py | 2,343 | 3.59375 | 4 | class interval:
def __init__(self,string='No input'):
self.string = string
self.firstchar=self.string[0] #either ( or [
self.lastchar=self.string[-1] #either ) or ]
comma=self.string.index(',')
self.lowerbound=int(self.string[1:comma]) #lower number
self.upperbound... |
743969f05efc7bc088ebeb20f5dcd21e2bf8e593 | arhodes4/NeuralNet | /NeuralNet.py | 553 | 3.640625 | 4 | import numpy as np
X = np.random.uniform(-1, 1, (4, 4))
class LayerDense:
def __init__(self, n_inputs, n_neurons):
self.weights = 0.1 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
def forward(self, inputs):
self.output = np.dot(inputs, self.weights) + s... |
f92375d4558dac9d4f6f1333b1dbae70aab68983 | abhishek4554/python37 | /class_03.py | 2,273 | 3.875 | 4 | """
1. Data structura : Dictionary, tuple, set
# Assignment:
1. Create dictionary of user data
2. Create list of user data dictionary with minimum of 10 user data
3. Create 5 dictionaries which have list values
"""
# dictionary_variable = {'Name': 'Abhishek',
# 'add': 'home',
# ... |
f90b5898335d0f840e8166d241e1e420263d89e0 | ErykK17/wizdanych | /lab5zadanie8.py | 665 | 3.640625 | 4 | class samogloski:
def __init__(self, dane):
self.dane=dane
self.index= -1
def __iter__(self):
return self
def __next__(self):
if self.index==len(self.dane):
raise StopIteration
self.index= self.index +1
samogloski=("a","e","i","o","u","... |
a6dc4b06d3b61ce039782008fdfbee7e8d2c7d29 | general10/Face | /calculation.py | 1,541 | 3.515625 | 4 | # -*- coding:utf-8 -*-
import numpy as np
class calculation:
"""計算クラス"""
def LSM_2d(self, x_list, y_list):
"""最小二乗法による2次関数フィッティング
@ param1[in] x_list X座標リスト
@ param2[in] y_list Y座標リスト
@ param[out] a, b, b 各係数
"""
a, b, c = np.polyfit(x_list, y_list, 2... |
360cd4c249e7685721cfeb212cdd75933f24508b | jrschmiedl/Sudoku | /SudokuSolver.py | 2,227 | 3.828125 | 4 | # Sudoku Solver 1.0
# @author Jacob Schmiedl
puzzle = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
# solves the puzzle... |
4978ac8ee5c526eb06d5df690de298c9ecba382b | KobiShashs/Python | /2_Strings/9_example.py | 251 | 4.125 | 4 | word = "spaceship"
# e,p,p
print('e' not in word)
#False
print(word.isspace())
#False
print(word.count('p'))
##2
print(word.find('sh'))
#5
print(word.endswith('e'))
#False
print(len(word))
#9
print(word[-2::-4])
#ic
print(word.startswith('spa'))
#True |
c81a9860b739d96fa79fec19be9d5ea87539a622 | KobiShashs/Python | /6_Lists/12_longest.py | 166 | 3.9375 | 4 | def longest(my_list):
longest_string=max(my_list,key=len)
print(longest_string)
list1 = ["111", "234", "2000", "goru", "birthday", "09"]
longest(list1)
|
cdf6f469a11b18a9e75955e67d3c592c492328dd | KobiShashs/Python | /2_Strings/0_concating_strings.py | 150 | 3.734375 | 4 | str1 = "is there "
str2 = "anybody out "
str3 = "there"
print(str1 + str2 + str3)
duplicate_me = ":-) "
print(duplicate_me * 8)
x = 3
print(type(x)) |
50bac6e14d8c1f9a83e031de3ba3e56e5c5d209a | KobiShashs/Python | /17_OOP/14_my_first_class.py | 800 | 3.703125 | 4 | class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposite(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def print_blance(self):
print("Current Balance is", self.balance)
def main():
newbie... |
351718cce900a99cf6b995716466963da7a3ee98 | KobiShashs/Python | /21_Exception_Handling/11_example.py | 205 | 3.703125 | 4 | def divider(a, b):
try:
result = a / b
print(result)
except ArithmeticError:
print("print me!")
except ZeroDivisionError:
print("don't print me!")
divider(5, 0)
|
62a005967b42a179be06eee1dadf5d50c5ce4be6 | KobiShashs/Python | /25_Advannced_Generators/5_pipelining_generators.py | 781 | 3.859375 | 4 | with open("capitals.txt") as file:
single_line_gen = (line for line in file)
with open("capitals.txt") as file:
single_line_gen = (line for line in file)
print(next(single_line_gen))
print(next(single_line_gen))
print(next(single_line_gen))
print(next(single_line_gen))
with open("capitals.txt... |
0ed0626a19721ebac54fb9e4d24b6c642ef9cbc1 | KobiShashs/Python | /22_Custom_Exceptions/7_regex.py | 439 | 3.546875 | 4 | import re
string_check = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
def contains_one_special_char(password):
if(string_check.search(password) == None):
print("String does not contain Special Characters.")
else:
print("String contains Special Characters.")
# contains_one_special_char("aaaaaa")
# ... |
29a6c2912c49f129f30dc5c1c27729ab2dfc144a | KobiShashs/Python | /2_Strings/8_methods.py | 443 | 3.890625 | 4 | print("print me in UPPERCASE".upper())
print("234".zfill(5))
print("1".zfill(5))
word = "Moshe"
print('e' in word)
print('e' not in word)
word = " "
print(word.count('p'))
print(word.find('irt'))
print(word.startswith('Ha'))
print(word.startswith('Ka'))
print(word.endswith('y'))
print(word.endswith('r'))
print(word[-... |
cbaf7d6f076d60706105a979da134ffdd45a04f9 | KobiShashs/Python | /27_Generator_Summary/4_years.py | 170 | 3.515625 | 4 | def gen_years(start=2019):
#<yield>
while True:
yield start
start+=1
years = gen_years()
print(next(years))
print(next(years))
print(next(years)) |
e68ce9f6d1ed66c5208d43ac0bdcd9b1fb0f1da8 | KobiShashs/Python | /14_Lambda/0_lambda.py | 221 | 3.640625 | 4 | import functools
print((lambda x,y: x+y)(2,5))
shopping_list = [200, 120, 330, 50]
print(functools.reduce((lambda x,y: x+y), shopping_list))
new_add = (lambda x,y: x+y)
print(functools.reduce(new_add, shopping_list))
|
67f7ace86376ed9907e2ae8cb7cc949af0ff867d | KobiShashs/Python | /5_Functions/1_param_vs_arg.py | 167 | 3.546875 | 4 | # Define the function square with the parameter number
def square(number):
print(number ** 2)
# Call the function square with the argument 3
square(3)
square("3") |
ebc7b1398553c026319103d012424d66e56529c3 | KobiShashs/Python | /23_Exceptions_Summary/2_playground.py | 708 | 3.671875 | 4 | def is_valid_username(username):
import re
string_check = "[.@!#$%^&*()<>?/\|}{~:]'"
for x in username:
if (x in string_check):
return False;
return ((any(char.isdigit() for char in username)) and
(any(c.isalpha() for c in username)) and ("_" in username))
def ... |
b670151d6f7668b69f08c595e1df359a363761b3 | KobiShashs/Python | /31_Iterators_Summary/1_id_validator.py | 1,970 | 3.609375 | 4 | class IDIterator:
"""This Iterator creater valid Ids"""
def __init__(self,id=0):
self._id= id % 10000000000
def add_employee(self, new_empl):
self._employee_list.append(new_empl)
def __iter__(self):
return self
def __next__(self):
self._id+=1
if(check_id_va... |
2066ed0d723e312a2b350da9def91ca9fbe618c0 | KobiShashs/Python | /29_Working_With_Iterators.py/8_example.py | 102 | 3.640625 | 4 | numbers = iter(list(range(1, 101)))
for i in numbers:
next(numbers)
next(numbers)
print(i) |
2cfac2f9c3759974fbb3268bb7f8273153075fa8 | shaon0000/csv-converter | /csv_converter.py | 7,583 | 3.65625 | 4 | # author: Shaon Bhuiyan
# description: a CSV data extractor that lets us generate another CSV file
# TODO: create testsamples of CSV lines
# TODO: build a testing system to test this code
# TODO: check with viv to see what he thinks of this idea
import csv
import os
import sys
import fnmatch
DEBUG = True # does more ... |
cfc8ab7e143726ea1b6579ef03ac0d51e4955aa3 | MarcosVRM/Exercices | /Guanabara/ex011.py | 410 | 3.984375 | 4 | print('Para calcular quatno de tinta ira aprecisar para pintar sua parede vamo precisar saber')
a = float(input('Quanto ela mede de altura, em metros?\nAltura:'))
b = float(input('Quanto ela mede de largura, em metros?\nLargura:'))
a1 = float(a * b)
a2 = float(a1 / 2)
print('As dimensões informadas são; {}m x {}m área ... |
4d74c56ffcbe147f5a01da32f9e1025336cd4f86 | MarcosVRM/Exercices | /Alura/object_orientation/conta.py | 1,452 | 3.84375 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite=0):
print("construindo objeto... {}".format(self))
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def extrato(self):
print(f"Saldo de R${self.__saldo:.2f}... |
b34079b91a8ce5b7aba24a69d6eef913419d523f | MarcosVRM/Exercices | /Guanabara/ex007.py | 254 | 3.875 | 4 | print('Vamos verificar a media de valores, no caso duas notas escolares')
a = int(input('Digite o valor da primeira nota:'))
b = int(input('Digite o valor da segunda nota:'))
abm = (a + b)/2
print('A media das notas {}, {} é de {}.'.format(a, b , abm))
|
ae0a61ca0b07f7d6a73d038c691586f89038752a | kmalves/productivity | /code.py | 1,018 | 3.703125 | 4 | from decimal import Decimal
print 'Enter the date of your inquiry in the following format mm/dd/year. When finished hit "ENTER".'
date = raw_input()
print 'Enter the total amount of hours worked for the day from your time card. When finished hit "ENTER".'
user_imput_day = raw_input()
print 'Enter tasks in minutes separ... |
26f2c25f17cd3e3ba09dcb7c8a855677b6f43e40 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/DynamicPrograming/FibonacciNumber.py | 254 | 3.96875 | 4 | def fibonacci(n: int):
fibs = []
for i in range(n):
if i < 2:
fibs.append(i)
else:
fibs.append(fibs[i - 1] + fibs[i - 2])
return fibs
if __name__ == "__main__":
ans = fibonacci(15)
print(ans)
|
8c71fd2c78e6da10b7385c7465884a7db65682fc | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/PathFindingAlgorithms/find_path_dist_in_matrix.py | 2,751 | 3.734375 | 4 | # Given a 2D matrix(binary maze) and a source and destination cell
# we will find length of the shorted path if it exists
# This can be solved using Breath-first search
# https://en.wikipedia.org/wiki/Breadth-first_search
'''
INPUT
matrix = [
[1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ],
[0, 0, 1, 0, 1, 1, 1, 0, 1... |
bd227281abb94c8791e31ce464d1640e4c8502b0 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Maths/RomanToInt.py | 596 | 4.1875 | 4 | # !/usr/bin/env python3.6
'''
Converts Roman Numeral into Decimal Number'''
mapping = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1),)
def romanToInt(s):
an... |
ee734229656ae70cc53893eb55e0193ff4064a5b | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/DynamicPrograming/LongestCommonSubsequence.py | 1,046 | 3.859375 | 4 | # This is Python Dynamic programming implementation of the
# Longest Common Subsequence Problem, built in bottom up fashion.
# Give 2 strings A and B, this program finds the length
# if the longest common subsequence
# Dynamic Programming implementation of LCS problem
def longestCommonSubsequence(A, B):
# storing... |
65fd056b3c9cdc37c72a927d314a1c83a21f3ebc | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Sieve Algorithms/sieveOfEratosthenes.py | 867 | 4.34375 | 4 | # Sieve of Eratosthenes
# It is an efficient algorithm used to find all the prime numbers smaller than
# or equal to a number(n)
# We will create a list and add all the elements and then remove those elements
# which are not prime
def sieveOfEratosthenes(n):
# Creating an empty list
primeList = []
for i... |
2b0868bd3657327411f653462ba8bcca9879fed7 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/Sieve Algorithms/Sieve of Eratosthenes.py | 489 | 3.75 | 4 | """
Sieve of Eratosthenes :
Generate all the primes less than any integer nn
"""
from math import sqrt
def get_primes(n):
m = n + 1
# numbers = [True for i in range(m)]
numbers = [True] * m
for i in range(2, int(sqrt(n) + 1)):
if numbers[i]:
for j in range(i * i, m, i):
... |
298170762539ec4d221841e269007516ceb6e333 | Py-Contributors/AlgorithmsAndDataStructure | /Python/DataStructure/Heap/Heap.py | 4,689 | 3.671875 | 4 | """
Heap
The heap is an important data structure. It provides the following
functionality:
findMin: Find the minimum of all the current data. O(1) runtime.
pop: Remove the minimum element from the current data and return it. O(log n)
runtime.
push: Add an element to the current data. O(log n) runtime.
The provided... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.