blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5488b8fb5f48b66fcc6fb09c558ad61d61841d70
smanuelguerrero/Exercises
/Height convert.pyp
412
4.1875
4
ft = float(input("What is your height in ft: ")) inches = float(input("How many inches: ")) metricft = ft*30.48 metricin = inches*2.54 metric=metricft+metricin print(metric) print('--------------------------') #Imperial Units converter distance = float(input('Enter distance (in ft.): ')) print("Inches: ", float...
0c00d37bbffe8f43ab0b40f4c74a695d858cd167
fengsky401/myUbuntu
/schdirfile_walk.py
482
3.59375
4
#coding:utf-8 import os def walk_dir(dir,fileinfo,topdown=True): for root,dirs,files in os.walk(dir,topdown): '''for name in files: print(os.path.join(name)) fileinfo.write(os.path.join(root,name)+'\n')''' for name in dirs: for f in files: print(os.path.join(root,n...
ee53de184e381bede9605f965b2f221779bd8305
vishnujha05/website
/oops.py
1,249
3.84375
4
"""class student: no_of_student=45 def study(self): inquary=f"name of student:{self.name}.total percentage in class{self.classs}:{self.mark}" print(inquary) vishnu=student() rahul=student() vishnu.name= "vishnu" vishnu.classs=5 vishnu.mark= "65 percentage" vishnu.study() rahul=student() rahul.n...
eb20ab9066f97211b26893dd8960d4b50d70a2c0
daniel-reich/turbo-robot
/6NoaFGKJgRW6oXhLC_12.py
686
4.25
4
""" Create a function that takes a string and returns the **sum of vowels** , where some vowels are considered numbers. Vowel| Number ---|--- A| 4 E| 3 I| 1 O| 0 U| 0 ### Examples sum_of_vowels("Let\'s test this function.") ➞ 8 sum_of_vowels("Do I get the correct output?") ➞ 10 ...
a7ce3c3e869053ab8ecbc57aa2648914f43024ef
lih627/python-algorithm-templates
/LeetCodeSolutions/LeetCode_0707.py
3,109
3.984375
4
class ListNode: def __init__(self, val=None, pre=None, nex=None): self.val = val self.pre = pre self.nex = nex def __repr__(self): return str(self.val) if self.val != None else '#' class MyLinkedList: def __init__(self): """ Initialize your data structure ...
371fce2fe0a1feabc6d5a2fe3b61ea61216d7b41
jabaier/iic1103.20152.s4
/fracciones.py
1,163
3.671875
4
def mcd(a,b): div = min(a,b) # retorna el minimo entre a y b while div > 1 and (a%div!=0 or b%div!=0): div = div - 1 return div class fraccion: def __init__(self,numerador=0,denominador=1): den=abs(denominador) num=abs(numerador) MCD=mcd(num,den) self.denominador...
7d8835f299eda1058b5b728276f4d30f12022504
gguillamon/PYTHON-BASICOS
/python_ejercicios basicos_III/ejercicios_resueltos_estructura_secuencial (1)/ejercicio8.py
638
3.953125
4
# Un vendedor recibe un sueldo base mas un 10% extra por comisión de sus ventas, # el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por # las tres ventas que realiza en el mes y el total que recibirá en el mes tomando # en cuenta su sueldo base y comisiones. sueldo_base = float(input("Dime ...
d840989daf21ecfb7587e274664df3f428336ab8
saigandham467/Python
/Data structures with python/chapter1/Dogclass.py
1,169
3.828125
4
class Dog: def __init__(self,name,month,day,year,speaktext): self.name=name self.month=month self.day=day self.year=year self.speaktext=speaktext def speak(self): return self.speaktext def getName(self): return s...
d1c1b25291ae93b4b7fec5161693da3f30560483
avergnaud/python-misc
/2.input.py
220
3.953125
4
# https://docs.python.org/2/tutorial/introduction.html # http://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard division = input("Quelle est la division ? ") print ("division saisie : ", division)
98aae912e2c2bfc2466ca669527f69797e2c632e
lololiu/show-me-the-code
/code/0011/0011.py
636
3.78125
4
# 敏感词文本文件 filtered_words.txt,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights # coding=utf-8 def getFormatList(): file=open('filtered_words.txt') str=file.readlines() formatStr=[] for i in range(len(str)): formatStr.append(str[i].strip('\n')) return formatStr def checkIsValid(input,filtered_words): for x in range(l...
b2c89dfed98c74ca1e798a329b04390ad28a3ca9
borko81/python_scripts
/Command_Line_Tool/main.py
468
3.671875
4
# Impot module, sys for get argv, getpass for secure enter pw import sys from getpass import getpass def check_name(): ''' Check name is enter from line, if not ask user to enter username, then password ''' try: name = sys.argv[1] except IndexError: name = input("What is your n...
cfd5c14eb2b2d63cdf2c0e0c2ac97b8e4d248ba9
puneeth-devadiga/COMP9021
/Lab_6_solutions/sum_of_digits_practice2.py
662
3.78125
4
available_digits = int(input('Enter digits: ')) desired_sum = int(input('Enter sum: ')) def solve(available_digits, desired_sum): if desired_sum < 0: return 0 if available_digits == 0: if desired_sum == 0: return 1 return 0 return solve(available_digits//10, ...
cdde6c6670649912e72f132ff226814a561e0525
vishrutkmr7/DailyPracticeProblemsDIP
/2019/12 December/dp12222019.py
1,241
4.09375
4
# This problem was recently asked by Apple: # Given 2 binary trees t and s, find if s has an equal subtree in t, where the structure and the values are the same. # Return True if it exists, otherwise return False. class Node: def __init__(self, value, left=None, right=None): self.value = value se...
16075866a5c7016f5ef9bd99f4559fa29f18dcad
erfankashani/Machine-Learning-Algorithms
/4-Clustering/Hierarchical Clustering/hc.py
1,593
3.90625
4
# Hierarchical Clustering #import library import numpy as np #for any mathematic codes import matplotlib.pyplot as plt # help for ploting nice charts import pandas as pd #import datasets and manage datasets #import a dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3,4]].values #takinf all the...
395c5094d1346eb904ee757d1c485ff4075a9bf8
tktam/testing_py
/src/main/my_program.py
1,122
3.96875
4
def main_prog(): m = input("Please enter the total number of students: \n") student_list = [] grade_list = [] module_list = [] for i in range(int(m)): student = STUDENT() student.set_asset('{},{}'.format(random.randrange(-100, 100), random.randrange(-100, 100)) ...
a61fb35982a129ea8e6c3752d735eacdd3d55935
takecian/ProgrammingStudyLog
/LeetCode/700/776.py
643
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def splitBST(self, root, V): """ :type root: TreeNode :type V: int :rtype: List[TreeNode]...
7975b2c161b200e110e9e75abd6148581b149cbd
krswan/raspi1
/reflexgame.py
1,060
3.703125
4
from gpiozero import LED, Button from time import sleep from random import uniform led = LED(24) right_button = Button(16) left_button = Button(12) round = 1 right_score = 0 left_score = 0 pressed = False left_name = input('left player enter your name:') right_name = input('right player enter your name:') while(rou...
f97895f0fc9a515941648b76b25105a8e25c4668
yookyungkho/Algorithm_Baekjoon
/백준 단계별로 풀어보기/03. for문/BOJ_8393.py
81
3.640625
4
n = int(input()) total = 0 for i in range(1,n+1): total += i print(total)
c4bc13064b167b6cfe4a8a23280299118b9621ed
Aasthaengg/IBMdataset
/Python_codes/p03544/s783361547.py
215
3.625
4
def Lucas_Update(L0,L1): L2=L0+L1 return L2 N=int(input()) L=[2,1] if N==0: print(2) elif N==1: print(1) else: for i in range(2,N+1): L.append(Lucas_Update(L[i-1],L[i-2])) print(L[N])
c5eae9b5d9561d707ae072691f2a5befc2aa3322
mavrovski/PythonPrograming
/Programming Basics - Python/06Drawing Figures with Loops/06RhombusOfStars.py
325
3.875
4
n = int(input()) # top side for row in range(1,n+1): print(" "*(n-row),end='') print("*",end='') print(" *"*(row-1), end='') print() # bottom side for row in range(n-1,0,-1): for col in range(n-row,0,-1): print(" ", end='') for col in range(1,row+1): print("* ", end='') pr...
d8b3a923befcd3f5078bb88db2d7228125db6d52
sbrandsen/2020_TICT-V1PROG-20_1_V
/pe_4_6.py
151
3.546875
4
s = "Guido van Rossum heeft programmeertaal Python bedacht." checkList = ["a", "e", "i", "o", "u"] for elem in s: if elem in checkList: print(elem)
28c1bff4e38fdf8493dca349c8fc65e434df35c7
matherique/uri-solve
/1036.py
327
3.5
4
#!/usr/bin/env python3 a, b, c = list(map(float, input().split(" "))) delta = b ** 2 - 4*a*c if delta > 0 and a > 0: r1 = (b * (-1) + (delta ** 0.5)) / (2 * a) r2 = (b * (-1) - (delta ** 0.5)) / (2 * a) print("R1 = {:.05f}".format(r1)) print("R2 = {:.05f}".format(r2)) else: print("Impossivel calc...
efaee6eb77f1db2077fd5bdddce5f103c12dbc33
maartjeth/NLP2
/project3/src/Classify.py
803
3.640625
4
from Helper import * from sklearn import svm def train_svm(data_vecs, labels, kernel_type): """ Train the linear classification model. Here LinearSVC from Scikit is used. Input: Data_vecs: List of feature vectors Labels: labels of the feature vectors (1 or -1) Output: Trained weights, example of format f...
23b6b4de6bc47ecc238ac2e2cb47dfbf65d4b9f3
Amiao-miao/all-codes
/month01/day08/extance01.py
474
3.734375
4
""" 斐波那契数列 [1,1,2,3,5,8,13…] """ long=int(input("请输入斐波那契数列的长度:")) if long==1: print([1]) elif long==2: print([1,1]) else: res=[1,1] # res=[1,1] for i in range(long-2): # a3=res[0]+res[1] a3=res[i]+res[i+1] # res.app...
52e9ad219ba40ad70f974924e46b283200b85f19
xros/temp_convert
/temp_convert.py
1,838
4.34375
4
""" This is a small program to convert temperature degrees between different types. Created by Songhua Liu """ def all_to_kelvin(x,y): a = ["","","","","","","",""] # declare an empty list a[0] = x # kelvin to kelvin a[1] = x + 273.15 # celsius to kelvin a[2] = ( x + 459.67...
4b0b48fcb69ca5489018e370130f7744c7518cf0
mandaltu123/learnings
/python-learning/brushup/contorl-and-loops/while_loop.py
114
3.640625
4
i = 0 numbers = [] while i < 10: numbers.append(i) i += 1 print(numbers) for i in numbers: print(i)
edf4c9587e5a8f33d68f6f133871ce0814644434
Nilsonsantos-s/Python-Studies
/urionlinejudge-python/1066.py
968
3.859375
4
''' Leia 5 valores Inteiros. A seguir mostre quantos valores digitados foram pares, quantos valores digitados foram ímpares, quantos valores digitados foram positivos e quantos valores digitados foram negativos. Entrada O arquivo de entrada contém 5 valores inteiros quaisquer. Saída Imprima a mensagem conf...
d34e46935196a24456f4578c79b98722dab63914
itsme-vivek/Akash-Technolabs-Internship
/Day-3/average.py
565
4.21875
4
# Type-1 print("Average of 5 numbers") a=int(input("Enter a value of 1st number:")) b=int(input("Enter a value of 2nd number:")) c=int(input("Enter a value of 3rd number:")) d=int(input("Enter a value of 4th number:")) e=int(input("Enter a value of 5th number:")) average=(a+b+c+d+e)/5 print("Average of 5 nu...
40558cb6cc9c66e30c481b095e53e77e3fc03686
AnthonyJamez12/Web-Portfolio-
/Nail Dodger/Nail Dodger.py
2,341
3.78125
4
import turtle import random import math import time #Screen win = turtle.Screen() win.title("IDK") win.bgcolor("black") win.bgpic("road.gif") scores = 0 score = turtle.Turtle() score.speed(0) score.penup() score.color("white") score.setposition(-290, 290) scorestring = "Score: %s" %score sco...
06d80e4358b573f30eaf8f4182d6edc3d1ed712a
lysukhin/optical-target-detection
/optard/detection.py
1,673
3.546875
4
""" https://learnopencv.com/homography-examples-using-opencv-python-c/ """ import cv2 import numpy as np def compute_target_position_with_perspective(corners, ids): from .template import image_width, image_height, margin, tag_image_size if ids is None: return None ids = [i[0] for i in ids] ...
1566b7bd3e0f2cf2d218db22650931ce2c3877ca
elihschiff/Rubber-Duck-Python
/utilities/gen_config_db.py
2,823
3.609375
4
import sys import os import sqlite3 import json if len(sys.argv) < 2 or len(sys.argv) > 3 or not sys.argv[1].endswith(".db"): print(f"Usage: {sys.argv[0]} DB_FILE (JSON_FILE)") sys.exit(1) if os.path.exists(sys.argv[1]): print("ERROR: database already exists... Aborting!") sys.exit(1) connection = sq...
f9d45841f409355a3501af3d775150d53edb187a
DualSapiens/cs207-FinalProject
/docs/examples/newton_multivar.py
1,460
3.59375
4
import numpy as np def newton_multivar(fun,var,xi,tol=1.0e-12,maxiter=100000): """ Multivariate Newton root-finding using automatic differentiation. INPUTS ======= fun: an autodiff Operation or Array object whose roots are to be computed. var: an array of autodiff Var objects that are independent...
03dc0e8a26ccdadd18f73764b41116d09b3c5f19
fmoralesii/todo
/create_db.py
2,134
4
4
# ORM or Object Relational Mapping is essentially a way # to use objects in our language, to represent tables # in our DB. Along with that, they provide access to # DB operations without the need to get into raw SQL # queries. # # For the course that inspired this, we use SQLAlchemy. # For those new to it, please see...
4e81e04f7d03c878b7d601173a0c262325f8ac2b
LuciooF/Simple-Python-Projects
/PasswordGenerator/services2.py
742
3.59375
4
# def generatePassword(pass_length = 8, number_amount = 0): # stringOfEverything = f'{string.ascii_letters}{string.digits}{string.punctuation}' # listOfEverything = list(stringOfEverything) # #possibly an unnecessary while loop (Sam) though I think it didn't work without this if length was over string lengh...
d0cb672e9b5a2ed0e9b29bb364b1ce8244bc189b
zuobing1995/tiantianguoyuan
/第一阶段/day07/exercise/dict1.py
425
4.03125
4
# 字典推导式练习: # 1. 已知有如下字符串列表 # L = ['tarena', 'xiaozhang', 'abc'] # 生成如下字典: # d = {'tarena': 6, 'xiaozhang': 9, 'abc': 3} # 注: 字典的值为键的长度 L = ['tarena', 'xiaozhang', 'abc'] # d = {'tarena': 6, 'xiaozhang': 9, 'abc': 3} # 方法1 # d = {} # 创建一个空字典 # for s in L: # d[s] = len(s) # 方法2 d = {s: len(s) for s...
7b8a68971949f68051c909888d33af71563d6d20
OldJohn86/Python_CPP
/CPP_LiaoPython_Exp/high-order/do_partial.py
328
3.65625
4
print(int('12345')) print(int('12345', base=8)) print(int('12345', 16)) def int2(x, base=2): return int(x, base) print(int2('1000000')) print(int2('1010101')) print(int2('1000000', base=10)) import functools int2 = functools.partial(int, base=2) print(int2('10010')) max2 = functools.partial(max, 10) print(max2(5,...
706cf91929c727d254e2da196378640ee83aafe2
techehub/pythonbatch20
/fileread1.py
1,207
3.765625
4
def readFile (filename): try : infile = open(filename, mode="r+t", ) return infile.readlines() finally: infile.close() def readFile (filename): with open(filename, mode="r+t" ) as infile: return infile.readlines() def processLines( lines): students= [] for line i...
ebaa1831bd93caf0bcd610d6d765154fe873501f
andreworlov91/PyProj
/InputLesson.py
565
4.0625
4
# name = input("Please enter Your name: ") # # print('Privet ' + name) # # num1 = input("Enter X: ") # num2 = input("Enter Y: ") # # summa = int(num1) + int(num2) # print(summa) message = "" while message != 'secret': message = input("Enter password ") if message == 'secret': break print(message + " P...
1727d76b52711e3a73863a4d02b438157dc7c416
AhmadShalein/amman-python-401d5
/class-02/demo/fizz_buzz_saed/fizz_buzz/fizz_buzz/fizz_buzz.py
1,241
4.3125
4
def fizz_buzz(number): """ if the number is dividable by 3 return Fizz if the number is dividable by 5 return Buzz if the number is dividable by 3 and 5 return FizzBuzz Args: number ([integer]): [an integer to check] Returns: [string]: [if it falls under the rules it ...
911bf8101db2953ec8f18cb7a33a61cd37d4dd95
IsaacPSilva/LetsCode
/Aula 04/[Aula 04] Lists and For.py
3,523
4.09375
4
### LISTAS ### ''' numero1 = 1 numero2 = 2 listinha = [] print(listinha) # indices: 0 1 2 3 numeros = [numero1, numero2, 'palavra', 2>1] print(type(numero1)) #print(numeros[0], numeros[1], numeros[2], numeros[3], numeros[4]) numeros[1] = 1000 numeros[2] = 'textotextotextotexto' #prin...
cfbd7e6cd460fd89fb4b3c68a60c1257c7dcce61
JBustos22/Physics-and-Mathematical-Programs
/computational integrals/dice.py
674
3.8125
4
#! /usr/bin/env python """ This program uses the random aspect of the numpy module to simulate two die being thrown at random, a fraction of double sixes to throws is calculated and compared to the expected value of 1/36. Jorge Bustos Mar 4, 2019 """ from __future__ import division, print_function import numint as ...
b169b04c43d99f935b2d547d130239d59d64535e
kittykatcode/Tkinter_projects
/ProjectFiles/viewer_1.py
3,194
3.671875
4
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title('Learn Tkinter') root.iconbitmap('light_bulb_copy.ico') my_img1 = ImageTk.PhotoImage(Image.open('Images/lotus.jpeg')) my_img2 = ImageTk.PhotoImage(Image.open('Images/bouque.jpeg')) my_img3 = ImageTk.PhotoImage(Image.open('Images/cat.jpg')) m...
7ec699044b75b38f2cba182fa64fe84fec5540a9
juanPabloCesarini/practicaPython
/Ej5.2.py
953
3.671875
4
def esLetra(x): return (x>="a" and x<="z") or (x>="A" and x<="Z") def buscarFrase1(txt): i=0 frase1="" frase2="" while i <len(txt): pal="" while i<len(txt) and not esLetra(txt[i]): i+=1 while i<len(txt) and esLetra(txt[i]): pal=pal+txt[i] ...
1f6236b2bdd5f4a708ae4b17b24f610cf298cf44
FazeelUsmani/Scaler-Academy
/005 Math 3 Mod/A4 To and Fro.py
757
3.78125
4
To and Fro Problem Description The Guardians of the Galaxy have just landed on Earth. There are N cities in a row numbered from 1 to N. The cost of going from a city with number i to a city with number j is the remainder when (i+j) is divided by (n+1). The Guardians want to visit every city but in the minimum cost. Wha...
5fbf235663e626e3e8bf1b56f535ef9d745f79d2
jakobkhansen/KattisSolutions
/Splash/Splash.py
1,576
3.59375
4
import sys import math def findColors(lines): num_paintings = int(lines[0]) lines = lines[1:] result_list = [] for painting_num in range(num_paintings): drop_list = create_drop_list(lines) lines = lines[int(lines[0])+1:] num_querys = int(lines[0]) lines = lines[1:] ...
710a41092c5d0fede9184580c7fbd2c283e01bd6
Thuvajarohana/Python-programming
/Beginner level/add2.py
59
3.53125
4
num=int(raw_input()) num1=int(raw_input()) print(num1+num)
5ff18ba115d64d206b0a222fd54a58253a373923
josemorenodf/ejerciciospython
/Ejercicios Métodos Listas/RebanarLista.py
475
4.125
4
# Rebanado de listas t = ["a","b","c","d","e","f"] print(t) print("Aplicando t[1:4]: ",t[1:4]) print("Aplicando t[2:100] (no genera error):",t[2:100]) print("Imprime la lista completa:",t[:]) # Un operador de rebanado al lado izquierdo de una asignación puede actualizar múltiples elementos: print("Lista co...
bd75196ae5fb6e16971a23e01b9df69681e2ebaa
Amannor/quantlib_sandbox
/main/calcStandardizedNormalDistSamples.py
1,433
3.703125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt np.random.seed(1) def get_standardized_normal_dist_samples(mean=0, std=1, numOfSamples=10): if (std == 0): raise ValueError("std=0 isn't suppoerted since there's no way to standardize the result") random_normal_dist_samples = np.rand...
26a2f42e49ff3c72f9481675f99ef1214e0eb1be
olatunji-weber/Probability-Calculator
/prob_calculator.py
1,275
3.578125
4
import copy import random # Consider using the modules imported above. class Hat(): def __init__(self, **ballsDict): self.ballsList = ballsDict self.contents = [] [[self.contents.append(k) for i in range(v)] for (k,v) in ballsDict.items()] def __str__(self): return str(self.contents) def dr...
9853a1a791276c914528c08a02d2abbaf311c0fc
Tiffanyzzx/PythonCoding
/com/tiffany/coding/Binary Tree/Invert Binary Tree_Top to Botom.py
722
3.921875
4
class TreeNode(): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(): def invertTree(self, root): # Signature: input original root, output inverse root # base case if not root: return root # current leve...
62f6bf6f73d9df71d48d2d758078e23303bf0a82
SamuelEngComp/RevisandoPython
/CAP-17/TrabalhandoComAPI.py
1,001
3.734375
4
# trabalhando com API # Requisitando dados usando uma chamada de API # Instalando o pacote requests import requests import json url = "https://api.github.com/search/repositories?q=language:python&sort=stars" r = requests.get(url) print("Status code: ",r.status_code) response = r.json() print(response.keys()) # Trab...
78360fd14f11b515b9408b81be359221f548cefa
Sandraopone1/python_fundamentals
/names.py
602
3.640625
4
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] # count = 1; # for i in students: # for data in i.values(): # if data % 2 == 0: # ...
280d705452ef671b92f1b51824e260c44292af30
giovannyortegon/PyNetworking
/NetworkignAndSecurity/Chap02-SystemProgramming/read_zip_files.py
243
3.90625
4
#!/usr/bin/env python3 import zipfile def list_files_in_zip(filename): with zipfile.ZipFile(filename) as myzip: for zipinfo in myzip.infolist(): yield zipinfo.filename for filename in list_files_in_zip("Images.zip"): print(filename)
7bb08d7b500a89992d6752a518451ace9030cda9
Studies-Alison-Juliano/geek_university_curso_python
/secao7_colecoes/default_dict.py
1,927
4.15625
4
""" Modulo Collection - Default Dict https://docs.python.org/3/library/collections.html#collections.defaultdict Recap Dicionário: dicionario = {'curso': 'Programação em Python: Essencial'} print(dicionario) print(dicionario['curso']) Default dict -> Ao criar um dicionário utilizando o default dict, nos informamos um...
2fc1ec05cc758ac5acbb6888a3f77dcdb587e3e9
ambarish710/python_concepts
/leetcode/hard/42_Trapping_Rain_Water.py
1,156
4
4
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. # # # # Example 1: # # # Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] # Output: 6 # Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3...
629f15a271b2648b12e8aad79185647eb3452c87
argriffing/xgcode
/lineario.py
7,324
3.703125
4
""" Read and write linearly. A sequence of objects is read from or written to a file one by one, either backwards or forwards. This is especially useful for the forward-backward algorithm which computes position specific posterior hidden state distributions given some hidden Markov model parameters and a sequence of ob...
445dcd83833c22651333fe691a4a800f7d3564b2
amansharma2910/Python3Tutorials
/venv/PrimeList_Functions.py
1,050
4.5625
5
## In this program, we will see how the main function is used within python. This program will print a list of prime numbers upto the number that the user inputs. # First, we define a function isPrime that checks if a number is prime or not. If it is prime, then it will return a value True, or else, it will return Fal...
d60bd904875b457951376401d96d6b5227296273
itbullet/python_projects
/reverse_integer_20190723/reverse_integer.py
1,097
3.53125
4
import sys class Solution: def reverse(self, x): INT_MAX = sys.maxsize INT_MIN = -sys.maxsize-1 x_str = str(x) if x_str[0:1] == "-": x1 = x_str[0:1] x2 = x_str[1:] x2 = x2[::-1] x3 = int(x1+x2) else: x3 = int(x...
63d592a0a61f041aec787e5bdb70478509b436cd
safhunter/pyBasics
/lesson_3/task_5.py
1,039
3.984375
4
def sum_elements(numbers): """ Возвращает сумму элементов списка и флаг успешного прохода всех элементов. В случае, если какой-то элемент не удалось просуммировать, возвращает False и уже посчитанную сумму предыдущих элементов. (list) -> bool, int Позиционные параметры: numb...
e44f6e4de92d45ed75b05c09f358af04c9ac8154
charlesdong/cpppp6py
/4/3.py
156
4.0625
4
fname = input('Enter your first name: ') lname = input('Enter your last name: ') print('Here\'s the information in a single string:', lname + ', ' + fname)
965e174fa1bbb5bc4b7705213c7312e7e9f34723
oaowren/IT3105---Artificial-Intelligence-Programming
/project1/game/board_visualizer.py
3,269
3.640625
4
import matplotlib.pyplot as plt import pygame class BoardVisualizer: def __init__(self, width=1000, height=800): self.width = width self.height = height def draw_board(self, board, board_type): height = self.height width = self.width horisontal_spacing = find_horisonta...
ebff329b66caf4f7156c3c0d5831a3a2a2c36db9
MKRNaqeebi/CodePractice
/Past/degree-of_an_array.py
1,862
3.953125
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explan...
76779a5b439cc52cc8800ebd6b66dcb7e390876f
masoom-A/Python-codes-for-Beginners
/while loop (squats per day).py
330
3.984375
4
day=0 squats=0 total=0 print("enter the numbers of squats you did on each day for the last one week") while day<=6: day=day+1 squats=int(input("Total numbers of squats on day {}:".format(day))) total=total+squats avg=total/day print("the average squats you did in the last one week are {:.2f}:".form...
902711a5e7098e7a0a14e8c95e3c344813d3d6e5
kennyestrellaworks/100-days-of-code-the-complete-python-pro-bootcamp-for-2021
/Day 5/day-5-password-generator.py
2,562
3.734375
4
#Password Generator Project import random # list_item letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',...
25950b6a96453eaa353cf932f602174244f45f6d
PauloVilarinho/algoritmos
/problemas uri/Problema1307.py
579
3.65625
4
quantity = int(input()) pair = 0 for i in range(quantity): pair += 1 listaa = list(input()) listab = list(input()) listaa.reverse() listab.reverse() numeroa = 0 numerob = 0 for i in range (len(listaa)): numeroa += int(listaa[i])*(2**i) for i in range (len(listab)): numerob += int(listab[i])*(2**i) anterio...
7143de870fe670e135c91a083d25b6c8192b949c
hrithik0/newbieProjects
/input.py
221
4.1875
4
print("{}".format(input("Write your name? ")) + " " + "likes" + " " + "{}".format(input("What is your favourite color? "))) print(f"{input('Write your name? ')} likes {input('What is your favourite color? ')}")
4bcb4a8dce55346fc9d73a2a1b14c1606ca075fa
ayushman-roy/python-freecodecamp
/Dictionaries, 2D Lists and Nested Loops.py
806
4.03125
4
day_conversions = { "sun": "Sunday", "mon": "Monday", "tue": "Tuesday", "wed": "Wednesday", "thur": "Thursday", "fri": "Friday", "sat": "Saturday" } # you can also use integral value for keys print(day_conversions["thur"]) a = input("Enter the Key: ") print(day_conversions.get(...
1548f0d6f3f1ac5ee66e8c04a7d600783e85faa7
shibinmak/advance-diploma-ai-nielit
/NLP RL DLK/NLP/nlp6/nlp6/ds1.py
587
3.5
4
from sklearn.feature_extraction.text import TfidfVectorizer; s1 = "The study of bees , birds, butterflies and animals is Zoology"; s2 = "Enneagram is the study of the divrse set of human minds"; s3 = "Botony is the study of the plants kingdom"; q = "about plants"; data_set = [s1,s2,s3]; tfidf = TfidfVectorizer(); ...
72cfd98e0d515d7e108e8819422412fbf3f08a36
farukara/misc
/deque_vs_list_perf.py
2,767
3.890625
4
#!python3 # coding: utf-8 # Compares deque and list performance to find the longest palindrome from time import perf_counter from typing import List def timed(function): def wrapper(*args, **kwargs): start = perf_counter() value = function(*args, **kwargs) finish = perf_counter() p...
ee607452cb34bea2dad06764b9087fc8b61d6d53
pasbahar/python-practice
/Min_number_of_jumps.py
1,455
3.734375
4
'''Given an array of integers where each element represents the max number of steps that can be made forward from that element. The task is to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element. Input: The first l...
3a018db914f2fdbc575e284b703b1161ff3fd231
aarifkhan0706/PYTHON-DATA-TYPES
/oops1.py
562
3.9375
4
class BookStore: noOfBooks=0 def __init__(self,title,author): self.title=title self.author=author BookStore.noOfBooks += 1 def bookInfo(self): print("Book Title:",self.title) print("Book Author:",self.author,"\n") #create a virtual book store b1=BookStore("G...
b12b5330904d77494738d2c176f5b05e8ce03a5a
wonderjeo/Python_Learn
/Exercise12.py
353
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 20:53:29 2019 @author: 45570 """ oList = []; n = int(input("PLease input a number, 0 means exit:")) while n != 0: oList.append(n) n = int(input("PLease input a number, 0 means exit:")) while len(oList)>1: print(oList[::2]) oList = oList[1:l...
51e918f64dd010cb1e47c27d0e8484973438fa5f
dchu07/MIS3640
/Session08/exercise05.py
1,688
4.40625
4
def any_lowercase1(s): for c in s: if c.islower(): return True else: return False ''' If the word(string s) starts with a lowercase letter it will return True, or else if it starts with a uppercase letter it will return False. Even if the word contains any uppercase letters ...
cf9b8849bc4b855dec2c0b1f15993fff7bcfbef3
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4501/codes/1715_3036.py
181
4.09375
4
x=float(input("valor de x: ")) if(x<=-1 or x>=1): f=x print(round(f, 2) elif((x<-1 and x<0) or (0<x and x<1)): f=x print(round(f, 2)) elif(x==0): f=x print(round(f, 2))
5f0d8ae83cd066c2c0b028998dfefbefa7faef3b
Mega-Barrel/Quiz-Game
/main.py
773
3.65625
4
import sys sys.path.insert(1, 'questions/') from helper import play_quiz def main(): print('|------------------------------|') print('|------------------------------|') print('|------ Welcome To Quiz! ------|') print('| |') print('| 1. True or false quiz |') ...
fc14a45ad233f2e12327ce9b94d7e1206537b99c
YasirChoudhary/Python-Basics
/DataStructure/List/list_13.py
259
3.703125
4
courses=['History', 'Maths', 'ML', 'Physics', 'CompSci'] popped=courses.pop() #pop method also return the popped element so that we can store it in another varible print(popped) print(courses) ''' Output: CompSci ['History', 'Maths', 'ML', 'Physics'] '''
e57bc026ca5a577ea8ec04fc90565abdcdb8c190
NidhinAnisham/PythonAssignments
/pes-python-assignments-2x-master/StringPackage/34.py
546
4.03125
4
list1 = [70,20,30,10,60,50,40] list2 = [7,2,1,4,3] list3 = [1997,1990,1995,1996] list1.sort() list2.sort() list3.sort() maxlist = [list1[len(list1)-1],list1[len(list1)-2] ,list2[len(list2)-1],list2[len(list2)-2] ,list3[len(list3)-1],list3[len(list3)-2]] minlist = [list1[0],list1[1] ,lis...
ce98c9e4dd67af5dbf83505d736d67ee1b94bf84
AndreeaMusat/coursework
/Artificial Intelligence (ongoing)/Assignment2/util.py
11,330
3.515625
4
import sys import pickle import itertools from copy import deepcopy # this is an instance of a predicate class Atom(object): def __init__(self, name, variables, values, is_static): if len(variables) != len(values): print("Error, could not create atom with vars = " + str(variables) + \ " and vals = " + str(...
cba00062883f57630209b23caf5dde245220ea77
Meenawati/competitive-programming
/evaluate_expression.py
424
3.765625
4
def evaluate(s): ops = ['+', '-', '*', '/'] for i in range(len(s)): if s[i] in ops: return operate(int(s[0:i]), int(s[i+1:len(s)]), s[i]) def operate(n1, n2, o): if o is '+': return n1+n2 elif o is '-': return n1-n2 elif o is '*': return n1*n2 elif o is '/': return n1/n2 ...
d7a585192a9bff57de99cee826f510c48e034e87
quangnguyen17/Python
/python/fundamentals/users_with_bank_accounts.py
1,973
4
4
class User: def __init__(self, email): self.email = email account_one = BankAccount(interest_rate=0.02, initial_deposit=0) self.accounts.append(account_one) def make_withdrawal(self, account_name, amount): for account in self.accounts: if account.name == account_nam...
61a89d3f4c4a98a8f6f1e9a102e2d5c8dcba07df
gavin-ci/meten-is-weten
/kaas.py
1,167
3.9375
4
answer = input("Is de kaas geel?") if answer == "ja": answer = input("Zitten er gaten in?") if answer == "ja": answer = input("Is de kaas belachelijk duur?") if answer == "nee": print("Leerdammer") elif answer == "ja": ...
e18e21d07510b09f75a2a85662da15866545da8f
guanqg123/Recursive-examples
/fib_recursive_proof.py
1,732
4.15625
4
print("Following is fib(n) = fib(n-1)+fib(n-2)") #stacking and executing like: #call fib(5) #store fib(4)+fib(3) #call fib(4) #store fib(3)+fib(2) #call fib(3) #store fib(2)+fib(1) #call fib(2) #store fib(1)+fib(0) #call fib(1) #has return value #call fib(0) #has return value #co...
e0d0ce031f1f87a5cf553ab261a5a67ae548ab0e
JuanPedraza/FundamentosPython
/palindromo.py
430
3.96875
4
def palindromo(word): word = word.replace(' ', '') word = word.lower() word_invertida = word[::-1] if word == word_invertida: return True else: return False def run(): word = input('Escribe una palabra: ') es_palindromo = palindromo(word) if es_palindromo == True: ...
4f5a31a6d9494e0af6f58abc004ccfa1f3c87007
Brooks79/Lab_3
/Prob_4_game.py
1,182
4.40625
4
# opens it as an open string game = " " # welcome for user to put name name = raw_input("Please enter your name: ") print ("\n") print "Hello", name print ("\n") # the loop for the game while game != "Y" or "Yes" or "y" or "yes": game = raw_input("Shall we play a game?: ") print ("\n") if game == "Y" or game == "...
26b80856c622c80cab2a37299c898d9d33897208
nandhakumarm/InterviewBit
/Math/powerOfTwoInt.py
604
3.546875
4
class Solution: # @param A : integer # @return a boolean def isPower(self, A): count=0 rem=0 temp=0 if A==1: return 1 import math for i in xrange(2,int(math.sqrt(A))+1): temp=A while temp!=1: rem=temp%i ...
83ecf76b792fdfe80306cdf56291e18066a5b3c5
KarthickJeo/Misc
/stack.py
257
3.75
4
import sqlite3 with sqlite3.connect("emails.db") as connection: c = connection.cursor() c.execute("DROP TABLE email_addresses") c.execute("CREATE TABLE email_addresses(title TEXT )") c.execute('INSERT INTO email_addresses VALUES("email")')
f06c9adce018af48d87692d6f9007f457374ed2a
hahohe1992/PythonPractice
/day3/practice4_personaltaxcal.py
716
3.890625
4
import time #輸入月收入和五險一金來計算個人所得稅 salary = float(input('monthly income: ')) insurance = float(input('insurance: ')) diff = salary - insurance - 3500 if diff <= 0: rate = 0 deduction = 0 elif diff < 1500: rate = 0.03 deduction = 0 elif diff < 4500: rate = 0.1 deduction = 105 elif diff < 9000: rate = ...
132a46b2ae104d13d818aabbbe193d575a92d173
saraivaufc/dojos
/Seções/Seção 4- 20_05_2016/gui.py
618
3.796875
4
from Tkinter import * class Window: def __init__(self, Tk): self.containers = [Frame(Tk), Frame(Tk), Frame(Tk), Frame(Tk)] self.containers[0].pack(side=LEFT) self.containers[1].pack(side=RIGHT) self.containers[2].pack(side=TOP) self.containers[3].pack(side=BOTTOM) self.b1 = Button(self.containers[0],...
8ec512492a9f47789c57b2e29013015747ff316a
gabinlin/pythonStudy
/dataStructure/maxSubSeqSum/maxSubSeSum1.py
400
3.765625
4
#!/usr/bin/python3 # 最傻的算法1 k = input() kArray = input() def caculateMaxSum(array, k): maxSum = 0 for i in range(k): --k for j in range(i, k): thisSum = 0 for h in range(i, j): thisSum += eval(array[--h]) if (thisSum > maxSum): maxSum = thisSu...
92d9858cc248a3983d06e2080bed1a8f2204084f
leungcc/pythonLxf
/advanceFeature/iteration/iteration.py
450
4.125
4
#迭代list或者tuple for x in range(10): print(x) #打印数组元素 #迭代dict d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) #打印的是key print('-----print d.value()', ':', d.values()) print(isinstance(d.values(), (list, tuple))) #这里竟然是False for value in d.values(): print(value) #如果要同时迭代key和value: print('print for key,valu...
e95b722c9a2500c609a3d6aba00bb831ea0d2ad8
seven320/AtCoder
/104/B.py
502
3.671875
4
#encoding utf-8 s = list(input()) count = [] code_pass = False if s[0] == "A": capital_count = 0 for i in range(len(s)): # print(s[i]) if "C" == s[i]: count.append(i) # print(count) if s[i].isupper(): capital_count += 1 # print(capital_c...
7389b2b9a1442fdd8225a3caee381004cb110798
heshiqiufenzuoan/practice
/python基础代码/元组、列表、字典、集合/列表.py
3,177
4.28125
4
''' 标准数据类型 包括可变数据类型和不可变数据类型: 不可变数据类型:数字number、字符串string、元组tuple 可变数据类型:列表list、字典dictioary、集合set ''' # 创建列表 list = [1, 2, 3, 4, 5] print(list) ''' 把列表当作堆栈(后进先出)使用: 1.用append()方法可以把一个元素添加到堆栈顶。 2.用不指定索引的pop()方法可把一个元素从堆栈中释放出来。 ''' # list.append(x):append--附加,把一个元素添加到列表的结尾。 list_stack = [1, 2...
4386f6f6c6cfea04c2f5c43a6da9e9337f68d4ba
wsampaio/cursoPython
/segundos.py
456
3.671875
4
#Conversor de segundos segundos = int(input("Por favor, entre com o numero de segundos que deseja converter: ")) #segundos = 178615 #segundos = 178685 minutos = 0 horas = 0 dias = 0 minutos = segundos // 60 segundos = segundos % 60 horas = minutos // 60; if horas > 0: minutos = minutos % horas dias = horas //...
d48141f2dfcfa986e0c8d645214ca404815a6abe
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_53/469.py
352
3.5
4
from sys import argv def snapper(n, k): return ((k % 2**n)==2**n - 1) if __name__ == '__main__': file = open(argv[1]) runs = int(file.readline()) for i in range(runs): string = file.readline() vals = string.split() res = 'OFF' if(snapper(int(vals[0]), int(vals[1]))): res = 'ON' print(...
9041898deb7890ec3652e333d4d2719d1c6cfb10
MiguelAGonFig/4th_Activity_Intro-Python
/main.py
1,452
3.921875
4
# Programa main.py, recurre a funciones para calcular el area de un circulo, un traingualo y un cuadrado def cuadrado(lado): return lado**2 def triangulo(base, altura): aux = base * altura return aux / 2 def circulo(radio): radio **= 2 return radio * 3.14159 continuar = True while continuar == T...
67dd5b9b2f4602bf51e13abc43e7ee5d356ddc87
JulianLopezB/covid19_datasets
/age/data/load/utils.py
987
3.890625
4
import pandas as pd import datetime import numpy as np def map_age(age): """Map ages to standard buckets.""" try: age = int(age) if age >= 90: return '90+' lower = (age // 10) * 10 upper = age+9 if age % 10 == 0 else ((age + 9) // 10) * 10 - 1 return f'{low...
2c2521ffcca7d26b36bc4aa3d7a35c8b5bd2702f
whiteowl-code/BMI
/BMI_input.py
1,000
3.9375
4
from BMI_health import BMI print("健康管理アプリケーションへようこそ。") name = input("名前を入力してください。:") height = float(input("身長(m)を入力してください。:")) weight = float(input("体重(kg)を入力してください。:")) person = BMI(name) while True : print("**********メニュー**********") obj = input("1)BMI指数計算 2)標準体重計算 3)肥満度計算 9)終了:") try : i...
2240ca7f543ed152a5f048b67891f3216e58be6e
blegloannec/CodeProblems
/HackerRank/palindrome_index.py
433
3.734375
4
#!/usr/bin/env python3 def is_pal(S): return S==S[::-1] def pal_index(S): s = len(S) for i in range(s//2): if S[i]!=S[s-i-1]: if is_pal(S[:i]+S[i+1:]): return i elif is_pal(S[:s-i-1]+S[s-i:]): return s-i-1 return -1 return -1 ...
d459580f4d6fa781a598845fc74c002e5640d9c4
hrz123/algorithm010
/Week07/每日一题/796. 旋转字符串.py
3,510
3.671875
4
# 796. 旋转字符串.py # 1. 穷举法 class Solution: def rotateString(self, A: str, B: str) -> bool: if len(A) != len(B): return False n = len(A) if n == 0: return True for i in range(n): if all(A[(i + j) % n] == B[j] for j in range(n)): retu...
b1d8d97472dc3ba69cd05b00b03ac4f59c7848bc
kds3000/Algo_and_data_structures
/Heap_realisation.py
1,612
3.75
4
"""Heap and heap sort realization""" class Heap: def __init__(self): self.values = [] self.size = 0 def insert(self, value): self.values.append(value) self.size += 1 self.sift_up(self.size-1) def sift_up(self, i): while i > 0 and self.values[(i - 1) // 2]...