blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
cb79d395415f75fdd0ab1fb39ebc4098e6d11db5
iAmMrinal0/grokking_algos
/chapter1/binary_search.py
798
3.703125
4
def binary_search(arr, num): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 guess = arr[mid] if guess == num: return mid if guess < num: low = mid + 1 else: high = mid - 1 return None def rec_search(arr...
68f70f58eb30f59d582d752b22cb1921e6bebe0b
ElectronicGomez/Python
/Py/TKINTER/SpinBox_opcion_lista.py
912
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri May 15 13:54:18 2020 @author: ASUS """ from tkinter import * from tkinter import messagebox def obtener(): messagebox.showinfo("Mensaje","tu seleccionaste" + valor.get()) messagebox.showwarning("Advertencia", "Peligro") ventana = Tk() valor = Str...
7bd98e5bebd6fbd4cb77ec1bcc779148b79397ea
suacalis/VeriBilimiPython
/Ornek11_7.py
467
3.96875
4
''' Örnek 11.7: Sayıları harf karşılıkları ile eşleştiren bir sözlük yapısı oluşturalım. Sonra da klavyeden girilen rakamın harf karşılığını ekrana yazdıran programı kodlayalım ''' rakam = int(input("1-9 arası bir sayı gir.:")) Sozluk = {1:"Bir", 2:"İki", 3:"Üç", 4:"Dört", 5:"Beş", 6: "Altı", 7:"Yedi", 8:"Sekiz", 9:"Do...
8070ee1da99ebbf927adbb9bb4117ccc18f596da
fagan2888/Coding-Interview
/Python/Data Structure/Sliding Window/Contains Duplicate.py
418
3.640625
4
class Solution: def containsDuplicate(self, nums: 'List[int]') -> 'bool': # we can use set very easily, or do sort or dictionary dict = {} for num in nums: if num in dict: return True else: dict[num] = 1 return False """ de...
084c04c3cf2fe77b13f36645e561ed08cc31c118
lorenzocogolo/repo1
/social science project/step1.py
3,069
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: from datetime import * from dataread import cheaters,kills,dic_kills # In[2]: def cheaters_accounts(): '''This function takes the cheaters list as input and estrapolates the cheaters' accounts for each match in the dictionary It returns a list made of sublists...
15b3b2c659548009094fb590ff4afd0d3f828fbf
osnaldy/Python-StartingOut
/chapter8/charge_acount_validation.py
556
4.09375
4
def main(): #Here we open the file and read the lines file_name = open("charge_account.txt", 'r') charges = file_name.readlines() file_name.close() #Here we create an empty array, loop through it and append the values to a list arr = [] for i in charges: name = int(i) arr.ap...
ee0a576cddca0543df503bc6f2884f6a3b6a319a
geshem14/my_study
/Coursera_2019/Python/week4/week4task9.py
1,319
3.890625
4
# week 4 task 9 """ текст задания тут 79 символ=>! Дано натуральное число n>1. Выведите его наименьший делитель, отличный от 1. Решение оформите в виде функции MinDivisor(n). Алгоритм должен иметь сложность порядка корня квадратного из n. Указание. Если у числа n нет дел...
cb9a30d3530cbcad2e75617f8484b3bbfdaa6793
sailengsi/sls-python-study
/001-test/study_cli.py
390
4.0625
4
''' 初步体验交互式Python编程 ''' print('欢迎来此新世界') username = input('请输入您的用户名:') password = input('请输入您的密码:') if username and password: print('登录成功,您的账号->username,密码是password') else: if not username: print('用户名不能为空') if not password: print('密码不能为空')
6d9a8ef988cb3d88685d06caeddc6dbf1b0eb408
ololo123321/euler
/problems/p071.py
1,052
3.8125
4
""" https://math.stackexchange.com/questions/39582/how-to-compute-next-previous-representable-rational-number https://en.wikipedia.org/wiki/Modular_multiplicative_inverse """ from problems.utils import modinv, log @log def main(): """ Consider the fraction, n/d, where n and d are positive integers. If n<d...
5ff11f101a8471a67afd2ccfe6b8d8277e831ed9
bingwin/python
/python/习题/mianshi7.py
627
3.734375
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 # 输入两个正整数计算最大公约数和最小公倍数 x = int(input('x = ')) y = int(input('y = ')) if x > y: x, y = y, x for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: print('%d和%d的最大公约数是%d' % (x, y, factor)) print('%d和...
28f3026db240559cca1c87c70aca4ce9b5316a9f
a01375832/Actividad-04
/calculopago.py
687
3.859375
4
#Encoding:UTF-8 #Autor:Manuel Zavala Gómez #Calculo de pago de un trabajador def main(): normal=int(input("Horas normales trabajadas")) extra=int(input("Horas extra trabajadas")) pago=int(input("Pago por hora normal")) print("Horas normales:",normal) print("Horas extras:",extra) print("Pago por...
d104d38a59a5866d2cb4c30de4a4cab203c9c49c
SvetlanaTsim/python_basics_ai
/lesson_3_ht/task_3_4.py
1,153
3.8125
4
""" 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. Подсказка: попробуйт...
5814ec32e1c0804f4ad0abeb749483c6a68316df
lkapinova/Pyladies
/05/dp_04.py
2,021
3.90625
4
# Napiš funkci tah_hrace, která dostane řetězec s herním polem, # zeptá se hráče, na kterou pozici chce hrát, # a vrátí herní pole se zaznamenaným tahem hráče. # Funkce by měla odmítnout záporná nebo příliš velká čísla a tahy na obsazená políčka. # Pokud uživatel zadá špatný vstup, funkce mu vynadá a zeptá se znova. ...
81b3092b3543fb97dc63f006991432044709ed6e
jmontara/become
/Data Structures/Hash Table/hashtable_start.py
621
4.4375
4
# demonstrate hashtable usage # create a hashtable all at once items1 = dict({"key1": 1, "key2" : 2, "key3" : "three"}) print(items1) # create a hashtable progressively items2 = {} items2["key1"] = 1 items2["key2"] = 2 items2["key3"] = 3 print(items2) # access a nonexistant key #print items1["key6"] # replace a...
bccdd38a7c6e3acf79ee2e88bdb215d784decbab
AldanaVallejos/Guia-5
/Guia5.Ejercicio6.py
1,111
3.609375
4
#*********************************************************** # Guia de ejercitación nº5 # Fecha: 06/10/21 # Autor: Aldana Vallejos #*********************************************************** # EJERCICIO 6: Desarrollar un procedimiento que imprima una fecha en # formato DD/MM/AA. El dato que recibe e...
7666e0fd76be260230ac59df4bcb49a056161b0b
spidernik84/udemypybootcamp
/milestone_proj1.py
3,893
4.28125
4
''' Simple TicTacToe implementation ''' import random def display_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' ...
bd049ab3ea3b8cb1313ba169c659d1859b4b5fa2
Bertram-Liu/Note
/NOTE/02_PythonBase/day01/code/variable.py
249
3.90625
4
# 练习: # 已知有矩形的长边长为6cm, 短边长为4cm, 求周长和面积 a = 6 # a变量代表长边的长度 b = 4 # b变量代表短边的长度 print("周长是", 2 * (a + b), "厘米") print("面积是:", a * b, "平方厘米")
0bacef1b8a51592327bf9e50e12707bb3b959496
amile/sql
/venicles1.py
297
3.75
4
import sqlite3 conn = sqlite3.connect("cars.db") cursor = conn.cursor() cursor.execute("update inventory set quantity = 2") conn.commit() cursor.execute("select * from inventory where make = 'Ford'") fords = cursor.fetchall() for ford in fords: print ford[0], ford[1], ford[2] conn.close()
6571e1e29c274d206d0edbb6e48da701c7c45a14
tww-software/py_ais_nmea
/pyaisnmea/export.py
6,180
3.953125
4
""" code for the export of data into various file formats """ import csv import json import logging import os import re AISLOGGER = logging.getLogger(__name__) INVALIDDIRCHARSREGEX = re.compile(r'[/\*><:|?"]') def write_json_file(jsonstations, outpath): """ write jsonstations to a json file Args: ...
2f050182c0320cfad901675cfb7e44c005d904f5
daniel-reich/turbo-robot
/AgGWvdPi56x5nriQW_12.py
1,146
4.15625
4
""" Create a function that takes a list of pyramid numbers and returns the maximum sum of consecutive numbers from the top to the bottom of the pyramid. /3/ \7\ 4 2 \4\ 6 8 5 \9\ 3 # Longest slide...
b776e18de7a0c45485411a03534292da780c9f83
jasonjiexin/Python_Basic
/magedu/jiexishi/List_comprehension.py
4,740
4.28125
4
#!/usr/bin/env python # coding: utf-8 # jason # ## 解析式 # 作用:解析式和生成器都是python特有的两个特性,他们能够帮助优化程序,大大减少代码的数量. # ### 1.生成一个列表,列表0~9,对每一个元素自增1后求平方返回新的列表 # In[31]: # 一般的写法 lst1 = list(range(10)) lst2 = [] for i in range(10): lst1[i] += 1 square_num = lst1[i]**2 lst2.append(square_num) print(lst2) print(lst1)...
500e5edfe531d04caad8d222a50aaf2e7ab05ee5
FedorAglyamov/Chemical-Equation-Balance
/ChemicalEquationBalance.py
7,306
4.0625
4
# Simple program for balancing chemical equations # v0.9 # Imports import numpy as np from scipy import linalg from fractions import Fraction import re import sys # Declare constants SEPERATOR = "=" TUTORIAL_MSG = "Please seperate left/right side of equation with '=' char, " \ "and exp...
22e1f3adb516f559cde7862cf775cf356b59f3b4
ashokmoorthi/Personal_Python_Learning
/Ram_Scenarios/R1_To_Match_String.py
741
4.09375
4
''' Ram scenario One: 1) Get input from user (String alone) 2) Check the characters in the string and see if you can form the word "idirect" 3) If yes print iDirect 4) Else print Not a valid Input 5) Later update it to get both inputs from user 6) Print the reuslts''' import sys input_text_string = input('Please Enter...
c69618f688f5a39895c5becb913500426dd16390
stevenluk/Advanced-Data-Storage-and-Retrieval
/app.py
4,350
3.578125
4
import numpy as np import sqlalchemy import datetime as dt from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify # Database Setup engine = create_engine("sqlite:///hawaii.sqlite") # reflect an existing database in...
ac2eecea1e53f97284eb08069c6e24b6975d7b14
Yaciukdh/RandomPythonCode
/tutorialPy/lesson2.py
2,013
4.28125
4
# Lesson two: libraries and functions import time def func1(): print("This function prints some lines") print("Functions are reusable pieces of code") print("Sometimes they make code more readable") def sumasafunction(begin, end, timeStep): sum = 0 for x in range(begin, end, timeStep): s...
6cd54f904b2b2f5fbb2e6742ad20861c28eaf437
a2aniket/Python-3
/DataSience Project/Predict_customer_Will_Leave_the-Bank/Predict_customer_Will_Leave_the-Bank-master/Bank_customerPredict.py
1,954
3.953125
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('BankCustomers.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # convert categorical feature into dummy variables states=pd.get_dummies(X['Geography']...
71987b0a1c367ddc7bc5e63a166fcf253461cd86
swapnil-sat/webwing-code
/ManthanBore/Collections/str_strip.py
135
3.546875
4
# str=" Rohit " # print("before=",str) # print("after=",str.strip()) # print("after=",str.rstrip()) # print("after=",str.lstrip())
8670f4319e7e2037f9c69314009143487e43dd5a
barshan23/snakeGame
/snake.py
2,947
3.578125
4
import pygame,random pygame.init() # WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) display_height = 600 display_width = 800 FPS = 20 blockSize = 10 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("Snake") pygame.display.update() clock = pygame.time.Clock()...
c1539856fc613119684c63097432783ad7110772
zranguai/python-learning
/day23/08 作业.py
3,803
4.09375
4
# 8点之前 统计作业完成度,难点 # 作业笔记 # 写每一个题的用时 # 遇到的问题 # 解决思路 #第一大题 : 读程序,标出程序的执行过程,画出内存图解,说明答案和为什么 # 请不要想当然,执行之后检查结果然后再确认和自己的猜想是不是一致 # (1) # class A: # Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的 # def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的 # self.name = name # self.age = age # ...
b9dbd8e5bb1cd3d9b258432a02e2cd4e62bfeb15
kaoru-kitajima/titanic
/pythonlearning.py
2,327
3.828125
4
words = ["start", "middle", "end"] #slice print(words[0:2]) #0~1までのlistを返す # for for wd in words: print(wd) else: # forが終わったあとに呼ばれる。 print("finished") for i, wd in enumerate(words): if i >= 2: print("too much!") break # for文から抜けてelseに飛ぶ if wd == "start": print("this is star...
f8d3b508efb0f1bfacc0169566a19b82d62432d2
S1AG0N/python_codes
/Play_Rock_Paper_Scissors_With_Computer.py
1,464
4.21875
4
import random # use randint to make the computer make a choice ran_num = random.randint(0, 2) # Human Choice human = input("Please Enter your choice against the computer! ::").lower() # Validate Human Input if human not in ("rock", "paper", "scissors"): print("Please input either 'rock' 'paper' or 'scissors' ") ...
6995963f0407e57fb3d46009c0ea3f62f37abea7
waredeepak/python_basic_beginners_programs
/in.python.basic/AverageCalculator.py
402
3.96875
4
print("Enter marks obtained in 5 subjects: "); m1 = input(); m2 = input(); m3 = input(); m4 = input(); m5 = input(); mark1 = int(m1); mark2 = int(m2); mark3 = int(m3); mark4 = int(m4); mark5 = int(m5); sum = mark1 + mark2 + mark3 + mark4 + mark5; average = sum/5; percentage = (sum/500)*100; print("out of 500 ",sum);...
5fdf526131ad0456fe24d7ee5566c6d0eccd61cd
rosrez/python-lang
/06-iteration/for-enumerate.pl
262
4.15625
4
#!/usr/bin/env python list = [2, 4, 6, 8, 10]; print "Iteration using enumerate to get index" for i,n in enumerate(list): # enumerate(s), where s is a sequence, returns a tuple (index, item) print "squares[%d] = %d**2 = %d" % (i, n, 2**n)
b7532900c8444144cdb24fa2e8e2053f4189f619
StewartCB/math
/arrayInfo.py
1,146
3.625
4
arr = [] l = input("Input number of items: ") for i in range(0, l): arr.append(1.0 * input("Item " + str(i) + " = ")) i = i + 1 print " " arr.sort() sum = 0.0 #Average / Mean for o in range(0, len(arr)): sum = sum + arr[o] print ("Sum = " + str(sum)) print ("Average = " + str(sum/(len(arr) ))) #Median if len(arr...
2bfde1b4f424d9d874a792d6abbdb96a61c54500
eds8531/Leitner_Notes
/Leitner-Notes-Dict.py
6,574
3.890625
4
import random import shelve import datetime from datetime import timedelta, datetime, date # is a function for developers only and will not be in the finished program. It resets the shelf file where words are saved to a blank list. # Creates an empty list and sends it to 'fcdata' def init(): sure = input("Are yo...
72f019884e5b5efc5f07e17d2b7556ade1cdc884
newbabyknow/python_practice
/longest_substring.py
454
3.78125
4
# 滑动窗口方法,计算字符串的最长不重复子字符串 def window(s): begin_index = 0 max_long = 0 for i in range(1, len(s)): if s[i] in s[begin_index:i]: max_long = max(max_long, len(s[begin_index:i])) begin_index += s[begin_index:i].index(s[i]) + 1 if max_long == 0: max_long = len(s) r...
0251c6a7dbe635da68165d24c0dd57afc51f7a49
dsintsov/python
/labs/lab3/class.py
2,737
3.78125
4
""" Вариант 1 Создать класс – Треугольник, заданного тремя точками. Функции-члены изменяют точки, обеспечивают вывод на экран координат, рассчитывают длины сторон и периметр треугольника. Создать список объектов. a) подсчитать количество треугольников разного типа (равносторонний, равнобедренный, прямоугольный, произво...
7b85c1bfd3a8ec347ddd742de2ae2703df5acd3f
benryan03/Python-Practice
/basic-part1-exercise049-list_directory.py
178
3.84375
4
#https://www.w3resource.com/python-exercises/python-basic-exercises.php #49. Write a Python program to list all files in a directory in Python. import os print(os.listdir())
99f975f464800047c30f9d596c8e10c4a0f6b346
nabin-info/hackerrank.com
/text-alignment.py
658
3.515625
4
#!/usr/bin/python import sys def input_arg(tr=str): return tr(raw_input().strip()) def input_args(tr=str): return map(tr, list(input_arg().split(' '))) def input_arglines(n,tr=str): return [input_arg(tr) for x in range(n)] def print_logo(t,c='H'): for i in range(t): print (c*i).rjust(t-1)+c+(c*i).ljust(t-1...
0d97917da23b63c4036fb2b579add0e46ddc85dd
emmanuel-mfum/Pomodoro
/main.py
3,961
3.609375
4
from tkinter import * import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 25 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 reps = 0 timer = None # ---------------------------- TIMER RESE...
1ff6bc17e6eea80fe4e3e9c8a3e57fd1189a6825
alieu93/Comp-Simulation-Assignments
/Assignment 1/Assign1_Part2B.py
3,056
3.703125
4
#Name: Adam Lieu #Student ID: 100451790 #Description: #Part 2B of Assignment 1, simulate the spread of an infectious disease # Constant Spread Rate: 0.15 # Fatality rate: 0.025 # Recovery rate: 0.15 import itertools as it import numpy as np import scipy as sp import pylab as pl import matplotlib.pyplot a...
3d524bfbc085da7c0efde07504414bf8f9cd9d12
xaneon/PythonProgrammingBasics
/python_example_scripts/documentation_in_python.py
608
3.609375
4
""" Beschreibung des Moduls. """ def addiere(arg1, arg2): """*Addiert* ``arg1`` und ``arg2``.""" return arg1 + arg2 # Kommentar eines Entwicklers def multipliziere(arg1, arg2): """ >>> multipliziere(3, 5) 15 """ return arg1 * arg2 def potenziere(basis, exponent): """ **Zusa...
94d2f25a28aa77cb71b87f563aaa4f498436e9fa
DTA-XCIV/Python
/ex30.py
1,298
4.25
4
# enkele variabelen met integers als waarde people = 30 cars = 40 trucks = 15 # deze blok vergelijkt in totaal 2 variabelen: cars en people # de if-functie komt als eerste en kijkt of er meer auto's zijn dan mensen # de waarde is True, dus print de script de lijn die onder de if staat # mocht het zijn dat de waarde no...
4493accafe7054910c37c82e96b7421fc98b0f00
daniel-reich/ubiquitous-fiesta
/FPNLQWdiShE7HsFki_6.py
830
3.578125
4
def spider_vs_fly(spider, fly): label = "ABCDEFGH" d = 4 - abs(4 - abs(label.index(spider[0]) - label.index(fly[0]))) path = [spider] ​ if abs(int(spider[1]) - int(fly[1]) > 0): while spider[1] != fly[1]: spider = spider[0] + str(int(spider[1]) - 1) path.append("A0" if spider[1] == "0" else spi...
a363b843b1070b4f244505dd15d85e7c3f20f700
babint/AoC-2015
/02/part2.py
1,377
3.953125
4
#!/usr/bin/env python3 import sys paper_needed = 0 ribbon_needed = 0 # Usage if len(sys.argv) != 2: print("usage: part2.py input.txt") exit(1) # Read File with open(sys.argv[1]) as f: lines = f.read().splitlines() for line in lines: dimensions = line.split('x') shortest = sys.maxsize short_a = short_b =...
9e492897afa9b8d19f3055f3e19cd7d53f1bff5b
burnasheva/scripts
/generate_files.py
316
3.53125
4
for value in range(10): # construct the filename; prefix or suffix optional filename = 'prefix-' + str(value) + '.txt' # open the file to be written fo = open(filename, 'w') # write the content in the file including the value being passed to each; %s indicates a string fo.write('%s' % value) fo.close()
ea3fd457c39c08c91b22d3e4200f1fe83aadcf38
simonmonk/prog_pi_ed3
/03_04_double_dice_while.py
276
3.84375
4
#03_04_double_dice_while import random throw_1 = random.randint(1, 6) throw_2 = random.randint(1, 6) while not (throw_1 == 6 and throw_2 == 6): total = throw_1 + throw_2 print(total) throw_1 = random.randint(1, 6) throw_2 = random.randint(1, 6) print('Double Six thrown!')
fcf36b2fd1228fe0d65951269002e48af858f638
tyraeltong/py-algorithms
/sorting/selection_sort.py
960
3.875
4
from sorting.utils import print_tests class SelectionSort: """ Time complexity: - Worst case: O(nˆ2) - Best case: O(nˆ2) - Average case: O(nˆ2) Space complexity: - O(1) """ @staticmethod def sort(data): if data is None: raise TypeError("data ...
e9817120246d9b29d18c1615be19bcbe0d8bbf7f
girishalwani/Training
/python/python fundamentals/functions_modules_packages/prog_1.py
359
3.96875
4
""" Write a function to return the sum of all numbers in a list. """ def sumAll(list): sum=0 for i in list: sum+=int(i) return sum number = input("enter list elements separated by space -> ") lis=number.split() lis2=[] for i in lis: lis2.append(int(i)) print('list items -> ',lis2) print(...
98efaf16c4b6c3fc9b0dc061c7f7a47e453fd203
newwby/EnaiRimDocumentationParser
/output_handlers.py
1,098
3.890625
4
######################### """ Accepts input in the form of a list containing dict entries for every item. (Basically objects but with built-in python types) """ ######################### def parser_printer(given_list: list, file_output_string: str, write_raw_to_file: bool = True, erase_file: bool = True): if write_...
e90c44641308f87815fe8e370799fc73e2a139aa
medifle/python_6.00.1x
/defMul.py
118
3.78125
4
# multiplication def iterMul(a, b): result = 0 for i in range(b): result += a return result
605632faca8f7f57558fa1bba084d643f4b8fa96
tchapeaux/project-euler
/004.py
1,030
3.828125
4
import math def is_palindrom(word): l = len(word) for i in range(math.floor(l / 2)): if word[i] != word[l-1-i]: return False return True assert(is_palindrom("")) assert(is_palindrom("1")) assert(is_palindrom("zz")) assert(is_palindrom("bob")) assert(is_palindrom("baobabbaboab")) asser...
beff943471560d3cb65d7eb999d55eec826672b7
DucarrougeR/COMP30670_Final-Project-DublinBikes
/bikes.py
2,376
3.6875
4
import requests import pandas as pd import sqlite3 import traceback import time # Setting up NAME = "Dublin" STATIONS = "https://api.jcdecaux.com/vls/v1/stations" APIKEY = "1c8d24323042b11c89877648adfe3c180f15fa3c" conn = sqlite3.connect("dublinBikes.db") # Connect to database (creates if it does not exist) curso...
a5062dcbfff7f5a60bbc3c78c6d7b9a174e7e178
gaoxinge/bible
/python/pysheeet/4/test.py
395
3.65625
4
def decorator(func): def wrapper(*args, **kwargs): print("I am decorator") ret = func(*args, **kwargs) return ret return wrapper @decorator def hello(str): print("Hello {0}".format(str)) @decorator def add(a, b): print("add %d + %d = %d" % (a, b, a ...
4bf612c9c3847ae6a6347afb4f98d632e0694faf
SinghGauravKumar/Project-Euler-Python-Solutions
/euler_problem_052.py
229
3.53125
4
import itertools def compute(): for i in itertools.count(1): digits = sorted(str(i)) if all(sorted(str(i * j)) == digits for j in range(2, 7)): return str(i) if __name__ == "__main__": print(compute())
1aa20111e6db5a61efd9af07110331258cbab7ce
sharanya-code/Telephone-Directory-Program
/Telephone Dictonary Program.py
5,591
4
4
import pickle ######################################## To Create the Binary File phone.dat def Append(): print("\n") Name=input("Enter name of the Person: ") RollNo=int(input("Enter Phone Number of the Person: ")) Data=[Name,RollNo] while True: try: inFile=open("phone....
782780d34b340f5e001a57cbb30768b2d70270e1
lapricope/personal_search
/searcher/searcher.py
726
3.609375
4
import os class Searcher(object): def __init__(self): self.__results = [] pass def search(self, start_path='D:\\', pattern=None): """ Function will search files/images which match the provided pattern Will place results in self.results list :param start_path: P...
f22d7d41d7744ce3f7be065873ec5cfdd6244fe7
jxseff/python-exercise
/chapter 4/animals.py
132
3.953125
4
animals = ['cat', 'dog', 'duck'] for animal in animals: print(f"A {animal} would make a great pet.") print('They are all loud.')
4922f808738c9f98ab50b9a74f16a87163a5e86b
StaroverovAleksey/GeekBrains
/lesson_4/lesson_4_task_6.1.py
232
3.671875
4
from itertools import count start = int(input('Введите начальное число: ')) stop = int(input('Введите конечное число: ')) for i in count(start): print(i) if i == stop: break
bf9c250b6b5fc2d38bec248a0d9b6b027b56c1c9
akbagai/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/week2/lecture4/fib.py
1,811
3.84375
4
# -*- coding: utf-8 -*- """ Add caching """ import timeit from timeit import Timer from functools import lru_cache def fibi(n): """ Iterative Fibonacci :param n: nth number to calculate the Fibonacci value :return: Fibonacci value """ a, b = 0, 1 for i in range(n): a, b = b, a + b...
edbeeca71e09940ae1f35a25df855b44071ce80a
lemnissa/1sem
/lab2/2.13.py
643
3.9375
4
import turtle as t def my_fill(col, R, tri=360): t.begin_fill() t.color(col) t.circle(R, tri) t.end_fill() t.color('black') t.circle(R, tri) t.shape("turtle") t.up() t.goto(0, -200) t.down() my_fill('yellow', 200) # t.up() # t.goto(-90, 60) t.down() my_fill('bl...
3de834acde82a669511370ab541848d98f03b060
mollinaca/ac
/code/practice/abc/abc099/a.py
109
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- n = int(input()) print ('ABC') if n <= 999 else print ('ABD')
991978eaaacb557f9a7143e9fe3968ea2b99c440
stevechuckklein/tstp-chapter-challenges
/chapter-seven-challenges.py
1,420
4.125
4
#1. Print each item in the following list: ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]. chal1 = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] for i in chal1: print(i) #2. Print all the numbers from 25 to 50. for i in range(25,51): print(i) #3. Pri...
c992962cd8498ee4a42313d4dff8f6217937b7bf
peacej/random
/algo_exercises/sqrt_multiple_implementations.py
1,151
3.921875
4
def sqrt_halving(x, epsilon=0.0001): if x > 0: res = (x + 1) / 2 else: raise ValueError("invalid input") i = 0 if res * res < x: while res * res < x: prev_delta = res res = 2 * res i +=1 else: while res * res > x: prev_d...
961d4060c73db8f9f2361f1ea82219e02f173c4b
iteong/comp9021-principles-of-programming
/labs_finals/Lab7_Recursion_Strings.py
2,543
4.3125
4
strings = [] ordinals = ('first','second','third') for i in ordinals: strings.append(input('Please input the {:} string: '.format(i))) print('\nInputs in Strings List: {:}'.format(strings)) # Sorting strings: assign index values to variables to check particular string's index in list strings using length, # so t...
93b2361806ab82b49f0f3283b65ff08247b07140
yatengLG/leetcode-python
/question_bank/keys-and-rooms/keys-and-rooms.py
674
3.578125
4
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:80 ms, 在所有 Python3 提交中击败了87.03% 的用户 内存消耗:14.6 MB, 在所有 Python3 提交中击败了10.98% 的用户 解题思路: 深度优先遍历,递归 """ class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: record = set() def visit_room(key): record.add(key) ...
128bb19c16cfc39e199647ed5364259517bccc50
olabarka5/python-selenium-automation
/hw_algoritms_1/Max_of_three.py
277
4.125
4
a = int(input ("input first value ")) b = int(input ("input second value ")) c = int(input ("input third value ")) if a < b: if b < c: print (" c-max") else: print ("b-max") else: if a > c: print ("a-max") else: print ("c-max")
24ea20577f4c937e94c67233b6dcc1e19f0ec28b
Muntaser/PythonExploration
/lab_9/test_pokerodds.py
8,343
4.09375
4
''' Lab 9-4 Module: test_pokerodds.py: Muntaser Khan ''' import random SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"] RANKS = ["", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"] class Card(): """ Represents a single playing card, whose ran...
a9bd5d5fe221f9a29c943a95e12b4dcc2d9ef3be
yashika51/Hacktoberfest
/Python/dictionary-comp.py
208
3.78125
4
# this is one of my favorite code snippets because it allows me to easily create an arbitrary size dictionary keys = ['key1','key2','key3','key4','keyn'] dictionary = {k : [] for k in keys} print(dictionary)
85ab204d40e2e61ae4074206cc005eeceb6c9595
TPIOS/LeetCode-cn-solutions
/First Hundred/0048.py
413
3.53125
4
class Solution: def rotate(self, matrix): n = len(matrix) if n == 0 or n == 1: return for i in range(0, (n+1)//2): for j in range(0, n//2): tmp = matrix[i][j] matrix[i][j] = matrix[n-1-j][i] matrix[n-1-j][i] = matrix[n-1-i][n-1-j] ...
2fcb3271e2616d658d6ff80e04c092615d9a1b5c
venkyvijayb/codingground
/New Project-20170703/main.py
538
4.09375
4
# Hello World program in Python print "hello "+\ "world"; print "keep going" integer = 101; print integer+10; name = age = 'venkat' print name+" is a good boy " + age print name+str(integer) print eval(name) a,b,c=10,20,30 print a+1,b+2,c+3 print name print name[0] print name[2:4] print name[1:] print name*3 ...
5be8d605b7347bcdb2fe33f6debf65a5fc3687b3
Kush1101/Standard-Data-Structures-and-Algorithms-Applications
/Printing Duplicates in array/002.py
425
4
4
# in any unknown range. # Here we will use the unordered map to maintain a frequency count of all elements and return the ones with frequency>1 def find_duplicates(arr): freq = {} # use a dictionary to store frequency values for i in range(len(arr)): try: freq[arr[i]]+=1 except: ...
98aa352616163788996edb9a9364cd592aa33f48
JoshMez/Python_Intro
/While_Input/Intro_While.py
1,293
4.59375
5
#Aim: Asking the user to enter an input. #Using the input fucntion. #How to keep program running as long as users want them to. #So they can enter as much information as they need to. ####### ####### #Use Pythons while loop to keep programs running as long as certain conditions remain true. #### ### ########## ########...
9ba155316e8934ce4720d0172e88958c2b509c8a
borjamoll/programacion
/Python/Act_05/09.py
409
3.890625
4
h=int(input('Un lado, un lado !!! ')) l=int(input('Dame la altura, compañero. ')) if l==h: print("Mira jefe, te voy a ser sincero, lo que me has puesto es un cuadrado pero te lo calculo igual, por pena o por burla, como quieras tomártelo.") halt=h*"*" halt2=(h-2)*(' ') halt3=("*"+str(halt2)+("*")) a=l for i in rang...
05ac083ac4426487b01f830fb214d63781652f94
mjmingd/study_algorithm
/08.Math/CountFactors.py
1,007
3.890625
4
''' Codility - CountFactors A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M. For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4). Write a function: def solution(N) that, given a positive integer N, returns the number o...
fb4398eca315ba86d27d3486c0ba8d61b9578024
creepjavaer/algorithm
/enunzip.py
882
3.78125
4
#enunzip.py def enhancezip(str): stack=[] result="" number="" end=-1 p="" temp="" for ch in str: if ch !="]": stack.append(ch) print(stack) elif ch=="]": p=stack.pop() if stack: while p!="[": temp+=p print("hahh") p=stack.pop() print(p) result=temp p="" temp="" ...
0bc7907c35eaee8703d941e66427a1e182ad236b
tommyvtran97/SnakeAI
/neural_network.py
1,594
3.6875
4
""" This script contains the feed forward neural network that is implemented to the algorithm to train the snake AI agent. """ import numpy as np from settings import * class Neural_Network(object): def __init__(self, weights=None, bias=None): self.layer = layer self.weights_size = weights_size self.bia...
673bf6f30551e600810a1ce468234ddc9763328d
kesia-barros/exercicios-python
/ex001 a ex114/ex060.py
682
4.03125
4
'''from math import factorial n = int(input("Digite um número: ")) f = factorial(n) print("Calculando o fatorial de {}! = {}".format(n, f)) # outra forma de fazer: n = int(input("Digite um número: ")) c = n f = 1 print("Calculando {}! = ".format(n), end="") while c > 0: print("{} ".format(c), end="") print("X...
035a149c36827230993cf1edc60171ac4d8c0181
sevda-ebadi/django-asvs
/app/xss.py
322
3.515625
4
invalid_chars = { ' ': '&nbsp', "\"": '&quot', '>': '&gt', '<': '&lt', "'": '&apos' } def xss(string): out = str() for character in string: token = invalid_chars.get(character, None) if token: out += token else: out += character return ou...
a32588c3b36950cc5ad0f4955a9bd2e29e60951e
ATLAS-P/Introduction
/Workshop 1/Concepts/For Loops.py
621
4.65625
5
#Every time the code is run, the for loop sets one variable. for i in range(5): print(i) print("Done!") ''' The output of the above code is: 0 1 2 3 4 Done! For now, we're only using for loops in combination with range(). This gives the following options: ''' for i in range(7): # loops i from 0 (included) ...
cf583385a8d299f6d1719e3062c90ef587a44dd5
JakubKazimierski/PythonPortfolio
/Coderbyte_algorithms/Medium/PairSearching/PairSearching.py
2,695
4.46875
4
''' Pair Searching from Coderbyte December 2020 Jakub Kazimierski ''' def PairSearching(num): ''' Have the function PairSearching(num) take the num parameter being passed and perform the following steps. First take all the single digits of the input number (which will always be a...
1fed4c344bfe5bb8f87bd2af479c45d5956e09ab
NTN-code/Bank-System
/with refactoring/class_BinaryTree.py
890
3.5625
4
from random import randint class Node: def __init__(self, node,number): self.node = node self.left = None self.right = None self.number = number def add(self, value,number): if value < self.node: if self.left is None: self.left = Node(value,n...
685b7af6b8f12a4e39c01cb046b47ebf2ba78497
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/shrdan007/question1.py
210
4.09375
4
# Assignment 3, Question 1 # Danielle Sher i = height = eval(input("Enter the height of the rectangle:\n")) d = width = eval(input("Enter the width of the rectangle:\n")) for i in range(i): print (width*"*")
478418471db2d1cba5b58e5543b9526e84af50bb
luizhmfonseca/Estudos-Python
/EXERCÍCIOS - meus códigos/EX13.py
301
3.546875
4
#Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário com 15% de aumento. sal1 = float (input('Digite o valor do seu salário atual: ')) acresc = sal1 / 100*15 reaj = sal1 + acresc print(f'O seu salário teve um reajuste de 15% totalizando o valor de {reaj:.2f} reais')
c9ebac8c60f0c75076206f1c6f4b486896b3d7ac
taruntej14/PYTHON-PROGRAMS
/sortbyvalue.py
152
3.71875
4
dic1={'n':'tarun','t':'likhith','s':'santosh'} for i in sorted(dic1.values()): for j in dic1.keys(): if dic1[j]==i: print(j,i)
912ced747225e9d0ca4ee4dff51b5de3d618dc72
EldanGS/Engineering
/Python/aiohttp-intro/install_peps_asyncly.py
1,510
3.78125
4
import aiohttp import time import asyncio """ The code is looking more complex than when we’re doing it synchronously, using requests. But you got this. Now that you know how to download an online resource using aiohttp, now you can download multiple pages asynchronously. Let’s take the next 10-15 minutes to write t...
0d084a2ebddcc9d395ecfd9b3d66419d2f63b578
rohithkumar282/LeetCode
/LeetCode1455.py
481
3.578125
4
''' Author: Rohith Kumar Punithavel Email: rohithkumar@asu.edu Problem Statement: https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ ''' class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: import re key=-1 list_c...
f0ca68b93317a099b1dcf59650c681a876e720a6
Holladaze804/Python-Problems
/Grade_Average_Calculator_Assignment 20.py
810
4.03125
4
test1 = int(input("What grade did you receive on test 1? ")) test2 = int(input("What grade did you receive on test 2? ")) test3 = int(input("What grade did you receive on test 3? ")) test4 = int(input("What grade did you receive on test 4? ")) testaverage = ((test1 + test2 + test3 + test4) / 4) if testaverage >=...
61a55fa10f431566b8b774eb31464da128667ad9
h4hany/leetcode
/python_solutions/891.sum-of-subsequence-widths.py
1,702
3.625
4
# # @lc app=leetcode id=891 lang=python # # [891] Sum of Subsequence Widths # # https://leetcode.com/problems/sum-of-subsequence-widths/description/ # # algorithms # Hard (26.58%) # Total Accepted: 3.4K # Total Submissions: 12.9K # Testcase Example: '[2,1,3]' # # Given an array of integers A, consider all non-empty...
a0bb435a8d3b6fde39a7f472433895d31934d992
ravi4all/Python_Aug_4-30
/CorePython/01-BasicPython/StonePaperScissor.py
750
3.953125
4
import random import time cpu_choice = ['stone', 'paper', 'scissor'] cpu_ch = random.choice(cpu_choice) user_choice = input("Enter your choice : ") print("Cpu choice is",cpu_ch) time.sleep(2) if user_choice == cpu_ch: print("Match Tie") elif user_choice == 'scissor' and cpu_ch == 'paper': ...
e28d149336752ffa3036695657485e8f1bb61a65
chunweiliu/leetcode2
/kth_largest_element_in_an_array.py
1,419
3.671875
4
"""K largest numbers in an array << [3, 1, 2, 5, 4, 9, 4, 2], k = 3 => 9, 5, 4 - Heap Time: O(n + klogn) Space: O(k) - Quick Select Time: O(n + n) in average Space: O(1) """ import random class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: ...
2f23249f4a1273abea55701f099747290b53ae6b
SensehacK/playgrounds
/python/PF/Intro/Day8/Exercise41.py
796
3.546875
4
#PF-Exer-41 #This verification is based on string match. def sum_all(function, data): total_sum = 0 normal_sum = 0 for d in data : if function(d) : normal_sum = normal_sum + d #total_sum = total_sum + normal_sum return normal_sum #list_of_nos=[1,3,4,5,6,7,8...
1a91d8877583316ae1e0df1a28c9160a83664d33
pedrohcf3141/CursoEmVideoPython
/CursoEmVideoExercicios/Desafio027.py
152
4.0625
4
# Desafio 27 nome = input('Digite seu nome ').strip().split() print('Primeiro nome {}'.format(nome[0])) print('Primeiro nome {}'.format(nome[-1]))
925bbd3f1fc80058cd94f48a93a396b88bbb8cf8
chenglinguang/python-class
/classnew.py
3,702
4.125
4
''' Created on Apr 12, 2016 @author: echglig ''' class Student(object): def __init__(self,name,score): self.name=name self.score=score def print_score(self): print('%s: %s' % (self.name,self.score)) def get_grade(self): if self.score>=90: return 'A' ...
4d9e0dbef8ce61e27cf5648ce35459ff4730a7d0
givaldodecidra/controle-combustivel
/consumo.py
1,076
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function ## pega o valor da kilometragem inicial do carro km_inicial = float(raw_input("Digite a kilometragem inicial: ")) ## pega o valor da kilometragem final do carro km_final = float(raw_input("Digite a kilometragem Final: ")) ## pega o ...
1a6af15e5d5ce5e04e11ff5b5fd9129c4e19a44b
314H/Data-Structures-and-Algorithms-with-Python
/Graphs/Prim's Algorithm Problem.py
3,088
3.953125
4
""" ----------------------- Prim's Algorithm Problem ----------------------------- Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. Find and print the Minimum Spanning Tree (MST) using Prim's algorithm. For printing MST f...
d93ed82879e70534a7ec1259fba89ba341c39c79
Tezameru/scripts
/python/pythontut/0011_tuples.py
231
3.78125
4
coordinates = (4, 5) # coordinates[1] = 10 does not work, because tuples are immutable, they cannot be changed print(coordinates[0]) # you can make a list of tuples coords = [(9, 4), (4, 6), (3, 7)] print(coords) print(coords[2])
b154e06fa331038bcb860fa3d3def67ce9834397
nickest14/Leetcode-python
/python/medium/Solution_79.py
2,680
3.65625
4
# 79. Word Search from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: rows, cols = len(board), len(board[0]) path = set() def dfs(r, c, i): if i == len(word): return True if (min(r, c) < 0 or r >= row...
05d63521e7703c4301cf72a984e73915eff1f1b1
isaacburke/GradeCalculator
/142_grade.py
1,136
3.84375
4
#weight LAB=.1 HW=.1 PROJ=.1 EX1=.17 EX2=.23 FIN=.3 def main(): #lab lab_g=100 lab_t=90 g_lab=score(lab_g,lab_t,LAB) #hw hw_g=10+10+12+15+18+20 hw_t=10+14+15+15+20+20 g_hw=score(hw_g,hw_t,HW) #proj proj_g=40 proj_t=40 g_proj=score(hw_g,hw_t,PROJ) #ex1 ex1_g=6...
14f952e81e76418707cfe91aaee7a6787ada8527
ishanoon/advance_python
/not_function.py
205
3.96875
4
def is_even(num): if num % 2 == 0: return True else: return False numbers = [1,56,234,87,4,76,24,69,90,135] print([n for n in numbers if not(is_even(n))])