blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c0436d190e4c117bd8addce7166ff5c56aa30d13
mohammedessamtga/Coffee-Machine-Project-
/coffee_machine.py
4,682
3.9375
4
# Write your code here class Machine : def __init__(self, water=400, milk=540, coffee_beans=120, disposable_cups=9, money = 550): self.water = water self.milk = milk self.coffee_beans = coffee_beans self.disposable_cups = disposable_cups self.money = money ...
1fd6325482c6dd606a673b165539b88bd9532425
DylanDing6464/lab3-python
/main.py
469
3.65625
4
# Author: Dylan Ding dvd5567@psu.edu # Collaborator: Eric Wang evw5332@psu.edu # Collaborator: Matthew Nagle men5266@psu.edu # Collaborator: Ryan Morgan rkm5607@psu.edu # Section: 7 # Breakout: 1 def sum_n(n): if n == 0: return 0 return n + sum_n(n - 1) def print_n(s, n): if n == 0: return print(s) pr...
5904f29eaed70f0dd1175aea77d62d5bbc233643
elkiplangat/classwork
/question4.py
1,404
3.6875
4
with open("Maze3.txt", "r") as f: lines = f.readlines() # print(lines) array = [line.split() for line in lines] # print(array[1][1]) # solve_maze(array,(0,0), ()) example = [line.split() for line in ['0 0 0 0 0 1 0 0', '1 0 1 1 0 0 0 0', '1 0 0 1 0 1 0 1', '0 1 0 0 0 1 0 0', '0 0 0 0 1 1 ...
4abcceb989da9c7810826b51887fbd8c3a3ba518
LuizFernandoR/CursoPython
/Python-aula 01/variaveis.py
347
3.515625
4
#Variáveis do tipo inteiro num1 = 10 num2 = 15 num3 = -125 #variáveis texto - string - str '' text1 ='Meu nome é python' text2 ='Meu nome não é python' #variaveis tipo boloeanas - boolean - bool verdadeiro = True falso = False #variáveis tipo ponto flutuante (numeros decimais) - float salario = 1000.58 divida = 150...
69c9eddd4b6a1c4607abd47912dd912af9f8e739
LuizFernandoR/CursoPython
/Python-aula03/Doc_String.py
736
4.0625
4
# menu = ''' # Opções # 1- Para oi # 2- Para tchau # 3- Para sair # Digite sua opção: # ''' # print(menu) # while True: # numero1= int(input('Digite o primeiro número: ')) # numero2= int(input('Digite o segundo número: ')) # menu=''' # Menu # 1- Somar # 2- Subtrair # 3- Dividir # 4...
2b52cd837f92e39aba1fc06492d982f1e72391b6
LuizFernandoR/CursoPython
/Exercicio_lista/Lista_funções_metodos.py
540
3.578125
4
# n = [1,2,3,4,5] # l = ['a','b','c','d','e'] # print({1 in n}) # print({'h' in l}) # print({'a' in 'amem'}) # h = [1,2,3] # i = [4,5,6] # print(id(h)) # print(id(i)) # lista = [1,2,3] # l = lista # print(f'id(lista): {id(l)}') # print(f'lista == l: {l==lista}' ) # print(f'lista is l: {l is lista}') # print(f'Minha l...
f0591a68a57905ea8f8bf83c3d37d9c21c44e39f
LuizFernandoR/CursoPython
/Python-aula03/Funcao.py
983
3.984375
4
# def somar(num1,num2): # soma_rest= num1 + num2 # return soma_rest # def subtrair(num1,num2): # soma_rest= num1 - num2 # return soma_rest # def multiplicar(num1,num2): # soma_rest= num1 * num2 # return soma_rest # def dividir(num1,num2): # soma_rest= num1 / num2 # return soma_rest # wh...
4f17e884ff3f1a39cf03eda2714b7077b0829644
DefCon002/Ubuntu
/Feet_Conv.py
319
3.890625
4
# Scratch def to_feet(cm): return cm*0.0328084 print("Welcome to this Feet coverter!") cont = "Y" while(cont.upper()=="Y"): cm = int(input("Enter cm : ")) print("That's {} Feet".format(to_feet(cm))) print() cont = input("Do you want to do another conversion [Y to continue]") print("Good bye!")
530e1def6ade8327aec6ecab7dca3ada8f98aa52
j-programming/py-2017-11-18
/repl.4.8.py
946
3.703125
4
#!/usr/bin/env python import sys def exit(arg): print ("Goodbye") sys.exit() def myEval(rest): try: value = eval(rest) except Exception as e: print(type(e).__name__) else: print(value) def empty(arg): print ("Enter Command") def splitLine(line): tokens = line.spli...
44f387e14cbbc329c9fc01f4c42b0a59394358b4
j-programming/py-2017-11-18
/dict.py
332
3.75
4
#!/usr/bin/env python import sys if __name__ == "__main__": text = 'Ala ma kota ala ala ala' dic={} for txt in text.lower().split(): if (txt not in dic): dic[txt]=1 else: dic[txt]+=1 for k, v in dic.iteritems(): print(k+" -> "+str(v)) #a = '123' if b ...
ad85f1655132b2206c7325a39cd6f57a58ce9fe6
j-programming/py-2017-11-18
/exc5.1.py
293
3.546875
4
#!/usr/bin/env python import sys if __name__ == "__main__": suma=0 for nmb in range(1001): if nmb%3==0 or nmb%5==0: suma+=nmb print(suma) if __name__ == "__main__": #print(sys.argv) print(sum([nmb2 for nmb2 in range(1001) if nmb2%3==0 or nmb2%5==0]))
6e8f8c1f5b776c8a676fd44cd52ae9a32454789b
nigma1985/freyr_pi_readings
/module/getOptions.py
1,153
3.53125
4
import sys, re def checkArgv(_input, _str): if _input is None: _input = sys.argv if type(_input) == str: if re.search(_str, _input): return True else: return False else: return False return False def findItm(item = "", options = sys.argv, mode = ...
5216291122e163fc216609789519104a503503ce
katemartin9/algorithms
/min_refills/min_refills_gas_station.py
706
3.84375
4
from typing import List def min_refills(x: List, n, L): """ :param x: petrol stations positions :param n: number of petrol stations :param L: full tank distance without refill :return: """ num_refills = 0 current_refill = 0 while current_refill <= n: last_refill = current_r...
b995b718bbbbaaad3d4b403f81e324346bc81011
katemartin9/algorithms
/the_sum_of_two_digits/a_plus_b.py
201
3.96875
4
def sum_of_two_digits(digit_one, digit_two): return digit_one + digit_two if __name__ == '__main__': a, b = map(int, input('Provide two numbers: ').split()) print(sum_of_two_digits(a, b))
400ec98269f3098913b7f26642c147ce5e1c0c69
rajaik1998/guvi_codekata1
/kart1.py
324
4.09375
4
a = int(input()) b = int(input()) c = int(input()) if (a > b and a > c): print("the largest number is: ",a) elif (b > a and b > c): print("the largest number is: ",b) elif (c > a and c > b): print("the largest number is: ",c) else: print("all the three values are equ...
a9299b8ee5e167ddfe36dd79f3926a5eca363be3
oceantie/Learn-Python
/data_demo/basic_dict.py
559
3.859375
4
#初始化 d={'a':1,2:'b','c':3,4:'d'} # print(d) #取长度 print(len(d)) #根据key读写 d['a']=100 print(d) #添加元素 d['e']=5 print(d) #删除元素 # del (d['a']) # print(d) #判断key是否存在 # if 'a' in d: # print('a in d') # if not ('x' in d): # print('x not in d') # else: # print('element in d') #判断字典是否为空 d={} if not d: print('d i...
ef5f2ebc6d6d006f51f7c3c8a088f8765d871911
oceantie/Learn-Python
/data_demo/basic_deduce.py
374
4.0625
4
#一维数组 print([i*2 for i in range(10)]) print([i*i for i in range(10)]) print([i*1 for i in range(10) if (i%3)==0]) print([(x,y) for x in range(3) for y in range(3)]) #二维数组 print('二维数组') a=[[3]*(i+1) for i in range(3)] print(a) #乘法问题 print('乘法问题') a=[[1,2,3]]*3 a[1][1]=100 print(a) a=[[1,2,3] for i in range(3)] a[1][1]...
12f472b9e023891b9cb69809d8607c19c90ba6ff
owenyoung75/QuFn_pylib
/lib_SP/SPdata_obtain.py
3,957
3.578125
4
""" function: read_SPdata return: a SPIndxData object from certain file arg: FilePath; path to the file, if file exist, directly read data, if no file, download from external website function: download_SPdata return: a string refering to the file-path of downloaded data default: ...
4c281e92cc7f5cd68ef7c58abed376c15fab2f0d
YonTess/Training-Regressions
/python-format-strings/exercise2.py
381
3.625
4
# message = str.capitalize('first message') # print(message) # message = 'second message'.capitalize() # print(message) # message = 'third message' # print(message.capitalize()) # message = 'hello world' # print(message.lower()) # print(message.upper()) # message = message.title() # print(message) # print(message.s...
86127bf3ea503dda745c06207cc03bc2d2c0aec3
andrecianflone/perm_attack
/resource/old_my_sorting_model.py
1,871
3.5625
4
"""Model class for sorting numbers.""" import torch.nn as nn class Sinkhorn_Net(nn.Module): def __init__(self, latent_dim, output_dim, dropout_prob): """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. in_flattened_vecto...
bb8ccb99ae593dab5d6403797fd4530b81336795
msanatan/codeeval
/easy/reverse_words/reverse_words.py
540
4.0625
4
#!/usr/bin/env python import sys def reverse_words(sentence): reverse_words = sentence.split(' ')[::-1] return ' '.join(reverse_words) def get_sentences(input_file): with open(input_file, 'r') as f: data = f.read() sentences = data.split('\n') return filter(lambda x: x != '', sent...
6e9a56f32c4d4bc3a67dece25b49083dac33a615
Aakashk123/PRO---100
/Atm.py
1,091
3.828125
4
class Atm: def __init__(self, cardnumber, pin): self.cardnumber = cardnumber self.pin = pin def balanceinquiry(self): print("Your Balance Is $100") def cashwithdrawal(self, amount): new_amount = 100-amount print("You Withdrawed: " + str(amount) +"Your Remaning...
7d02abe3f1e340a8743c53c39d073474e8dcfd2b
nbrown-dsl/tkinter
/tkinter-db.py
12,438
4
4
from tkinter import * import sqlite3 root = Tk() root.title('tkinter address database') root.geometry("400x600") # Databases # Create a database or connect to one conn = sqlite3.connect('address_book.db') # Create cursor c = conn.cursor() # Create table (uncomment and run once then comment in again) # c.e...
c601b87bb894f49acc9ed78c4d4e56b51b0935f6
georgian2all/practicepython.org-Python-3.5
/duplicateelements.py
799
4.25
4
""" Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and wri...
8f43c205bd6605c9d15e5f8f6895a8f97f01339f
osama1998H/standerdLearnd-string
/q24.py
207
3.90625
4
text = "meijasnpiasnvi" n = input("enter the litter: ") def new_func(text, n): if text[1] == n: print(f"started with {n}") else: print(f"not started with {n}") new_func(text, n)
1b0aca372d7f1b609d7a6aff71a4fc9611caf12d
osama1998H/standerdLearnd-string
/q93.py
131
3.890625
4
string = input('enter some text :').split() nums = [] for i in string: if i.isdigit(): nums.append(int(i)) print(nums)
25e003e8b286c14384f9736ef674b80ba66a5b5f
osama1998H/standerdLearnd-string
/q9.py
450
3.90625
4
string = input("enter the text: ") def remove_th_voice(string: str) -> str: string = [i for i in string] new_string, n = "", "t" for i in string: if (string.index(i)+1) <= len(string): if i == n and string[string.index(i)+1] == "h": string.remove(string[string.index(i...
9f7d69d76b5b1fd7d423c4dc15262c1a776344de
osama1998H/standerdLearnd-string
/q29.py
446
3.96875
4
import textwrap text = ''' Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. ''' print(text)...
db89f2d9abf5908836e0ca13a21d890000b28925
osama1998H/standerdLearnd-string
/q57.py
138
4.15625
4
string = input("enter the string : ") def remove_space(string:str): return string.replace(' ', '') print(remove_space(string))
1c11aab23898f9ab5c9929fef608a41d25d08320
osama1998H/standerdLearnd-string
/q6.py
296
4.1875
4
string = input("input the string: ") def new_func_ing(string: str) -> str: if len(string) < 3: return("enter a longer text") elif string[-3] + string[-2] + string[-1] == "ing": return(string + "ly") else: return(string + "ing") print(new_func_ing(string))
13c43e065b2809f1a2768fc59a131adcb86a601a
osama1998H/standerdLearnd-string
/q66.py
251
3.875
4
str1 = input("str1: ") str2 = input("str2: ") new_str = '' if len(str1) > len(str2): str1, str2 = str2, str1 elif len(str2) == len(str1): pass else: for i in str1: for n in str2: new_str += n print(str1) print(new_str)
7ce23743ab7e63bd36f3d0e4a75d2d50fc86c0cb
osama1998H/standerdLearnd-string
/q49.py
219
3.828125
4
vowels = "aeiuoAEIOU" string = input('enter the text: ') freq = {} for i in vowels: count = 0 for n in string: if i == n: count += 1 if count > 0: freq[i] = count print(freq)
43e3eae1152339dcff998e374455bfb9eb58c1f0
osama1998H/standerdLearnd-string
/q48.py
278
3.921875
4
string = input("enter the text: ") string = [i for i in string] comma = string.index(',') dot = string.index('.') string[comma] = '.' string[dot] = ',' text = '' for i in string: text += i print(text) maketras = text.maketrans print(text.translate(maketras(',.', '.,')))
5e6ea399fbd0edf20cc28507331433978f92b48e
osama1998H/standerdLearnd-string
/q41.py
167
3.96875
4
text = input("hit some keys: ") chars = ["a", "b", "s"] def strips(text, chars): return "".join(c for c in text if c not in chars) print(strips(text, chars))
766e5a35b3a7edb9114ffbc9121dedff5f95510a
politkovd/ip-politko-victor-1
/Homework/hw2/Homework2.py
2,922
4
4
# __author__ = 'Политко Виктор Дмитриевич' # Задача-1: Запросите у пользователя его возраст. # Если ему есть 18 лет, выведите: "Доступ разрешен", # иначе "Извините, пользоваться данным ресурсом можно только с 18 лет" age = int(input('Укажите ваш возраст: ')) if age >= 18: print('Доступ разрешен') else: ...
1eb9178aab52cb3cc1c9c1b51d051393810d0670
politkovd/ip-politko-victor-1
/Homework/hw3/Homework3.py
7,694
3.75
4
# __author__ = 'Политко Виктор Дмитриевич' # Easy # Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: вос...
777e44c5330ac8322d777bd863282e7d9aa9dc1b
brentnunn/wsgi-calc
/calculator.py
2,443
3.84375
4
#!/usr/bin/env python math_ops = {'multiply': lambda x, y: x * y, 'divide': lambda x, y: x / y, 'add': lambda x, y: x + y, 'subtract': lambda x, y: x - y, } def usage(): """ Explain the usage of calculator.py """ usage_page = """<html> <head> <title>WSG...
9ffe2003245e5acc5aaa3c0d4f0f1074244ca826
sideb0ard/Skateboard-Cat-Killer
/skateboardcatkiller.py
14,148
3.578125
4
#!/usr/bin/env python # coding=utf-8 # Music by Delroy Edwards - Slowed Down Funk - http://www.sloweddownfunk.net/ # my first version based on this kid's tutorial - http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python # Then i made it more object oriented after reading this tutorial - htt...
34743b0cfa9778c9c384af3f66fbf347d39aeb86
patrickkidd/pksampler
/pk/povray/sdl.py
7,193
3.5
4
import sys, os class File: def __init__(self, fname, *items): self.file = open(fname, 'w') self.__indent = 0 self.write(*items) def include(self,name): self.writeln( '#include "%s"'%name ) self.writeln() def indent(self): self.__indent += 1 def dedent(...
40b5e6da003aa829473dd9d5f513e65b8feb3bc6
joy-gajjar/turtuleGaming
/main.py
262
3.84375
4
import turtle colors = ["red", "blue", "green", "yellow", "cyan", "magenta", "purple", "orange"] t = turtle.Pen() turtle.bgcolor("black") for i in range(360): t.pencolor(colors[i%8]) t.width(i/100+1) t.forward(i) t.left(59) turtle.exitonclick()
df29c5df48a281ec1aed37303be58425ed9b100c
neo-astro/calses-estructura-de-datos-
/deber_s1/eje11.py
1,001
4.09375
4
# Diseñe un pseudocódigo para calcular la suma y producto de N números enteros # utilizando un bucle controlado por el usuario. class Calcular: def run(self): try: acu = 1 num = int(input("Ingrese un dato:")) numeros = [] numeros.append(num) preg...
c78bb5173ea298f61960e65a2d10676461539cd7
neo-astro/calses-estructura-de-datos-
/deber_s1/eje06.py
465
3.65625
4
class Mayor: def run(self): try: n1 = int(input("Escriba un numero entero: ")) n2 = int(input("Escriba otro numero entero: ")) n3 = int(input("Escriba otro numero entero: ")) bi = [n1, n2, n3] print("El numero mayor es: ", max(bi)) except V...
52cba810d527c241a94d99d88b587f753f9b0f0d
neo-astro/calses-estructura-de-datos-
/semana s3/estructura_clase_04.py
3,021
3.578125
4
class FOR: def __init__(self): pass def usofor(self): # nombre = "Adrian" # datos = ["Daniel", "Se" ,True ] # numeros = (2, 5.6, 4 ,1) # docente = {"nombre":"Daniel","edad":50 , "fac":"faci"} # listaNotas = [(30,40),(20,40,50),(50,40)] # listaAlumnos = ...
4919b3fc6238145b9202bef1f39688b0afb9db47
neo-astro/calses-estructura-de-datos-
/deber_s1/eje12.py
743
3.984375
4
# Diseñe un pseudocódigo para calcular la suma y producto de N números enteros # utilizando un bucle controlado por centinela. class Calcular: def run(self): try: acu = 1 num = int(input("Ingrese un dato:")) numeros = [] numeros.append(num) while...
92fe0464cdb4ca2a24989ec9d1c2ca23844c7f85
neo-astro/calses-estructura-de-datos-
/deber_s1/eje02.py
438
3.734375
4
# En una tienda se ofrece un descuento del 15% sobre el total de la compra # y un cliente desea saber cuánto deberá pagar finalmente por su compra. def porcentaje(): try: total = float(input("Escriba el total a pagar: ")) res = total - total*0.15 print("El total a pagar es de {} $".format(re...
e9a09af7b98c4c9da120e7b71bdd41ebd0ae25b6
AmauryCarrade/wine-contest-quizz
/quizz/text_processors.py
877
3.71875
4
import string from Levenshtein import distance from unidecode import unidecode def gentle_levenshtein_distance(string1, string2): """ Computes the Levenshtein distance between two strings, but ignoring punctuation, multi-spaces, line breaks and accents. :param string1: The first string. :param s...
8fa219ea54f77d85c0b7ea64aedb80600f98d884
tenchd/ipdTournament
/example_submission.py
1,066
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 22:29:10 2019 @author: devd """ import deciders as d #This is an example file a participant would submit for the tournament. #The participant defines a decider function and instantiates a submission #object with it. That's pretty much it. You...
c9c8825ce67f1f8b5fa861b587b72c25a46591f8
shijiez777/mobilegameFeatureComparison
/dataFormatting.py
1,674
3.78125
4
import pandas #read in, index_col is the first col by default us = pandas.DataFrame.from_csv('features-full-us-2017-06-13.csv', sep = ";", index_col = None)#,, header is for skipping prior rows, index_col set to none to automatically generate integer index #sort values based on multiple columns, feature and choice,...
bb61465f789e7b8c4d9f0b2f7ea84306848cf755
HimNG/daily_coding_problem
/problem_19.py
1,264
3.640625
4
''' A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minim...
c04a585cc23f7bf2d84b00f70ec3813a42bc953b
FcoJavierGlez/ExamenAbrilProgram
/figuras/Python/figuras/TestRectangulo.py
657
3.5
4
''' Created on 5 abr. 2019 Clase TestRectangulo para testear el funcionamiento de la Clase Rectángulo @author: Francisco Javier González Sabariego ''' import sys import time from figuras.Rectangulo import Rectangulo print("Intentemos un rectángulo a de 7 de ancho y 5 de alto") try: a = Rectangulo(7,5) ...
3cfc83bf20d4d2f9630847ab7c78d65a620d299a
zahidaMassin/DeepLearning
/ann_mnist.py
1,816
3.59375
4
#Training Ann with Mnist datasets by AliZahid import numpy as np from keras.utils.np_utils import to_categorical from keras.models import Sequential from keras.layers import Flatten , Dense from keras.datasets import mnist import matplotlib.pyplot as plt (trainX, trainy), (testX, testy) = mnist.load_data() print('Trai...
72ce651ed9bdcc8680d067fbb9422c2e011e75e8
Daniel1999Akama/HowtothinkLACOSCIE_2
/Keypress_Events.py
957
3.609375
4
import turtle # screen and turtle. screen = turtle.Screen() screen.title('Handling Keypresses!') screen.bgcolor('lightblue') tess = turtle.Turtle() tess.color('red') tess.pensize(2) tess.speed(6) # The next 4 functions are our 'event handlers'. def h1(): tess.forward(50) def h2(): ...
b3a3fb765622c06ce900a2649bf745f91e3686d7
njckfletcher/Tutorials
/basics/tuples/tuples4.py
402
4.1875
4
''' Created on Mar 5, 2017 @author: Hunter ''' empty_tuple = () test1 = ("a",) # Must include a comma for single element tuple or else result is a String! test2 = ("a", "b") test3 = ("a", "b", "c") print(empty_tuple) print(test1) print(test2) print(test3) # Tuples do not need parenthesis to create: test4 = 1, test...
30849dd0b40dd0887a727cb4b0028b55e30f6463
njckfletcher/Tutorials
/sqlite/sqlite_1.py
434
3.671875
4
''' Created on Mar 5, 2017 @author: Hunter ''' import sqlite3 conn = sqlite3.connect('tutorial.db') c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEST, keyword TEXT, value REAL)') def data_entry(): c.execute("INSERT INTO stuffToPlot VALUES(14512...
145f3b24b3e2a1d38904b3410dcf8daaf3c4f227
RohanGautam/OpenCv-Book
/7_simple_thresholding.py
979
3.5625
4
# Run : python 7_simple_thresholding.py -i coins.png import numpy as np import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) '''Thresholding is binarization of an img. Pixel values of either 0 or 255''' image =...
128ba5ea4d7bb2eb484af94fd152c086b6a525ad
silkkr/LPTHW
/EX52/gothonweb/map.py
3,760
3.5
4
class Scene(object): def __init__(self, title, urlname, description): self.title = title self.urlname = urlname self.description = description self.paths = {} def go(self, direction): default_direction = None if '*' in self.paths.keys(): default_direc...
4b08807e4d36bbfee06b3dd960a0f6b5edc6b370
cnsr/SadBot
/pydick.py
346
3.96875
4
from PyDictionary import PyDictionary d = PyDictionary() def meaning(word): answer = '' try: m = d.meaning(word) for k, v in m.iteritems(): answer += '[b]' + k + ':[/b] ' for x in v: answer += x + '\n' except Exception as e: answer = 'no such...
7d713d1ec109c2e7d03381f6c2238417ed670317
tfchan-rob/Code-War
/Isograms.py
670
4.3125
4
#!/usr/bin/env python # coding: utf-8 # # Isograms # An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. # is_isogram("Dermatoglyp...
b1c0993b1c3d98ea322ca31061d283a0ab8d0bc7
tfchan-rob/Code-War
/Convert a Number to a String!.py
332
4.34375
4
#!/usr/bin/env python # coding: utf-8 # # Convert a Number to a String! # We need a function that can transform a number into a string. # # What ways of achieving this do you know? # # Examples: # 123 --> "123" # # 999 --> "999" # ## my solution # In[2]: def number_to_string(num): return str(num) #...
58a1964eadddc926ea8b93410179f53daccdaa29
Harrison97/TicTacToe
/tictactoe.py
1,491
3.984375
4
class TicTacToe: grid = [] for i in range(3): grid.append(['-', '-', '-']) def print_game(self): for row in self.grid: print(row) def __str__(self): # this function is basically the same as the above # but instead allows us to print with print(game) s = '' for row in self.grid: ...
f43e07ba3198e2f83bfc58b07aae2e9a61c8081e
upgirlnana/algorithm017
/Week_04/lemonadeChange.py
962
3.671875
4
# coding: utf-8 # In[ ]: def lemonadeChange(self, bills: List[int]) -> bool: if len(bills)==0: return False five_count=0 ten_count=0 twenty_count=0 for i in range(len(bills)): if i==0 and bills[i]<5: return False elif bills[...
cabc504dcc33246453dff2922bbd88a24bc110ef
nickywhiteson/phyton-
/prime_number.py
234
4.125
4
number = int(input("Enter a Number : ")) condition = (number%2 != 0) and (number%3 != 0 ) and (number%5 != 0) and (number%7 !=0) if condition == True: print("This is a Prime Number") else: print("This is not a prime number")
fe235827ff496aa6f7fb0e2944272ceb059e2be3
Erioifpud/codewars
/esolang-interpreters-#4---boolfuck-interpreter/boolfuck.py
2,018
3.515625
4
''' The tape for Brainfuck contains exactly 30,000 cells with the pointer starting from the very left; Boolfuck contains an infinitely long tape with the pointer starting at the "middle" (since the tape can be extended indefinitely either direction) Reads a bit from the input stream, storing it under the pointer. The ...
991fdc464194b10626560f9b2bd82d412d097e52
ljubankrstic/python-projects
/nqueens.py
3,098
4.1875
4
'''Nqueens problem is a classic backtracking example. Given the width of the chessboard n, and n queens, output every combination of queen positions, such that no queen attacks another (ignore colors of the pieces) n - width of the chessboard and number of queens to be placed board - list which stores solution that is ...
493e7f31ee456398859d91623abce6e638dd47bf
emichester/trader_bot
/utils/data_analysis.py
1,647
3.796875
4
""" https://www.macrotrends.net/stocks/charts/CSV/carriage-services/stock-price-history https://www.lawebdelprogramador.com/foros/Python/1548513-Derivadas-numericas.html https://stackoverflow.com/questions/10345278/understanding-lambda-in-python-and-using-it-to-pass-multiple-arguments https://matplotlib.org/2.1.1/api/...
b26ae5f36d17eff41b896c5652db336687dfeebe
Kevinfhu/PrograApp_P57
/While_demostration.py
165
4.09375
4
""" Created on Tue Jan 5 15:11:48 2021 @author: ♫♪ Kevin Fausto ♪♫ """ x=input('Enter a number to count to: ') x=int(x) y=1 while y<=x: print(y) y=y+1
80feb00681928fb657e7c40137639f9e4ca487bb
remintz/programacaoemcasa
/exercicios/lista_aula_4/exercicio 5.py
1,558
4.0625
4
''' (dicionarios e listas) Dada a lista de dicionários abaixo: Notas = [ # cada indice da lista corresponde a um trimestre { 'ciencias': 80, 'ingles': 55, 'matematica': 70, 'portugues': 85 }, # trimestre 1 { 'ciencias': 90, 'ingles': 75, 'matematica': 74, 'portugues': 75 }, # trimestre 2 { 'ciencias': 85, 'ingles': 8...
0d025bcc232daf0586c9619a40ced4adb0eb8d47
remintz/programacaoemcasa
/exercicios/fatoracao.py
337
4.09375
4
numero = float(input('Qual é o número? ')) if numero <= 0: print('O número deve ser maior que zero') exit() if numero % 1 != 0: print('O número deve ser inteiro') exit() numero_int = int(numero) print(f'Os divisores de {numero_int} são: ') for i in range(1, numero_int + 1): if numero % i == 0: ...
1217de39202f0a7d62b98660de3c69f0207638ad
remintz/programacaoemcasa
/exercicios/bubble_sort/bubble_sort.py
1,028
4.09375
4
# Algoritmo do artigo do wikipedia em https://pt.wikipedia.org/wiki/Bubble_sort # # procedure bubbleSort( A : lista de itens ordenaveis ) defined as: # do # trocado := false # for each i in 0 to length( A ) - 2 do: # // verificar se os elementos estão na ordem certa # if A[ i ] > A[ i + 1 ] then #...
ace1666ad156c8940f284c1140f0a8ab30077268
remintz/programacaoemcasa
/exercicios/lista_aula_3/exercicio_2.py
789
3.96875
4
''' Crie uma lista com os ‘n’ primeiros números primos, onde o valor de ‘n’ é informado pelo usuário. Lembrando que os números primos são aqueles que só são divisíveis por eles mesmos e por 1. ''' quantos = int(input('Quantos números primos você quer? ')) contador_de_primos = 0 dividendo = 0 while ...
1ce2e4385ca011f36496cbc13f79fe07c3e46bfa
bsobocki/NumericalAnalysis
/calculations/task7.py
1,009
3.71875
4
import math from decimal import Decimal # odemowanie 1 - sqrt(1 - ( x/2^k )^ 2 ) # wygląda następująco: # od 1 odejmujemy 1 + e # gdzie |e| > 0 (mała liczba, im większe n tym mniejsza) # więc im większe n tym bliższym 0 jest wynik odejmowania, # wtedy następuje utrata cyfr znaczących, # a co za tym idzie wyniki mnoż...
ce38a4aa7ac59b34b4c3a441d1e7dd055ab21451
maxeleron/Learn_Python
/BasicTypes/Strings.py
603
4.28125
4
# #!/usr/bin/env python # -*- coding: utf-8 -*- # Python 2.x has two types of strings. # Byte string str1 = b"Meat" # Unicode string str2 = u"Fish" # You can use " or ' literals to create strings. l1 = u"Wish" l2 = u'Arial' # Strings decoding. newStr1 = str1.decode("utf-8") # We can create new ...
d79e944e9f8ab08c5d63456d48fad2676c56a002
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/42-OOP/00- done/57.12-classAndInstance__dict__.py
3,197
4.1875
4
# INTERVIEW REVISION # NOTE: # - instance variables are stored in the object dictionary whereas static variables are # stored in the class dictionary # - When you try access a variable in a object, Python will look first in the object, # if it is not there then it looks in class dict. class Test: # static/cl...
435b4937f6664caf5f268cdaceb82c00f8510ba5
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/30-CompositeDataTypes/30.8-MappingTypes/30.8.2-HashableKeys.py
10,344
4.375
4
# Hashable objects: # An object is hashable if it has a hash value which never changes during its lifetime. The hash value is like a # numerical value which can be used as a signature for that particular object. # In python, immutable data types are hashable and come with a built-in method for computing their hash v...
d922280a635ba77846935cec8e022887e6a8e6fe
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/Jupiterised/30-CompositeDataTypes/30.6-Set Types/30.6.6-SetOperations.py
2,455
4.53125
5
# https://www.programiz.com/python-programming/set # Sets can be used to carry out mathematical set operations like: # union, intersection, difference and symmetric difference. # We can do these operations with operators or methods. #Let us consider the following two sets for the following operations. A = {1, 2, 3, 4...
8030200fd46a4ebeb304b215ae78f1f6da5a2c5b
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/30-CompositeDataTypes/30.12-inKeyword.py
2,283
4.375
4
# The 'in' and 'not in' keywords are used to check if a value exists in python's built-in composite data types (sequences, sets and # mapping types) TODO Objects? # --- Strings: # It returns a boolean value and is used as below: # Example strings (Same for list, tuple, byteArray, byte, range, xrange, dictionary, set ...
331f6d344c8d258aaf70e8d26e1560560df5914f
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/Jupiterised/30-CompositeDataTypes/30.4-SequenceTypes/30.4.4-list-tuple-And-range/30.4.4.10-range.py
1,493
4.46875
4
# range(start, stop[, step]) # where start is optional. Default = 0 # stop is mandatory # step is optional. defaults to 1 # The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times # in for loops. # The advantage of the range type over a regular list or tu...
627a651414354d26b3927de7f01865f1cdd4dd96
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/36-ErrorsExceptionsAnd-with/36.10-with-as/36.10.6-ContextlibModule.py
1,860
3.921875
4
# INTERVIEW REVISION # Here, we require the knowledge of generators, decorators and yield. # The contextlib module # https://docs.python.org/3/library/contextlib.html # A class based context manager as shown previously is not the only way to support the with statement in user defined # objects. The contextlib module p...
53ec96f72499fb59fdd2a7cd0673f4f40155fd30
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/Jupiterised/30-CompositeDataTypes/30.4-SequenceTypes/30.4.8-CommonSequenceMethods.py
1,853
4.1875
4
# index(), count() are available in string, list, tuple, bytearray and bytes sequences and discussed in a separate topic. # --- strings: s = "Syed Saquib Saeed" # index( str_value [, startIndex, EndIndex] ): # Finds the position of the first occurrence a given str_value in a list # We can also provide a start index o...
3df09a3e5bd187231627f73288f3c4f9b70299ca
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/42-OOP/00- done/57.14-StaticMethods.py
2,724
4.53125
5
# We saw how to create class attributes in the previous section. To access and change a class attribute we could use # instance methods for this purpose: class Robot: __counter = 0 def __init__(self): type(self).__counter += 1 def RobotInstances(self): return Robot.__counter x = Robot() p...
20e93751b33adc0d0198ddc9ba9c4b941b596408
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/46-IteratorsAndGenerators/60.3-CustomIterator.py
958
4.0625
4
# TODO https://rszalski.github.io/magicmethods/#sequence # For an object to be an iterable, we should be able to call the iter() function on it ie # it should have a dunder method __iter__() defined in it which will return an iterable # object # Similarly, for an object to be an iterator, we should be able to call the ...
c87af5db8f07e54070cf0055daa7c448cd82d36e
zachsaeed/python_notes
/assignments/assignment_class_3.py
2,180
4.40625
4
# 1 Comments in Python are written with a special character, which one? ?This is a comment # 2 Use a multiline string to make the a multi line comment: ? This is a comment written in more that just one line ? # 3 Create a variable named carname and assign the value Volvo to it. # 4 Display the sum of 5 + 10, using ...
ee76885b4c0a8ad81d1a765ac7b26eb4b333f217
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/42-OOP/.ipynb_checkpoints/57.34-OperatorOverriding__magic__methods-checkpoint.py
2,377
4.40625
4
# https://micropyramid.com/blog/python-special-class-methods-or-magic-methods/ # 2- Operator overriding where the same operation works differently for different kinds of # objects (Internally via special dunder methods). # https://docs.pytho n.org/3/reference/datamodel.html#special-method-names # # print(2 + 2) # 4 # ...
20008a69b50ea22fc9a7f1fd76d4de656165ae74
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/53.5-PDB-pythonDebugger.py
1,672
4.09375
4
# Debugging in python # To set breakpoints in our code, we can use pdb by inserting this line: # import pdb # pdb.set_trace() # Also commonly on one line: # import pdb; pdb.set_trace() # when python encounters 'pdb.set_trace()', it pauses and in the terminal we can interact # with values or step thru one line at a t...
7e3a5cf3e1a377dad56b0a5dda7588073813ffa8
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/48-Decorators/48.5-wrapsLibraryToPreserveMetaData.py
775
3.71875
4
from functools import wraps # wraps preserves a functions metadata when it is decorated # It is a wrapper function we use to wrap our wrapper function def log_function_data(fn): @wraps(fn) # decorator to replace ou wrapper's metadata with fn's def wrapper(*args, **kwargs): """I AM WRAPPER FUNCTION"""...
50f397a8db052eb70de750e9768f4733f699523e
zachsaeed/python_notes
/099 Notes Under preparation/old/etc note files. Need to move to main files and delete/Jupiterised/6-basicDatatypes/6.0-datatypesAnd-type-sizeof-Method.py
2,832
4.4375
4
# Python is dynamically-typed, which means it only checks the types of the variables you specified when you run the # program. Variables can store data of different types, and different types can do different things. # Python has the following data types built-in by default, in these categories: # Numeric Types: int, ...
3c9d89c48a15adbe17994568b59aa0f692a24df5
Sofloud/Algorithm_
/data_class.py
1,133
3.609375
4
Months = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) class Date: def __init__(self, day = 0, month = 0, year = 0): if type(day) == str: day = day.split('.') self.day = int(day[0]) self.month = int(day[1]) self.year = int(day[2]) else: ...
592a1b121d2380d4164b3fe90e87ab78205e49e2
Vicky0916/Practice1
/成绩输入.py
300
3.921875
4
score=int(input('请输入成绩:')) if score>100: grade="输入错误!" elif score>=90: grade="优秀" elif score>=80: grade="良好" elif score>=70: grade="中" elif score>=60: grade="及格" elif score<60: grade="不及格" else: grade="输入错误!" print(grade)
2e86704791b978a8e45800da150e6221888e29f8
allanliebold/data-structures
/src/binheap.py
1,458
4.0625
4
"""Implementation of a Max Binary Heap.""" class Heap(object): """Create Heap class object.""" def __init__(self, iterable=()): """Initialization of Heap.""" self.contents = [] self._size = 0 if isinstance(iterable, (tuple, list)): for i in iterable: ...
dd7a07af17764169fc8f1c8d277baca023a67d9c
Ritapeace/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
216
4.03125
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): if len(a_dictionary) != 0: lista = sorted(a_dictionary.keys()) for i in lista: print("{}: {}".format(i, a_dictionary[i]))
3ee5c2196a6a612fbbf7b5b1e818468eedcdaeff
Ritapeace/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
515
3.90625
4
#!/usr/bin/python3 """ function that adds into a file a string, but only after get a match of a string in this case after match search_string inside the file, we are going to put the new_string """ def append_after(filename="", search_string="", new_string=""): result = "" with open(filename) as fd: f...
fe20288820ef9bdee87c5f7cd640ec1f6679cdfd
Ritapeace/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,515
4.15625
4
#!/usr/bin/python3 """ Function that divide every element of the matrix by the div number """ def matrix_divided(matrix, div): """ Args: matrix: list of list div: integer or float different from zero Raises: TypeError: * matrix must be a matrix (list of lis...
372e4df913041876feb803e69a9b242453e16583
Ritapeace/holbertonschool-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
197
3.671875
4
#!/usr/bin/python3 """ create an object from a json file """ def load_from_json_file(filename): import json with open(filename) as fd: obj = fd.read() return(json.loads(obj))
ef64d1a31ad0a24ecc5cae2f51dee3f1b0d9b94f
Ritapeace/holbertonschool-higher_level_programming
/0x11-python-network_1/102-starwars.py
1,841
3.578125
4
#!/usr/bin/python3 """ getting info from Star Wars API """ if __name__ == "__main__": import sys import requests API = "https://swapi.co/api/people/?search=" complete_API = API + sys.argv[1] # go to the first page of the search while(1): r = requests.get(complete_API) prev = r.j...
3be12d6c26aaff7df553f3ff571b853c43418f57
Ritapeace/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
275
4.125
4
#!/usr/bin/python3 """ function that append the content of a file. and if the file is not created it is created automatically """ def append_write(filename="", text=""): number = 0 with open(filename, 'a') as fd: number = fd.write(text) return (number)
d093fab555bcd9f596249543d0559df0fa84e065
fly2rain/LeetCode
/valid-sudoku/valid-sudoku.py
1,575
3.53125
4
class Solution(object): def isValidSudoku(self, board): """ :type board: List[str] :rtype: bool """ # check vertically for j in range(9): hash_table = [0] * 9 for i in range(9): if not (board[i][j] == '.'): ...
292e40f97913bc38e831aa8116919a756b9986e7
fly2rain/LeetCode
/reorder-list/reorder-list.py
1,771
4.21875
4
from utils import ListNode class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ # make sure the length of list is more than 3 if not head or not head.next or not head.nex...
5a5261b10676614713e0b3172ec293bc8d8056e8
fly2rain/LeetCode
/insertion-sort-list/insertion-sort-list.py
1,759
4.03125
4
from utils import ListNode class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None sorted_head, sorted_end = head, head current = head.next head.next = None ...
bc531913d18e5af4bd5129b6dadfcbaac0dbc4bf
fly2rain/LeetCode
/house-robber-ii/house-robber-ii.py
857
3.828125
4
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ def rob_line(nums, start, end): odd_sum = nums[start] even_sum = 0 for i in range(start+1, end+1): if (i - start) % 2: ...
f82fb02818c9fd23a4cf44fa31f43ad48cd5a419
fly2rain/LeetCode
/h-index/h-index.py
600
3.796875
4
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ citations.sort() h_index = 0 for i in reversed(citations): if h_index + 1 <= i: h_index += 1 else: ret...