blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d423f5f63cbb5c7c529097dc8e284a75a4b76152
vandecloud/python
/16-POO-clases/main.py
2,822
3.984375
4
# Programacion orientada a objetos (POO o OOP) # definir una clase ( Model para crear mas objetos de ese tipo) # (coche) con caracteristicas similares class coche: #Atributos o propiedades (variables) #Caracteristicas del coche color = "rojo" marca = "Ferrari" modelo = "Aventador" velocidad =...
a22cab4d09de949dc3a4101f7ce59dd409e496c0
vandecloud/python
/20-proyecto-python/notas/acciones.py
1,470
3.734375
4
from datetime import time import notas.nota as modelo class Acciones: def crear (self, usuario): print(f"\nOK {usuario[1]}!! Vamos a crear una nota ...") titulo = input ("Introduce el titulo de tu nota: ") descripcion = input ("Introduce el contenido de tu nota: ") ...
de7ba808f6b8b5e1296dfa2ab02918ba520b8b0f
vandecloud/python
/10-set-diccionarios/diccionarios.py
836
4.3125
4
""" DICCIONARIOS Un diccionario es un tipo de dato que almacena un conunto de datos. en formato clave > valor es parcecido a un array asociativo o un objeto json. """ """ persona = { "nombre": "Pablo", "apellido": "Vande", "Web": "a definir" } print(type(persona)) print(persona["apellido"]) # Acceder ...
30c5cd489f974ce911434d09579dc80c59455370
RavidRomy/PythonAnswers
/AnswerSix.py
1,459
3.578125
4
################################ # Python Answer for Question 6 # # ====== BY HEISENBERG ======= # ###### . - - - - - - - - . ##### ###### | | ##### #### ----= ___________ =---- ### ######## ___ ___ ######## #######_| ___) == (___ |_####### #########\ *** /######## ##########\ * = * /...
728f72b3f0d8f780a48935e95088d27616e69216
prathapSEDT/TM_PYTHON_SDET
/Colections/List/RemoveList.py
240
3.75
4
mylist=["Raj","Krish","Mahesh"] # if "krishna" in mylist: # mylist.remove("Krishna") # else: # print("Wrong input value") # print(mylist) # mylist.pop(0) # print(mylist) # # del mylist # print(mylist) mylist.clear() print(mylist)
159fd792fbcd15891c5b4e7f43f71d9e58cd5f8b
prathapSEDT/TM_PYTHON_SDET
/FileHandling/ReadAndCreate.py
670
3.609375
4
import os srcFilePath=r"C:\Users\hanshik\Documents\Python Scripts\Dict.txt" destFilePath=r"C:\Users\hanshik\Documents\Python Scripts\dest.txt" # file1=open(srcFilePath,'r') # file2=open(destFilePath,'r+') # # # #print(file.read()) # # # # # print() # # # # # # data=file.readline() # # # # # # while len(data)>0: # #...
9c259a090410830ad93881c4ddc6e75133d072bf
NONVME/Hackerrank-solutions
/python/itertools/itertools-combinations-with-replacement.py
190
3.5
4
from itertools import combinations_with_replacement word, line = input().split() result = combinations_with_replacement(sorted(word), int(line)) for i in result: print(f"{''.join(i)}")
530ea52a544724af74f04882d60ed2835966e269
NONVME/Hackerrank-solutions
/python/strings/python-string-formatting.py
239
3.8125
4
def print_formatted(number): lenth = number.bit_length() for i in range(1, number + 1): print(f'{i:{lenth}d} {i:{lenth}o} {i:{lenth}X} {i:{lenth}b}') if __name__ == '__main__': n = int(input()) print_formatted(n)
dd82079472c22cdf51de39fbf60c6244adbe6b4e
runphilrun/kaggle-radiation-prediction
/preprocessing.py
2,201
3.8125
4
'''Import and prepare data for analysis. Philip Linden September 10, 2017 ''' ## IMPORT LIBRARIES import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import pytz # timezones def ingest_data(filename): '''Read data from a CSV file and construct a pandas DataFr...
a47f3410e534f9d24a12a5b46a389a9be8eedca9
Sorabh-Kumar/python-programing
/prime.py
192
4.03125
4
n= int(input('enter the number')) i=2 t=0 while i<n: if n%i==0: print('number is not a prime number') break i=i+1 else: print('number is a prime number')
73d2bf6e4d910d6a7db3ee6b7a3392096bb10c03
Kiru-axis/Password-Manager
/password.py
1,842
3.9375
4
# Cridential class class Cridential: """ Class that generates new instances of passwords """ password_list = [] # 1. Initialisation def __init__(self,account,username,password): self.account = account self.username = username self.password = password #2. save acount passwor...
ede643361b6369acd50207dcaa63e1a326886e23
rejithry/class
/algo2_misc/2sat.py
5,183
3.59375
4
"""TwoSatisfiability.py Algorithms for solving 2-satisfiability problems. For theory and references, see http://en.wikipedia.org/wiki/2-satisfiability All instances should be represented as a directed implication graph in which the vertices represent variables and (via Not.py) their negations. A variable may b...
79a0a5565aafcc780a4db2068411a60de9eb61f7
rejithry/class
/algo2_stanford/knapsack2.py
1,815
3.546875
4
def main(): f = open('e:\\knapsack1.txt' , 'r') head = 0 W = 0 v = [] w = [] for i in f: if head != 0: s = i.strip().split(' ') v.append(int(s[0])) w.append(int(s[1])) else: W = int(i.strip().split(' ')...
e4dc5f51b9e527d06934d083e8cd64054a67a45b
antonioan/repeat-free-py
/rip/linked_list.py
4,963
3.75
4
# Source: https://github.com/Darthfett/Hashtable/blob/master/LinkedList.py from typing import Optional, Iterable, Reversible class Link: """ Link Used in the ChainedHashtable, a Link is a (key, value) pair for use in a linked list. """ key: int = 0 value: Optional = None next: Optional[...
18f8067ddfdc0ca9143b46bf469a3d6576f3bea2
umepy/recommend_competition
/analysis/confirm_rule.py
729
3.546875
4
#coding:utf-8 #sample submitを調査してルールの確認 import pandas as pd import numpy as np #予測者数の確認(全員予測するのか?) df = pd.read_csv('../data/sample_submit.tsv',delimiter='\t',names=['user_id','item_id','rank']) print('予測する人数の合計: '+str(len(df[df['rank']==0]))) a= df[df.apply(lambda x: 'A' in x['user_id'],axis=1)] b= df[df.apply(lambd...
9794b1ce63c7d7e3fe93186f5cb48212efeb8af4
samroman3/PythonLoops
/PythonFundamentals.py
9,886
3.8125
4
#Imports import math from numpy import asarray print(type(math)) # #Lists and Loops def has_lucky_number(nums): """Return whether the given list of numbers is lucky. A lucky list contains at least one number divisible by 7. """ lucky = False for i in nums: if i % 7 == 0: luc...
d47ab68845126b7cab185abf014668bebb381bc0
Nidolex/Nidolex
/RUNumber.py
5,208
3.734375
4
print("Проверка номера на стоимость") print("1 балл - 1 рубль") print("Пример: 89291239999") number = input("Введите номер телефона: ") #1-ый этап numberfind1 = number.count("1") numberfind2 = number.count("2") numberfind3 = number.count("3") numberfind4 = number.count("4") numberfind5 = number.count("5") ...
6a40da9daeb7b5c96488dd8552caafac2f0e0044
tedgey/while_loop_exercises
/p_a_s_II.py
346
4.15625
4
# print a square II - user chooses square size square_size_input = input("How long should the square's sides be? ") square_size_length = int(square_size_input) symbol_count = square_size_length * ("*") counter = 0 while counter < square_size_length: counter = counter + 1 if counter <= square_size_length: ...
8cc7776e6788bad1fb5ce63630521a094c39ca82
CPE202-PAR/project-1-enzosison
/bears.py
756
3.59375
4
# int -> booelan # Given integer n, returns True or False based on reachabilty of goal def bears(n): by_2 = n % 2 by_3 = n % 3 by_4 = n % 4 by_5 = n % 5 if n < 42: return False elif n == 42: return True if by_2 == 0: test = bears(n - n/2) if test ...
22f7df39cb5e448034c348c6b3587138de937361
MTDahmer/Portfolio
/hw2.py
2,972
4.28125
4
# File: hw2.py # Author: Mitchell Dahmer # Date: 9/18/17 # Section: 503 # E-mail: mtdahmer@tamu.edu # Description: a program that takes two operands from a user and then modifies them based on the operation given by the user in the form of a string import math def main(): firstInteger = int(input("Please...
780813e479254da4cd58827ee87fd2266ea3ad26
MTDahmer/Portfolio
/hw3testrealm.py
1,630
3.828125
4
SIZE = 5 def main(): #dataList = list() for i in range (SIZE): value=str(input("Please enter a sentence")) dataList.append(value) print(dataList) choice = int(input('please enter four bitch') if (choice == 4): snt1 = int(input('Please enter index ...
a9bbf4d49e927d8a04ffea3f199484459e48aa3b
lucaslk122/Comandos-em-python-essencial
/Aula_atributos.py
727
3.859375
4
class Produto: def __init__(self, nome, descricao, valor): self.nome = nome self.descricao = descricao self.valor = valor class Usuarios: def __init__(self, nome, email, senha): self.nome = nome self.email = email self.senha = senha class Acesso: def __in...
8657791d880205ac654997874fce1c2ee158fa5c
sukhvir786/Python-DAY-4
/fun3.py
493
4
4
""" Program to add the sum of the digits in any range may be from 12 to 93 from 34 to 57, from 15 to 27, from 1 to 100 etc... """ s1 = 0 for i1 in range(12,94): s1 = s1 + i1 print("Sum (12 to 93) : ",s1) s2 = 0 for i2 in range(34,58): s2 = s2 + i2 print("Sum (34 to 57) : ",...
ea84d83db6a672ef7a015ef0fec2f0af48368284
sukhvir786/Python-DAY-4
/fun12.py
525
4.25
4
""" Problem: Heron's formula a,b,c are length of sides of a triangle s = semi circumference s = (a+b+c)/2 area = sqroot(s(s-a)(s-b)(s-c)) """ # %% def FUN(): """ computes area of triangle using Heron's formula. """ a = float(input("Enter length of side one: ")) b = float(inp...
6b98575ef1068223741548676a718f1d1918a14d
JoshL51/MazeProject
/resize.py
2,085
3.78125
4
import numpy as np from PIL import Image import runFile def resize(image): maze = image imageRGB = Image.open(maze).convert('RGB') # This converts to RGB so we can draw colours imageDataRGB = np.asarray(imageRGB) imageBW = Image.open(maze).convert('1') # This is black/white imageDataBW = np.asa...
c097917a104b8d1fbb1614c90c7af19d0a2ce64b
TrinityChristiana/py-functions
/cash-to-coins.py
938
4.125
4
# **************************** Challenge: Cash to Coins **************************** """ Author: Trinity Terry pyrun: python cash-to-coins.py """ import math # Now do the reverse. Convert the dollar amount into the coins that make up that dollar amount. The final result is an object with the correct number of quarters,...
93cf97db0b7b5631ee246281572a1e31b4a16341
REDBEANCAKE-LI/ud120-projects
/outliers/outlier_cleaner.py
858
3.671875
4
#!/usr/bin/python import math def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple...
090a00e1cf0073c10f069aad0230083524e1d579
Nemiadier/task1
/task1.py
1,338
3.8125
4
import re #Ввод символів row=input("\nВведіть слова та числа: ") #Виведення введених символів print("\nВведені символи ", row) extract_letter=" ".join(re.split("[0-9]+", row)) extract_number="".join(re.split("[a-zA-Z]+", row)) extract_com_let=", ".join(extract_letter.split()) extract_com_num=", ".join(...
bc086f2df1944bbd72c2a8cf284932f43cacab90
NateJune/Orbital-Components
/Orbital Parameters.py
6,973
3.734375
4
# coding: utf-8 # In[143]: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # In[37]: # This function will calculate the length of the semi-major axis of an ellipse given the distance at perigee and apogee. def semi_major(r_p,r_a): a = (r_p + r_a)/2 return a ...
3819a9520dca8eefb2a863014238951f62b19562
AJ-Davis/metis
/Project_Luther/Archive/Pair Problem 7-13.py
1,247
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 13 07:39:50 2018 @author: ajdavis """ import random sims = 1000 doors = ["FML", "FML", "ca$h"] # Switching doors strategy wins = 0 losses = 0 for i in range(sims): random.shuffle(doors) # shuffle door assignment d = random.randra...
8b05cc454e51dff241f665b29a3d1d00286b4ef5
sayantansatpati/python-data-engg
/weeks/wk9/reducer.py
484
3.59375
4
#!/usr/bin/env python import sys last_word = None word_count = 0 for line in sys.stdin: line = line.strip() word, count = line.split("\t") count = int(count) if not last_word: last_word = word if word == last_word: word_count += count else: result = [last_word, word...
c948f17ba992903ec808f0a6783d6bbfd8827aa4
Aniketshukla123/Latin-square
/latinsquare.py
344
3.71875
4
class Solution: def solve(self, mat): ch=set(j for i in mat for j in i) m=zip(*mat) for i,j in zip(mat,m): for c in ch: if c not in i or c not in j: return False return True ob = Solution() mat = [["x", "x", "z"],["z", "x", "y"], ["y", "z", "x"]]...
337cc80c749ecf95b1ddc718859b537f2043f1a4
zavalacl/python
/proj03old.py
3,945
4.21875
4
print("At the prompts, please enter the following:\n") print(" Customer's classification code (a character)") print(" Number of days the vehicle was rented (an integer)") print(" Odometer reading at the start of the rental period (an integer)") print(" Odometer reading at the end of the rental period (an in...
e8d88b7ad4e3b6240c490fb76dba2a79179b8a91
zavalacl/python
/proj09.py
7,565
4.09375
4
################################################# #Computer Project #9 #Algorithm # Run function main # Establish deck # Shuffle deck # Create empty list to keep track of rounds # Run while loop # Create empty lists for both hands # Run function deal # Run function pr...
2f8da2eb3fc9ac3025cc5b2ca018e46a3eb9bceb
Gabospa/Matrix
/invert.py
1,782
3.546875
4
def get_determinant(A): if len(A) == 2: det = (A[0][0]*A[1][1])-(A[0][1]*A[1][0]) if len(A) == 3: det = ((A[0][0]*A[1][1]*A[2][2])+(A[1][0]*A[2][1]*A[0][2])+(A[2][0]*A[0][1]*A[1][2]) -(A[0][2]*A[1][1]*A[2][0])-(A[1][2]*A[2][1]*A[0][0])-(A[2][2]*A[0][1]*A[1][0])) return det d...
bfba3f216131e4cb0ab13e38bb38c04b25c52f18
ofir1080/stegonography-cli-app
/modules/inject.py
727
3.53125
4
""" injects message into the carrier matrix represents the image. """ import numpy as np def inject(carrier, msg): bit_counter = 0 for row in range(carrier.height): for col in range(carrier.width): if bit_counter >= msg.size: # run as long as there are bits to inject ...
342d5e2da2bc517fb797959e875fb580910ff14d
DAVIDCRUZ0202/cs-module-project-algorithms
/UPER.py
933
3.84375
4
# UPER ## Understand, Plan, Execute , Reflect ### To Understand # Re-phrase the problem. # Make sure to fully grasp what is being asked # If you understand what success looks like, you understand the problem ### To Plan # Gather info nonstop # get rid of repeat info ### Execute # Execute the plan! ### Reflect ...
6d63f96591f210049407b3930d131435727b2dfa
nicodlv99/100-days-of-code
/basics/sequence-types.py
1,657
4.59375
5
#Creating a string s = "Hello World, how are you doing!" #Creating a string to print print(s) s1 = """This is a line of code with multiple ines""" print(s1) #defining a string that contains multiple lines print(s[0]) #indexing to find the first letter in a word using dictionaries ...
88c364836a1fee5e8469fd4260549e1a817758e7
yanshaozhuo/ysz_python
/random_number.py
1,007
3.578125
4
import random class random_len: def __init__(self,length,times): self.length = length self.times = times def random_length(self): char = 'ABCDEFGHIJKLMNOPQRSTUVWXZYabcdefghijklmnopqrstuvwxyz0123456789' with open('随机码.txt','a+') as f: ''' #第一种方式: ...
ca5817f7c3b7bd15b21591b43ba0fe69a9f0afa5
faelzsouza/blue_mod01
/Aula_08_Exercícios_Listas.py
4,816
4.21875
4
""" 1- Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: a) tamanho da lista. b) maior valor da lista. c) menor valor da lista. d) soma de todos os elementos da lista. e) lista em ordem crescente. f) lista em ordem decrescente. """ """ 2- Utilizando listas faça um prog...
73747e1c02af5c3d61dc77b373f2b04809b65f1e
faelzsouza/blue_mod01
/Aula_06_Exercícios_For.py
3,019
4.03125
4
"""01 - Dado uma string com uma frase informada pelo usuário (incluindo espaços em branco), conte quantas vezes aparece as vogais a,e,i,o,u""" # import unidecode # string = input("Digite uma frase:\n") # stringSemAcento = unidecode.unidecode(string) # vogalA = 0 # vogalE = 0 # vogalI = 0 # vogalO = 0 # vogalU = 0 # ...
15448367ed0eeaf69c94a2b6cd2b30ae6496a3b5
faelzsouza/blue_mod01
/teste.py
692
3.703125
4
## Programa que solicita a quantidade de jogos de um usuario e retorna os numeros sorteados para um jogo ## import random v = [] m = [] numJogos = 0 sorteio = 6 # Solicita a quantidade de jogos que o usuario deseja. print("Número de jogos: ") numJogos = int(input()) print() # Logica, baseado no conseito de matriz, ...
bec6f80c9128322c695b2c93ceed59f8b3af08d6
vlasiuk-andrii/Base_of_simple_programs
/Minimal_mehrere.py
259
4.03125
4
a = int(input('Insert a: ')) b = int(input('Insert b: ')) d = 0 if a == 0 or b ==0: print('Zero values are not allowed') else: while 1: d+=1 if (d%a == 0) and (d%b == 0): print('Minimal mehrere=', d) break
4eea5a87d1c98a292a1f9814b4829e0a040190c9
Perrywzp/python-learning
/adv-features/iterator.py
229
3.515625
4
# -*- coding: utf-8 -*- from collections import Iterable isinstance([], Iterable) for x in [1, 2, 3, 4, 5]: pass it = iter([1, 2, 3, 4, 5]) while True: try: x = next(it) except StopIteration: break
13ce88f518409486a537fed71a3829b8979466b4
leomazuran/python
/guessing game using binary search.py
1,293
3.953125
4
#Computer guessing game using Binary Search #author: Leonardo Mazuran #last modified: 8 September 2016 import random input1 = int(input("Input maximum range from 1 to 1000: ")) while input1 >1000 or input1 <1: input1 = int(input("Incorrect input! Try again: ")) first = 1 last = input1 while first <= last: ...
77ed3cea07cdb43fc23d969358a901db9a550540
l-duan/python_basic
/day5/抽象类.py
259
3.578125
4
# -*- coding:utf-8 -*- __auth__ = 'christian' from abc import ABCMeta, abstractmethod class Bar(object): __metaclass__ = ABCMeta @abstractmethod def Fun(self): pass class Foo(Bar): def __init__(self): print "__init__" Foo()
5ed30bf80ba7ab8e7d8e77922309394f9e7e8709
l-duan/python_basic
/else.py
479
3.515625
4
def average(*args): s=0.0 l=len(args) if l==0: return s for x in args: s+=x return s print average() print average(1, 2) print average(1, 2, 2, 3, 4) def Person(**kwargs): print kwargs if kwargs.has_key("name"): print kwargs["name"] else: print "must inpu...
545fc9af3eaf0cb27a22f6db955f7a4db29c1abc
l-duan/python_basic
/day5/随机数.py
673
3.59375
4
# -*- coding:utf-8 -*- __auth__ = 'christian' import random print random.random() print random.randint(1,2) print random.randrange(1,10) checkcode = '' for i in range(6): current = random.randrange(0,6) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) ...
998352bca9a061355d772e676f6567821a7be48b
l-duan/python_basic
/day2/yield.py
402
3.71875
4
def run(): for i in range(100): print '--->',i yield i task = run() print task.next() print "do something else....." print task.next() print "do something else....." print task.next() print "do something else....." print task.next() print "do something else....." print task.next() print "do somethi...
8865268c8593ccc2f47e0d7d1e7e135e213e1f36
l-duan/python_basic
/day6/thread_demo/direct_call_threading.py
879
3.578125
4
# -*- coding:utf-8 -*- __auth__ = 'christian' import threading import time def sayhi(num): # 定义每个线程要运行的函数 print("running on number:%s" % num) time.sleep(1) print ("task done", num) if __name__ == '__main__': start_time = time.time() t_obj = [] # 存线程实例 for i in range(50): t = thread...
d77a076163fd6624806f1e7b986bb8b34c77891d
l-duan/python_basic
/day2/shopping_teacher.py
1,039
3.78125
4
# -*-coding:utf-8-*- products = [ ['Iphone', 8000], ['ipad', 5000], ['Tesla', 30000], ['Coffee', 35], ['Clothes', 500], ['Shoes', 800], ] salary = 9000 shop_list = [] while True: for index,p in enumerate(products): print index, p[0], p[1] choice = raw_input("Choose something to ...
9f185d3acb416079dabe6f68500d043bacd2d246
l-duan/python_basic
/network programming of python/find_service_name.py
511
3.640625
4
#!/usr/bin/env python # Python Network Programming Cookbook # This program is optimized for Python 2.7. It may run on amy # other Python version with/without modifications. import socket def find_service_name(): protocol_name = 'tcp' for port in [80, 25, 3306, 22, 21]: print 'Port: %s => service name:...
498ad83c72a19819771d194b4b2a2f76ea60f7fe
Aytijha/DAA_Lab_Assignments
/Week 2/lab2_ques1.py
2,366
3.65625
4
''' Name: AYTIJHA CHAKRABORTY BTech (CSE-AI/ML) Sem: 5 Class Roll: 17 Sec: K University Roll: 1914009 Problem Statement: Given a sorted array of positive integers containing few duplicate elements, design an algorithm and implement it using a program to find: Whether the given key element is present in the ...
09b936e163ac957673a62a0e31bf7a551c65d4b8
imchandeliya/Hackerrank-Solutions
/PYTHON/Strings/String Formatting/main.py
858
4.03125
4
""" String formatting @author adityachandeliya """ def print_formatted(number): # logic to print decimals length_binary = len(bin(number)) for i in range(1, number + 1): # logic to print decimals print(' ' * (length_binary - len(format(i, 'd')) -2), end='') print(format(i, 'd'...
714455bd654417511263275e5adb668acaf04ce8
TiagoCalmon/learnPython
/readintsafely5-1-6-4.py
508
3.984375
4
def readint(prompt, min, max): # # put your code here v=None while True: try: v=int(input(prompt)) assert v > min and v < max except ValueError: print('Error: wrong input.') continue except AssertionError: print('Error: the valu...
bdc4c9139073bdaf9f3a8fdac96ef326e37cd9d6
park-ki-yeon/MSE_Python
/ex030.py
388
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # string 문자열 함수값을 abcd로 지정한다. string = 'abcd' # abcd의 b를 replace 메서드를 이용하여 B로 변환한다. 하지만 문자열은 변경할수 없는 자료형이기 때문에 값은 그대로 출력된다. string.replace('b','B') # string 함수값을 print함수를 이용해 출력한다. print(string)
6f4f9939f453116e33ac9916e8d4cddb6b2cac8e
pedrograngeiro/Exercicios-Python
/exercicios cap 4/exercicio 4.1.py
287
3.65625
4
# Analise o programa da listagem 4.2. Responda o que acontece se o primeiro e o segundo valores forem iguais? a = int(input("Primeiro valor: ")) b = int(input("Segundo valor: ")) if a > b: print("O primeiro número é o maior!") if b > a: print("O segundo número é o maior!")
306fb474637af230b7cd4be92de14632438f10d7
pedrograngeiro/Exercicios-Python
/exercicios cap 5/exercicio 5.24.py
557
3.953125
4
# Modifique o programa anterior de forma a ler um número n. # Imprima os n primeiros números primos. núm = int(input("Digite um número: ")) while True: tot = 0 cont = 1 while cont <= núm: # cont vai percorrer todos os números abaixo de núm if núm % cont == 0: tot = tot + 1 # se tot igua...
2389b4ac4d8193c3ac929897827ba35cd31fe79b
pedrograngeiro/Exercicios-Python
/exercicios cap 4/exercicio 4.2.py
484
3.953125
4
# Escreva um programa que pergunte a velocidade do carro de um usuário. # Caso ultrapasse 80 km/h, exiba uma mensagem dizendo que o usuário foi multado. # Nesse caso, exiba o valor da multa, cobrando R$ 5 por km acima de km/h. velocidade = int(input("Digite a velocidade em km/h: ")) if velocidade > 80: diferenca ...
1c1666ca838e171cc711981f4b3a612ab9991d6f
pedrograngeiro/Exercicios-Python
/exercicios cap 5/exercicio 5.2.py
107
3.9375
4
# Modifique o programa para exibir números de 50 a 100 x = 50 while x <= 100: print(x) x = x + 1
82db76776aeeb6f49c014ac1b2ba554871792078
pedrograngeiro/Exercicios-Python
/exercicios cap 3/exercicio 3.4.py
324
4
4
# Escreva uma expressão para determinar se uma pessoa deve ou não pagar imposto. # Considere que pagam imposto cujo salário é maior que R$ 1200,00 salario = float(input("Digite o salario da pessoa: ")) if salario > 1200: print("A pessoa deve pagar imposto.") else: print("A pessoa não precisa pagar imposto.")
dc02e2674e050ee24c10111fa7509167a6721f19
pedrograngeiro/Exercicios-Python
/exercicios cap 3/exercicio 3.11.py
348
3.9375
4
# Faça um programa que solicite o preço de uma mercadoria e o percetual de desconto. # Exiba o valor do descoto e o preço a pagar. valor = float(input("Digite o preco da mercadoria: ")) percentual = float(input("O valor do desconto: ")) valor_novo = (valor * (percentual/ 100)) valor_novo_final = valor - valor_novo ...
e81e4de45e779e94c2ec82d8af3d1c28cd8514f0
hyj1116/LeetCode-HYJ
/2-Medium/5341. Product of the Last K Numbers/5341. Product of the Last K Numbers.py
1,162
3.859375
4
class ProductOfNumbers: def __init__(self): self.A = [1] def add(self, a): if a == 0: self.A = [1] else: self.A.append(self.A[-1] * a) def getProduct(self, k): if k >= len(self.A): return 0 return self.A[-1] // self.A[-k - 1] #...
968d6acf0ecdf954b7cf47612dd3b3d5a3a6858d
hyj1116/LeetCode-HYJ
/2-Medium/5313. Angle Between Hands of a Clock/5313. Angle Between Hands of a Clock.py
329
3.671875
4
class Solution: def angleClock(self, hour: int, minutes: int) -> float: hour_angle = 360/12*(hour+minutes/60) minutes_angle = minutes / 60*360 if abs(hour_angle-minutes_angle) < 180: return abs(hour_angle-minutes_angle) else: return 360 - abs(hour_angle-minute...
a3cdd1c694e16b5ea7e65fc4f0d254cc2f1830e3
hyj1116/LeetCode-HYJ
/2-Medium/34. Find First and Last Position of Element in Sorted Array/Binary Search.py
1,274
3.875
4
""" Complexity Analysis Time complexity : O(\log_{10}(n))O(log 10 ​ (n)) Because binary search cuts the search space roughly in half on each iteration, there can be at most \lceil \log_{10}(n) \rceil⌈log 10 ​ (n)⌉ iterations. Binary search is invoked twice, so the overall complexity is logarithmic. Space compl...
81abbf877551503e5acacb72ae0a2bae3b57c3ef
hyj1116/LeetCode-HYJ
/1-Easy/66. Plus One/Plus_One.py
105
3.703125
4
def iterator(): for num in range(10): yield num def num in iterator(): print num
1ed43674c86b36c829fca7df75e9ff6d9d0800b3
hyj1116/LeetCode-HYJ
/2-Medium/1143. Longest Common Subsequence/Recursive.py
919
3.640625
4
# https://leetcode.com/problems/longest-common-subsequence/ import functools class Solution: def longestCommonSubsequence(self, text1, text2): @functools.lru_cache(None) def helper(i, j): if i >= len(text1) or j >= len(text2): return 0 if text1[i] == text2[j...
c545280b24d8f3e1f6236356f3c8d8aafaebcc13
hyj1116/LeetCode-HYJ
/LeetCode Contest/1201. Ugly Number III/1201. Ugly Number III.py
1,794
3.875
4
# https://leetcode.com/contest/weekly-contest-155/problems/ugly-number-iii/ class Solution: """ Write a program to find the n-th ugly number. Input: n = 3, a = 2, b = 3, c = 5 Output: 4 Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. """ # Function to find the nt...
cdc1be69b8af13cffaf00985202e60b83004c7d8
antatranta/Educational-Game-Recursions
/src/family_tree.py
8,678
3.734375
4
"""Family Tree Class.""" import enum from abc import ABC from family_tree_node import FamilyTreeNode class FamilyTree: """Represents a single FamilyTree.""" def __init__(self, root=None): """ :param root: The root FamilyTreeNode of the tree. """ self.root = root or FamilyTree...
613c4ff4124869c98dee20deca33ac160d8edbe6
dials/dials
/src/dials/algorithms/scaling/reflection_selection.py
16,547
3.953125
4
""" Algorithm to select a well connected subset of reflections for scaling. Description of reflection selection algorithm. To get the best 'connectedness', we want to select groups of reflections which belong to more than one class. A class in this case is a volume of reciprocal space (e.g 12 areas on the surface of a...
164ebf80a67377f1a19d6ac0d5f647f0216744a6
dials/dials
/src/dials/util/observer.py
1,615
3.578125
4
""" Define an interface for observers and subjects. A singleton decorator is also defined. """ from __future__ import annotations import functools def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] re...
621c0d35b6e0a2ff8fad1f30b74164b30c09115b
kicksmackbyte/project_euler
/p004.py
589
4.3125
4
""" Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(i): str_ = str(i) if str_ == str_[::-1]: return True else: return False def main(): num_1 = 999 num_2 = 999 palindromes = [] for i in range(900): a = 999 - i ...
1eed8e4956fff6c1e99a44e316dda4e51a8b000c
junebash/Sprint-Challenge--Data-Structures-Python
/names/singly_linked_list.py
2,108
3.9375
4
class ListNode: def __init__(self, value=None, next_node=None): self.value = value self.next_node: ListNode = next_node class LinkedList: def __init__(self, head=None): self.head = head self.tail = head self.length = 0 if head is None else 1 def __len__(self): ...
8faa9ef69ed763164ec130d4a91088df7d30030d
satishraut/inter-prep
/oops/methodOverLoadingAndRiding.py
799
4.125
4
''' Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other. Like other languages (for example method overloading in C++) do, python does not supports method overloading. We may overload the methods but can only use the latest defined meth...
f7cc06320b7060535dc00bb98cb2c005c2386b1e
AnushreeBagchi/Learning-Data-Structures-and-Algorithm-Python
/deep_reverse.py
809
3.875
4
def reverse(l): out = list() if len(l) == 0: return list() for index in range(len(l),0,-1 ): if isinstance(l[index-1], list): to_append = reverse(l[index-1]) else: to_append = l[index-1] out.append(to_append) return out def test_function(test_case...
465541d5c4c6bb5c4aac20855ad814ffbc541503
AnushreeBagchi/Learning-Data-Structures-and-Algorithm-Python
/keypad_combi.py
760
3.875
4
def get_characters(num): if num == 2: return "abc" elif num == 3: return "def" elif num == 4: return "ghi" elif num == 5: return "jkl" elif num == 6: return "mno" elif num == 7: return "pqrs" elif num == 8: return "tuv" elif num == ...
404a75e78c4d8f05fe034edfbd584abe32c07e24
AnushreeBagchi/Learning-Data-Structures-and-Algorithm-Python
/Reverse_stack.py
1,073
3.828125
4
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head = None self.num_element = 0 def push(self, value): if self.head is None: self.head = Node(value) else: new_node = Nod...
f76ac1b587b0cae18943b164260060a02926d1b0
pkiuna/CS490-MachineLearning-Python
/3.2/ICP 3.2.py
1,769
3.515625
4
import pandas as pd from sklearn.decomposition import PCA #PCA Library from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") data = pd.read_csv("CC.csv") #reading file print(data["Longing"].value_counts(...
0bf5883db8abc4f19b9fa91778012fc4a0faa28d
pkiuna/CS490-MachineLearning-Python
/ICP2/ICP2.py
1,350
4.15625
4
class employee: # Members to count employees and find average salary counter = 0 salary = 0 #contructor to initialize family, salary, department using self def _init_(self, name, family, salary_num, department): self.name = name self.family = family self.salary_num = salary_...
6fe50aabb48e469fc0b750fbfb311cd9342da8fc
AgroDan/adventofcode2020
/d2p2.py
1,751
4.03125
4
#!/usr/bin/env python3 from string import ascii_letters class PasswordEntry(): def __init__(self, entry_string): """ entry_string will be the single line of the file. Upon ingesting, all computations of this password will be performed on it. """ self.firs...
7df2ca3e25b301f33e223516bd3816f02436e92e
akki111singh/InterviewBit-Solutions
/linked-list/palindrome-list.py
1,016
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : head node of linked list # @return an integer def lPalin(self, A): n = 1 head = A curr = head while curr.next: ...
1aa7d63d7c598d824d9272b42a48bf21774d79be
lucapericlp/coding_deepdive
/pythonic/generators.py
404
4.09375
4
def reverse_enum(array): return ((index,array[index]) for index in reversed(range(len(array)))) def reverse_enum_full(array): for index in reversed(range(len(array))): yield index, array[index] if __name__ == "__main__": array = [1,2,3,4] for index,item in reverse_enum(array): print(item,end="") print("\n...
36c0ee77d2368aee7f479ef9c0c5b2802c3ef09f
ansariimran/small-python-programs
/perfect_square.py
1,038
4.0625
4
import math n = int(input("Enter the number to make it a perfect square: ")) number = 2 def perfect_square(n): count1 = 0 x = n cond1 = True while cond1: sqrut1 = math.sqrt(x) if (sqrut1 - math.floor(sqrut1)) == 0: cond1 = False else: x = x + number...
f162ad816fd042b77c190a314d018ae4f489d12a
ansariimran/small-python-programs
/pattern.py
1,061
4.5
4
def pattern(n): # for i in range(1, n+1): # # print i number of * s in # # each line # print("*" * i) for i in range(1, n+1): li = [ ] # print("INCREMENTED FOR LOOP") for j in range(1, i+1): li.append(j) #print("\n DECREMENTED FOR L...
f5539c9aaf45b31bfdf3011babe21e3094afeed2
ansariimran/small-python-programs
/DectoBin.py
190
4.03125
4
num = int(input("Enter any number: ")) def DecimalToBinary(num): if num > 1: DecimalToBinary(num // 2) a = (num % 2) print(type(a)) DecimalToBinary(num)
c37828fc2bf2d50806ef74d2de08fc7104b6f7a9
atarancon/HarrTrainingHandGesture
/enumarate.py
164
4.03125
4
presidents = ["WAshington","ADAMS","Jefferson","Madison","Adams","Monroe"] for num, name in enumerate(presidents): print("President { }:{ }".format(num,name))
f088180c7364cb15e6e47522b6a9d31637b71474
LJZSR/basic-py3
/panic2.py
211
3.546875
4
phrase="Don't panic!" plist=list(phrase) print(phrase) print(plist) new_phrase=''.join(plist[1:3]) new_phrase=new_phrase+''.join(plist[5])+''.join(plist[4])+''.join(plist[7:5:-1]) print(plist) print(new_phrase)
38e720be01409c48a5e84c07f1acfc070bfb9161
Lynn-Lau/Algorithm-Toolbox
/2nd week/01_Codes/lcm/least_common_multiple.py
280
3.828125
4
#Uses python2 def GCD(a, b): while b != 0: c = a%b a = b b = c return a def LCM(a, b): Least_Common_Multipule = a*b/GCD(a,b) return Least_Common_Multipule Nums = raw_input('').split() gcd = GCD(int(max(Nums)), int(min(Nums))) print LCM(int(max(Nums)), int(min(Nums)))
5493eddc6e37f078d9ec50b0ded6d3efaf5e0847
Lynn-Lau/Algorithm-Toolbox
/2nd week/01_Codes/fibonacci_last_digit/fibonacci_last_digit .py
893
4.40625
4
#Uses python2 """ A Simple Program for Coursera Algorithmic Toolbox & The Last Digit of a Large Fibonacci Number & Given an integer n, find the last digit of the nth Fibonacci number Fn. Author: Lynn Lau Date: 2016/07/27 """ ''' Naive Algorithm ''' def Calc_Fib_Lst(n): FibList = [0, 1] #print FibList if n == ...
926a267e4ecb8bc09122746a442be1629a561922
AnaCarolina86/Python-Exercises
/sublist.py
205
3.78125
4
def check_lists(first_list, second_list): if first_list == second_list: print("EQUAL") else: value = second_list.find(first_list) if value > 0: print("SUBLIST")
16602785563cb7d142bf4e29af73fe24dfd1bf05
rmotadutra/PFG_2020
/codes/defs.py
20,012
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import matplotlib.pyplot as plt def read_litho_types(path): """Reads the contents of a CSV file. Parameters ---------- path : string The path of the file to read. Returns ------- dict A dictionary contain...
15e168e24814d8799510823ae1fb942cea256c51
yangliunk1987/LearningLeetcode
/215.Kth_Largest_Element_in_an_Array/Solution.py
1,123
3.640625
4
from random import randint class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: # 改进的快排 def quick_sort(left, right, nums): l, r = left, right index = randint(l, r) nums[l], nums[index] = nums[index], nums[l] while l < r: ...
3afeb4fc37cd295be6d1cef342a8b3f58529e274
yangliunk1987/LearningLeetcode
/105.Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/Solution.py
913
3.8125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): n = len(inorder) inOrderMap = {inorder[i]: i for i in range(n)} r...
b9fa189ee18f52daa1b44478567683773ce1b9ec
ndrsn0208/Snake-Ai
/snake.py
1,495
3.546875
4
import pygame class snake(): def __init__(self,screen,color,position,direction,cube_size): self.__myscreen = screen self.__mycolor = color self.__myposition = position self.__mydirection = direction self.__turns = [] self.__cube_size = cube_size def drawSn...
b17aefee8bcb6dae03f1820d310e22788923fb0c
kailIII/Drogueria
/consultas.py
11,499
3.515625
4
#encoding: utf-8 import csv import sys import math from operator import itemgetter def obtener_indice(headers, nombre_indice): """ funcion de obtener indice para evitar tener que hacerlo cada vez que se necesita saber un header especifico, recibe lista a iterear y nombre buscado, devuelve numero de posici...
bd32ee4f524983eb4d4ae05e81c68daf4182c7fd
aleksanderhan/Exercises-from-NTNU
/TDT4120/07/mergesort.py
871
3.703125
4
from sys import stdin def main(): # Making datastructures decks = [] letters = {} for line in stdin: temp = line.split(':') deck = map(int, temp[1].strip().split(',')) decks.append(deck) for number in deck: letters[number] = temp[0] # Merg sorting decks in decks list while len(decks) > 1: a = deck...
1f92f9926bb96baf98b36bb63d986cad187ff6ff
aleksanderhan/Exercises-from-NTNU
/TDT4136/assignment4/simulated_anneling.py
5,029
3.546875
4
import random from copy import copy from math import exp class Simulated_annealing_solver(object): def __init__(self, T_max = 100000, dT = 1, n = 10): self.n = n # number of neighbors created self.T_max = T_max self.dT = dT random.seed() #initializes the rng with a new seed def set_problem(self, problem):...
1f2e7f5b30d3fef77dfe85772e0db15eb91877b8
narimetisaigopi/learnpythonin30days_telugu
/python youtube code/15_break_continue.py
196
3.984375
4
# for x in range(0,10): # if(x == 5): # print("*************** 5 is triggred") # break # print(x) for x in range(0,10): if(x == 5): continue print(x)
7d8df1e20aff05ba504700d9435e577fe5a0800e
annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan
/homework_1/arithmetic_progression.py
308
3.75
4
first_num = int(input("enter a first number of progression: ")) second_num = int(input("enter a second number of progression: ")) N = int(input("enter an index of number: ")) diff = second_num - first_num N_est_num = first_num + (N - 1) * diff print("The N-est number of progression is: " + str(N_est_num))
7e24870e885624f70f0532f545823d73e3a16a1a
annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan
/Lecture_6/insertion_sort.py
345
4.15625
4
def insertion_sort(num): for i in range(1, len(num)): value_to_insert = num[i] j = i - 1 while j >= 0 and value_to_insert < num[j]: num[j + 1], num[j] = num[j], num[j + 1] j -= 1 numbers = [int(elem) for elem in input("enter the numbers: ").split()] insertion_sort(n...