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
89b15bdb61ca1b9f74a9b469db8e568f2c430f57
Junyang-chen/HackerRank
/LinkedList.py
1,371
3.734375
4
""" This file is written by Junyang Chen for datastrucutures of Linked list """ class DoubleLinkedNode(object): def __init__(self, data = None, prev = None, next = None): self.data = data self.prev = prev self.next = next def __repr__(self): return 'Node({0})'.format(self.data)...
14e194401397c6046daff8b604fee7e2781b0b33
shubhdashambhavi/learn-python
/org/shubhi/sorting/selectionSort.py
499
3.9375
4
#In every iteration of selection sort, # the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. selectionarr= [45,24,12,65,11,9] for i in range(len(selectionarr)-1): min_index=i for j in range(i+1,len(selectionarr)): if selectionarr[j]<...
82f27f0d7e43200604ed1c712b3f889528bc952c
tbholstein95/dnddmtracker
/Classes/subclasses/playerclasses/ranger.py
1,077
3.546875
4
from Classes.subclasses.half_caster import * ranger_dict = {} class Ranger(HalfCaster): def __init__(self): self.ranger_options = {} super().__init__() def create_ranger_options(self): self.ranger_options['0'] = "[5]: Change Level\n" + "[6]: Exit\n" self.ranger_options['5'] = self.change_half_caster_level ...
f3518874666cdd815807248737d78207922866b3
codydeatherage/CSE-015
/Lab 2/Lab2 (1).py
422
3.984375
4
import itertools from itertools import product from itertools import combinations def cartesian_product(X,Y): list = [] for i in itertools.product(X,Y): list.append(i) return list X = [1,2] Y = ['a', 'b', 'c', 'd'] print cartesian_product(X,Y) print def power_set(X): set = [] for i in range(len...
9efa7ea494bf8299bdbd4070fbc3acb06bc4bee9
codydeatherage/CSE-015
/LAB7.py
1,683
3.921875
4
def chars_to_nums(c): nums = [] for i in c: nums.append(ord(i)-32) return nums def nums_to_chars(n): chars = "" for i in n: chars = chars + chr(i+32) return chars # Exercise 1: Implement an encode procedure for the Caesar cipher. def caesar_encode(plaintext...
59fec7ba4fabb990bf79f231e6c9458f9435a4d5
henryxzx/algorithm_python
/1-9/jumpFloor.py
450
3.5
4
# -*- coding:utf-8 -*- class Solution: def jumpFloorII(self, number): # write code here a= [] for i in range(number): ans = 0 if i == 0: a.append(1) continue for j in range(i): ans += a[j] a.appen...
4e66bca22cef9b2af23910bfea482b0464cc5067
nucle0tides/Python-Data-Structures
/Trees/trees.py
808
4.0625
4
""" UHHHH, A TREE """ class Node(): def __init__(self, data): self.data = data self.left = None self.right = None def visit(self): print(self.data) def in_order(node): if node is not None: in_order(node.left) node.visit() in_order(node.right) def pre_order(node): if node is not None: node...
db2aab1d75d0cf72c765544ced062f017a91ac7c
shombo/cyberstakes-writeps-2018
/is_that_a_warble_in_your_voice/test.py
452
3.515625
4
def chunks(l, n): n = max(1, n) return (l[i:i+n] for i in xrange(0, len(l), n)) if __name__ == "__main__": for i in range(8): i = bin(i).split('b')[1].zfill(3) a = '00110111100000000100111101011000111110110011010001110000101101110100110010011011110011110001101000001001011111111000100101001'...
850a14c6c662870e1bf0f0f41217a9de9ed6a735
016mm/hyle
/util/progress_bar.py
1,518
4.0625
4
#!/usr/bin/env python3 # coding: utf-8 """ Simple console progress bar. """ # print iterations progress def print_progress_bar(iteration, total, suffix="", decimals=1, length=100, fill="█", print_end="\r"): """ call in a loop to create terminal progress bar @params: iteration - Required : c...
e345f06e0571cbc60f0282b76084133bb1828b79
premgolani/python-codes
/count and check char.py
869
3.984375
4
text=str(input('enter any string')) count1=0 count2=0 count3=0 count4=0 for i in range (len(text)): if text[i]>='A' and text[i]<='Z': count1+=1 elif text[i]>='a' and text[i]<='z': count2+=1 elif text[i]>='0' and text[i]<='9': count3+=1 else: count4+=1 pr...
305a163a9e467d8d50185bb88dfb98a0039c2e30
lenick22/LearningtoPython
/if_else_example.py
148
3.5
4
print('What is the password?') password = input() if password == 'swordfish': print('Password Accepted') else: print('Password Denied')
f07b1fee2f34a282311397d2d37561df7fb25865
majosara/proyectoFinal
/proyectoShell/obtenerpreguntas.py
3,382
3.5
4
preguntas_grado = [] #Lista que guarda las preguntas segun el grado id_answers = [] #esta lista contiene las respuestas de acuerdo al id de opciones id_options= [] #esta variable contiene la lista de las opciones de cada pregunta segun su id def getQuestions(grado,preguntas_grado): """ Esta funcion recibe el grad...
3fe35d9a8063ad04f468c47e71bb9bd66e1664b9
leamont-siue/ME492
/loop_ex4.py
149
3.765625
4
myvect1 = ['a','bob',3, 'd', 'e'] for i, item in enumerate(myvect1): print('i = ' +str(i)) print('item =' +str(item)) print('after for loop')
9ec4277cb9d0f88290a5f1c7abd4815d12677a90
mdisieno/Learning
/Python/FCC_PythonBeginner/14_ifStatements.py
278
4.15625
4
isMale = True isTall = False if isMale and isTall: #checks if either true print("You are a tall male") elif isMale and not(isTall): print("You are a male") elif not(isMale) and isTall: print(("You are not a male, but are tall")) else: print("You are a female")
2083a2dcfe7efb5edb9b058f31b3c8f1f6ff7315
mdisieno/Learning
/Python/MOSH_PythonBeginner/14_dictionaries.py
504
3.859375
4
#first val is key customer = { "name":"John Smith", "age" : 30, "is_verified": True } print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") #call key print(customer["name"]) # Exercise print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") numbers = { "1":"One ", "2":"Two ", "3":"Three ", "4":"Four ", "5"...
3e16393f1d6433a4df7ec3753e40ec9e5f2d0a05
fabianocardosodev/exercicios-Python-cursoIntens
/testcontinu.py
329
3.96875
4
#considere um laço que conte de 1 a 10, # mas apresente apenas os números ímpares desse intervalo # a instrução continue diz a Python para ignorar o restante do laço e voltar ao início numero_atual = 0 while numero_atual < 10: numero_atual += 1 if numero_atual % 2 == 0: continue print(numero_atua...
9329ad1dd7442b3c51cb0f46644579cf7636d538
fabianocardosodev/exercicios-Python-cursoIntens
/dicionarios7.py
513
3.953125
4
favorite_languages = { 'jen' : 'Python', 'sarah' : 'c', 'edward' : 'ruby', 'phil' : 'Python' } print('As seguintes linguagens foram mencionadas: ') # usamos o metodo values para apresentar os valores no dicionario sem as chaves # A instrução for, nesse caso, extrai cada valor do dicionário e o armazen...
6844efba502325707c3feaa2c9af6aa1ae0fdb7b
fabianocardosodev/exercicios-Python-cursoIntens
/exerdiciona6.py
403
3.71875
4
#cria um dicionario #cada chave possui em valores 1 ou mais elementos #depois imprimi chaves e valores lugares_favoritos = { 'alan' : ['copacabana','fernando noronha'], 'lucas' : ['rio grande do norte'], 'monica': ['rio de janeiro','porto seguro','ilha bela'], } for name, lugares in lugares_favoritos.i...
62e29f3ea68b3f4e39bf6bb4194f07092c01978e
fabianocardosodev/exercicios-Python-cursoIntens
/removelista.py
203
4.125
4
#remove as instancias de valor especifico de uma lista #funçao "remove" pets = ['dog','cat','dog','goldfish','cat','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
f734a6e1ead31b0a94cddf8f2acc3fe4cd076eae
Oviep/pluralsight_tutorial
/roll_dice.py
241
3.96875
4
import random roll_dice = random.randrange(1, 6) guess = int(input("Guess the dice roll: \n")) if guess == roll_dice: print("Congratulations you rolled a " + str(roll_dice)) else: print("Wrong. They rolled a " + str(roll_dice))
cee2af388c3f055bd66b2846e54b15b4ffbe9e7f
amsearles/meisysnatch
/game.py
1,239
3.75
4
# A simple text-based game inspired by BanderSnatch #Coded By Anthony M Searles #Story & design by Meisy Tunay print("Welcome to MeisySnatch!!!! A game where you have to please Meisy else you will be snatched") print("Shall we begin?") print("You walk down a cold, empty hallway that is bare of any furnishings.") prin...
8ce5023ebd1d135b689494a8d03bd5d7779014b9
teribsandy/ML-Ng-Python
/线性回归/1_LinR_SkL.py
882
3.703125
4
# coding: utf-8 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model '''准备数据''' data=pd.read_csv('/Users/zhangying/Desktop/243-ML-吴恩达/ex1-linear regression/ex1data1.txt',header=None,names=['Population','Profit']) data.insert(0,'Ones',1) #data.shape (97, 3) type(data...
390e6e11a0cf5cc31f5e8342d1c9585324f74e22
Aayush789/C97
/pocketMoney.py
204
3.828125
4
pocketMoney= int(input("enter the pocket money you get: ")) if (pocketMoney>500): print("u are rich") elif(pocketMoney>200): print("u have a good life") else: print("i know what u feel")
f265955f3d859d37396a326c8733a8af9b22c225
ricardo-ribeiro/8PuzzleSolver
/uk/Heuristics/LinearConflict.py
1,483
3.609375
4
from uk.Heuristics.Manhattan import Manhattan __author__ = 'ricardo' class LinearConflict: def __init__(self,goalState,mh): self.linearConflict = 0 self.goalState = goalState self.manhathan = mh def calculate(self,currentState): distance = 0 distance += self.manhathan....
0c3bceb4730ec73b7aa0876f44df02ec3573ee43
dunkybaldy/Python
/src/CompanySim/Company.py
683
3.640625
4
from src.CompanySim.Employee import Employee class Company: name = "" active = False requiredMonthlyIncomeToPayEmployees = 0.00 wantedMonthlyProfit = 0.00 employees = [] employeesFired = [] def __init__(self, name): self.name = name self.active = True def SetActive(sel...
767a44cb7c8506e89336a3362484a42b6730f77a
Akasame0315/1082OOPPractice
/StudentCard_Composition/StudentCard_Composition.py
272
3.515625
4
from Date import Date from Student import Student stu1 = Student("Jerry", 6, 1, 1999, 90) stu2 = Student("Marry", 10, 8, 1997, 80) n = str(input()) m = int(input()) d = int(input()) y = int(input()) stu1.setName(n) stu2.setDate(m, d, y) stu1.toString() stu2.toString()
7cb302ea332596426c1dce3155fda967021d999a
YMonnier/AdvAlgoLP
/Assignment1/Social/FSM.py
1,235
3.546875
4
# # FSM.py # String matching with finite automata # or Finite State Machine (FSM) # University Of Lodz, Poland # String matching # import string import time ''' Build a two-dimentional array which reprensent the Finite Automata ''' def computeTransition(P): m = len(P) alphabet = string.ascii_letters + string.punct...
e8378b7616109fdac3dc8ebeb390f813adf67965
YMonnier/AdvAlgoLP
/Assignment2/Social/Supervisor.py
1,578
3.5
4
# # Author Ysee Monnier # University Of Lodz, Poland # from Labyrinth import Labyrinth from Wizard import Wizard labyrinth = Labyrinth() # Add nodes labyrinth.add_node('A') labyrinth.add_node('B') labyrinth.add_node('C') labyrinth.add_node('D') labyrinth.add_node('E') labyrinth.add_node('F') # Add edges labyrinth.a...
3e12d16e775dc303c63c021e832dbb459bba0d39
zhsword/exercise
/Copy/Create txt.py
413
3.734375
4
def file_write(file_name): f = open(('%s.txt' % file_name ) , 'w') print('请输入文件内容【单独输入“:c”保存退出】:') while True: write_content = input() if write_content != ':c': f.write('%s\n' % write_content) #/n每输入一句话,自动换行。如果没有,则无法换行 else: break f.close() file_name = input('请输入文件名:') file_write(file_name)
816efaf9a4bee14559809f0cf7474d49a29c7263
zhsword/exercise
/Copy/Print N_lines.py
1,043
3.765625
4
#打印文件的前N行,方法1 file_name = input('请输入要打开的文件:') file_lines = int(input('请输入要显示前几行:')) count = 0 f1 = open(file_name) for each in f1: count += 1 if count <= file_lines: print(each) else: break f1.close() #打印文件的前N行,方法2 file_name = input('请输入要打开的文件:') file_lines = int(input('请输入要显示前几行:')) f1 = open(file_name) for...
3cecf72b087141a4517b77f0cb7e959958e156c6
thealmikey/Test_Practice
/sudoku_test.py
417
3.9375
4
"""This is a test to check the Validity of the funtion in sudoku.py""" import unittest from sudoku import check_sum class TestSudoku(unittest.TestCase): def test_sudoku(self): self.assertTrue(check_sum() == 45) # Checks that the function returns 45 self.assertGreater(check_sum(),0) # Checks that t...
5a9415cd368fcebe25f900cb9a0802b9f9faec10
FelicxFoster/Sources
/Learning/Python/Tkinter/tk12-4.py
207
3.640625
4
from tkinter import * m = PanedWindow(orient=VERTICAL) m.pack(fill=BOTH, expand=1) top = Label(m, text='top pane') m.add(top) button = Label(m, text='button pane') m.add(button) mainloop()
239b6f070013d417b25149dc4bf423d0e07bd4c1
FelicxFoster/Sources
/Learning/Python/Python数据结构与算法/算法/排序/7归并排序/mergeSort.py
831
4.03125
4
#归并排序法 #something wrong!? def mergeSort(k): list1 = k[:len(k)//2] list2 = k[len(k)//2:] if( len(k) > 1 ): mergeSort(list1) mergeSort(list2) merging(list1, list2) def merging(list1, list2): temp = [] i = j = 0 while( i<len(list1) and j<len(list2) ): ...
63b5362ec8355980ceddd442aa7a3609a74f56d6
FelicxFoster/Sources
/Learning/OtherLanguages/C/C练习题/Use Python/20.py
247
3.640625
4
h = 100 n = 1 s = 0 while n <= 10: s += h h = h / 2 #自动转为float n += 1 print('第10次落地时共经过%.4f米\n第10次反弹高度为%.4f米' % (s,h)) #格式化成定点数 .4指定小数点后的位数
061dfd701d9967b870f879b614dbe87fe17dc710
FelicxFoster/Sources
/Learning/Python/Python数据结构与算法/数据结构/树/pybtree_traversal.py
1,561
3.796875
4
# -*- coding: utf-8 -*- #Filename: pybtree.py #因为二叉树每个结点的儿子数是确定的 #因此用类的方式构建更好 class BTree: def __init__(self, value): self.left = None self.data = value self.right = None def insertLeft(self, value): self.left = BTree(value) return self.left def in...
d8caba87defcaedadccb189e7a345ef3308b54b6
SaiSree-0517/19A91A0517_SAISREE_CSEA_PYTHON_LAB_EXPERIMENTS
/2.1experiment.py
476
4.25
4
""" 2.1Implement a python script to compute distance between two points taking inp from the user (Pythagorean Theorem) """ x1=int(input("enter x1 : ")) x2=int(input("enter x2 : ")) y1=int(input("enter y1 : ")) y2=int(input("enter y2 : ")) result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5) print("distance between",(x...
7c605808dcd9fbc93692577403bbc40eb1f9bc58
imdadahad/multi-clipboard-automatic-messages
/mclip.py
557
3.828125
4
import pyperclip import sys TEXT = { "agree": "Yes, I agree. That sounds fine to me.", "busy": "Sorry, can we do this later this week or next week?", "upsell": "Would you consider making this a monthly donation?", } if len(sys.argv) < 2: print("Usage: python mclip.py [keyphrase] - copy phrase text") ...
9b0f854e314cefc5ce148106f3b2cf50260a1496
Hamsike2021/Practice_4
/5.py
105
3.546875
4
k = int(input('Введите высоту узора: ')) for i in range(0, k): print(f'#{" " * i}#')
ddd0e10352c241548a81bc74f6acee45e50542f8
onRightSide/level_2
/№3.py
481
3.5
4
import yaml info = {'books_name': ['book_1', 'book_2', 'book_3'], 'books_num': 3, 'books_price': {'book_1': '100€', 'book_2': '200₽', 'book_3': '300¥'} } with open('file.yaml', 'w', encoding='utf-8') as writing: yaml.dump(info, writing, default...
020fb0da8430a2787b679d2cb838f8af7e975d9c
radostina5454/homework
/Lyudmil_hwe6.py
373
3.515625
4
#!/bin/python3 def cmap(func, *args, **kwargs): return_value = [] return_value.append(func(*args, **kwargs)) print(f'{return_value}\n'+'-'*40) return return_value #################Example###################### if __name__ == '__main__': a = ['a', 'c', 'b', 's', 'd', 'g'] b = [1, 2, 5, 6, 8, 10, 16, 7, 8, 1...
9640282d80ff2a2992116d82190d2cc9dc28cc21
radostina5454/homework
/Lyudmil_hwe5.py
1,032
3.859375
4
#!/bin/python3 if __name__ == '__main__': n = input() p = 0 countercirc = 0 countersq = 0 countercur = 0 for p in range(len(n)): if n[p] == '(': countercirc += 1 elif n[p] == ')': countercirc -= 1 elif n[p] == '[': countersq += 1 elif n[p] == ']': countersq -= 1 elif n[p] == '{': counte...
84c1c34a71a7669c87511098f81ecbc402fa7880
SamerN88/DRE.94
/misc.py
740
3.9375
4
"""Miscellaneous functions.""" # Ciphers/keys/text can be saved manually in any text format, but this method expedites the saving process def save(string, file): """Saves ciphers or keys or any text to the given file path; more efficient than manual saving.""" save_file = open(file, 'w') save_file.write(...
ab8c96f455a002c9b311d5734aac115183cf0615
lc-leonesse/Python
/Coursera - Parte 1/Semana 6/jogoNim.py
6,209
4.09375
4
""" Você deverá escrever um programa na linguagem Python, versão 3, que permita a uma "vítima" jogar o NIM contra o computador. O computador, é claro, deverá seguir a estratégia vencedora descrita acima. Sejam n o número de peças inicial e m o número máximo de peças que é possível retirar em uma rodada. Para garantir...
98c525481eb9dee1e07e6cfec4290f35763ebae9
lc-leonesse/Python
/Coursera - Parte 2/Semana 4/lista_ordenada.py
358
3.953125
4
""" Escreva a função ordenada(lista), que recebe uma lista com números inteiros como parâmetro e devolve o booleano True se a lista estiver ordenada e False se a lista não estiver ordenada. """ def ordenada(lista): a = [] for x in lista: a.append(x) a.sort() if lista == a: return True...
0871b4c5aac16706dfb4b70491f35af78586be05
lc-leonesse/Python
/Coursera - Parte 1/Semana 7/funcaoPrimo.py
503
3.96875
4
""" Informar se o número que o usuário está digitando é primo ou não """ def primo(n): divisores = 0 i = 1 while i <= n: if n % i == 0: divisores = divisores + 1 i = i + 1 if divisores == 2: return True else: return False n = int(input("Digite um núme...
36fa9f53eb2f77227a6777c4fa9b2d17cb2be9c3
lc-leonesse/Python
/Coursera - Parte 1/Semana 5/maximo2.py
480
3.953125
4
""" Reescreva a função 'maximo' do outro exercício, que devolve o maior valor dentre dois inteiros recebidos, para que ela passe a receber 3 valores inteiros como parâmetros e devolva o maior dentre eles. Note que maximo(30,14,10) deve devolver 30 maximo(0,-1, 1) deve devolver 1 """ def maximo(x,y,z): if x > ...
810a4be116a530b1dbe0a360a3cc0df2a71b3b7e
lc-leonesse/Python
/Coursera - Parte 1/Semana 2/ConversorTemperatura.py
498
3.9375
4
""" Conversor de temperatura (Celsius e Fahrenheit """ temp = float(input("Insira o valor da temperatura: ")) tipo = input("Informe (C)elsius ou (F)ahrenheit: ") celsius = "c" farenheit = "f" if tipo == "f": conv = (((temp - 32) * 5) / 9) print("A temperatura informada é", int(conv), "graus celsius") elif...
4a255b356c51817df305eb3daf745661ae38156a
lc-leonesse/Python
/Coursera - Parte 1/Semana 4/primo.py
405
3.921875
4
""" Escreva um programa que receba um número inteiro positivo na entrada e verifique se é primo. Se o número for primo, imprima "primo". Caso contrário, imprima "não primo". """ n = int(input("Digite um número inteiro: ")) divisores = 0 i = 1 while i <= n: if n % i == 0: divisores = divisores + 1 i...
018cff8cfc329bb581c75c05edc627bca3362569
sumitkt/PythonPrograms
/oops3.py
751
3.875
4
#####class methods############ class Employee: no_of_leaves=34 def __init__(self,e_name,e_doj,e_dob): self.name=e_name self.doj=e_doj self.dob=e_dob @classmethod def change_no_of_leaves(cls,leaves): cls.no_of_leaves=leaves #here i will be using class method as alt...
2f6c9460af688402b4c218c4ab2838573f297ae2
SaM-0777/OOP
/Exercise.py
1,393
3.78125
4
##Exercise ##Problem 1 def Max(Num1, Num2): if Num1 >= Num2: return Num1 else: return Num2 print("Max Valuse : ", Max(20, 15)) ##Problme 2 def numberGame(Num): if Num % 3 == 0: return "number" elif Num % 5 == 0: return "Game" elif Num % 3 == 0 and N...
916e34cc0cce126412c21d0c4cb71fc640f2e73d
SaM-0777/OOP
/Strings.py
462
4.3125
4
##Strings in Python str1 = "Python is Easy" print(str1[:]) print(str1[::]) print(str1[:3]) ##Print first 3 characters print(str1[-2:3]) ##Slicing of String in Python s = "Computer Science" slice_1 = slice(-1, -6, -1) slice_2 = slice(1, 6, -1) slice_3 = slice(0, 5, 2) print(s[slice_1]) print(s[slice_2]) print(s[sli...
376ac59c86c6ffd58a0a3d7059ec5e815954a370
SaM-0777/OOP
/BinaryToDecimal.py
951
3.84375
4
class BinaryToDecimal: def Options(self): ch = int(input("Enter 1 for Decimal or 2 to Binary : ")) if ch == 1: self.Binary() elif ch == 2: N = int(input("Enter Decimal Number : ")) self.Decimal(N) else: print("Invalid Inp...
2624adf68591e885926d1a3fea74a5c4183b126d
SaM-0777/OOP
/Dictionary.py
1,781
4.59375
5
##Dict is an unordered set or collection of items or objects where unique keys are mapped yhe values ##These keys are used to access the corresponding paired value. While the keys are unique, values can be common and repeated ##The data type of a value is also mutable and can change whereas, the data type of keys mus...
6c85c106cc93146dada47bdace5cce255086292e
KenOtis/UniTest-Framework
/main.py
1,416
3.578125
4
import unittest from selenium import webdriver import page class PythonOrgSearch(unittest.TestCase): # a sample test class to show how page object works def setUp(self): #this will be run every time the test cases are run self.driver=webdriver.Chrome() self.driver.get("http://www...
aabc927d90eb74ca700eba1023f3c8a5e9923b87
cwern40/Algorithms
/making_change/making_change.py
716
4
4
#!/usr/bin/python import sys def making_change(amount, denominations): change = [0 for i in range(amount + 1)] change[0] = 1 for value in denominations: for more in range(1, amount + 1): if value <= more: change[more] += change[more - value] return change[amount] if __name__ == "__main_...
af013906acb2a3128ca481fb9dd89f769edb021d
Sjaiswal1911/PS1
/python/Exception_handling/Exception_argument.py
379
3.953125
4
# Exception as an argument # try: # You do your operations here # ...................... # except ExceptionType as Argument: # You can print value of Argument here... def temp_convert(var): try: return int(var) except ValueError as Argument: print ("The argument does not contain numbers\n", ...
9e8f6697e9e32dfefe4635dcf3326809af3a2230
Sjaiswal1911/PS1
/python/Phonebook/driver_final.py
1,287
4
4
from Phone_book import Phonebook decision = input("Do you wanna use the current DB ? \n Y/N:") if decision == 'Y' or decision == 'y': mode = 1 else : mode = 0 pb = Phonebook(mode) stmt = """Enter the proper index to utilise functions 1 : Add a new number 2 : Update a new Number 3 :...
29cbc1f0648551d2a0faa9fae7192dcca92e6f85
Sjaiswal1911/PS1
/python/IO/rename_remove.py
252
3.65625
4
# Renaming files # os.rename(current_file_name, new_file_name) import os # Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" ) # Removing files # os.remove(file_name) # deletes the file 'file_name' os.remove("text2.txt")
37ca6b7b8428c6adfd9502e68c4f355396ab4e2a
Sjaiswal1911/PS1
/python/contact book.py
5,210
4.125
4
class ContactBook(object): def __init__(self): self.contacts = [] self.contact_names = [] def add_Contact(self): print("Hello adding now.") # taking the mobile number as input number = input("Please enter the contact number :") while (len(number) != 10): ...
f0d0f136058ba7b063ff00fe6e4e9165f106d0c2
Sjaiswal1911/PS1
/python/Lists/methods_1.py
1,030
4.25
4
# LIST METHODS # Append # list.append(obj) # Appends object obj to list list1 = ['C++', 'Java', 'Python'] print("List before appending is..", list1) list1.append('Swift') print ("updated list : ", list1) del list1 # Count # list.count(obj) # Returns count of how many times obj occurs in list aList = [123, 'xyz', 'za...
bbd53f3e02a9457aeba7d71bc4f82270ae11c0e4
satheesh22g/Infitq-programs-Optimized
/_substring_.py
149
3.8125
4
ip=input() low=ip.lower() x="" for i in ip: if i.lower() not in x.lower(): x=x+i if len(x)>=3: print(x) else: print("X")
30d2883d97b00f87c0b54ab5fa24f8d2d500fda2
nchuynh2/projectEuler
/problem4.py
234
3.828125
4
palindrome = 0; for a in range(1,1000): for b in range(1,1000): product = a*b; string = str(product); if string == string[::-1] and product > palindrome: palindrome = product; print(palindrome)
9d73da51fdb379e9d3b163a98f32af5ae330c875
mwhittaker/polynomials
/polynomial.py
2,499
3.609375
4
from typing import Any, Callable, Union class Polynomial: PolynomialLike = Union[int, float, 'Polynomial'] def __init__(self, f: Callable[[int], float]) -> None: self.f = f def _to_poly(self, x: PolynomialLike) -> 'Polynomial': if isinstance(x, Polynomial): return x el...
91f52f42163a64d652153479b694b9ce65fc4d31
iamqingmei/Leetcode-Practice-Python
/345. Reverse Vowels of a String(Easy).py
775
3.984375
4
""" Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not include the letter "y". """ class Solution(object): def reverseVowels(self, s): #79ms 88.6% ...
d2540428d5fc168535431d51bc7003b4b5e71137
iamqingmei/Leetcode-Practice-Python
/342. Power of Four (Easy).py
648
3.828125
4
""" 342. Power of Four Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. """ class Solution(object): def isPowerOfFour(self, num): #59 ms 30.6% """ :type num: int :rtype: bool ...
d4108d8747f70780453e880fbcb78c5c86f28532
JAI-2002/narcissistic-numbers
/main.py
955
3.890625
4
def narcissistic(num): sumOfDigits = 0 digits = [int(ch) for ch in str(num)] power = len(digits) for i in range(len(digits)): sumOfDigits += digits[i]**power return (sumOfDigits == num) # ------------------ TEST ------------------ print('7 is narcissistic: ' + str(narcissist...
15449e1043649cf221e878405e1db4437bb74bfb
manish711/ml-python
/regression/multiple_linear_regression/multiple_linear_regression.py
1,688
4.125
4
# -*- coding: utf-8 -*- """ @author: manishnarang Multiple Linear Regression """ #Importing Libraries import numpy as np #contains mathematical tools. import matplotlib.pyplot as plt #to help plot nice charts. import pandas as pd #to import data sets and manage data sets. #Importing Data Set - difference bet...
8396df8bea56862b85638c27cad0a24dfabfdd72
satoshi6380/Hangman
/Hangman/task/hangman/hangman.py
1,137
3.765625
4
# Write your code here import random from string import ascii_lowercase li = ('python', 'java', 'kotlin', 'javascript') answer = random.choice(li) word = '-' * len(answer) typed = set() print('H A N G M A N') while input('Type "play" to play the game, "exit" to quit:') != 'play': if 'exit': exit() count...
e1d3ace3be50540ebbc72635ab55eb319d612f2a
nicky1503/Python-OOP
/defining_classes/guild_system_7/project/guild.py
1,097
3.578125
4
from defining_classes.guild_system_7.project.player import Player from typing import List class Guild: def __init__(self, name: str): self.name = name self.players: List[Player] = [] def assign_player(self, player: Player): if player in self.players: return f"Player {player...
c3710c71ffc0ae730f7772d1482e5a3388645b74
wwest4/tdd-by-example
/part-1/monays/money.py
1,776
3.765625
4
class Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency def times(self, multiplicand): return Money(self.amount * multiplicand, self.currency) def equals(self, other): return self.amount == other.amount and self.currency is other.cur...
c326dc8d4f36ffd70faba62ce499ab0be9f3dfcb
minat-hub/myprojects
/binary search algorithm.py
1,528
4.0625
4
'''a_list = [2, 4, 6, 8, 10, 12, 42, 40, 48, 60, 72, 74] item = int(input("Enter a number: ")) if item in a_list: position = a_list.index(item) print("Your item is at position", position) else: print("Not found in the list") # Recursive method def binary_search_recursive(array, element, start, end): ...
7312689061a008c1b4c8dbc6a73b2849a4754776
YanisKachinskis/python_basic_200120
/lesson5/hw3.py
1,073
4.3125
4
# homework lesson: 5, task 3 """ Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. Пример файла: Иван...
ba03100376a78109c3eba450db0d767b374480a0
YanisKachinskis/python_basic_200120
/lesson5/hw6.py
1,723
3.859375
4
# homework lesson: 5, task 6 """ Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содер...
81cfd1cc7fc648bf530101b8dd9af3e92b220d9b
YanisKachinskis/python_basic_200120
/lesson6/hw1.py
2,935
3.828125
4
# homework lesson: 6, task 1 """ Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый. Продолжительность первого состояния (красный) составляе...
cda4893eaa642ff053f86194f8494525bf7bc112
YanisKachinskis/python_basic_200120
/lesson4/hw2.py
624
4.15625
4
# homework lesson: 4, task 2 """ Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. """ my_list = [1, 7, 6, 13, 34, 23, 9, 11] new_my_...
937cc1de41851438ed2658dab2fdc734a737eecb
YanisKachinskis/python_basic_200120
/lesson8/hw7.py
1,401
4.0625
4
# homework lesson: 8, task 7 """ Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число», реализуйте перегрузку методов сложения и умножения комплексных чисел. Проверьте работу проекта, создав экземпляры класса (комплексные числа) и выполнив сложение и умножение созданных экземпляров. П...
7c64c664f4b889dc69e75daafc48a20a0a410428
robertdanyi/mlp_from_scratch
/mlp_multiclass_spiral_data.py
5,792
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ toy multilayer perceptron for classifying a "spiral dataset" reference: https://cs231n.github.io/neural-networks-case-study/ """ import numpy as np import matplotlib.pyplot as plt import activation_functions as af from tqdm import trange N = 5000 # nr of examp...
b2f0932d5edc727511fe0f2ab95e7e55dc904c4f
pranjalraj/random_password_generator
/passgen.py
964
3.8125
4
import string import random if __name__ == "__main__": print("Welcome to password generator. Help us build your password by answering the following questions with a y or n (lowercase)") a=input("Do you want lowercase letters in your password?") b=input("Do you want uppercase letters in your password?")...
9aae48aeae5c81ef96ed1e28e6764e67a89fc4fa
FordMcLeod/witAdmin
/python/rockpaperscissors.py
2,234
4.53125
5
# Rock Paper scissors demo for python introduction. SciCamps 2017 # Extentions: Add options for lives, an option to ask the player to play again. # 2 player mode. Add another option besides rock/paper/scissors. etc. import random import time computer = random.randint(0,2) # Le...
8f65dc4ae113bb9deb6fac3b304fcfe4d770e68d
ShaoQiBNU/Topk
/heap_sort_ascend.py
1,988
3.796875
4
########## 堆调整函数 ########### ''' 实现num[j]~num[n]的调整,使其满足小根堆的性质 ''' def heapadjust(num,j,n): ##### j节点的左孩子 ##### i=2*j ##### j节点的值 ##### temp=num[j] ##### 从j节点开始调整 ##### while i<=n: ##### 判断j节点是否有右孩子以及比较左右孩子的大小 ##### if (i+1)<=n and num[i]>num[i+1]: ##### 如果左孩子>右孩子,则i=i+1,这样i的值是最小孩子的下...
c23f60d5e88146dccbe8e42c0ef730c216aee227
pritilively/python
/python.py
200
3.671875
4
sentence=input("enter a sentence") p=0 k=0 for a in sentence: if a.isdigit(): p=p+1 elif a.isalpha(): k=k+1 else: pass print("letters", p) print("digits", k)
8630694f4720cd44c81a43cc5c6e248168cb5dbe
gxdaf/PCA-SI-2020-02
/Protótipo/cod/main.py
1,453
3.796875
4
import questions data = questions.Data def ask(): wallet_points = 0 for key, value in data.items(): #Informa a chave da pergunta e o seu valor question = '{0}: {1}'.format(key ,value['question']) print(question) for optionKey, optionValue in value['options'].items(): ...
b8a02298b0f9644f32373df89bc6f42e16492f12
adamnovak/sphinx-autodoc-example
/src/hello.py
481
3.9375
4
""" This is a module docstring """ class Hello(object): """ This is a Hello class docstring """ def __init__(self, name): """ This is an __init__ method docstring. Creates a new :class:`Hello` instance. :param name: name for the hello :type name: str "...
60297aa1e2fa8e2b78b65b2da74b7bbd1c5bc8aa
mertmetin/projecteuler
/ProjectEuler/src/21.py
327
3.578125
4
def sum_divisors(num): sum = 0 for i in range(1,num): if num % i == 0: sum+= i return sum sumOfAmicables = 0 for i in range(0,10000): a = sum_divisors(i) b = sum_divisors(a) if i == b: if i != a: sumOfAmicables+= i print sumOfAmicables ...
5aa26b25873ca04dbdb1e586502329683348b30b
RyuAsuka/python-utils
/mycalendar.py
3,664
4.09375
4
import sys import time weekday = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'] def str_week(year, month, day): """ Calculate a specific day is what day of a week. :param year: The year :param month: The month :param day: The day :return: The weekday of this date. """ if m...
d81c8918a31ad2299039cdcc2517d1eeacb72599
RyuAsuka/python-utils
/color-code-change.py
2,192
4.125
4
import sys usage = """ Usage: python color-code-change.py <rgb|hex> <number> Arguments: rgb: Convert RGB color to hex number style. hex: Convert hex number color code to RGB color number. Examples: python color-code-change.py rgb 100 90 213 -> #645AD5 python color-code-change.py hex...
6fb000907798ff6426fd8fc933ecf2cc5656ab40
ravularajesh21/Python-Tasks
/Count number of alphabets,digits and special characters in STRING.py
532
4.28125
4
# Count number of alphabets,digits and special characters string=input('enter string:') alphabetcount=0 digitcount=0 specialcharactercount = 0 for x in string: if x>='A' and x<='Z' or x>='a' and x<='z': alphabetcount = alphabetcount + 1 elif x>='0' and x<='9': digitcount=digitcou...
c7cf39004c6961400afcb2983112060aba156f44
ravularajesh21/Python-Tasks
/Palindrome 1.py
553
4.5
4
# Approach 1 date = input('enter the date in dd/mm/yyyy format:') given_date = date.replace('/', '') reversed_date = given_date[::-1] if given_date == reversed_date: print(date,'is palindrome') else: print('It is not palindrome') # Approach 2 day = input('enter day:') month = input('e...
147f28959b71aff8263c49d10e03f3efa27276a6
ravularajesh21/Python-Tasks
/Multiple Inheritance 1.py
2,199
3.828125
4
# Exm 1 : class Bank: def __init__(self,employee,role): self.employee = employee self.role = role def Office(self): print('My name is',self.employee,'employee in this bank') print('Role is',self.role) class Bank2: def __init__(self, employee, role,experience,sal...
ceabcbfdb9a563d8d905618296ba7a7d7b6a9f4d
ravularajesh21/Python-Tasks
/Tuple.py
1,316
3.96875
4
t1 = (10) print(t1) print(type(t1)) t2 = ('Python') print(t2) print(type(t2)) t1 = (10,) print(t1) print(type(t1)) t2 = ('Python',) print(t2) print(type(t2)) t1 = (10,20,'rajesh',2.5,10+25j) print(t1) print(type(t1)) t2 = tuple(range(10,110,10)) # to get the output in tuple ...
8ec195327f2ea68141cd615300ebf7be8108cc6c
ravularajesh21/Python-Tasks
/Inner class.py
3,690
3.96875
4
# Aproach 1: class A: def __init__(self,name,age): self.name = name self.age = age def Raj(self): print('This is',self.name) print('Im',self.age,'old') class B: def __init__(self,DOB,sal): self.DOB = DOB self.sal = sal def R...
7ad865bbaf37fcd44a2a859455503ccd184db700
ravularajesh21/Python-Tasks
/overidding.py
736
3.921875
4
# Method overriding class P1: def __init__(self,name,gender,age,place,interest): self.name = name self.gender = gender self.age = age self.place = place self.interest = interest def raj(self): print('My name is',self.name) print('Im',self.gende...
29adf4df701597e28f158c8b444dae39ce4e616e
ravularajesh21/Python-Tasks
/Overriding.py
1,337
3.53125
4
# Overriding class cricket: print('Welcome to World cup matches') def __init__(sachin,player_name,runs,wickets,catches): sachin.player_name = player_name sachin.runs = runs sachin.wickets = wickets sachin.catches = catches def ODI(sachin): print('Best opene...
7d259ad36999ba958bd3dba8c9c980294d107a6e
alyasfya98/Image-Processor
/utility.py
2,357
3.765625
4
import numpy as np '''Second derivative of x it takes a matrix as parameter and returns a matrix ''' def derive2x(mat, m): d2x = np.zeros((m, m)) for i in range(0, m-1): for j in range(0, m-1): d2x[i, j] = float(mat[i+1, j]) + \ float(mat[i-1, j])-2*float(mat[i, j]) r...
10f037eeccff27cba24f24d3d61b80f6f189d2f3
shbm/project_euler
/p14.py
540
3.609375
4
def compute(): ans = max((i for i in range(1, 1000000)), key=collatz_chain_length) return str(ans) collatz_cache = {1: 1} def collatz_chain_length(x): if x not in collatz_cache: if x % 2 == 0: y = x // 2 else: y = x * 3 + 1 collatz_cache[x] = collatz_chain_l...
52ed55fd66a0fd09a0ad2b10ac681e25cf10894a
shbm/project_euler
/9.py
710
4.09375
4
# PROBLEM 9 # Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a**2 + b**2 = c**2 # For example:- # 3**2 + 4**2 = 9 + 16 = 25 = 5**2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product a*b*c #!/usr/bin/env python # -*- coding: utf-8 -*- ...
f296bf761523949ed9dbb881af9c84bdb796023e
shbm/project_euler
/34.py
767
3.8125
4
# Problem 34 # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # Find the sum of all numbers which are equal to the sum of the # factorial of their digits. # Note: as 1! = 1 and 2! = 2 are not sums they are not included. import math cache = {} def fact(x): return cache.setdefault(x,math.factorial...
7a0d274824b197c5c767b1e67fdc9f5de6dba470
MagusDei/massive-ironman
/Robottiohjelmointi_ARDroneProject_Valorinta/Quadcopter.py
1,254
3.53125
4
# Essentially defining the python equivalent of an "interface", # an empty class, for controlling a flying robot of some kind, then # defining a class that implements the methods for controlling # the AR drone in particular. This is so the code can easily be # ported to other drones. import time, ps_drone #class Flyi...
ad4a6cb067c98baaf6a47da942d4084caea85d9d
bstenm/generic_flask_restful_api
/code/create_tables.py
315
3.734375
4
import sqlite3 connection = sqlite3.connect('data.db') cursor = connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS stores (id INTEGER PRIMARY KEY, name text, feature1 text)") cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)") connection.close()
8893c3499948795a1bd68f9b6b6407505a9950bd
yjv/PythonProjects
/censor.py
595
3.8125
4
__author__ = "Reuven Deray" def censor(text, word): """return text with word censored out returns string""" if text == '' or word == '': result = "Did you fill everything in?" else: result = ("*" * len(word)).join(text.split(word)) return result if __name__ == "__main__": my...