blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
80f97992306ea1e9b22767785777097708cd3489
robertomacedo/exerc_python
/palindromo.py
377
4.15625
4
""" Exercicios com strings """ print("*"*40) print("") print("BRINCANDO COM STRING USANDO PALINDROMO") print("") print("*"*40) enter = input("Digite uma palavra ou frase: ") def palindromo(enter): if enter[::-1] == enter: return f"A palavra {enter} é um palindromo" else: return f"A palavra {e...
3f3707643ecf72b522ee2707df9c78d60ea7853a
zionhjs/algorithm_repo
/1on1/new_course/1074-numberofsubmatrix.py
2,060
3.53125
4
# 这个方法太过于暴力了 遭遇TLE class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: n, m = len(matrix), len(matrix[0]) self.count = 0 # 1.make the matrix to sum_matrix for i in range(n): for j in range(m): #0, 0 ...
d80a8b4c88c8d0851127747cfb717fb85dd1667b
franciscoquinones/Python
/Clase2/ACtividades/Fibona.py
401
3.84375
4
# -*- coding: utf-8 -*- """ @author: Francixco """ #serie de Fibonacci print "Mi primer reto" n=input("Ingrese cantidad de terminos a mostrar: ") i=1 num_ant=0 num_act=1 print num_ant print num_act while i<=n: temp=num_act num_act=num_act+num_ant num_ant=temp print num_a...
3ab17af1e4ede7d43a224284e4894a2c3f3aef2c
nogajaakanksha/AQPG
/gui/login.py
3,604
3.71875
4
from Tkinter import * import sqlite3 import main import register import sys import os #==============================METHODS======================================== def Database(): global conn, cursor conn = sqlite3.connect("pythontut.db") cursor = conn.cursor() cursor.execute("CREATE TAB...
3bb2c04db1ca5b446287800607c6e13d32b52e4f
pichu0528/Python
/Data Structure/Sorting and Searching/Sorting 6 - Quick Sort.py
1,655
4.09375
4
def quick_sort(arr): quick_sort_help(arr,0,len(arr)-1) def quick_sort_help(arr,first,last): if first < last: splitpoint = partition(arr,first,last) quick_sort_help(arr,first,splitpoint-1) quick_sort_help(arr,splitpoint+1,last) def partition(arr,first,last): ...
431c7f7e5cfbfae71e2900cf562ce9fffad2de37
lukihd06/B2-Python
/scripts/1c-moy.py
1,176
3.734375
4
#!/usr/bin/env python3 # nom : 1c-moy.py # auteur : lucas erisset # date : 15/10/18 # script affichant la moyenne des notes et prénoms des personnes et un top 5 des notes # fonction top5 mais je n'arrive pas à la faire #def Top5 (valueDict): # i = 0 # concatVal = "" # valueDict = sorted(valueDict) # for name,score...
6b6e666d5a8f4e7a122c345abba56b9cdbaf1252
aleenaadnan15/official-assignment
/pattern1.py
317
4.125
4
#Question num 41: ''' The following pattern, using a nested for loop ''' n = int(input("Enter no. of rows: ")) for i in range (0,n): for j in range (0,i): print("*",end="") print("") for i in reversed(range(0,n+1)): for j in range(0,i): print("*",end="") print("")
1e31f026d689e97af4f110c031e9ef3ae3bbde7a
EstherChoi1245/Choi_Esther
/Semester1/Py_Lesson_04/Receipt2.py
757
4.09375
4
def printf (item, price): print ("* {:>20} ........\t{:0.2f}".format(item, price)) item1 = input("Please enter Item 1: ") price1 = float(input("Please enter the price: ")) item2 = input("Please enter Item 2: ") price2 = float(input("Please enter the price: ")) item3 = input("Please enter Item 3: ") price3 = floa...
645eb53b784ee7972089a913571e307274f5396d
vidun1208/python-projects
/temperature 2.py
89
3.796875
4
value=int(input("enter fahrenheit value")) celsius=((5*(value)-160)/9) print(celsius)
0eb18aa441c32e0b2fe1aeffc23208535403f886
felipemcm3/ExerPython
/Pythonexer/ExerPython/aprendendopython/testepython/aula09a.py
195
3.59375
4
frase: str = ' Olá felipe ' print(frase.replace('Olá', 'Oi')) print(frase.upper()) print('w' in frase) print(frase.find('ipe')) print(frase.split('e')) print(frase.strip()) print('+'.join(frase))
514861cab01147947da232796791bf261a1706c8
tzytammy/requests_unittest
/学习/机器学习/Pandas2.py
290
3.9375
4
from pandas import Series,DataFrame import pandas as pd obj2=Series([4,7,-5,3],index=['d','b','c','a']) print(obj2) obj2['c']=6 print(obj2) print('f' in obj2) #字典变数组 sdata={'beijing':3500,'shanghai':60000} obj3=Series(sdata) print(obj3) obj3.index=['bj','sh'] print(obj3)
0736d194f6328a17483e4f992711fb6017d2dbf8
AndreyIvantsov/PythonBeginner
/Ex23.py
970
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Блок finally # # При обработке исключений также можно использовать # необязательный блок finally. Отличительной особенностью # этого блока является то, что он выполняется вне # зависимости, было ли сгенерировано исключение: try: number = int(input("Введите число:...
7c6cce33c0f9f8e00e8f5a562ef01600f49b8388
MartinDardis/Algoritmos-2-FIUBA
/TP3/procesar_linea.py
1,166
3.53125
4
def separar(entrada): split = entrada.split(' ') if split [0] == 'viaje': comando = split[0]+' '+split[1] param_1='' for i in range(2,len(split)): param_1 +=split[i] if not i == len(split): param_1 += ' ' param_1 = param_1.rstri...
f09a4f269957ef0653f7689469896b34d9eac8c1
akishwary/Portfolio-Tracker
/Stock.py
11,178
3.6875
4
""" @author: Amrin.Kishwary The purpose of this class is to create a single stock portfolio. """ #import libraries import numpy as np #mathematical computation import pandas as pd #dataframe and data structure import matplotlib.pyplot as plt #plot and graph from matplotlib import style #customized plot design import ...
a068f91c95f9f7e57dd9135ee04abe37d4e97eda
Iam-El/Random-Problems-Solved
/leetcodePractice/easyProblems/Remove Outermost parenthesis.py
476
3.578125
4
def removeOuterParenthesis(s): count1=0 count2=0 val=[] res='' for i in range(0,len(s)): if s[i]==')': count1=count1+1 val.append(s[i]) if s[i]=='(': count2=count2+1 val.append(s[i]) if count1==count2: val=val[1:-1] ...
89111aea568a83e60c894492a56e2bdd11b561f2
ResolveWang/algorithm_qa
/other/q7.py
959
3.875
4
""" 问题描述:有一个机器按自然数序列的方式吐出球(1号球、2号球、3号球...),你有一个 袋子,袋子最多能装K个球,除了袋子外,没有别的可用空间。设计一种方案,使得当机器 吐出第N个球的时候(N>K),你袋子中的球数是K个,同时可以保证从1号球到N号球中的每一 个,被选进袋子的概率都是K/N. """ import random class KNRandomGetter: @classmethod def get_res(cls, k, n): if k < 1 or n < 1: return if n <= k: retu...
57b1aa16ae56a639ddb8fbcd617cef833856c4ba
raulgranja/Python-Course
/PythonExercicios/calculadora.py
2,310
4.3125
4
# -*- coding: utf-8 -*- print(" ") print("-----------CALCULADORA v1.0-----------") print(" ") print("Realiza operações de soma, subtração, divisão, multiplicação e exponencial") print("Os sinais de cada uma dessas operações são:") print(" ...
aba5c38867bf1f3106d9981090a874e9efe79b4b
mjaitly/LeetCode
/Algorithms/Easy/28_Implement_strStr.py
1,610
4.1875
4
''' Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 For the purpose of this problem, we will return 0 when needle is ...
00ef0929c090c87e1ebfdb39005e5d95a95205be
meysiolio/Collections.OrderedDict
/Collections.OrderedDict.py
273
3.6875
4
from collections import OrderedDict commodities = OrderedDict() for _ in range(int(input())): item, number = input().rsplit(maxsplit=1) commodities[item] = commodities.get(item, 0 ) + int(number) for item,quantity in commodities.items(): print(item,quantity)
11346f1fb81cf64fd30becf83ce3bfa922dc98cf
zoobereq/comp-ling-assignments
/Methods in CompLing I/MP2/fibonacci_numbers.py
1,180
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 13 13:42:21 2019 @author: zub """ """ def fibonacci(number: int) -> int: if number == 0: return 0 elif number == 1: return 1 else: return fibonacci(number-1) + fibonacci(number-2) print(fibonacci(100)) The ...
9f25b67229804e00964911da42f0d42a2e733dc7
Charptr0/Kruptos-Encryption
/main.py
6,996
3.84375
4
import tkinter as tk from tkinter import Label, filedialog from encryption import * from constants import * app = tk.Tk() #Start the app app.title("Kruptos Encryption") #Title app.config(bg= darkColor) app.geometry("800x800") #Resolution app.resizable(0,0) def openEncrypt(): #If the user clicked the "encrypted butto...
61751a6a68d6237fec100933916bf9122697e82c
psihanorak/critter-creation
/animals/animal.py
228
3.53125
4
from datetime import date class Animal: def __init__(self, name, species, food, chip_num): self.name = name self.species = species self.food = food self.date_added = date.today() self._chip_num = chip_num
7d245d99a0b417157de27fd129ae475b16beacda
lcppcl/S1
/day3/8函数.py
1,246
3.984375
4
def say(): #定义函数 print('hello, python') return 123 #函数返回值 f = say #把函数名赋给另一个变量,f指向这个函数 f() #执行函数 say() #执行函数 value = f() #拿到返回值 print(value) #默认参数必须放在指定参数后面 def show(a1, a2=1, a3=3): print('ok') #指定参数 def show2(a1, a2): print(a1, a2) show2(a2=1,a1=3) #动态参数 def show(*arg): #一个*把传入的参数当成...
19b68a9f81c246c5873563108031c09e9a131eb8
kimxoals/Algorithm_Practice
/07/namu_0723.py
335
3.828125
4
n = int(input()) max = 2*n-1 for i in range(2*n-1): if i < n - 1: space = i else: space = 2*(n-1)-i fill = max - 2 * space print(' ' * space + '*' * fill) ''' OR for i in range(n-1,0,-1): print(('*' * (2 * i + 1)).center(2 * n)) for i in range(n): print(('*' * (2 * i + 1)).cent...
a12442a56ac007a1c54873f45ae2931e7c0309ee
Seiji-Armstrong/seipy
/seipy/pandas_/base.py
14,195
4
4
""" helper functions to use with pandas library. Conventions: df -> pd.DataFrame Ideology: - Write functions that do one thing - Try write functions that are idempotent """ from functools import reduce from collections import namedtuple import numpy as np import pandas as pd import re def drop_uniq_cols(df): ""...
7f385ad49fd391f4d9c4ee8652e72a1e6a44bee0
andylinpersonal/CSX.Python.Class.HW
/src/Lv8.3091.class.py
790
3.921875
4
#!/usr/bin/env python3 #-*- coding:utf8 -*- import os class student: ''' 說明文件區塊必須緊鄰class宣告 This is readme of class student ''' name = '' gender = '' grades = [] def __init__(self): self.name = input() self.gender = input() def avg(self): summ = 0 for...
3715f21805f93498d8736d1668cea43c7c5cffc4
BelowzeroA/artificial-thinking
/src/simple_train.py
93
3.640625
4
a = 0 f = 1 for i in range(1, 10): if i >= 5: print(f) else: print(a)
fd10658e7d4b2559afea854982342060a166aec2
wedunsto/ContinuedPythonLearning
/testdf.py
567
3.53125
4
import pandas as pd test = dict() value = [] color = [] df = pd.DataFrame() test["1"] = [1,2,3,4,5,6] test["2"] = [7,8,9,10,11,12] for keys in test.keys(): for val in test[keys]: value.append(val) color.append(keys) df["Value"] = value df["Color"] = color df.to_csv("practicedictionary.csv") prin...
d96dbc126677fb3b658644c693bf992ec5413ae8
PacktPublishing/Advanced-Deep-Learning-with-Keras
/chapter1-keras-quick-tour/plot-linear-1.1.1.py
668
4.03125
4
'''Utility for plotting a linear function with and without noise ''' import numpy as np import matplotlib.pyplot as plt want_noise = True # grayscale plot, comment if color is wanted plt.style.use('grayscale') # generate data bet -1,1 interval of 0.2 x = np.arange(-1,1,0.2) y = 2*x + 3 plt.xlabel('x') plt.ylabel('y=...
4686fc9649755f93ea2ef8f534bfa39fd37ab726
ranjithsekar/python
/py-core/variables/variables-casting.py
442
4.15625
4
# Declaration my_num = 5 my_string = 'Ranjith' print(my_num) print(my_string) # Casting my_num1 = '4' my_num1_int = int(my_num1) print(my_num1_int) my_num2 = 3 my_num2_str = str(my_num2) print(my_num2_str) my_num3 = '6' my_num3_float = float(my_num3) print(my_num3_float) # Get the type print(type(my_num3)) print(t...
5fbeb1e7345d98cd35bf1a0552cf82bdc650af89
jsh2333/pyml
/day6/gyudon_keras.py
1,635
3.546875
4
from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras.utils import np_utils import numpy as np # 분류 대상 카테고리 root_dir = "./image/" categories = ["normal", "beni", "negi", "cheese"] nb_classes = len(categories) imag...
641038f5b2009b7c769009bca9343deb301e2935
niteesh2268/coding-prepation
/leetcode/Problems/1491--Average-Salary-Excluding-the-Minimum-and-Maximum-Salary-Easy.py
190
3.578125
4
class Solution: def average(self, salary: List[int]) -> float: sal = sum(salary) sal -= max(salary) sal -= min(salary) return sal/(len(salary)-2)
62a8885d420fb0036cb86ef861f3254c01d65414
tarcisiocsn/4epy
/ex_03_02.py
426
3.828125
4
sh=input('Enter Hours: ') sr=input('Enter Rate: ') try: fh=float(sh) # poderia colocar int(sh) mas é melhor assim fr=float(sr) except: print('Error, please enter a numeric input') quit() # não continua mais e não dará outro erro, só testar sem esse quit que verá o erro print(fh, fr) if fh>40: reg=fh...
9add02e688ea39612ad038b54e3e1e5e8174dfd1
python-13/homework
/04/宫祥瑞/str2int.py
291
3.859375
4
import cmath nums = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} def char2int(s:str): num = 0 for i in range(len(s)): num += nums[s[i]] if not i == len(s)-1: num *= 10 return num s = '123456789' n = char2int(s) print(n) print(type(n))
8f40cd6705b014f2e2fa2ffd831171c77bd481f2
jamalamar/Python-intro-Functions
/dogclass.py
137
3.53125
4
class Dog: def __init__(self, name, age): self.name = name self.age = age * 7 alf = Dog("Alf", 5) print(alf.name) print(alf.age)
9287691cc3a376cfb3bfff8957b0a84520377f77
harihara-n/nba_draft_lottery
/generate.py
2,884
3.984375
4
from numpy.random import choice class TeamPercentage(object): def __init__(self, team_name, team_lottery_pick_percentage): self.team_name = team_name self.team_lottery_pick_percentage = team_lottery_pick_percentage def generate_draft_order(teams, num_lottery_picks): draft_order = [] while len(draft_order) < nu...
0b503bd6eab4a7b2513b0265dab27b3c6abe3a4d
Will-Bailey/co
/coursework/SimulatedAnnealing.py
1,778
3.671875
4
from Ranking import Ranking import random import math class SimulatedAnnealing: tournament = None initial_ranking = None initial_temp = None temp_length = None cooling_ratio = None num_non_improve = None def __init__(self, tournament=None, initial_ranking=None, initial_temp=None, temp_leng...
b5fc6718662c77c3d7cf9a07c4047cc122418f98
LizaChelishev/class1310
/page32_11.py
160
4
4
a = int(input('Enter 1st number: ')) b = int(input('Enter 2nd number: ')) for i in range (a, b+1, 1): print(i) for t in range (b, a-1, -1): print(t)
fe82faabfd06e204c1ff3d696862302cb5a1f16e
vdakinshin/learn1
/list.py
480
4.03125
4
mylist = ['Вася', 'Маша', 'Петя', 'Саша'] #print(mylist) #print(len(mylist)) mylist.append('Маша') #print(mylist) #print(len(mylist)) #a = mylist.count('Ольга') #print('Сколько Маш в списке? Ответ:{}' .format(a)) #print(mylist) #print(mylist[-2]) #mylist.sort() #print(mylist) #c = mylist.index('Петя') #print(c)...
977c8624759726001ac752c1f2b734abf6d9144c
calvinsettachatgul/cara
/algorithms/test/test_count.py
779
3.75
4
from count import count # sum up all the numbers from 1 to input_num # if its less than 1 then return 0 def test_input_0(): '''testing input 0''' assert count(0) == 0 def test_input_None(): '''testing input None''' assert count(None) == 0 def test_input_1(): '''testing input 1''' as...
e7f57109d7751d446a5507cf1ecc12506f53be60
squeakus/bitsandbytes
/astar/graph.py
340
3.5
4
all_nodes = [] for x in range(20): for y in range(5): all_nodes.append((y, x)) def neighbors(node): dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]] result = [] for dir in dirs: neighbor = (node[0] + dir[0], node[1] + dir[1]) if neighbor in all_nodes: result.append(neighbor...
8f442a1871283ed5ed4c882b83d82710ec2ed10f
edunoodt/CFP_tkinter
/Tkinter Ej.2.a.py
3,657
4.03125
4
from tkinter import * # Define la ventana principal main = Tk() main.title('Calculadora de Financiación') C = StringVar() F = StringVar() I = StringVar() # Función convocada desde el boton de cálculo de la financiacón. # Utiliza la formula de calculo de valor actual de una renta fija prepaga: # Va=R * {[1-(1+tasa)^...
10de64eadd037bdc642913d773eff0d6af7748f1
tatsuya4559/ClassicComputerScienceProblemsInPython
/chap1/dna_search.py
1,111
3.609375
4
from enum import IntEnum from typing import Tuple, List import bisect Nucleotide: IntEnum = IntEnum("Nucleotide", ("A", "C", "G", "T")) Codon = Tuple[Nucleotide, Nucleotide, Nucleotide] Gene = List[Codon] def str2gene(s: str) -> Gene: gene: Gene = [] for i in range(0, len(s), 3): if (i + 2) >= len(s...
454762aa7fd392bdc68ed3048b675393ac6a364b
Om-krishna/Tkinter_GUI_python
/bind_function.py
324
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 5 20:28:18 2020 @author: Om Krishna """ from tkinter import* root = Tk() def printName(event): print("Hello my Name is Turners") button_1=Button(root, text="Print my name") button_1.bind("<Button-1>",printName) button_1.pack() root.main...
045bce7a658dfe085de8f8899af6a53c5905a910
Kortemme-Lab/klab
/klab/pymath/discrete.py
1,127
3.78125
4
#!/usr/bin/python # encoding: utf-8 """ A module for discrete mathematics. Not that this is something we should do in Python. Created by Shane O'Connor 2016 """ import fractions dumb_relative_prime_const = { 6 : 5, 5 : 2, 4 : 3, 3 : 2, 2 : 1, # yep, I know 1 : 0, # yadda yadda } def dumb_r...
0643dba567afa8728eaedcf63df771f10da83178
Bilsteen/Axenous_test
/Quest-2.py
727
4.1875
4
#Question 2: #Find number of small and capital letters in a string and replace all capital letters by same small letter and all #small letters by same capital letters def capital_small(word): new_word = [] cap = 0 small = 0 for char in word: if char == " ": new_word.app...
11e8a3fbc5670bc8428bf6457eca782aa37b87f2
managorny/python_basic
/homework/les04/file6.py
677
4.15625
4
""" 6. Реализовать два небольших скрипта: а) бесконечный итератор, генерирующий целые числа, начиная с указанного, б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее. Подсказка: использовать функцию count() и cycle() модуля itertools. """ from itertools import count, cycle from time...
ac611914e59a93523a5c2946947adcbba9a50d78
Jongy/knesset-committees-data
/make_wordcloud.py
732
3.53125
4
from typing import List from wordcloud import WordCloud def make_wordcloud(words: List[str], filename: str) -> None: # reverse all words, because wordcloud doesn't handle rtl words = list(map(lambda w: w[::-1], words)) font_path = "NotoSansHebrew-Regular.ttf" # copied from /usr/share/fonts wordcloud...
0561162acbe75d2d1693babb2c65601471afe0b6
prathamtandon/g4gproblems
/Arrays/min_steps_to_desired_array.py
1,529
4.21875
4
import unittest """ Given an array with n elements, value of all the elements is zero. We can perform following operations on the array: 1. Incremental operations:Choose 1 element from the array and increment its value by 1. 2. Doubling operation: Double the values of all the elements of array. The desired array target...
d25907e014e9c425b00e242c82f6718abeb70f39
kraktos/SimpleSearch
/Main.py
1,372
3.5
4
""" This is the single inception point for running the search mechanism. This file primarily performs (a) indexing the input file (b) persisting the indices locally (c) using indices to return search results for a given query """ import time import sys from optparse import OptionParser import utils.Utility as utility ...
491b066f5e174c096d13c1ea6a4669f0bea0238c
xxwqlee/pylearn
/pydemo/mypy09.py
522
3.8125
4
# 嵌套函数(内部函数) def print_name(is_chinese, name, family_name): c = 10 def inner_print(a, b): print("{0} {1}".format(a, b)) nonlocal c print(c) if is_chinese: inner_print(family_name, name) else: inner_print(name, family_name) print_name(True, "xx", "高") print_na...
1ea82a86d5bc8ee8ad291009c1ea54e6827e6035
CaoZhens/ML_Learning
/study/4_PythonFoundation/numpyBasics/flatx.py
698
3.90625
4
# coding: utf-8 ''' Created on Oct 16, 2017 @author: CaoZhen @desc: Basic Usage of numpy.chararray.flat numpy.chararray.flatten numpy.flatiter (class) numpy.ravel @reference: ''' import numpy as np x = np.arange(1, 7).reshape(2, 3) print x try: print x[3] except Ex...
05d67ef3b5d13c5b8fc968fa393bf75f68634486
manuelduarte12/iniciaci-n
/david aroesti/curso inicial/calendario.py
215
3.921875
4
contadorYear = 0 contadorMonths = 0 while contadorYear < 13: while contadorMonths < 31: print(f"{contadorYear}, { contadorMonths}") contadorMonths += 1 contadorYear += 1 contadorMonths =1
14285cbd0273acd06045cca30c723a210a104de1
tlvb25/AirBnB_clone
/tests/test_models/test_city.py
1,447
3.59375
4
#!/usr/bin/python3 """Unittest for City class""" import unittest from models.city import City from models.base_model import BaseModel import os class TestCity(unittest.TestCase): """Runs tests for City class""" def setUp(self): """Sets up the testing environment""" self.c1 = City() s...
668c4ccc2f619bb7d86307b1320f85928fef9421
KiraGol/Hillel
/homework_3/3.3.py
386
4.0625
4
friends = ["John", "Marta", "James"] enemies = ["John", "Johnatan", "Artur"] for friend in friends: if friend in enemies: print(friend + ', we are not the friends anymore') elif friend in friends and friend != 'James': print(friend + ', we are the best friends') # This pring is excess. Try to l...
eac6431a44f9e9bdb23808cee245cdcd62462f22
kwura/python-projects
/Foundations of Programming/phone.py
880
4.15625
4
def isPhoneNumber(text): # Check if phone number is correct length if( len(text) != 12 ): return False # Check for hyphens and numeric digits for i in range(3): if( text[i].isdigit() == False ): return False if(text[3] != "-"): return False for i in range(4,7): if( text[i].is...
431d2f5111eb1ed266c777c04d448afd35c96165
Bharadwaja92/HackerRank10DaysStats
/Day1_InterQuartileRange.py
1,856
4.25
4
"""""" """ The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3-Q1). Given an array, X, of n integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each xi occurs at frequency fi. Then calculate and pr...
39e0ff679a137244b15157e4b72215710e7a436e
maggielaughter/tester_school_dzien_6_v2
/good_range.py
329
3.640625
4
def good_range(number1, number2): while number 1 > number2: try: number1=int(input("Podaj liczbę :")) number2=int(input("Podaj liczbę :")) except ValueError: print('Liczba nr 2 jest za mała w stosunku do liczby nr 1!') return number1, number2 print(good_range...
93d98545748f35a2897631cdc1f85ac4a9680831
freeOcen/algori
/algoriDiagram/charpter3/tail.py
102
3.765625
4
def fact(x,y): if x==0: return y else : return fact(x-1,y+1) print(fact(3,0))
ab9bee7386b61a163e419c849482b574ecc2856e
TrellixVulnTeam/Demo_933I
/leetcode/994.py
597
3.59375
4
def main(grid): l1, l2, l0 = [], [], [] for num, value in enumerate(grid): for n, v in enumerate(value): if v == 2: l2.append([num, n]) elif v == 1: l1.append([num, n]) elif v == 0: l0.append([num, n]) if n...
55044e243dea9823e3f620b2d58f56af43757731
holod2020/Laborator
/Lab1/1. calculator.py
396
4.1875
4
def calculator(a, b, c): if c == "+": return a + b elif c == "-": return a - b elif c == "*": return a*b elif c == "/": return a/b else: return "operation" result = calculator (int(input("Enter number: ")), int(input("Enter number: ")), ...
12097ef43fbf1387aae8880acb6f8c9c366295b7
sornaami/luminarproject
/functionalprogramming/employeelist.py
865
3.75
4
class Employee: def __init__(self,id,name,salary,desig): self.id=id self.name=name self.salary=salary self.desig=desig def printEmployee(self): print("id=", self.id) print("name=", self.name) print("salary=", self.salary) print("desig=", self.desig...
d6ba610db8415ed6469d26e7667d485060825a76
xxxzc/public-problems
/PythonBasic/BasicGrammar/OOP/3_Point/solution.py
393
3.5
4
'''TESTCASE 3.0 4.0 6.0 0 - 1.4 -2.0 1.5 4.2 - -1 1.2 -3.2 5 - 0 0 0 0 ''' class Point: def __init__(self, x, y): self.x = x self.y = y def __sub__(self, rhs): return ((self.x-rhs.x)**2+(self.y-rhs.y)**2)**0.5 x1, y1 = map(float, input().split()) x2, y2 = map(float, input().split())...
3cc56898b36957ecd4da5dba46487cba571e2080
karenahuang/BackUp_PythonClassCode
/in_class2/test1.py
1,623
4.3125
4
#asks user to input year year = input("Enter the year: ") #asks user to input name name = input("Enter your name: ") #asks user to input age age = input("Enter your age: ") #asks user if they already had their birthday bday = input("Did you already have your bday this year? (Y or N): ") #casts the input from years into...
523bdfc9afc82cd5198016181f4acb2cebe334e7
juliansmoller/images
/timeline.py
3,123
3.765625
4
''' Julian Smoller ~ 2017 This module contains a Timeline class, which can plot time ranges as horizontal lines on an image. ''' from PIL import Image import pandas as pd import numpy as np from datetime import datetime class Timeline: def __init__(self,time_ranges,x_pixels=1000): '''Given a dataframe o...
728d94b3b8684c581ba068742ee48326df829d55
JiaquanYe/LeetCodeSolution
/Array/leetcode164.py
712
3.796875
4
''' 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 如果数组元素个数小于 2,则返回 0。 示例 1: 输入: [3,6,9,1] 输出: 3 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。 示例 2: 输入: [10] 输出: 0 解释: 数组元素个数小于 2,因此返回 0。 ''' class Solution: def maximumGap(self, nums): """ :type nums: List[int] :rtype: int """ ...
438767e8fe6e3f7315da5a5d276fa7dc8241ef14
FiberJW/hsCode
/guess_my_number_v3.py
3,930
3.96875
4
def guess_user_num(): import random, time print('\t\t\tGuess My Number!\nI will think of a number between 1 and 100 (Inclusive)\n\nTell me what you think the number is. I\'ll give you hints\n\n') def main(): #define main instructions as function for calling later num = random.randint(0, 100) ...
70a5d68acbef715c691971e001abdcb60301905a
doomnonius/advent-of-code
/2017/day03.py
2,795
4.09375
4
class Coord: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"{(self.y, self.x)}" def __add__(self, other): return Coord(self.x + other.x, self.y + other.y) def full_neighbors(self): return [self + Coord(0, 1), self + Coord(0, -1), self + Coord(1, 0), self + Coord(-1, 0), s...
e610b93b76fcf4b5a5bb489ac781a51049fa93bd
rjc89/LeetCode_medium
/unique_paths.py
651
3.671875
4
#https://leetcode.com/problems/unique-paths/discuss/959838/12-MS-oror-EASY-oror-PYTHON-oror-RECURSION-oror-MEMOISATION-oror-DP class Solution(object): def uniquePaths(self, m, n, cache = dict()): """ :type m: int :type n: int :rtype: int """ if (m,n) in cache: ...
b8a5a8f67384aee0caa6940c04c55ac1e246829d
7Biscuits/Calculator_Tkinter
/app.py
3,621
4.15625
4
import tkinter from tkinter import * root = tkinter.Tk() root.title("Calculator") user_entry = Entry(root, width=35, borderwidth=5) user_entry.grid( row=0, column=0, columnspan=3, padx=10, pady=10) def on_button_click(number): current = user_entry.get() user_entry.delete(0, END) user_entry.insert(0, st...
65790b34649ab12dd0015b0b17c02fd9f95c6b70
CircularWorld/Python_exercise
/month_01/test_01/test_05.py
564
3.953125
4
''' 5.需求:在终端中录入5个疫情省份的确诊人数, 打印最大值、最小值、平均值.(使用内置函数实现) 步骤:循环获取信息,使用列表记录,使用内置函数计算。 ''' list_num = [] for __ in range(5): confirm_num = int(input("请输入确诊人数:")) list_num.append(confirm_num) print(list_num) print('最多的有%d人' % max(list_num)) print('做少的有%d人' % min(list_num)) print("平均有%d人'" % (sum(list_...
360819013e0ba377002ccac046e9809bc1a9226c
CodecoolBP20161/python-data-visualisation-sf
/connection.py
808
3.5625
4
import psycopg2 class Database(object): def __init__(self, dbname, user, password): self.dbname = dbname self.user = user self.password = password def connect(self): connect_str = "dbname=%s user=%s host='localhost' password=%s" % ( self.dbname, self.user, self.pa...
60ad65bf86370b48796546ebbf53e4f88748f9f6
Sonatrix/Sample-python-programs
/temp.py
233
3.96875
4
def reverse(a,start,stop): if start>=stop: return a else: a[start],a[stop-1] = a[stop-1],a[start] reverse(a,start+1,stop-1) if __name__ == '__main__': a = reverse([3,7,198,32],0,3) print a #print reverse([1,2,3,4],0,3)
af68e75fa3e9cd2d2c4f77edf992f07677cdb555
kli99/python_challenge
/PyPoll/main.py
5,814
4.0625
4
<<<<<<< HEAD #load csv import os import csv #Path to collect data election_data_csv="C:/Users/Keke/git/python_challenge/PyPoll/Resources/election_data.csv" #define variables totalvotes= 0 #define column 3 as a dict to refer to occurence number of votes candidates={} #define value in column 3 as a list to cross refere...
bdda6bbe7a59096b4acdc3dc5a0a64a1c9a60fa0
edgardeng/design-patterns-in-python
/Command/stock_buy_sell.py
1,305
4.03125
4
from __future__ import annotations from abc import ABC, abstractmethod class Order(ABC): """ Order: The Command interface to execute buy or sell command """ @abstractmethod def execute(self) -> None: pass class Stock: def __init__(self, name=None, q=None): self.name = name ...
e3c29413e3797a6840c964d573e9e424209e5d0a
jabedude/0x2
/graduation.py
134
3.796875
4
#!/usr/bin/env python from datetime import date t = date(2018,2,16) -date.today() print('{} days until graduation!'.format(t.days))
398123f4f74e9425725a0ae3a92ac3295a225c60
bestchanges/hello_python
/sessions/4/konstantin_shrayber/main.py
695
3.828125
4
import rates current_rates = rates.load_current_rates() print(current_rates) is_continue = True while is_continue: input_string = input("input: ") if input_string == 'quit': is_continue = False else: if " " in input_string: for s in rates.calculate_currency_values(current_ra...
80f96519529e8434b05c2202c6e6094770e521a9
jedzej/tietopythontraining-basic
/students/synowiec_krzysztof/lesson_01_basics/sum_of_digits.py
242
3.65625
4
def main(): givenNumber = int(input()) lastDigit = givenNumber % 10 tensDigit = givenNumber // 10 % 10 hundredDigit = givenNumber // 100 print (lastDigit + tensDigit + hundredDigit) if __name__ == '__main__': main()
17eba7bcc0b449eaba26161f2d231300c98036a4
MrRa1n/Python-Learning
/Random.py
524
3.921875
4
# The 'random' module can generate pseudo-random numbers from random import * # Random floating point number between 0 and 1 print(random()) # Random whole number between 1 and 100 print(randint(1,100)) x = randint(1,100) print(x) # Random floating point number between 1 and 10 print(uniform(1,10)) # Fun with lis...
8d6bb266015f82879680df4140dd6dde8b3a97c8
harundemir918/Python-Samples
/02-basic_algorithms/02-reverse_text.py
230
4.59375
5
# Author: harundemir918 # Reverse text print("The Program That Reverse The Text That Entered") # Enter the text text = input("Enter a text: ") # The text will be reversed using indexes print("Reversed: ", text[::-1])
06ffb2cdb079f0f10b1484d86a62a028baf44f08
Brian-West/eclipse
/LearnPython/advanced/functional.py
4,065
3.875
4
# -*- coding: utf-8 -*- # 高阶函数就是可以接受函数参数的函数 import math def add(x, y, f): return f(x) + f(y) print add(25, 9, math.sqrt) def format_name(s): newS = '' newS += s[0:1].upper() newS += s[1:len(s)].lower() return newS print map(format_name, ['adam', 'LISA', 'barT']) # List的每一个元素作为定义域,返回值域的List de...
836d31f3017a92bea77c2157a37799da087dde51
TopaGeor/Hamiltonian-cycle-and-Plain-Graph
/hamilton_cycle_and_plain_graph.py
6,665
3.765625
4
import copy import sys alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # For a graph, we calculate the neighbors of every point # alphabet, every point has a character of the alphabet as id # Returns a list that for every point in graph has another list # that represents the neighbors of point def neighbors(graph): nei...
71bfcef2ff9305dd8313c1c89b9f266291f279c1
maulita291/UAS_SMT2_2021
/UAS_SMT2_2021.py
2,242
3.546875
4
ulang = 'y' while ulang == 'y': #Format UANG def rp(uang): x = str(uang) if len(x) <= 3: return 'Rp. ' + x else: a = x[:-3] b = x[-3:] return rp(a) + '.' + b #SiapkanVar kode = ['1','2','3'] ...
e069c7bff3bbf2f8833e6e44effb9052f5ee864b
dpaneda/code
/jams/advent/2021/5/solve.py
931
3.546875
4
#! /usr/bin/env python import sys from dataclasses import dataclass def step(a, b): if a == b: return 0 else: return 1 if a < b else -1 @dataclass(frozen=True) class Point: x : int y : int def parse(s): return Point(*map(int, s.split(','))) @dataclass class Line: a :...
5670860d909ed651cfaef4c3f67654b0c2870b68
leslie-toone/Cat-or-Dog
/wk 1 Transfer Learning Programming Assignment.py
15,565
4.15625
4
# # Programming assignment: Customising your Models TensorFlow 2 # ## Transfer learning # ### Instructions # Create a neural network model to classify images of cats and dogs, using transfer # learning: use part of a pre-trained image classifier model (trained on ImageNet) # as a feature extractor,and train additiona...
3865cc98acc46cf0f33c6ff8ccb756f795ccbe70
csams/python_examples
/examples/functional/cons.py
1,689
4.125
4
""" Lists can represent uncertainty in calculations. They allow functions to return several values instead of just one. Each of those values get fed to the next function, which returns it's own list of possible values for each input. """ from monad import Monad class List(Monad): @classmethod def unit(cls, x)...
11fb8a5fc1afc0866601643bea669d18eb872b28
thebiochemguy/sre-class
/Python_101/medium_exercise/box.py
264
4.03125
4
#Exercise 4: Print a box w=int(input("Width? ")) h=int(input("Height? ")) for y in range(h): for x in range(w): if(x == 0 or x == w-1 or y == 0 or y == h-1): print("*", end ='') else: print(" ", end='') print("")
2175c555d52ed7b48114f168fb784944145c6bce
vpisaruc/Python
/Программирование 2 сем/Лабараторные Python/Tkinter.py
3,020
4.25
4
# Бутолин Александер ИУ7-22 # Задано множество окружностей. # Определить ту, которая пересекает больше всего окружностей. from math import sqrt from tkinter import * try: def distance(x1,y1,x2,y2): return sqrt((x2 - x1)**2 + (y2 - y1)**2) def pifagor(r): return (sqrt((2*r)**2 + (2*r)**2))/2...
237c013d753d26cbe6210315978d3f7e87777ae5
viralmehta9/Web-Scraping
/NFL_Weekly.py
1,634
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 11 01:35:34 2016 @author: viral """ import urllib from bs4 import BeautifulSoup import csv import os #path and output data file os.getcwd() directoryPath = "..\.." os.chdir(directoryPath) f = csv.writer(open("NFL_Weekly.csv","w")) f.writerow(['Tea...
ae759ef6446371e39b537ef2e9a5a39e0bd33e44
alcebytes/Phyton-Estudo
/Prandiano_Python I/03_estruturas_de_decisao/exemplos_de_ifs.py
350
4.1875
4
a = 3 if a > 0: print("Você digitou um valor POSITIVO") b = 3 if b>0: print("Você digitou um valor POSITIVO") else: print("Você digitou um valor NÃO POSITIVO") c = -3 if c>0: print("Você digitou um valor POSITIVO") elif c==0: print("Você digitou um valor NULO") else: print("Você digitou um...
9862d57ff5a87f7e2f4749b9d603dfbd6f0d8173
Nkugsw/python-notes
/10152018.py
242
3.765625
4
Restaurant = ('rice','noodles','pizza','orange','ice cream') for food in Restaurant: print(food) #Restaurant[0]='cake' print('\n') NewRestaurant = ('cake','falafel','pizza','orange','ice cream') for food in NewRestaurant: print(food)
a3985cc785da63b45670fe5d96c96d75fa4889ac
GuoYunZheSE/Leetcode
/Easy/1475/1475.py
658
3.578125
4
# @Date : 23:13 04/26/2022 # @Author : ClassicalPi # @FileName: 1475.py # @Software: PyCharm class Solution: def finalPrices(self, prices: [int]) -> [int]: order_dic = {} mono_stack = [] for index, price in enumerate(prices): while mono_stack and mono_stack[-1][1] >= price: ...
818a80a935b3fb76bcdeeb5fb28a4309bf495d3d
kojuki/python_intense
/lesson4.3.py
839
3.859375
4
def attack(atacker, victim): victim['health'] = victim['health'] - atacker['damage'] return victim # для игрока сделаем изменение значения существующего ключа player = { 'name' : None, 'health' : 100, 'damage' : 50 } # А для противниа сделаем ввод нового ключа со значением enemy = { 'heal...
bd50afd20753a90868d11916d15f54f9c5211743
mikeehun/codewars
/kyu7/the-old-switcheroo/vowel_2_index.py
593
3.96875
4
def vowel_2_index(string): switched_string = '' position_in_string = 0 vowels = set('aeiouAEIOU') for letter in string: position_in_string += 1 if any((v in vowels) for v in letter): switched_string += str(position_in_string) else: switched_string += lette...
40530c42b95e71a34858fa30860298450fcfb094
mgundogan20/semester-1-Problem-Set-1
/ps1d.py
1,559
3.953125
4
# Your solution for part d # Your solution for part d import math monthly_salary = float(input("What is your monthly salary? ")) total_cost = float(input("What is the cost of your dream car? ")) percentage_increase = float(input("Enter the increase in said car's price in decimals: ")) salary_raise= float(input("Enter t...
39cc60f18fa35bc0206229fb9fedc82ec5c9d230
suyundukov/LIFAP1
/TD/TD2/Code/Python/7.py
410
3.875
4
#!/usr/bin/python # Calculer les racines rééles d'un polymer du second degré from math import sqrt print('Donne moi trois entiers, un par un : ', end='') a = float(input()) b = float(input()) c = float(input()) d = b * b - 4 * a * c if d < 0: print('Pas de racine réels.') elif d == 0: print('Une racine doubl...
4a1f020ae889c7b6fa482726e811b2af33018ad0
renaldyresa/Kattis
/oktalni.py
520
3.703125
4
biner = input() while len(biner)%3!=0 : biner = "0"+biner hls = "" for i in range(0,len(biner),3): if biner[i:i+3] == "000" : hls+="0" elif biner[i:i+3] == "001" : hls+="1" elif biner[i:i+3] == "010" : hls+="2" elif biner[i:i+3] == "011" : hls+="3" elif biner[i:i+...
7547ec70fea92c6d820293f47ae5c95c8446de38
timsergor/StillPython
/068.py
1,330
3.84375
4
#1123. Lowest Common Ancestor of Deepest Leaves. Medium. 64.4%. #Given a rooted binary tree, return the lowest common ancestor of its deepest leaves. #Recall that: #The node of a binary tree is a leaf if and only if it has no children #The depth of the root of the tree is 0, and if the depth of a node is d, the depth ...
e79778d274e9bf89b4ea4fa5fbb9780cbe6cbd4d
MihailMihaylov75/algorithms
/linked_lists.py
2,282
3.984375
4
__author__ = 'Mihail Mihaylov' # Singly linked list class Node(object): def __init__(self, value): self.value = value self.next_node = None @staticmethod def cycle_check(node): """Check if linked list contains cycle""" marker1, marker2 = node, node # If link is No...
d8bc298b18d557b73c482a4990eade3fa8a9ea88
marciofleitao/ifpi-ads-algoritmos2020
/04 - Lista Fábio 01 - Parte 2 - Entrada, Saída e Operadores/f1_p2_q20_eq_linear.py
457
3.921875
4
# 20. Um sistema de equações lineares do tipo , pode ser resolvido segundo mostrado abaixo: # ENTRADA a = int(input('Insira o a: ')) b = int(input('Insira o b: ')) c = int(input('Insira o c: ')) d = int(input('Insira o d: ')) e = int(input('Insira o e: ')) f = int(input('Insira o f: ')) # PROCESSAMENTO x ...