blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6d44eeb3076105ed28ea127912191c2014866d13
seesoft/SoftUni-Courses
/Python/Basics/0.1-First-Steps-In-Coding/Exercises/fish_tank.py
360
3.859375
4
length = int(input()) width = int(input()) height = int(input()) taken_space = float(input()) taken_space_in_percents = taken_space * 0.01 available_space_in_centimeters = length * width * height available_space_in_meters = available_space_in_centimeters * 0.001 needed_liters = available_space_in_meters * (1 - taken_...
e153c7d9b15a596c5e19c67b1e573c67bb3faba1
superwenqistyle/1803
/14day/第七题.py
211
3.796875
4
def xxx(): list = [{"beijing":{"mianji":1290,"renkou":123123},"shanghai":{"mianji":12331,"renkou":123123}}] for temp in list: for k,v in temp.items(): for p,j in v.items(): print(k,p,j) xxx()
bf5b496e345713923d8d783e838e113d4785fe39
le-birb/advent-of-code_2020
/day6.py
1,105
3.75
4
groups = [] curr_group = [] with open('day6-input', 'r') as f: for line in f: line = line.strip() if line == "": # blank lines separate groups if curr_group: groups.append(curr_group) curr_group = [] else: # store answer...
1066830533798c32ab67d97432f311af439a8961
SergMT/Prolux
/Fechas.py
1,378
4.125
4
#Se importa la librería datetime, timedelta para hacer operaciones con fechas from datetime import datetime, timedelta #Se obtiene la fecha actual con datetime.now() fechaActual = datetime.now() #Para concatenar con strings, se convierte la fecha en string print("La fecha actual es: " + str(fechaActual)) """Uso de ti...
bcfc55d277069946b75cab734d2f63edc35b18c3
JiangWeixian/Algo
/docs/Sword2offer/CH4-解题思路/Python/checkBST.py
921
3.953125
4
def split_lr(arr): root = arr[-1] for i in range(len(arr)): if arr[i] > root: return i def is_bst(arr): root = arr[-1] if arr[0] < root and arr[1] > root: return True return False def recurvise_check(arr): result = False if len(arr) > 3: mid = split_lr(arr) if mid >...
143bd551e0539d4d8c713dcd024da0b62322f44e
PhoenixGreen/Python-GUI
/Lesson 2.2 - Auto image slides - advanced.py
1,420
3.6875
4
from tkinter import * # The main app window and background image window = Tk() window.title("My Slide Show") window.geometry("600x500") background_image = PhotoImage(file = "landscape.png") background_label = Label(window, image = background_image) background_label.place(relwidth = 1.0, relheight = 1.0) # upper fra...
9460b6d954c25a57da6fd9d3f4f2ec79642e76d8
olesmith/SmtC
/Curve/Roulette.py
2,382
3.796875
4
from math import * from Vector import * class Curve_Roulette(): ##! ##! Get rolling angular velocity as function of t ##! def Curve_Roulette_Angle(self,t): n=self.T2n(t) s=self.S[n] return -s/(self.Roulette_A) ##! ##! Calculates curve unit normal v...
3879e669ede0407269fd9daabf73e18879b3582d
Haider8/matrix-happiness
/lib/matrix.py
1,184
4
4
#matrix.py def matrix_add(order): alpha = order*order elements1 = [] elements2 = [] add = [] for i in range(0, alpha): elements1.append([]) elements2.append([]) add.append([]) print("Enter elements in first matrix...\n") for i in range(0, alpha): elements1[i]...
1b84cc187ed57b8c2706d06f5d3275296df3f0e4
to-Remember/TIL
/June 7, 2021/2_picachu_func.py
1,590
3.6875
4
hp = 30 exp = 0 lv = 1 def 밥먹기(): global hp #hp는 전역변수임을 의미 print('피카추 밥먹음') hp += 5 def 잠자기(): global hp #전역변수라고 지정하는 것 print('피카추 잠잠') hp += 10 def 놀기(): global hp, exp #전역변수라고 지정하는 것 print('피카추 논다') hp -= 8 flag = hp > 0 #살아있다면 아래와 같이 경험치 추가 if flag: exp += 5 ...
5ea22b620ea584b439281a88f88804923e935739
dmccloskey/EvoNetPyScripts
/MNIST_expectedPredicted.py
5,403
3.515625
4
from matplotlib import pyplot as plt import numpy as np import csv import sys def read_csv(filename, delimiter=','): """read table data from csv file""" data = [] try: with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile, delimiter=delimiter) ...
cd9c22a5e27178c5dd55bc102e534ed0f39066b5
pala9999/python
/week1/week1_q4.py
558
4.0625
4
my_list = ["a", "c", "d", "e", "f", "g", "h", "i"] print("Initial List: ", my_list) my_list.append("j") print("\nAdd \"j\" to the end of list:") print(my_list) print("\nInsert \"b\" between \"a\" and \"c\":") my_list.insert(1,"b") #Specify postion , character to add# print(my_list) print("\nRemove \"e\" from list:") my...
4d1f500949c0599c542aacc784ca128c2a87b89d
HesterXu/Home
/Lemon/Python_Base/Lesson6_function_20181107/Lesson6_function_20181107.py
3,300
3.578125
4
# -*- coding: utf-8 -*- # @Time : 2018/11/7/20:04 # @Author : Hester Xu # Email : xuruizhu@yeah.net # @File : Lesson6_function_20181107.py # @Software : PyCharm # 函数: # append pop insert range print input int str list replace strip split # 内置函数 # 参数:可以是0个,1个,或多个。 有参数时,调用时必须传参。 # return 变量的个数 变量个数可以是0...
ee4d151114477797795924ead51c62340389f489
rajputsher/LinearAlgebra
/1_Vectors/8_LengthVector.py
267
3.703125
4
import numpy as np # a vector v1 = np.array([ 1, 2, 3, 4, 5, 6 ]) # methods 1-4, just like with the regular dot product, e.g.: vl1 = np.sqrt( sum( np.multiply(v1,v1)) ) # method 5: take the norm(norm is the length directly) vl2 = np.linalg.norm(v1) print(vl1,vl2)
f45008733799d5d89b770764b371be4a2a3287b3
Levintsky/topcoder
/python/leetcode/dp/1027_longest_arith.py
2,300
3.921875
4
""" 1027. Longest Arithmetic Sequence (Medium) Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all ...
9f2da46d92bcc86dd5338f181fd7c2a8cd12741d
pi-2021-2-db6/lecture-code
/aula04-exercicios/calcula_divida.py
343
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Determina o valor da dívida com base no capital, taxa de juros e periodo transcorrido @author: Prof. Diogo SM """ p = float(input("Capital (R$): ")) i = float(input("Taxa de juros (entre 0 e 1): ")) n = int(input("Periodo (em meses): ")) j = p * i * n d = p + j prin...
446e4531858b9b3d06d1800278db0b917feb5505
mehzabeen000/list
/front_back.py
272
3.671875
4
#we have to see whether the particular list look same form front and behind a=[1,1,2,1,1] i=0 mid=len(a)//2 same=True while i<mid: if a[i]!=a[len(a)-i-1]: print("No") same=False break i+=1 if same==True: print("Yes")
a3c10c105c5fb526d610d18467a7525db58b27eb
lxhguard/django-
/blog/data/mysql_to_excel.py
1,652
3.53125
4
""" mysql_to_excel(username, password, database_name, port) 参数:username:数据库用户名 password:数据库用户密码 database_name:要存入的库的名称 port:数据库端口 功能:将数据库相应库的num张以table+n为名称表存入excel中,保存到当前文件夹 返回值:void date:2018.11.24 author:Benjamin """ import pymysql import openpyxl ...
cf1fc981b883f9a27e6f727b6eef4766bb718db4
wktfraser/ArtifactMarketAnalysis
/feature_MarketPricing.py
1,105
3.53125
4
import math from Feature import Feature from constants import RARITIES class MarketPricing(Feature): def print(self, market_data): longest_rarity = len(max(RARITIES, key=len)) card_data = market_data.get_card_data_by_rarity() print(f"[ {'RARITY':>{longest_rarity}} MEDIAN AVERAGE ]...
429ab228864b3fe4dec19753d31037be31813aea
suprviserpy632157/zdy
/ZDY/Jan_all/pythonbase/Jweekends/weekend2/exam3.py
1,138
4.375
4
# 3.用字典的方式完成下面一个小型的学生管理系统。 # 学生有下面几个属性:姓名,年龄, # 考试分数包括:语文,数学,英语的分 print("--------------张明,李强的原始信息-------------------------") ainfo={'name':'李明','age':'25','score':{'chinese':80,'math':75,'English':85}} binfo={'name':'张强','age':'23','score':{'chinese':75,'math':82,'English':78}} print(ainfo) print(binfo) print("--------...
839eea459a33ae083b95e8c85b85b0d223853a52
knoxTIMATE/questiopython3
/Some basic Hackerrank/Mini-max sum.py
431
3.859375
4
def miniMaxSum(arr): sumlist=[] arr=[5, 5, 5, 5, 5] print (len(arr)) print (max(arr)) print (min(arr)) for i in arr: sum=0 for j in arr: if i==j: continue elif max(arr)==min(arr): sum+=j els...
88efcb5ab9b289214dbba478dccad7944e69a532
egbrighton/BaylorIRES2020
/PyEval/src/FindAST/Find.py
1,378
3.515625
4
''' Elizabeth Brighton Evaluation Assignment (Python) Find.py ''' import os from CreateAST.Create import * ''' FindClass This Class takes a directory as an argument and searches through the directory and subdirectories to find .py files and create AST's for each ''' class FindClass: count = 0 create = CreateC...
9796a59f64851795ddddc65216d0c3be51da4a95
Myles-Trump/ICS3U-Unit6-03
/main.py
906
4.15625
4
#!/usr/bin/env python3 # Created by: Myles Trump # Created on: May 2021 # This program randomizes 10 numbers and figures which is the smallest import random def main(): # this function randomizes 10 numbers and figures out which is the smallest my_numbers = [] smallest_num = 100 # input for lo...
f4267be865674374803dd4a83ed82ced78efb138
nstella67/python
/section08/03-numpy3.py
930
3.765625
4
#/section08/03-numpy3.py #배열 연산 import numpy grade=numpy.array([82, 76, 91, 65]) print(grade) #[82 76 91 65] #모든 원소에 대하여 2씩 더함 new1=grade+2 print(new1) #[84 78 93 67] #모든 원소에 대하여 5씩 뺌 new2=grade-5 print(new2) #[77 71 86 60] #배열 원소끼리 연산 #인덱스가 동일한 원소끼리 수행 arr1=numpy.array([10, 15, 20, 25, 30]) arr2...
c1bdcb646142281e90fc15b35020926f846fa2f2
michelleweii/Leetcode
/16_剑指offer二刷/剑指 Offer 16-数值的整数次方.py
1,149
3.625
4
""" middle 快速幂 https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/ """ class Solution: # 超出时间限制 def myPow(self, x: float, n: int) -> float: if n==0:return 1 sign = 0 if n<0: sign = 1 n = -...
178d8fae544dc0f52375d380f152fd6bc8e8a782
megnabb2/WECEtechmusiclights
/weather_lights/wind_speed_lights.py
2,307
3.703125
4
# implementation of windspeed function. # the wind_speed_lights function generates a visual lights representation # of the current wind speed based on import board import neopixel import time # local imports # is there a better way to do this? try: from weather_lights.WeatherLights import WeatherLights except: ...
c1c22a75dfa8b2c2f6cdf6bfe55455a1db672d25
mullerpaul/RC_circuit_model
/model.py
344
3.8125
4
# initial conditions vinit=10 r=1000 c=0.001 Q=c*vinit # set up time variable and time step t=0 dt=0.10 # loop - increment the time by the time step value until we hit the end while (t<10): print ("at time ", t) dQ=Q*dt/(r*c) Q=Q-dQ v=Q/c i=c/r t=t+dt print("voltage is ", v) # TODO: save i and v values so we ...
10c78565c9e312a3918cabe7b4ae4a00e81df4b9
Mr-Helpful/NEA-project
/Scrabble/dictionary.py
10,849
3.96875
4
''' A trie based mathod of storing a dictionary. This allows it to be more compact and allow for faster searching ''' class Dictionary: def __init__(self): self.Trie = self.retrieveDict() pass def retrieveDict(self): # retreives the trie for use in the program trieCheck = self....
0c60d082ee62c12e8544d08df282134ca8868ac8
dwij2812/Siemens-App
/setup.py
576
3.5625
4
from matplotlib import pyplot as plt from matplotlib import style import numpy from numpy import genfromtxt data = genfromtxt('example.csv',delimiter=' ') data=data[~numpy.isnan(data)] print(data) listobj=data.tolist() print(listobj) plt.plot(data) plt.title('Epic Info') plt.ylabel('Y axis') plt.xlabel('X a...
cfdb493491d1d7f78ff3aab33d261e6d059a00d3
rogeriosilva-ifpi/adsi-algoritmos-2016.1
/atividade_d/Osmar_Junior_ADS2016_1/atdq10.py
379
3.75
4
#coding: utf-8 def escreva_tabuada(numero, indice): if indice>10: print("Tabuada Feita!") else: print(">> ",numero,"x",indice," = ",(numero*indice)) escreva_tabuada(numero, indice+1) def main(): numero = int(input("Digite um numero: ")) indice = int(input("Digite um indice da tabuada (1-10): ")) escreva_ta...
0302e467791200a5be33c70ebca03fc196bca5fa
alaz1812/My_Homework
/Pack_1/task_2.py
235
3.84375
4
A = raw_input ("Could I ask you for a number? ") B = int(A) def divisors(A): help = list() help.append(B) for i in range(B//2, 0, -1): if B % i == 0: help.append(i) return help print (divisors(A))
b67adede94b00030647e145bea17292b5caa7928
Aminaba123/LeetCode
/501 Find Mode in Binary Search Tree.py
2,834
3.90625
4
#!/usr/bin/python3 """ Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains...
413e026002d18641c93b590985168911ca5861a3
ganjingcatherine/LeetCode-1
/Python/Add and Search Word - Data structure design.py
1,954
4.0625
4
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. For example: addWord("bad") addWord("dad") addWord("mad") sea...
eeb51c39072f03622dc4f5726cbd98404fd59e8f
phucle2411/LeetCode
/Python/employee-importance.py
912
3.859375
4
# https://leetcode.com/problems/employee-importance/ """ # Employee info class Employee(object): def __init__(self, id, importance, subordinates): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.impor...
04cee459d76fae0cfc261eb6d96b351d6d058ea4
ShiekhRazia29/Dictionary
/samp4.py
222
4.15625
4
person={1:"Razia",2:"Rani",3:"Rutuja",4:"Rahila",5:"Ranveer",6:"Ranjitha" } print(person[3]) x=person.get(4) #helps in accessing the elements of the dictionary print(x) print(person[6]) name=person[5] print(name)
ce28effb7a82860ea55f6d70b7c1fe08525bb3b8
starwriter34/Advent-of-Code
/2020/03/code.py
1,654
3.53125
4
def readFile() -> list: with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return [line[:-1] for line in f.readlines()] def count_trees(mylist, dx, dy): x, y, cnt, length, mod = 0, 0, 0, len(mylist) - dy, len(mylist[0]) while y < length: x = (x + dx) % mod y += dy ...
ab26cd7adfb59b192727b79c597c2104f20eaf52
GarfieldJiang/CLRS
/P4_AdvancedTech/DP/problem_15_2.py
2,733
3.734375
4
import unittest def get_longest_palindrome_subsequence(s): """ Problem 15-2. __calc_lps_length runs in \Theta(n^2) time. __build_lps runs in \Theta(n) time. :param s: input string. :return: a longest palindrome subsequence (LPS) of s. """ if not s: return () n = len(s) length...
76812ae6b042fbb019586b34b8db5bbe51d2536d
JamCrumpet/Lesson-notes
/Lesson 7 function/7.11_project_2.py
755
3.765625
4
def make_shirt(size,text): """Display size and text on shirt""" print("\nYou have chosen a size " + size + " shirt.") print('Printing "' + text + '" on shirt.') make_shirt("M", "Hello World!") def make_large_shirt(text, size = "L"): """Display size and text on shirt""" print("\nYou have c...
83b91698e84fc8f56d0fb5069461c9cbee9ffdd0
olanlab/python-bootcamp
/02-varibles/temperature.py
176
4.15625
4
celsius = float(input("Enter a temperature in Celsius: ")) fahrenheit = (celsius * 1.8) + 32 print(celsius, "degrees Celsius is equal to", fahrenheit, "degrees Fahrenheit.")
b61af147e8d93ba60d6bb747f05f15c64892c547
Shivani161992/Leetcode_Practise
/Microsoft/BoundaryOfBinaryTree.py
3,241
3.609375
4
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 1 # / \ # 2 3 # ...
69b754a39ba390a94e33b048673e646465720d2a
mmokko/aoc2017
/day11.py
2,037
3.515625
4
from day11_input import INPUT class Coordinates(object): def __init__(self, x=0, y=0): self.x = x self.y = y def travel(self, direction): if direction == 'n': self.y += 1 elif direction == 'ne': self.y += 1 self.x += 1 elif direction...
b28143162638ba5d2c6cb14316412c5eb3a2871c
Maynot2/holbertonschool-higher_level_programming
/0x0B-python-input_output/101-stats.py
1,275
3.734375
4
#!/usr/bin/python3 """reads stdin line by line and computes metrics:""" import sys import re def print_size_errors(size, error_counts): """Print the size of all error files and a count of the error types""" print('File size: {}'.format(size)) for k, v in sorted(error_counts.items()): if v: ...
25c6b8baff6f02dc51e92e7a03e98c60aca7bbc4
edutomazini/courseraPython1
/quadrado.py
186
3.671875
4
strLado = input("Digite o valor correspondente ao lado de um quadrado: ") intLado = int(strLado) perimetro = 4*intLado area = intLado**2 print("perímetro:", perimetro,"- área:", area)
380e73a1b2b4d77c7389717667790cc930f6017b
GitDruidHub/lessons-1
/lesson-12/main.py
1,756
3.640625
4
from sqlalchemy.orm import Session from database import setup_db_engine, create_database_if_not_exists, create_session from functions import create_user, create_product, create_purchase, get_user_purchases from models import User, Product template = """ Please choose one of the options: 1. Create user 2. Create p...
69da67956333926a01d7c00ef7f5338152f90eaf
dud3/py-diff-and-nx-parser
/tree.py
1,217
3.734375
4
class Tree(object): "Generic tree" def __init__(self, name='root', value='', children=None): self.name = name self.value = value self.children = [] self.indent = 0 if children is not None: for child in children: self.add_child(child) def...
2ac0026837320cf6d715b93752f8e83141687f98
abhitechegde/py_sample_apps
/CAGR_FD_SIP_EMI/cagr.py
436
3.5625
4
# CAGR= (L/F)^(1/N) -1 # Where: # F = first value in your series of Values. # L = last value in your series of values. # N = number of years between your first and last value in your series of values. F = float(input("Enter The Initial Value: ")) L = float(input("Enter The Final Value: ")) N = int(input("Enter...
7d6801687f58163e6ffcc7b290886f5f13ff26f0
Mansi149/Python
/02 Area of Circle.py
204
4.125
4
""" PROBLEM 2 Write a program to calculate the area of a circle? """ import math Radius = float(input("Enter Radius : ")) area = 2 * math.pi * Radius print("Area of the circle is :", area)
a5bbf5df5613c9f23985ca09f9902c6fc1a6488e
data61/blocklib
/blocklib/encoding.py
1,982
3.515625
4
"""Class to implement privacy preserving encoding.""" import hashlib import numpy as np from typing import List, Set def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int): """ Hash string and return indices of bits that have been flipped correspondingly. :param string: string: to be hashed...
b55fcf5569b34e2924076ad8d978412cb242f9c0
AdamZhouSE/pythonHomework
/Code/CodeRecords/2649/60731/313120.py
274
3.90625
4
n=int(input()) a=[] for i in range(n): d=input() a.append(d) if a==['17 2 3', '50 2 4']: print(23) print(60) elif a==['17 2 3', '50 2 5']: print(23) print(44) elif a==['17 2 3', '44 3 4']: print(23) print(32) else: print(23) print(34)
5f7699b3e6d15fde566b1bb42b010fb8ad48c1a6
arcarchit/mit-ds-algo
/dsalgo/cs/graph/topo_sort.py
2,638
3.859375
4
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) self.vertices = set() def addEdge(self, u, v): self.graph[u].append(v) self.vertices.update([u, v]) def topo_sort(self): ans_stack = [] visited = set() ...
1bc84d0e315ded514309f9c868fa57901c381c49
algoORgoal/ICPC-Training
/Baekjoon/num_1068_별찬.py
2,790
3.8125
4
# name: 트리 # date: July 17, 2020 # status: solved from sys import stdin class Node: def __init__(self, label, parent=None): self.label = label self.parent = parent self.children = [] class Tree: def __init__(self, root=None): self.root = root def insert(self, label, par...
65baff134ad40c2d179a4a595051f8df48be8dc9
gnsaddy/Python
/specificMethodInString.py
1,263
4.53125
5
# find() method, it specified the starting location of the original string string = "welcome to the world of python" print(string.find('the')) print(string.find('of')) # replace('1','2') method, in the we basically replace the original string with some other string print(string) print(string.replace('python', '...
c3b8346266a20734452bdb6cc5cdbbd051aa6e93
jackjyq/COMP9021_Python
/ass01/poker_dice/print_roll.py
523
4.09375
4
def print_roll(roll): """ print_roll Arguements: a list of roll, such as [1, 2, 3, 4, 5] Returns: print roll, such as "The roll is: Ace Queen Jack Jack 10" """ poker_roll_book = { 0: 'Ace', 1: 'King', 2: 'Queen', 3: 'Jack', 4: '10', 5: '9' } ...
db1c852eba12fde4ac7cb2fa13dc1c3411d0258c
rohith788/Leetcode
/Others/28th/760. Find Anagram Mappings.py
311
3.53125
4
class Solution: def anagramMappings(self, A: List[int], B: List[int]) -> List[int]: map_anagram = {} arr = [] for j in range(len(B)): map_anagram[B[j]] = j for i in A: if(i in map_anagram): arr.append(map_anagram[i]) return arr
b8e0c6dbdffa19e7bce2b4241da1945475e6bc32
rafaelperazzo/programacao-web
/moodledata/vpl_data/85/usersdata/213/58953/submittedfiles/funcoes1.py
1,707
3.578125
4
# -*- coding: utf-8 -*- def crescente (lista): contador=0 for i in range(1,len(lista),1): if lista[i]>lista[i-1]: contador=contador+1 if contador==(len(lista)): return (True) else: return (False) def decrescente (lista): contador=0 for i in range(1,len(lista...
c19f078a9801864608a5b8ac37df1ea904312d87
kosemMG/gb-python-basics
/4/5.py
633
4.09375
4
# 5. Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти # четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов # списка. from functools import reduce num_list = [number for number in range(100, 1001,...
130869bb91ff66448e67d52427fb0e3cb85cf7fa
Jimmyopot/JimmyLeetcodeDev
/data_structures/stacks.py
3,757
3.9375
4
''' - A stack is a data structure that stores items in an Last-In/First-Out manner(LIFO). - There are two types of operations in Stack- Push– To add data into the stack. Pop– To remove data from the stack. - Example, the Undo feature in your editor. ''' myStack = [] myStack.append('a') myStack.append('b') myS...
f3c0f4aacdd48721f419a8fe2e5e78bef3066675
haell/AulasPythonGbara
/mundo_TRES/ex086.py
1,418
4.1875
4
# Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. # No final, mostre a matriz na tela, com a formatação correta. """ ################### COM USO DA BIBLIOTECA RICH! ############################# from rich.table import Table from rich import print table = Table() tabl...
a274ea78bf16222281640ae2679473ce5b5fd91e
MeirLebowitz/encrypt-gmail
/PythonEmailCoder2.py
1,861
4.03125
4
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage print("Enter a phrase that requires encryption, an email will be sent to your email address") input= input('Enter All Your Private Info:') input= input.lower() encrypt = [] for le...
4b60261e374a66b531ddedc2a44be66a29612c14
sky-dream/LeetCodeProblemsStudy
/[0079][Medium][Word_Search]/Word_Search.py
1,221
3.625
4
# -*- coding: utf-8 -*- # leetcode time cost : 424 ms # leetcode memory cost : 30.7 MB class Solution: # def exist(self, board: List[List[str]], word: str) -> bool: def exist(self, board, word): R, C = len(board), len(board[0]) def spread(i, j, w): if not w: ...
4ec885b9d3f504ff789f3e414b9b9956accb71e5
eBLDR/MasterNotes_Python
/Database_SQLite3/scripts.py
751
3.859375
4
import sqlite3 db = sqlite3.connect(':memory:') # Using a db in ram c = db.cursor() # Writing the script script = '''CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT); CREATE TABLE accounts(id INTEGER PRIMARY KEY, description TEXT); INSERT INTO users(name, phone) ...
49045a45a275225b77a21f394d85e95792f6216d
ilkerkopan/OOP-python
/week4_point.py
314
3.96875
4
import math class Point(): def __init__(self, x, y): self.x = x self.y = y def calculate_distance(self): return math.sqrt((self.x*self.x) + (self.y*self.y)) point1 = Point(3,4) point2 = Point(2,8) print(point1.calculate_distance()) print(point2.calculate_distance())
edd74e0f8776f61ecce3172fdf474d3b8426c309
katelevshova/py-algos-datastruc
/Problems/general/jumping_clouds.py
2,944
4.4375
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number ...
2541af96f47e5d557164c2609c1dd07cb2cd1ab1
Joseph-Waldron/riboviz
/riboviz/utils.py
8,294
3.515625
4
""" Useful functions. """ import os import os.path import numpy as np import pandas as pd def value_in_dict(key, dictionary, allow_false_empty=False): """ Check that a value is in a dictionary and the value is not ``None``. If dictionary is:: { "A":1, "B":None, "C"...
0fc64f312a05690551b3026d32c3a1ee8cee2d45
mpsardz/comp110-21ss1-workspace
/exercises/ex04/factorial.py
272
3.953125
4
"""An exercise in computing the factorial of an int.""" __author__ = "730004269" # Begin your solution here... some_int: int = int(input("Choose a number: ")) i: int = 1 total: int = 1 while i <= some_int: total *= i i += 1 print("Factorial: " + str(total))
8e2a5391fa20d1d3891ae03f38e0f7530848f818
igor-fortaleza/myrepository
/Codes/python/data_science/grafico_comparacao.py
533
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 23 16:39:37 2019 @author: igor2 """ import matplotlib.pyplot as plt # "as"= o apelido da forma que vc vai usar a função x1 = [1, 3, 5, 7, 9] y1 = [2, 3, 7, 1, 6] x2 = [2, 4, 6, 8, 10] y2 = [5, 1, 3, 7, 4] titulo = "Grafico Comparação em Python" eixo_x = "Eixo X" eixo_...
17573f672b77999304f5c474ba637c3af400cbb6
sarathkumar1981/MYWORK
/Python/AdvPython/oops/Inheritence/multiinherit3.py
464
3.875
4
class A: def method(self): print("This is A class") super().method() class B: def method(self): print("This is B class") super().method() class C: def method(self): print("This is C class") class X(A,B): def method(self): print("This is X class") super().method() class Y(B,C): def method(self): pr...
f871bd9b8891c91e1c5fbcb08895e51b7267aa24
Hidenver2016/Leetcode
/Python3.6/818-Py3-H-Race-car.py
3,340
3.796875
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 29 16:19:31 2018 @author: hjiang """ """ Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse)...
8e86b9876e7e87cc91d451b02157a95cf0fabef9
marshuang80/mmtf-pyspark
/mmtfPyspark/ml/datasetBalancer.py
2,148
3.859375
4
#!/user/bin/env python ''' dataBalancer.py: Creates a balanced dataset for classification problems by either downsampling the majority classes or upsampling the minority classes. It randomly samples each class and returns a dataset with approximately the same number of samples in each class Authorship information: ...
2d03f854795ed3ab4d5b225953bc09a04b07a2e1
Judahmeek/OldCode
/Python/Python 3/Library Fine.py
2,059
4.03125
4
#Problem Statement #The Head Librarian at a library wants you to make a program that calculates the fine for returning the book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows: #If the book is returned on or before the expected return date, no fine will be ...
207772668a404769c35e9d34b043fe00b42a4874
softborg/Python_HWZ_Start
/kurstag_9/aufgaben_9/Radio.py
720
3.640625
4
class Radio: def __init__(self, volume): self.volume = volume # hier wird das 'volume' dem Property Wert self.volume zugewiesen # - implizit wird die Methode set_Volume aufgerufen # somit kann das Radio auch beim Instanziieren keinen grösseren Wert als 100 zulassen. # kein W...
0a360ec0a9ce038dc77e7617a86e6ea091726376
ChangxingJiang/LeetCode
/0201-0300/0207/0207_Python_1.py
1,432
3.546875
4
import collections from typing import List def build_graph(edges): graph_in = collections.defaultdict(set) graph_out = collections.defaultdict(set) for edge in edges: graph_in[edge[1]].add(edge[0]) graph_out[edge[0]].add(edge[1]) return graph_out, graph_in def topo(graph_in, graph_ou...
00fce67dfa712eddff1649c801421ffe9b932784
ggsant/pyladies
/iniciante/Mundo 03/Exercícios Corrigidos/Exercício 078.py
917
3.875
4
""" EXERCÍCIO 078: Maior e Menor Valores na Lista Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. """ listanum = [] mai = 0 men = 0 for c in range(0, 5): listanum.append(int(input(f'Digite um...
f80a34c02d039a675cd57f7d0b6b667fe04ef207
GeorgiIvanovPXL/Python_Oplossingen
/IT-Essentials/Hfst6/oefeningen slides/oefening2.py
192
3.796875
4
def print_formatting(): for i in range(1, 15): print("{:3d} {:4d} {:5d}" .format(i, i * i, i * i * i)) def main(): print_formatting() if __name__ == '__main__': main()
cdc88568720bf87133427894a2d03e79fb4f2da9
Emmawxh/RecommandSystem
/script/Factorize.py
9,714
3.53125
4
from Data import * import numpy as np import sys class MF(object): ''' implement Matrix Factorization(data-U*M) for Recommend System ''' def __init__(self,min=0,max=1): ''' ''' self._data = Data() self.min = min self.max = max ...
be7b978b44e5dcefc4015de36c66c8d6578aa74f
DamianBarzola/frro-soporte-2020-02
/practico_04/ejercicio02.py
2,560
3.890625
4
## 2 Ejercicio Hacer un formulario en Tkinter una calculadora que tenga 1 entry y 12 botones para los dígitos 0 al 9 ## y las operaciones + - / * = , que al apretar cada botón vaya agregando al valor que muestra en el entry el carácter ## que le corresponde ( como se ve imagen ) y cuando se aprieta en = pone el result...
14934017b3e17301b4ac8929cadb15e70e7f2363
YuboLuo/budgetrnn_backup
/conversion/layer_conversion.py
2,037
3.671875
4
import numpy as np from .conversion_utils import create_matrix, tensor_to_fixed_point, float_to_fixed_point, create_constant def weight_matrix_conversion(layer_name: str, weight_name: str, weight_matrix: np.ndarray, precision: int, is_msp: bool) -> str: """ Converts the given Tensorflow variable to a C varia...
e17fa153a42e313b2aba4b663db20eaee5503fb5
2kunal6/self_practice
/python/tuple.py
116
3.8125
4
tup=("aa", "bb", "aa") print(tup) print(tup[0]) #tup[0]="a" for item in tup: print(item) print(tup.index("aa"))
540157a40081530d8f94077aaf6f8b5cd1d69dc3
rafaelperazzo/programacao-web
/moodledata/vpl_data/10/usersdata/71/10020/submittedfiles/testes.py
428
3.75
4
# -*- coding: utf-8 -*- from __future__ import division #entrada p=input("Insira p: ") q=input("Insira q: ") #atribuições contp=0 contq=0 ip=1 iq=1 #contagens de digitos while p//ip!=0: contp=contp+1 ip=ip*10 while q//iq!=0: contq=contq+1 iq=iq*10 #CP>=cQ if contq<contp: print("Não é subnúmero!") el...
d83ade29f98a797ffe28f8dba3a66ee30ad99459
nhanlun/code
/Python/Ex33.py
343
4.0625
4
numbers = [] def add_numbers(numbers, n): # i = 0 # while i < n: for i in range(n): print(f"At the top i is {i}") numbers.append(i) i = 10 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") add_numbers(numbers, 10) print("The numbers: ") for num in ...
a4258819587dd532c589a52072234fcf7ca60879
sluzhynskyi/oop_battleship
/Battle_ship/modules/game.py
3,024
3.546875
4
from field import Field from player import Player class Game: def __init__(self): """ This method initializes a new instance of Game class. """ self.__fields = [Field(), Field()] name1 = input("Player 1, input your name\n:") name2 = input("Player 2, input your name\...
346167b151a561405a49ef4cf2ac11e5dd5dc48d
bbluebaugh/Data_Cleanup
/pandas_tutorial.py
1,511
4.40625
4
# tutorial for working with excel files in python import pandas as pd import numpy as np excel_file = "Pandas_Workbook.xlsx" # create a variable to hold a reference to our excel file df = pd.read_excel(excel_file) # create a dataframe variable for the excel file # print(df) # print(df.head(5)) # Using the hea...
d17c687f7efe0ad640a198a1c7dad28ababf55f4
EduardoMachadoCostaOliveira/Python
/CEV/ex051.py
528
3.796875
4
# Desenvolva um programa que leia o primeiro termo e a razão de uma PA. # No final, mostre os 10 primeiros termos dessa progressão. pri = int(input('Primeiro termo: ')) raz = int(input('Razão: ')) #decimo = pri + (10 - 1) * raz for c in range(pri, ((10 * raz) + pri), raz): print(c, end='->') print('ACABOU') ''' Pr...
142312d7e5104159020e09d567bce0d935d069e4
jessrenteria/advent_of_code
/day1/first.py
360
3.96875
4
def parse_input(): with open("input1.txt", 'r') as f: return f.read() # Prints the current floor after following the instructions in the input. def find_floor(): string = parse_input() floor = 0 for c in string: if c == '(': floor += 1 elif c == ')': flo...
412f67856f48e582e2d8b0bac14357db471fdc7d
iswetha522/Plural_Sight
/corepy/files_I_O_and_resource_management/context_manager.py
1,187
4.375
4
# files are context managers which close files on exit. # Context managers aren't restricted to file-like objects. """Demonstrate raiding a refridgerator.""" #Use closing: from contextlib import closing # A class for raiding the fridge class RefridgeratorRaider: """Raid a refridgerator""" # Open the refrid...
4338714dd9ce3bc7ebcc2763e871851d9ace350e
Jonatas-Soares-Alves/Exercicios-do-Curso-de-Python
/MUNDO 2/Exercícios/Exercício 43 (vi12).py
573
3.515625
4
#IMC = 80 kg ÷ (1,80 m × 1,80 m) = 24,69 kg/m2 (Peso ideal) peso = float(input('Qual o seu peso? ')) altura = float(input('Qual sua altura? ')) imc = peso / (altura ** 2) if imc < 18.5: print('Você está \033[33mABAIXO DO PESO!\033[m') elif imc >= 18.5 and imc < 25: print('Você está \033[32mNO PESO IDEIAL!\0...
be2c3f20ae7c054cdfcacc9540932459cce2b07f
aishwat/missionPeace
/treeUtils.py
1,211
3.78125
4
class TreeNode: def __str__(self): return str(self.val) or 'None' def __init__(self, x): self.val = x self.left = None self.right = None self.sum = None self.next = None class Tree: def __init__(self, a): if a: self.root = self.createTre...
0558cb9dc6b91d176526837ad32f91ef20868332
natayuzyuk/homework
/TPOG11-237.py
311
3.9375
4
def maptolist(map) : lst = list(map) print("первый элемент списка: {0}".format(lst[0])) print("последний элемент списка: {0}".format(lst[len(lst)-1])) maptolist(map(int, input("Введите целые значения через пробел: ").split()))
628c9642a2f4e934f26f76ddf10126c8cdbde777
XhuiA/Leetcode-collections
/101.对称二叉树.py
854
3.921875
4
#2019.11.18-2 #时间10分钟 #问题分析:需要比较左子树的左、右节点和右子树的右、左节点是否相同,复用原本的树进行比较 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: #复用递归比较 ...
b2dd97f1a0221ffdfc5f31af32c4fd76ad11537c
RoPalacios74/python-challenge
/PyBank/main.py
1,839
3.75
4
import os import csv #set path budgetpath = os.path.join('Resources','budget_data.csv') textpath= os.path.join("Analysis", "Analysis") #initiate values total =0 average_change = 0 total_rows = 0 greatest_increase = 0 greatest_decrease = 0 with open(budgetpath, newline='') as csvfile: csvreader = csv.read...
64ca9ea30c439216ba55ec4cff9f5ace40536821
Nektarium/Morozov_N_homework
/lesson2_normal.py
4,778
4.125
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ...
2f717ed599a2eb65fc734f85286146e358cd59ed
Strugglingrookie/oldboy2
/module8/01排序算法/01二分查找.py
2,478
3.671875
4
# 二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。 # 非递归 时间复杂度 O(logn) lis = [1,2,3,4,5,6,7,8,9,10] def bin_search(lis,value): low = 0 high = len(lis) - 1 while low <= high: mid = (low+high) // 2 if lis[mid] == value: return mid elif lis[mid...
677da282d14c5f0ce73f850a8a4386eff85ff8b0
salmonofdoubt/TECH
/PROG/PY/py_dummies/pyschools.py
1,196
4.15625
4
2/ 1/13 - %operator # Write a function that does a decimal to hexadecimal conversion. # Hint: Make use of "%x" for hexadecimal format. def dec2hex(num): hexa = "%X" % num return hexa 1/12 + complex numbers # Compute the sum and product of 2 complex numbers: # (2+3j) and (4+5j) a = complex(2+3j) b = complex(...
a77d9bc37f1995c08b3cd74f64149fa7a107a30a
anderalex803/nuwara-online-courses
/datacamp/ML-unsupervised-learning-python/01_kmeans_normalize_pipeline.py
904
3.875
4
"Create pipeline that contains normalizing data then KMeans clustering for stock data" # KMeans and make_pipeline have been preloaded from sklearn # Import Normalizer from sklearn.preprocessing import Normalizer # Create a normalizer: normalizer normalizer = Normalizer() # Create a KMeans model with 10 clusters: km...
2ec1193679f7af8352058a172ccc26a528ac058a
arrebole/Ink
/src/algorithm/design/1.Brute-Forc/穷举查找/breadth_first_search.py
605
3.8125
4
#!/usr/bin/python3 # Bfs 广度优先搜索, 输入邻接链表法表示的图, 第一个遍历的key # 象征谨慎:从最近的元素开始搜索 class BFS(): def __init__(self, graph: dict): self._graph: dict = graph self._result: list[str] = [] def bfs(self, key: str): queue: list[str] = [key] while(len(queue) > 0): local = qu...
217f8e5a500076b7fd552df2ddb6a0869ca850b2
D12020/my-first-python-programs
/hello.py
336
3.765625
4
# This program says hello and greets a person by name. # # Saleem # August 24, 2017 print("Hello.") print("What is your name?") name=input() print("It is good to meet you, " + name + ".") print (" Where were you born," + name + " ? ") born = input () print(" That is interesting. I'd like to visit " + born +...
5353dcc60618e6ccb583ef625ecfd094bd11964d
Sambit2001/Python
/Projects/Fibonacci_Series.py
197
3.9375
4
def fib(n): if(n<=2): return 1 else: return fib(n-1)+fib(n-2) r=int(input("Enter the limitation for fibonacci series: ")) print("\n") for i in range(1,r+1): print(fib(i),end=' ')
a0e4ec6bb067ceabd8e02a42abe9d79aa752a217
sonsuzus/sonsuzus
/Python/Small Pyton Codes/sudoku_solver.py
7,578
3.828125
4
sudoku = list() """ Squares: +-+-+-+ |0|1|2| |3|4|5| |6|7|8| +-+-+-+ """ def getSquare(game:list, square_num:int): my_list = list() for i in range(3): for j in range(3): if square_num == 0: my_list.append(game[i][j]) elif square_num == 1: my_list...
5261a4e89ebade2b9baa757e966385fe568f60e1
PoojaK97/PythonSem4
/9a.py
565
3.953125
4
class time: def __init__(self,h=0,m=0,s=0): self.hours=h self.minutes=m self.seconds=s def set_time(self,h,m,s): self.hours = h self.minutes = m self.seconds = s def __str__(self): return 'Time: '+str(self.hours)+':'+str(self.minutes)+':'+str(self.seco...
49ff04317e0243625af4aafca9369a319d423f30
cejjenkins/robot_controller
/main.py
3,044
4.125
4
"""Main class to guide the robot.""" from exceptions import ( OutsideGridException, InvalidInputException, InvalidCommandException, ) class RobotController: """The class that controls the robot.""" def __init__(self, size_of_grid, location, commands): """Initiate robot controler.""" ...
e7db77fe0d40b71cdcaea2f03d7b400920e96144
BereketAbera/alx-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
231
3.625
4
#!/usr/bin/python3 def max_integer(my_list=[]): max = None for index, value in enumerate(my_list): if index == 0: max = value else: max = max if max > value else value return max