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
ca2b09253dc6407dcb86409ed6b044d352307fbe
yechan2468/AccountManagementSystem
/client.py
1,295
3.5
4
# python 3.8.3 ############################################################################################################################################ # <Account Management System> # This program is for handling financial tasks; More specifically, you can input, store, inquire account informations(revenue, expen...
679714deadd68cf3ab40cef82c179dcf263e6d01
Larry1524/w10-css225game-
/chapter3.py
1,469
4.0625
4
import random import battle1 import time def chapter3(): time.sleep(1) print("*you set out to look on your own*") time.sleep(1) print("You come across two roads, You see claw scratches on one and the other has shredded fabric. which do you follow?") road = int(input("Type 1 for claw road...
f6703d5667fbc553b43ca1afb6174da10c771f4c
yoobarhaha/pyhonHW1-github.io
/18.py
325
3.65625
4
class Calculator: def __init__(self): self.value = 0 def add(self,val): self.value += val class MaxLimitCalculator(Calculator): def add(self,val): super().add(val) if(self.value>=100): self.value=100 cal = MaxLimitCalculator() cal.add(50) cal.add(60) print(cal.v...
f72418ec64cca449601bd8deb12408f58387c498
astsu-dev/exapi1
/exapi/utils/numbers.py
605
3.609375
4
"""Has utils for work with numbers.""" import decimal from decimal import Decimal from typing import Optional def decimal_to_str(n: Decimal, precision: Optional[int] = None) -> str: """Converts decimal `n` number to string with `precision`. Args: n (Decimal) precision (Optional[int]): number...
0fe5a365520b29533817e0267a5120be9ece8d74
nahusznaj/Hackers_News_dataquest
/count.py
2,481
3.84375
4
import read df = read.load_data() # Before moving on I run some checks that are commented now: #print(df.head(3)) #print(df['headline'].iloc[6]) #print(df['headline'].dtype) #In order to count which words appear most often in the headlines I will combine all the values of the column headline into one string; then I ...
c005cad4848bc63c41e3b85d5d1f828b19245158
tengshiquan/AgarAI
/a2c/hyperparameters.py
3,253
3.5
4
""" File: hyperparameters Date: 2019-07-25 Author: Jon Deaton (jonpauldeaton@gmail.com) """ import json class HyperParameters: """ Simple class for storing model hyper-parameters """ def __init__(self): self.seed = 42 # to fill in by sub_classes self.env_name = None self.En...
6c76a0442f2a905987e828363062f5d38792f5da
kiranjv888/file_search
/search_file.py
1,903
3.671875
4
#!/usr/bin/env python3 import os import csv import sys import socket # search recusively where the file is existing def findAll(name, path): result = [] for root, dirs, files in os.walk(path): if name in files: result.append(os.path.join(root, name)) return result #read the search pa...
190fa8ca290c8d9970f79e29392f50f79d2f4446
florespadillaunprg/t10_flores.padilla
/olazabal/libreria.py
4,560
3.546875
4
def validar_entero(n): if (isinstance(n, int)): return True else: return False def validar_rango(n, ri, rf): if ( validar_entero(n) == True): if (n >= ri and n <= rf): return True else: return False else: return False def pedir_numero(msg...
beb4470dd98b3af380b85af1eafdacb84442460b
florespadillaunprg/t10_flores.padilla
/olazabal/app5.py
667
3.671875
4
import libreria #MENU PARA ELEGIR MARCAS DE LAPTOPS def agregar_marca(): libreria.pedir_marca("Ingrese la marca:") print("Se agrego marca") def agregar_memoria(): libreria.pedir_memoria("ingrese cantidad de memoria:") print("se agrego cantidad de memoria ") #MENU GENERAL opc=0 max=3 while(opc!=3): ...
2ed357cd2358e7287788930c6bf1e3a6df435285
nguyentuanvn/Algorithm
/Course3/3.1.3_HeapMST.py
1,508
3.8125
4
""" Coursera Algorithm Programming Assignemnt 3.1.2: Prim's Minimum Spanning Tree Algorithm. Heap-based implementation by storing unprocessed vertices in heap. @author: Tuan M. Nguyen """ from heapq import heappush,heappop,heapify def MST(G,num): unprocessed = [] processed = [] for index in range(2,num+1)...
225eee86e5a0d6e329b0d650f22111f278e2f0bc
nguyentuanvn/Algorithm
/Course4/4.1_APSP.py
4,937
4.09375
4
""" Coursera Algorithm Programming Assignemnt 4.1: All pairs shortest path implement with 1. Floyd-Warshal Algorithm 2. Johnson's Algorithm using reweighting edges 3. Optimized Johnson Algorithm For optimized Johnson Algorithm, stop after running Bellman-Ford on graph with extra vertex s.The minimum among shortest pa...
908dae9898a024bbc81003aae85c0acd0028ea8c
guilhermegoesgarcia/Python
/Manipulacao_String/Introducao_colection.py
88
3.53125
4
idades = [39,30,27,18] idades.append(int(input("Digite Idade:"))) print() print(idades)
6c66de63e7ae00e59220d24260ff47a8aa5d8d63
guilhermegoesgarcia/Python
/Listas_Tuplas/introducao.py
3,182
3.90625
4
' Objetos próprios' class ContaCorrente: def __init__(self,codigo): self.codigo = codigo self.saldo = 0 def deposita(self, valor): self.saldo += valor def __str__(self): return "[>> Código: {} --- Saldo: {} <<]".format(self.codigo,self.saldo) conta_do_gui = ContaCorren...
1b6a9a95e4f7d9ee1ee6d85e22d8194a41231f51
RudyHarun99/Remedial_Alamat_Email
/02AlamatEmail.py
700
4
4
x = input('Input email: ') def tes(x): x = x.replace('@', ' ') x = x.replace('.', ' ') xPisah = x.split(' ') if len(xPisah) != 3: return 'EMAIL INVALID' else: namaUser = xPisah[0] namaHosting = xPisah[1] ekstensi = xPisah[2] if ekstensi.isalpha() == False or...
73168e14ec5dacf536c2f622ffaaa5febe562dc2
tayyabmalik4/Numpy_python
/08_trignomatic_functions_numpy_practical_7.py
3,312
4.0625
4
# *******************trignomatic functions in numpy************** # //////sin(),cos(),tan() functions using numpy as python # /////if we want to plot the graph than we use matplotlib # /////matplotlib is a python module which we use to plotting the graph using values # ********NOTE(sec,cosec,cot values are not defined...
a74a851d35b2a8089651be65f72dcd09968a287e
abrar-farhad-nirjhar/Five-mini-python-programming-projects
/Random_game.py
786
3.921875
4
import random def match_random_and_guess(guess, to): to = random.randint(0,to) if guess==to: return True else: return False def main(): print("Enter the range:") to = input() to = int(to) print("Enter your guess:") guess = input() guess = int(guess) res...
ac6c50740e7e886a9b75087b1e47cf22bb854d02
Errege/Tensor
/HomeWork_1/Task_2.py
375
3.90625
4
def append_word_to_age(): number = input("Введите целое число в диапазоне от 0 до 200: ") if int(number) % 5 == 0 or int(number) in range(6, 20): print(f"{number} лет") elif int(number) % 10 == 1 & int(number) != 11: print(f"{number} год") else: print(f"{number} года") append_...
294b824c311e56bb5f5b40e7b85d2d70f3098d6f
robinrob/python
/practice/enum.py
602
3.625
4
#!/usr/bin/env python3 from enum import Enum from operator import attrgetter class MyEnum(Enum): one = '1' two = '2' three = '3' enum = MyEnum.one print('enum: %s' % enum) val = MyEnum.one.value print('val: %s' % val) name = MyEnum('1').name print('name: %s' % name) enum = getattr(MyEnum, name) pri...
d597e7d2be110cd68d2c3eff12b8ba4f1af07ca5
robinrob/python
/practice/codility/binary_gap/binary_gap.py
549
3.9375
4
#!/usr/bin/env python3 # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def binary_gap(N): # write your code in Python 3.6 binary = list(bin(N)[2:]) max_sequence = 0 sequence = 0 for digit in binary: if digit == '1': if sequen...
c80ded33bb688fdf89c3f50450128e3430cf5d80
robinrob/python
/practice/nester/nester.py
236
4.09375
4
"""This module contains a list-printing function that uses recursion to print each item in a list.""" def print_item(item): if (isinstance(item, list)): for i in item: print_item(i) else: print(item)
cb0ae7e3a71550c42711351027a21917668560ba
robinrob/python
/practice/print_reverse.py
441
4.125
4
#!/usr/bin/env python class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def ReversePrint(head): if head is not None: if head.next is not None: ReversePrint(head.next) print head.data head = Node(data=0) one =...
85eea12126e026e8985f10e85b20d4798a2ff6a0
robinrob/python
/practice/hackerrank/deque/deque.py
603
3.78125
4
#!/usr/bin/env python3 from collections import deque def do_command(deque, command): parts = command.split() action = parts[0] if action == "append": item = parts[1] deque.append(item) elif action == "appendleft": item = parts[1] deque.appendleft(item) elif a...
552344c202bf99e4a981d47c7fdf00c1fb023dbf
robinrob/python
/practice/sparse_arrays.py
280
3.59375
4
#!/usr/bin/env python def _query(strs, query): ans = sum([ 1 for s in strs if query == s ]) print str(ans) n = int(raw_input()) strs = [] for i in range(n): strs.append(raw_input()) q = int(raw_input()) for i in range(q): _query(strs, raw_input())
8024224b04957412177632c9fd6c23c2b81bfbe0
robinrob/python
/practice/class_instance.py
355
3.640625
4
#!/usr/bin/env python class Obj1: def __init__(self): pass def hello(self): print 'hello' class Obj2(object): def hello(self): print 'hello' class Obj3: def hello(self): print 'hello' Obj1().hello() Obj2().hello() Obj3().hello() cls = Obj1().__class__.__name__...
237a9ccbbfa346ff3956f90df5f52af4272b9291
robinrob/python
/practice/postorder_traversal.py
727
4.1875
4
#!/usr/bin/env python class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right """ Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.data (the value of the node) """ lr = Nod...
3b33e39e6fb8087a77d9b660c43b41d6b69d9985
robinrob/python
/practice/sets/test_robinset.py
7,250
3.515625
4
import unittest from robinset import RobinSet class TestRobinSet(unittest.TestCase): def test_new_set_should_be_empty(self): set = RobinSet() self.assertEquals(0, len(set)) def test_should_add_item_when_empty(self): set = RobinSet() value = 0 set.add(value) ...
e556b37e9c1b363bf9408c089802659de9d0162d
arrowtype/typelab-2021
/example-source/build-helpers/add-familyname-suffix.py
4,146
3.515625
4
""" A script to add suffixes to the family names of a font binary (TTF/OTF). For example, this can add a suffix like "Var" to a variable font. USAGE: python3 example/build-helpers/add-familyname-suffix.py <font_path> -s <suffix> """ from fontTools.ttLib import TTFont NAME_IDS = { 1: 'familyNam...
95a97a5d4eb826109e24835d6db1824b4c368fdf
xuting1108/Automate-the-Boring-Stuff-with-Python-EXAMPLES
/exemplosLivro/TorF.py
271
3.890625
4
#page 82 nome = '' while not nome: print('Insira seu nome: ') nome = input() print('Quantos convidados voce terá? ') numConvidados = int(input()) if numConvidados: print('Tenha certeza que vc tera o numero de qurtos para todos os convidados') print('Feito!')
7cb5f566dddc0b8877d37c7e0b3e141e09f0828e
gurpreet-ai/digital_libraries
/Assignment_2/adaptive_arithmetic_encoding_decoding.py
1,237
3.78125
4
import random # simple arithmetic encoding and decoding algorithn def encode(string, probabilities): lower_bound = 0 upper_bound = 1 for symbol in string: symbol_lower_bound = probabilities[symbol][0] symbol_upper_bound = probabilities[symbol][1] # print symbol_lower_bound, symbol_upper_bound lower_bound ...
2217d0d465da844e4e358a7c16fa774f71511308
blckOS/blckOS
/shiftKey.py
382
4.03125
4
import string def shift(char): shiftDict = {"1":"!","2":"@","3":"#", "4":"$","5":"%","6":"^", "7":"&","8":"*","9":"(", "0":")","-":"_","=":"+", "[":"{","]":"}","\\":"|", ";":":", "'":"\"", ",":"<", ".":">","/":"?"} if (char in string.punctuation or char in string.digits): return shiftDict...
9260aeff0cfc452e2825bbd511d466322da71069
shengdade/PythonAlgorithms
/stru.py
6,863
4
4
# Module for ADT(abstract data type) # Implementation of a stack class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): ...
f018fd6b49d3cb72598c89c12717dc27506a542a
balirh12/hajarbalirh-ateliers
/atelier11/exercice51.py
279
3.78125
4
#compter les chiffres d'un nombre def compter(num) : #condition d'arret if num<10 : return 1 else : return 1 + compter(num/10)\ #demander un nombre de l'utilisateur nbr = int(input("Entrez un nombre : ")) #afficher resultat print(compter(nbr))
57aa12f8b441b9a85dddb12fb7573713372b3515
CameronWitz/Intro-To-AI
/Labs/Lab4/src/student_code.py
3,822
3.6875
4
import common class variables: counter=0 def finished(sudoku): done = True for i in range(9): for j in range(9): if sudoku[i][j] == 0: done = False return done def findNext(sudoku): found = False y = None x = None for i in range(9): for j in range(9): if sudoku[i][j] == 0: ...
cbc3da725d0fdc151a184889043ac179f3f764bb
edureimberg/learning_python
/first.n.squares.py
216
3.765625
4
#função clássica def get_squares(n): return [x ** 2 for x in range(n)] print(get_squares(10)) #Generator def get_squares_gen(n): for x in range(n): yield x ** 2 print(list(get_squares_gen(10)))
40ec2b8e8774583d2ae4163952c80005aff4a0ee
edureimberg/learning_python
/exercicios/ex9.py
241
3.625
4
dias = int(input("Digite o número de dias que o carro foi alugado: ")) km = int(input("Digite a quilometragem percorrida: ")) preco_total = (60 * dias) + float(0.15 * km) print("O total a ser pago pelo aluguel do carro é:", preco_total)
8192bb766b91dcaddb9a4b9e9999c16635303a46
rocity/atm-app
/atm.py
2,973
3.875
4
class Machine(object): def __init__(self): self.stored_money = 1000 self.members = [ { 'name': 'Kurdapyo Cholo', 'pin': 6996, 'balance': 300 }, { 'name': 'Ben Dover', 'pin': 1111, ...
71e04bc30953211c391db36994b7375c3de21f86
KyleLawson16/mis3640
/session03/type-demo.py
349
3.96875
4
''' Age Validator w/ Error Handling ''' age = input('Please enter your age: ') def check_age(age): try: age = int(age) if age >= 21: print('yes, you can.') else: print('sorry, you cannot.') except: age = input('Please enter a valid number: ') ch...
1c047ac76bcb2fa3e902d3f5b6e0e145cc866c5d
KyleLawson16/mis3640
/session02/calc.py
871
4.21875
4
''' Exercise 1 ''' import math # 1. radius = 5 volume = (4 / 3 * math.pi * (radius**3)) print(f'1. The volume of a sphere with radius {radius} is {round(volume, 2)} units cubed.') # 2. price = 24.95 discount = 0.4 copies = 60 cost = (price * discount) + 3 + (0.75 * (copies - 1)) print(f'2. The total wholesale cos...
cbab4f84594ecde4e3f82646160cde05c7a9e51a
atticusg/SummerProject
/load_test.py
400
3.546875
4
import json import random num = int(input("How many examples would you like to see?")) examples = [] with open("test", "r") as f: lines = f.readlines() for line in lines: examples.append(json.loads(line)) count = 0 for example in examples: if count == num: break print(example["sentence1"...
78baac8e4e62dd064a5dadbc012d82de6f2ff94d
mukhtarabdelsalam/exam_project_nice_body
/main.py
1,250
3.984375
4
from Protain import Protain from Calories import Calories from Carb import Carb from Fat import Fat from Water import Water def main(): weight = float(input("Please enter your weight:\n")) x = int(input("Are you : 1-lightly_active, 2-moderately_active, 3-very_active, please enter 1, 2, or 3\n")) y = int(i...
302333b5dacd99c59ef182e8882762c38d21f0d1
MarkTLite/Machine_Learning
/Practice/ML(iLabs)/01_Pandas/2_pandas.py
794
3.5
4
# -*- coding: utf-8 -*- """ Created on Sun May 24 15:14:12 2020 @author: Mark_T """ import pandas as pd #import matplotlib.pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') web_stats = {'Day' : [1,2,3,4,5,6], 'Visitors' : [23,56,77,55,44,54], 'Bounce_Rate' :...
e59d5266beb5766df2996f5a9911a93a90855b4a
zhangli709/algorithm009-class01
/Week_09/062.py
813
3.65625
4
# 062 不同路径 """ 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? """ # 思路: dp[i][j] = dp[i-1][j] + dp[i][j-1] class Solution: def uniquePaths(self, m: int, n: int) -> int: # 1 .定义状态方程 dp = [[0] * n for _ in range(m)] # 2. 定...
6a9365ca8734b830ba1e730d03459df278ead019
zhangli709/algorithm009-class01
/Week_09/917.py
613
3.84375
4
# 917 仅仅反转字母 """ 给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。 """ class Solution: def reverseOnlyLetters(self, S: str) -> str: index_dict = {} list1 = [] for index, value in enumerate(S): if not value.isalpha(): index_dict[index] = value ...
74721f2b1e6b878f08e600e38956db9e66ec60ad
KrzysiekJa/PITE-2019--python
/scan.py
461
3.53125
4
import socket IP = input("Input IP: ") Ip_range = input("Range (example: 5-100): ") port_low = int(Ip_range.split("-")[0]) port_high = int(Ip_range.split("-")[1]) print("Scan", IP, "from", port_low, "to", port_high) for port in range(port_low, port_high + 1): s = socket.socket(socket.AF_INET, socket.SOCK_...
67cf1c78b300282078a2e00abafe7b8f81d4f837
roshandcoo7/DSA
/Hashing/Hash_chaining.py
723
4.25
4
# Function to display hash table def dispay(hashTable): for i in range(len(hashTable)): print(i, end = " ") for j in hashTable[i]: print("-->", end = " ") print(j, end = " ") print() # Creating hash table as a nested list HashTable = [[] for _ in range(10)] # Hash ...
a505d2e7912bd22c14d95df0e29c7caec4e28ac4
roshandcoo7/DSA
/Tree/BST.py
2,578
4.125
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # INSERTING AN ELEMENT TO THE TREE def insert(self, data): if self.data is None: self.data = data else: if self.data <= data: if s...
b3fde42fbda00a48a193c3b3d5d871fd5c3be5fd
maxchrist/multi-party-codefile-encryption
/admin_encrypt_and_sign.py
5,448
3.53125
4
''' This code should be run after the administratior receives a public key from a user who wants to participate in the project. The code will use the users public key to publicly encrypt the symmetric key. It will also create a digital signature using the administrators public and private signature keys...
e5ce7db3e99098453de532c7ea7c5b91696d0184
wsilveiraf/effective-memory
/Lista04/exercicio37.py
452
3.890625
4
def entradaPl(frase): palavras = frase.split() junto = ''.join(palavras) def palindromo(junto): inverso = '' for letra in range(len(junto) -1, -1, -1): inverso += junto[ĺetra] if inverso == junto: print('Temos um palindromo') else: print('Não temos um palidromo') de...
31432fe1bbfd95541a346dd688a624ea18a33478
ss4328/Machine-Learning
/Machine Learning - Drexel/dimentionality reduction/src_python/venv/lib/python3.7/site-packages/preprocessing/spellcheck.py
4,759
3.65625
4
''' Spelling checker module: ''' import re from os import path from collections import Counter from preprocessing.errors import InputError EN_ALPHABET = 'abcdefghijklmnopqrstuvwxyz' WORD_DISTRIBUTION = Counter(re.findall(r'\w+', open(path.join(path.dirname(__file__), 'data/bnc_wiktionary_corpus.txt')).read().lower...
31e3576652b18a0deb112eebe8f6370cf5dadcfe
jimmyshuyulee/duke-ece590-algorithm-projects
/ece590_project3/project3.py
3,262
3.625
4
""" Math 590 Project 3 Fall 2019 Partner 1: Shu Yu Lee Partner 2: Fang Feng Date: 11/15/2019 """ # Import math and p3tests. import math from p3tests import * ################################################################################ """ detectArbitrage output a single list of vertex ranks co...
569ec018281543d8d808e37c78201408cf77d15a
DataEnggDataSc/HadoopCodes
/PySpark/Movielens Dataset Processing.py
5,652
3.515625
4
# Import necessary modules from pyspark.sql.functions import * # Define dataset location home_dir = "/user/subhtech099501/Movielens/" # Create a dataframe on movies.csv file movies = spark.read.format("csv") \ .options(header = True) \ .options(inferSchema = True) \ .load(home_dir + "movies.csv") \ .cache() # Keep th...
f8e8877443004af3a93c8e551545b694f407ff3d
CQU-yxy/IntelligentSystem
/DataControl/ControlData_delete.py
1,358
3.5
4
# 控制数据的删除 # 1.全部删除 # 2.时间段删除 # 删除全部控制数据 请谨慎操作!! import config def ControlData_delete_all(): temp=input('删除全部控制数据,输入 yes 确认') if(temp!='yes'): return cursor=config.connect.cursor() sql='''delete from %s '''%(config.ControlData.tablename ) res= cursor.execute(sql) ...
fee1baccf975bc0922486284cf70d3b1b6c9cf49
Rubabesabanova/BasicAuthenticationSystem
/functions.py
3,397
3.828125
4
from lib import * import json import json with open('db.json') as json_file: db = json.load(json_file) def CheckLetters(x, str): while not x.isalpha(): x = input("Please enter correct {}: ".format(str)) return x def InfoInput(): order = input('''If you want to register, press 1, If you want ...
54c06f9b4d6cf62d0eebfabe9b714a9e70c505f5
jorgeortizc06/curso_python
/class/ocultamiento.py
1,105
3.796875
4
class Carrera: def __init__(self, nombre): self.nombre = nombre self.materias = {} def anadirMateria(self, id, nombre): self.materias[id] = nombre class Materia: def __init__(self, nombre, profesor, fecha): self.nombre = nombre self.profesor = profesor #no ...
2edf1b59279ba88f504a800fc9faae1bcd71000d
jorgeortizc06/curso_python
/sets.py
407
4.125
4
#Set: es una coleccion que no esta ordenada ni indexada y se mete en llaves. #Create an empty set s = set() #Add elements to set s.add(1) s.add(2) s.add(3) s.add(4) s.add(3) #Los sets no admite valores repetidos. No se agrega a la cadena print(s) s.remove(2) print(s) #f me permite introducir parametros en println e...
4f5eedb8e103999b036fb7691bbaad9ed67ddc91
amolsmarathe/python_programs_and_solutions
/3-ObjectOriented/10-UnitTests.py
1,923
3.671875
4
# 2 basic unit testing tools: pylint and unittest # pylint: this is a library which looks at the code and reports styling issues or invalid code, cmd: pip install pylint # from command line, use pylint script.py to run test on script.py # unittest: built-in library which allows to test your own programs and ch...
91b435e4c6afda99270bec91eae519bcb8a09cf8
amolsmarathe/python_programs_and_solutions
/2-Basic_NextConceptsAndNumpy/4-LocalGlobalVariables.py
1,522
4.40625
4
# Local- defined inside the function # Global- defined outside the function # Global can always be accessed inside function, given that same variable is not defined inside function, however, # local variable cannot be accessed outside the function # Local and global variables are different # 'global'-Global variable ...
ada3d722a6fbaca3d8c31cf0c47eee61924be741
amolsmarathe/python_programs_and_solutions
/2-Basic_NextConceptsAndNumpy/11-Challenge-1_Functions.py
1,563
3.859375
4
# # SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and # extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. # # summer_69([1, 3, 5]) --> 9 # summer_69([4, 5, 6, 7, 8, 9]) --> 9 # summer_69([2, 1, 6, 9, 11]) --> 1...
30a9464d99def27837a31aa58c3dc01a4e494ce6
amolsmarathe/python_programs_and_solutions
/3-ObjectOriented/5-Polymorphism-3&4-MethodOverload&Override.py
1,439
4.71875
5
# Method Overload (within same class): 2 methods exist with same name but different number of args # - NOT supported as it is in python,we CANNOT have 2methods with same name in python. But there is a similar concept # - In python,we define method with arg=None &while creating an object,it will get default value No...
4a4dad2807bf92541efd58adcca79ee84c4963e5
amolsmarathe/python_programs_and_solutions
/3-ObjectOriented/8-AbstractClass.py
1,257
4.0625
4
# What is Abstract Class? # abc module- Python does not support Abstract classes by default but we have abc module to use Abstract classes # abc = Abstract Base Classes - Every class which inherits the class ABC in abc, is an Abstract Class # Abstract class is a class which has at least one abstract method. Use decora...
3edc4f379c9f50000e730688edfb0219a96ecaa8
amolsmarathe/python_programs_and_solutions
/1-Basic_ProgramsPython/PrintPatternExample1.py
1,467
4
4
# QUE: Print following patterns: # Pattern-1: (include all hash in print) # # # # # # # # # # # Pattern-2: (include all hash in print) # # # # # # # # # # # Pattern-3: (exclude all hash in print) # 1 2 3 4 # 1 2 3 # 1 2 # 1 # Pattern-4: (exclude all hash in print) - THIS IS TRICKY! # A P Q R # A B Q R # A B C R # A ...
7e80d14f432de3c010b81b3a1e0b575c3efd0aad
jmarq/advent2020
/18/18.2.py
1,941
3.671875
4
import re infile = open("input.txt", 'r') lines = infile.read().strip().split("\n") # line = "1 + (2 * 3) + (4 * (5 + 6))" # line = "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2" # line = "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))" # line = "5 + (8 * 3 + 9 + 3 * 4 * 3)" #line = "1 + 2 * 3" line = "1 + 2 * 3 + 4 * ...
4e82610b6a02221d890222195a93819ff87d219a
mat0823/Triangulo_Sierpinsky
/Tarea01_2019.py
4,006
3.703125
4
#Tarea01_2019.py import time import turtle import random # def main(): iteracion = leeValor('Ingrese numero de la iteración (máx 6): ', 0, 6) eleccion = leeValor('Escoja Estilos: A la Chilena(0), Suave(1), Blanco(2), Aleatorio(3): ', 0, 3) eleccionBorde = leeValor('Escoja Color Borde: Negro(0), Rojo(1...
6e2034a728b9182eb0b305e2848fc614998f1009
kaleungting/python101
/python_mastery/section6/extending_list.py
305
3.875
4
#inheriting all of the methods from the superclass List class SuperList(list): # def __init__(self): # super().__init__() def __len__(self): return 1000 super_list1 = SuperList() super_list1.append(5) print(len(super_list1)) print(super_list1) print(issubclass(SuperList, list))
5566fe97934b49f65cdd19b6408d38273d62bef6
kaleungting/python101
/leetcode/linked_list/remove_nth_node.py
483
3.578125
4
class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: # we want to initialize a dummy node, so we can start the left pointer at one ahead, so we can remove the node dummy = ListNode(0, head) left, right = dummy, head while n: right = right.next ...
3bcfbd4afd47e854fe14a25a8810838462dddfbe
kaleungting/python101
/leetcode/easy/203_remove_ll_elements.py
675
3.5
4
class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy = ListNode(0) dummy.next = head curr = dummy while curr and curr.next: if curr.next.val == val: curr.next = curr.next.next else: curr = cur...
f6d9ea80a515d273117f71113369219b4f95df5e
kaleungting/python101
/leetcode/intervals/56_merge_intervals.py
285
3.6875
4
def merge(intervals): intervals.sort() result = [intervals[0]] for interval in intervals: last = result[-1] if interval[0] <= last[1]: result[-1][1] = max(interval[1], last[1]) else: result.append(interval) return result
8f0c790fb6928c40f698100f336cdcda494b5247
kaleungting/python101
/python_mastery/section3/list.py
1,035
4
4
basket = [1, 2, 3, 4, 5] # print(len(basket)) # adding # modifies list in place # basket.append(100) #inserts at last element # basket.insert(4,100) #inserts at index # basket.extend([100, 101]) #appends list to the original list # removing # basket.pop() # removes from end # basket.pop() # removes from whatever i...
223b54044b4dbf7e3790c702c01c86f3ea359b32
prosales95/PythonNewboston
/tut 45.py
645
3.9375
4
# average of list def drop_first_last(grades): first, *middle, last = grades avg = sum(middle) / len(middle) print(avg) # zipping lists drop_first_last([2, 45, 5, 6, 6, 7, 4, 3, 34, 4, 5, 6, 6, 5, 34]) first = {'csdafc', 'sdadfd', 'dsfafdsf'} last = {'dsfaf', 'dsafsdfg', 'sadfsdf'} names = zip(first, la...
6b7990e5343b9d1d270c6ce96391a63ca89a708c
v-v-d/algo_and_structures_python
/Lesson_1/3.py
994
4.125
4
# 3. По введенным пользователем координатам двух точек вывести # уравнение прямой вида y = kx + b, проходящей через эти точки. try: x1 = float(input('Введите значение \'x\' первой точки: ')) y1 = float(input('Введите значение \'y\' первой точки: ')) x2 = float(input('Введите значение \'x\' второй точки: ')...
6ae308c70df76a428172a9afa44fc0a4870e55ca
v-v-d/algo_and_structures_python
/Lesson_7/2.py
1,348
4.34375
4
""" 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. """ import random def merge_sort(lst): if len(lst) > 1: center = len(lst) // 2 left = lst[:center] rig...
516073604835fd28c8f1c6e3a63656d9e513efdb
v-v-d/algo_and_structures_python
/Lesson_2/4.py
1,487
4.1875
4
""" 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. """ # Рекурсия def get_sum_of_series(num_of_elements, num=1, summ=0): summ += num num /= -2 num_of_elements -= 1 if num_of_elements: return get_sum_of_series(num_of_elem...
c6e0c945b6f00c0737698ee25c0b91e907b685cb
v-v-d/algo_and_structures_python
/Lesson_3/8.py
914
3.828125
4
""" 8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк. Программа должна вычислять сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки. В конце следует вывести полученную матрицу. """ import random rows = 5 cols = 4 matrix = [[random.randint(-50, 50) for _ in ...
1fc8cda6f22a9dead9fa5062fcdd4e824f8a73b2
v-v-d/algo_and_structures_python
/Lesson_4/1.py
7,416
3.90625
4
""" 1. Проанализировать скорость и сложность одного любого алгоритма, разработанных в рамках домашнего задания первых трех уроков. Примечание: попробуйте написать несколько реализаций алгоритма и сравнить их. """ import timeit import cProfile import random # Рекурсия def get_ascii_table_recursively(from_symbol, to_sy...
d90b0446da8f2201d5bc0ac0bed1b15dca86eefd
qikuta/python_programs
/text_to_ascii.py
760
4.5
4
# Quentin Ikuta # August 7, 2022 # This program takes input from user, anything from a-z, A-Z, or 0-9 -- # converts the input into ASCII code, then finally prints the original input and ASCII code. # ask user for input user_string = input("please enter anything a-z, A-Z, and/or 0-9:") # iterate through each character...
89f0c2b668d143f46812fe49f56d7b26adf7f67d
GamalC/ISW-Volunteer-Rota
/utilities.py
11,580
3.578125
4
from classes import * #SCHEDULED_YEAR = '2015' MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] #MAX_SLOTS = 5 #maximum slots to assign to volunteers who did not specify a clear max def convert_to_date(string_date, schedule...
b2581fced1c7ddf80371d34f5a82b7c74cf55f3e
ICANDIGITAL/crash_course_python
/chapter_11/test_cities.py
629
4.0625
4
import unittest from city_functions import city_country class CityFormatTester(unittest.TestCase): """Tests city_functions to find out if it outputs the correct string.""" def test_city_country(self): """Tests city_functions to find out if it outputs the correct string.""" formatted_city = ci...
544f7d9b9b31e6e938654ffef6114b6d8258cf25
ICANDIGITAL/crash_course_python
/chapter_5/hello_admin.py
291
3.90625
4
usernames = ['chris', 'kyle', 'admin', 'joker', 'joao'] for username in usernames: if username is 'admin': print('Hello ' + username.upper() + ', would you like to see a status report?') else: print('Hello ' + username.title() + ", thank you for logging in again.")
4709da37276a2630a541ccf8c5fd9fff0c7360c4
ICANDIGITAL/crash_course_python
/chapter_8/city_names.py
365
3.984375
4
def city_country(city,country): """Displays the city and country of a place.""" location = (city.title() + ", " + country) return location cool_place_1 = city_country('rio de janeiro', 'Brazil') cool_place_2 = city_country('new york', 'USA') cool_place_3 = city_country('lison', 'portugal') print(cool_plac...
2b3cb34f4d91c43bd4713619e0adbd53dbd6f17e
ICANDIGITAL/crash_course_python
/chapter_7/restaurant_seating.py
230
4.1875
4
seating = input("How many people are in your dinner group? ") seating = int(seating) if seating >= 8: print("You'll have to wait for a table of " + str(seating) + ".") else: print("There is currently a table available.")
d415802c81d337356a85c4c0f94ca993fbcb1d7d
ICANDIGITAL/crash_course_python
/chapter_8/unchanged_magicians.py
421
4.125
4
def show_magicians(magicians): """Displays the name of each magicians in a list.""" for magician in magicians: print(magician.title()) magical = ['aalto simo', 'al baker', 'alessandro cagliostro', 'paul daniels'] def make_great(tricks): """Modifies the original function by adding a message.""" ...
b956d61ba4f283990ff1be066828561f9dc26a8c
ICANDIGITAL/crash_course_python
/chapter_4/squares.py
258
4
4
squares = [] for value in range(1,11): square = value**2 squares.append(square) print(squares) print(sum(squares)) #Below I am learning how to create the same list by list comprehension. squares = [value**2 for value in range (1,11)] print(squares)
d22cbb7352ac48d1e6fa3fd99b5e38b9d56c2bb7
ICANDIGITAL/crash_course_python
/chapter_8/cities.py
218
3.65625
4
def describe_city(city,country='USA'): """Displays the name of a city.""" print(city.title() + " is in " + country + ".") describe_city('new york') describe_city('los angeles') describe_city('paris','France')
ce0505889b1071f6161715d93665cf51889b8420
ICANDIGITAL/crash_course_python
/chapter_9/admin.py
894
4.03125
4
from users import User class Privileges: """Stores a list of privileges unique to admin users.""" def __init__(self, *privileges): """Initialize attributes of class.""" self.privileges = privileges def show_privileges(self): """Print a statement listing privileges common to Admin ...
15ece823aedcb00ec9bcc99a52e7e61b24e5371f
ICANDIGITAL/crash_course_python
/chapter_9/privileges.py
449
3.8125
4
class Privilges(): """Stores a list of privileges unique to admin users.""" def __init__(self, *privileges): """Initialize attributes of class.""" self.privileges = privileges def show_privileges(self): """Print a statement listing privileges common to Admin users.""" print(...
de05492841d36052d70b5557a663ba670479cbee
saintandy/python
/guess_the_number.py
584
4.0625
4
import random name = raw_input('Hi, please enter your name: ') number = random.randint(1, 100) guess_number = 0 while guess_number < 8: guess = int(raw_input('Please enter your guess: ')); guess_number += 1 print 'Your guess is {0}'.format(guess) if guess > number: print 'Your number is too big' elif guess ...
c1cf99b0ff6abb83f0526086ebfd879bbaf00b04
andrehsu/Advent-of-Code-2019-Python
/adventofcode/day6.py
1,567
3.53125
4
from dataclasses import dataclass from typing import List, Dict from utils import read_input_lines INPUT = read_input_lines('day6') @dataclass(frozen=True) class Planet: _planets: Dict[str, 'Planet'] _parent_name: str name: str @property def parent(self): if self._parent_name == 'COM': ...
d13d378ac3ba53279864e205439454b893c52dbf
monkop/Data-Structure-in-Python
/Sorting/bubble_sort.py
441
4.28125
4
arr = [] n = int(input("Enter size of array :")) #this input ask for our array size for i in range(n): n1 = int(input("Enter Array : ")) arr.append(n1) print("Your Array : ",arr) #for Showing Your actual array for i in range(n): for j in range(n-1-i): if arr[j] > arr[j+1]: ...
cc66dc5a777f7d9b33eba4178e1404bf36a1b61d
monkop/Data-Structure-in-Python
/Sorting/selection_sort.py
350
3.890625
4
arr = [] n = int(input("Enter Size of array :")) for i in range(n): n1 = int(input("Enter Your Array : ")) arr.append(n1) for i in range(n-1): minpos = i for j in range(i,n): if arr[j] < arr[minpos]: minpos = j temp = arr[i] arr[i] = arr[minpos] arr[minpos] = temp pri...
7cd438649c6339d0c494ceaac380295e75aa2a97
monkop/Data-Structure-in-Python
/Arrays/insertionSort.py
382
4.125
4
arr = [] n = int(input("Enter Size Of array : ")) for i in range(n): array = int(input("Enter Lisy Of Array : ")) arr.append(array) print("Your Unsorted Array",arr) for i in range(1,n): temp = arr[i] j = i-1 while j >= 0 and arr[j] > temp: arr[j+1] = arr[j] j -=...
5550808695e2649c4c0f1136ba6ddf741ac1da8a
monkop/Data-Structure-in-Python
/Arrays/bu_pratice.py
401
4.125
4
arr = [] n = int(input("Enter size of array : ")) for i in range(n): array = int(input("Enter list of array : ")) arr.append(array) print(f"Your Unsorted Array {arr}") for i in range(0,n): for j in range(n-1-i): if(arr[j] > arr[j+1]): temp = arr[j] arr[j] = arr[j+1] ...
e75281768755ccae44dc2ea91b4cba0f1b775f3a
monkop/Data-Structure-in-Python
/Arrays/PraticeBS.py
348
4.125
4
arr = [] n = int(input("Size : ")) for i in range(n): array = int(input("Enter List Of array : ")) arr.append(array) print(f"Your Array {arr}") for i in range(n-1): for j in range(n-1-i): if(arr[j] > arr[j+1]): temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp pri...
01bd642dc7efd24ccd048990641f377c2fdb2098
monkop/Data-Structure-in-Python
/Numpy/reverse.py
133
3.71875
4
import numpy as np arr = [] n = int(input()) for i in range(n): n1 = int(input()) arr.append(n1) print(np.array(arr)[::-1])
19dc012b2b67719a8ee05679324a89f8e4abcb72
diordnar/DesignPattern
/Python/Prototype/Prototype.py
513
3.546875
4
#! /bin/python # -*- coding: utf-8 -*- import abc import copy class Prototype(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def clone(self): pass class ConcretePrototype(Prototype): def clone(self): clone = copy.deepcopy(self) return clone def setNum(self, n): ...
e90382d0e5d677d36e545d4e053de89b8d4e5eb9
alexcg1/godel_escher_bach
/python/bloop_floop/bloop-mn.py
531
3.890625
4
# How calculate m - n, using only addition def subtract(m, n): original_n = n assert(m >= n) counter = 0 while m > n: n += 1 counter +=1 return counter def if_subtract(m, n): original_n = n assert(m >= n) counter = 0 for i in range(0, m): if n == m: ...
8259ac6fad1cfbb6c2b80b02aa4d0241c240b3fb
Darkphilip/Python_Study
/python_level_3/chapter2/property_2.py
1,903
4.03125
4
""" Chapter2 Python Advanced(2) -Property(2) - Getter, Setter Keyword - @Property """ """ 프로퍼터(Property) 사용 장점 1. 파이써닉한 코드 2. 변수 제약 설정 3. Getter, Setter 효과 동등(코드 일관성) - 캡슐화-유효성 검사 기능 추가 용이 - 대체 표현(속성 노출, 내부 표현 숨기기 가능) - 속성의 수명 및 메모리 관리 용이 - 디버깅 용이 - Getter, Setter 작동에 대해 설계된 여러 라이브러리(오픈소스) 상호 운용성...
cca5267d83eb049c381d25ab550587ff329c8c5b
Darkphilip/Python_Study
/python_level_3/chapter2/method_overriding.py
3,879
4.3125
4
""" Chapter 2 Python Advanced(2) - Method Overriding Keyword - Overriding, OOP, 다형성 """ """ 메소드 오버라이딩 효과 1. 서브클래스에서 슈퍼(부모)클래스를 호출 후 사용 2. 메소드 재 정의 후 사용 가능 3. 부모클래스의 메소드 추상화 후 사용 가능(구조적 접근) 4. 확장 가능, 다형성(다양한 방식으로 동작) 5. 가독성 증가, 오류 가능성 감소, 메소드 이름 절약, 유지보수성 증가 등 """ # EX1 # 기본 Overriding 예제 class ParentEX1(): def...
e5a6cde3ab1722528f48077ea8daa4b3bfabd07e
Darkphilip/Python_Study
/python_level_1/module.py
456
4
4
# Module: 함수, 변수, 클래스 등 파이썬 구성 요소 등을 모아놓은 파일 def add(x,y): return x+y def substract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x / y def power(x,y): return x ** y if __name__ == '__main__': print('-' * 15) print('called!__main__') print(add(5,5)) print(substract(15...
049a86d3d47d6fdea6d5d74e0c679e760fdd3b35
towenxie/tncrawler
/tncrawler/utils/stringutil.py
1,391
3.59375
4
# -*- coding: utf-8 -*- import difflib class StringUtil(object): @staticmethod def str_is_empty(str=None): """string is empty return True else return False""" return True if str is None or str == '' else False @staticmethod def str_to_int(str=''): """change str to int""" ...
a5957069cc2e5dd672b688dfea09b11e1beb3c92
dharmangbhavsar/review_mining
/other/new_sequence_matching.py
958
3.84375
4
import difflib #search is the search term search = "Empire State Building" #text is the tweet text = "Empire Building is an excellent Place to be!!!" #splitting ans finding the size of tweet and search word words = text.split() word = search.split() tweet_words = len(words) query_words = len(word) #all_words contai...