blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6a800a7bff8e3b8062e205a46f8d6c00e37021ca
Jatzek3/Python-Morsels
/deep_add/digits.py
496
4.1875
4
""" 3. We can determine how many digits a positive integer has by repeatedly dividing by 10 (without keeping the remainder) until the number is less than 10, consisting of only 1 digit. We add 1 to this value for each time we divided by 10. Here is the recursive algorithm: 1. If n < 10 return 1.2. Otherwise, return 1 + the number of digits in n/10 (ignoring the fractional part).""" def digits(number): if number < 10: return 1 else: return 1 + digits(number // 10)
true
aa78a36e42596e8caa6ad92d558c21e98d6bbd06
boubakerali69/python_exemples_ali
/python-basics-master/functions.py
804
4.28125
4
''' examples of built in function len() input() lower() upper() islower() - How to write function def function_name(): code - how to call function function_name() - type of functions a- does not return value ( display text) b- return value ( calculate tmeperatre or curreny) ''' # simple function with no parameters def hello(): print('hello') print('welcome to my program') hello() # function with parameters def hello2(name): print(f'hello {name}') print('how are you today') hello2('ali') # a - sum two number a = 10 b = 20 def total(num1, num2): return num1 + num2 print(total(a, b)) print(total(20, 40)) # convert temp from f to c # c = (F − 32) × 5/9 def convert_f_to_c(f): c = (f - 32) * 5/9 return round(c, 4) print(convert_f_to_c(70))
true
9cee3af98e2bf363253504002420a15882ae8613
boubakerali69/python_exemples_ali
/python-basics-master/challenge1.py
778
4.28125
4
''' hint : - import random - to get random number use random.randnint(a,b) - to get user input use input() funciton - use for loop with range(0,5) - use break ''' import random def guessGame(): secretNum = random.randint(1, 20) print('I have secret number(1-20) , can you guess ?') for guessNum in range(0, 5): print('what is the number ?') guess = int(input()) if guess < secretNum: print('your number is smaller than my number') elif guess > secretNum: print('your number is larger than my number') else: break if guess == secretNum: print(f'your number is correct- mine was {secretNum}') else: print(f'Please try again- mine was {secretNum}') guessGame()
true
465e939190d863f3c416bdb408a6c384a736a287
zsm55555/LearningPython
/Dev330x_Introduction_to_Python_Unit_3/adder.py
1,073
4.4375
4
# [ ] Write a program that reads an unspecified number of integers from the command line, # then prints out the sum of all the numbers # the program should also have an optional argument to show the product of the numbers (in addition to the sum) # help message should look like: ''' usage: adder.py [-h] [-p] [numbers [numbers ...]] positional arguments: numbers numbers to be added (or multiplied) optional arguments: -h, --help show this help message and exit -p, --product show the product of the numbers (in addition to the displayed sum) ''' import argparse parser=argparse.ArgumentParser() parser.add_argument('numbers',action='store',nargs = "*",type=int,help='numbers to be added (or multiplied)') parser.add_argument('-p','--product',action='store_true',help='show the product of the numbers (in addition to the displayed sum)') args=parser.parse_args() sum=0 for i in args.numbers: sum+=i print("The sum of all the numbers is:",sum) if args.product: print("The product of the numbers:",args.numbers)
true
74ffbd80647216ce397bc55b02cd21f3dc831d17
SampathGanesh01/internship-task-e-bibil
/internship_task.py
1,752
4.15625
4
#INTERNSHIP TASK #Name : Sampath Ganesh Kandregula #TASK 1 IN PYTHON """1. Write a Python program which asks the user to enter a number 'n' and then iterates the integers from 1 to 'n'. For multiples of three print "3n" instead of the number and for the multiples of five print "5n". For numbers which are multiples of both three and five print "your-name". """ n = int(input("please enter a number"))#input function for i in range(1,n): if i % 3 == 0 and i % 5 == 0:#if divisible by both 3 and 5 print("your-name") continue elif i % 3 == 0:#if divisible by 3 print(3*n) continue elif i % 5 == 0:#if divisible by 5 print(5*n) continue print(i)# if not divisible by both 3 and 5 print the integer #TASK 2 IN PYTHON """2. Hitting a GET request to the following URL endpoint https://jsonplaceholder.typicode.com/todos/1 gives { "userId": 1, "id": 1, "title": "aut consectetur in blanditiis deserunt quia sed laboriosam", "completed": true } as the response, If we just change the userId parameter(todos/1 or todos/2) in the URL endpoint and hit the GET request again at https://jsonplaceholder.typicode.com/todos/2 we recieve a different response with the same structure having userId, id, title and completed key value pairs. Now write a Python program to send GET requests 5 times for 5 different userIds(1,2,3,4&5) and append the title from response to a common list. Finally print the list. """ import requests for i in (1,2,3,4,5):#looping over id's url = 'https://jsonplaceholder.typicode.com/todos/' + str(i) # conacetnating the link and the number r = requests.get(url) answers = r.text common_list = [] common_list.append(answers) print(common_list)
true
eb3829623d106e973979263b05c303006f1a663a
CCallahanIV/data-structures
/src/stack.py
804
4.25
4
"""This module defines the Stack data structure.""" from linked_list import Linked_List class Stack(object): """The stack data structure is a composition of the Linked List structure.""" def __init__(self, iterable=None): """Initialize stack as a Linked_List-esque object.""" self._container = Linked_List(iterable) def push(self, val): """Use Linked List push method to add one Node to stack.""" self._container.push(val) def pop(self): """Use Linked List pop() method to remove one from stack.""" return self._container.pop() def peek(self): """Peek the top of the stack.""" return self._container.head def __len__(self): """Return number of items in Stack.""" return self._container.size()
true
23e1799fbf0eae42f8df33ffcb1ab73b3f27ac57
michaelgadda/pytest_cov
/leap_year.py
660
4.1875
4
#in order to run this file use either: #python michael_gadda_hw1.py #or #python3 michael_gadda_hw1.py #And when prompted please enter a valid year ( x > 0) def leap_year_test(year): try: int(year) except(ValueError): return False if year <= 0: print("Let's try again... Enter a number greater than 0") return False else: if year % 4 == 0: if year % 100 != 0: print(f"{year} is a leap year") return True else: if year % 400 == 0: print(f"{year} is a leap year") return True else: print(f"{year} is not a leap year") return False else: print(f"{year} is not a leap year") return False
false
014249f982511b1bb564861cef48e44f380a2d01
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao7/M_C-Ordered_Dict.py
885
4.21875
4
""" O Ordered Dict é um dicionário comum, só q ele possui algo a mais, o mesmo dá a certeza q os dados inseridos no dicionário estarão ordenados por inserção. dicionario = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(dicionario) for c, v in dicionario.items(): print(f'Chave: {c} | Valor: {v}') """ from collections import OrderedDict dicionario = OrderedDict({'A': 1, 'B': 2, 'C': 3, 'D': 4}) # Certeza da ordenação por inserção for c, v in dicionario.items(): print(f'CHAVE: {c} | VALOR: {v}') d1 = {'a': 1, 'b': 2} d2 = {'b': 2, 'a': 1} print(d1 == d2) # Vai dizer q os dois dicionários são iguais, mesmo estando em ordem diferente # Usando o OrderedDict od1 = OrderedDict({'a': 1, 'b': 2}) od2 = OrderedDict({'b': 2, 'a': 1}) print(od1 == od2) # Agora com o OrderedDict dirá q os 2 dicionários n são iguais (a ordem dos elementos importa pro dicionário)
false
6c9a5ef99419b7cb605420cf89a60a72b63aad7a
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao12/xii_modulo_random.py
1,762
4.28125
4
""" O que são módulos? Em Phyton, módulos nada mais são do q outros arquivos Python. Módulo random -> Possui várias funções para geração de números pseudo-aleatórios (que podem se repetir). # OBS: Existem 2 formas de se utilizar módulo ou função: # Forma 1 - Importar todo o módulo de uma vez (N RECOMENDADO). import random # A função random() é uma das funções do random, ela gera um número real aleatório entre 0 e 1 (o 1 não é incluido mas o 0 sim - >= 0 < 1. # random() # Desta forma todas os atributos do módulo random entrarão na memória, deixando o programa mais pesado, se você saber # qual funções irá utilizar, essa forma n é recomendada. print(random.random()) # Note q é necessário botar o nome do método e depois da função separando por ponto (.) # OBS: A função random() é apenas uma das várias funções q estão dentro do pacote random. Não confunda! # Forma 2 - Importar apenas a função necessária (RECOMENDADO) from random import random # Do módulo random importe a função random() for i in range(5): print(f'{random():.2f}') # Note q agora n é mais necessário botar o nome do pacote, agora basta colocar o nome direto da função importada. # Usando a função uniform() - > Gera um número real pseudo-aleatório com valores estabelecidos from random import uniform for i in range(5): print(uniform(0, 11)) # valores de 0 à 10 # Função randint -> gera número inteiro pseudo-aleatório de valores estabelecidos from random import randint for i in range(5): print(randint(0, 11)) """ # choice -> Gera um valor ateatório dentro de um interável jogada = ['papel', 'pedra', 'tesoura'] from random import choice print(choice(jogada)) print(choice('Pedro Henrique Castoldi Bezerra'))
false
7485ff98b6fbc25135df4d599bc6af1f252fdb02
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao7/Tuplas.py
2,980
4.75
5
""" Tuplas são bastante parecidas com listas Elas possuem 2 diferenças básicas: 1- As tuplas são representadas por parenteses '()' 2- Elas são imutáveis, ou seja, depois de criada ela n muda. Toda operação em uma tupla gera uma nova tupla. #CUIDADO 1: Tuplas são representadas por '()' tupla1 = (2, 6, 3, 0) print(tupla1) print(type(tupla1)) tupla2 = 4, 2, 6, 77 print(tupla2) print(type(tupla2)) #CUIDADO 2: Tuplas com 1 elemento n são reconhecidas como tuplas. É reconhecido como um int (por exemplo) tupla3 = (3) print(tupla3) print(type(tupla3)) # Para ser reconhecida como tuple é necessário colocar uma vírgula dentro dos parenteses tupla4 = (5,) print(tupla4) print(type(tupla4)) tupla5 = 4, print(tupla5) print(type(tupla5)) # CONCLUSÃO: Tuplas são definidas pela vírgula! (4) -> N é tupla (4,) -> É tupla 4 -> É tupla # Tupla com range tupla = tuple(range(11)) print(tupla) print(type(tupla)) # Desempacotamento tuplan = ('Pedro', 'Henrique') print(tuplan) print(type(tuplan)) primeiron, segundon = tuplan print(primeiron) print(segundon) print(type(primeiron)) # Adição e remoção de elementos em tuplas n existem, dado q elas são imutáveis # Valor: maior, menor, soma e tamanho em tuplas tupla = (66, 8, 3, 2, 11, 34, 6) print(max(tupla)) print(min(tupla)) print(sum(tupla)) print(len(tupla)) # Concatenação de tuplas tupla1 = (5, 3, 8) tupla2 = (99, 33, 22) print(tupla1) print(tupla2) print(tupla1 + tupla2) # Imprimiu as 2 juntas print(tupla1) print(tupla2) tupla1 = tupla1 + tupla2 # N é exatamente modificar, mas sim, sobrescrever print(tupla1) # Verificar se determinado elemento está na tupla tupla = (55, 'i', 7, 44, 12) print(12 in tupla) # Interando sobre uma tupla tupla = (55, 'i', 7, 44, 12) for n in tupla: print(n, end= ' ') print('\n') for tupla in enumerate(tupla): print(tupla) # Contando elementos dentro de uma tupla tupla = (5, 3, 2, 5, 3, 'y') print(tupla.count(5)) # Convertendo de string para tupla convertt = tuple("Juninho é um cachorro") print(convertt) # Dica de quando utilizar tuplas: # SEMPRE quando n for necessário modificar uma coleção de elementos # EX 1: meses = ('janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro') print(meses) # Acesso a uma casa print(meses[8]) # Interar com while i = 0 while i < len(meses): print(meses[i]) i += 1 # Verificar em qual indice o elemento está na tupla print(meses.index('Setembro')) # Slicing # Tupla(inicio:fim:passo) print(meses[0:9]) # Copiando uma tupla tupla = (1, 2, 3, 4) nova = tupla # Com tupla n existe o problemade Shallow Copy print(tupla) print(nova) outra = (5, 6, 7) nova = nova + outra print(nova) print(tupla) # POR QUE USAR TUPLAS? # 1 - Tuplas são mais rápidas q listas; # 2 - Tuplas deixam seu código mais seguro. # * Isso pelo fato de se estar trabalhando com elementos inutáveis! """
false
b2a7914bb945c65b75a3c35cc65ef5734eaaf052
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao11/11_try_except_else_finally.py
2,037
4.34375
4
""" Dica de quando e onde tratar o código: TODA ENTRADA DEVE SER TRATADA!!! OBS: A função do usuário é destruir o sistema. # else - É executado somente quando o erro não ocorrer. n = 0 # com o else não dará o NameError, atribuir um valor à n no começo se tornou optativo. try: n = int(input('Digite um número inteiro: ')) except ValueError: print('Valor errado') else: print(f'Você digitou {n}') # Essa mensagem só será exibida se não ocorrer o erro. # Finally - SEMPRE é executado, tendo erro ou não. try: n = int(input('Digite um número inteiro: ')) except ValueError: print('Erro no valor inserido.') else: print(f'Você digitou o número {n}.') finally: print('Processo encerrado.') # OBS: O finally é utilizado geralmente para fechar ou desalocar recursos # EX mais complexo (ERRADO) def multi(a, b): return f'RESULTADO: {a * b}' try: na = int(input('Digite o primeiro número: ')) except ValueError: print('Erro no valor.') try: nb = int(input('Digite o segundo número: ')) except ValueError: print('Erro no valor.') else: print(multi(na, nb)) # EX mais complexo (CORRETO): # O programador é responsável pelas entradas da sua função, então o mesmo deve trata-las. def divisao(a, b): try: # Tratando erro dentro da função return f'{int(a) / int(b):.2f}' # Convertendo do string para int except ValueError: return 'Valor inserido inválido.' except ZeroDivisionError: return 'Não é possível dividir um número por zero.' na = input('Digite um número: ') # Note q as entradas fora da função não tem um tipo definido. Isso é definido dentro da função. nb = input('Digite um número: ') print(divisao(na, nb)) """ # EX complexo de forma SEMI-GENERICA def divisao(a, b): try: return f'{int(a) / int(b) :.2f}' except (ValueError, ZeroDivisionError): return 'Ocorreu um erro.' na = input('Digite um número: ') nb = input('Digite um número: ') print(divisao(na, nb))
false
153dc578231109388ab7ebbbdea11db6f184f65d
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao17/heranca_multipla.py
2,653
4.625
5
""" POO - Herança Múltipla É a possibilidade de uma classe herdar de múltiplas classes. Desse modo, a classe filha herda todos os atributos e métodos das super classes. OBS: A Herança Múltipla pode ser feita de duas maneiras: - Multiderivação Direta; - Multiderivação Indireta. # Exemplo de Multiderivação Direta class Base1(): pass class Base2(): pass class Base3(): pass class Multipladerivacao(Base1, Base2, Base3): # Note q a herança é dada diretamente na classe Multipladerivacao pass # Exemplo de Multipladerivação Indireta class Base1(): pass class Base2(Base1): pass class Base3(Base2): pass class Multipladerivacao(Base3): # Note q a classe Multipladerivacao herda de modo indiretamente as classe Base2 e Base 1 pass # OBS: N importa se a classe herdar diretamente ou n outra classe, a mesma herdará todos os atributos e métodos das super classes. """ # EX de Herança Múltipla class Animal: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome def cumprimentar(self): return f'Olá. Meu nome é {self.nome}.' class Terrestre(Animal): def __init__(self, nome): super().__init__(nome) def cumprimentar(self): return f'Olá. Meu nome é {self.nome} da Terra.' def andar(self): return f'{self.nome} está andando.' class Aquatico(Animal): def __init__(self, nome): super().__init__(nome) def cumprimentar(self): return f'Olá. Meu nome é {self.nome} do mar.' def nadar(self): return f'{self.nome} está nadando.' class TerestreAquatico(Aquatico, Terrestre): # Retornará: "Olá. Meu nome é pinguim do mar.". Isso pq a classe Aquatico foi chamada antes da Terrestre. def __init__(self, nome): super().__init__(nome) tatu = Terrestre('Tatu') print(tatu.cumprimentar()) print(tatu.andar()) print() tubarao = Aquatico('Tubarão') print(tubarao.cumprimentar()) print(tubarao.nadar()) print() pinguim = TerestreAquatico('Pinguim') print(pinguim.cumprimentar()) # Aparece pinguim do mar e não pinguim da terra. Isso pq a primeira classe está primeiro à esquerda na chamada de herança. print(pinguim.andar()) print(pinguim.nadar()) print() # Saber se um objeto é uma instância de uma classe print(f'Pinguim é instância de Terrestre? : {isinstance(pinguim, Terrestre)}') # True print(f'Tatu é instância de Aquatico? : {isinstance(tatu, Aquatico)}') # False print(f'Tubarão é instância de objeto? : {isinstance(tubarao, object)}') # True (todos as classes são instâncias de object).
false
cf07b61e1e35b87a89e127a574a977a426c927c5
Shauqi/Modelling_And_Simulation
/Lab_1_Estimation_of_pi_using_Monte_Carlo/Monte_Carlo.py
2,103
4.25
4
import random import numpy as np import matplotlib.pyplot as plt ### This link:"http://mathfaculty.fullerton.edu/mathews/n2003/montecarlopimod.html" describes ### the theorem behind pi estimation Using Monte Carlo ### In Monte Carlo Simulation we are going to simulate pi value from probability theorem. We are considering a ### circular field which is surrounded by a rectangle. First of all we are going to simulate Raindrops from uniform ### distribution. The default Random.Random() function returns values which are uniformly distributed. After getting ### the co-ordinates of raindrops we are going to calculate if the raindrop is faliing inside the circle or outside. ### After getting the numbers of raindrops inside and outside the circle we can estimate value of Pi.. num_of_raindrops = 10000 batch = 100 # At a time 100 drops can fall. So batch represent number of raindrops at t. outer_loop = int(num_of_raindrops / batch) in_circle_x = [] out_circle_x = [] in_circle_y = [] out_circle_y = [] circle = plt.Circle((0, 0), radius=0.5, color='BLACK', fill=False) # Drawing the circle field which has radius .5 ax = plt.gca() ax.add_artist(circle) for j in range(outer_loop): for i in range(batch): x = .5 - random.random() # Generating X co-ordinate of raindrop y = .5 - random.random() # Generating Y co-ordinate of raindrop if x**2 + y**2 <= .25: # Checking if the raindrop is falling inside the circle in_circle_x.append(x) in_circle_y.append(y) else: out_circle_x.append(x) out_circle_y.append(y) plt.figure(1) # plot1 simulates raindrops plt.scatter(in_circle_x,in_circle_y,c='b') plt.scatter(out_circle_x,out_circle_y,c='r') plt.pause(.0001) pi = 4 * (len(in_circle_x)/ (len(in_circle_x) + len(out_circle_x)) ) plt.figure(2) # plot2 shows the estimation of Pi with respect to time plt.hlines(np.pi,0,outer_loop) # For showing real value of Pi plt.scatter(j,pi) plt.title("%s" %(pi)) plt.ylim(3.01,3.99) plt.pause(.0001) plt.show()
true
be53a38482408a009bab29a2e4b6cb995cac7732
imradhetiwari/python
/ternary.py
656
4.125
4
# a, b = 10, 20 min = a if a < b else b print(min) # a, b = 10, 20 print((b, a)[a < b]) print({True: a, False: b}[a < b]) print((lambda: b, lambda: a)[a < b]()) # a, b = 10, 20 print("Both a and b are equal" if a == b else "a is greater than b" if a > b else "b is greater than a ") #nested ternary operator a, b = 10, 20 if a != b: if a > b: print("a is greater than b") else: print("b is greater than a") else: print("Both a and b are equal") #conditional operator a, b = 10, 20 min = a < b and a or b print(min) #division operator print(5 / 2) print(-5 / 2) print(5 // 2) print(-5 // 2) print(5.0 // 2) print(-5.0 // 2)
false
29b4b01e0291b0a0b86a7604979a5a628ce6b90a
1802343117/Python-Learn
/Python Basic grammar/Exercise80.py
876
4.1875
4
""" 多线程1 """ import threading import time # 创建一个多线程 my_thread = threading.Thread() # 创建一个名称为 my_thread 的线程 my_thread = threading.Thread(name="my_thread") def print_i(i): print('打印i:%d' % (i,)) # 通过参数target传入,参数类型为callable my_thread = threading.Thread(target=print_i, args=(1,)) # 启动线程 my_thread.start() def print_time(): # 在每个线程中打印 5 次 for _ in range(5): # 模拟打印前的相关处理逻辑耗时 time.sleep(0.1) print('当前线程%s,打印结束时间为:%s' % (threading.current_thread().getName(), time.time())) # 开辟3个线程,装载到 threads 中 threads = [threading.Thread(name='t%d' % (i,), target=print_time) for i in range(3)] # 启动三个线程 [t.start() for t in threads]
false
fcdf3bf1a6dc8d46f0764cc60517b726cc331274
HaziqyWqjiq/MyProjectPython
/Programme Result/Dice(OnlyText)3.py
593
4.3125
4
import random import time # Global variable roll_again = "yes" while roll_again == "yes" or roll_again == "y": print("Rolling the dice...") # make a delay of 1 second time.sleep(1) # create a random number b/w 1 to 6 dice = random.randint(1, 6) # print the number print("Dice: ", dice) # ask the user to roll_again or not roll_again = input("Do you want to roll again? (yes/y)") # if the user entered "yes" or "y", the loop continues # else, if the user entered anything besides "yes" or "y", the loop breaks and game ends print("You ended the game!")
true
5e42994c166da68af0f49b03a0e2f9237b69ef77
JseveN14/CSC201_program04
/Project 2.py
1,165
4.125
4
#Lab 4 - Project 2 Evaluate Simple Expressions def evaluateSimpleExpression(string):#function to calculate expression if string.find("+") > -1:#if + is found first_number = int(string[0:string.find("+")]) second_number = int(string[string.find("+")+1: ]) total = first_number + second_number#add numbers if string.find("-") > -1:#if - is found first_number = int(string[0:string.find("-")]) second_number = int(string[string.find("-")+1: ]) total = first_number - second_number#subtract numbers if string.find("*") > -1:#if * is found first_number = int(string[0:string.find("*")]) second_number = int(string[string.find("*")+1: ]) total = first_number * second_number#multiply numbers if string.find("/") > -1:#if / is found first_number = int(string[0:string.find("/")]) second_number = int(string[string.find("/")+1: ]) if second_number == 0: return "Divide by Zero error"#n/0 is undefined else: total = first_number / second_number#otherwise, divide numbers return total#integer value
true
951ce46630fefacc25708d392601c127e5f215bc
pseudonative/ultrapython3
/pythonBootCamp/v3.py
1,541
4.21875
4
from random import randint player_wins=0 computer_wins=0 winning_score=4 while player_wins< winning_score and computer_wins<winning_score: # for time in range(3): print(f"Player Score: {player_wins} Computer Score: {computer_wins}") print("Rock...") print("Paper...") print("Scissors...") player=input("Player, make your move: ").lower() if player=="quit" or player=="q": break rand_num=randint(0,2) if rand_num==0: computer="rock" elif rand_num==1: computer="paper" else: computer="scissors" print(f"computer plays {computer}") if player==computer: print("it's a tie") elif player=="rock": if computer=="scissors": print("player wins") player_wins+=1 else: print("computer wins") computer_wins+=1 elif player=="paper": if computer=="rock": print("player wins") player_wins+=1 else: print("computer wins") computer_wins+=1 elif player=="scissors": if computer=="rock": print("computer wins") computer_wins+=1 else: print("player wins") player_wins+=1 else: print("Please enter a valid move") if player_wins>computer_wins: print("Congrats,you won!") elif player_wins==computer_wins: print("Forfit") else: print("Oh no :( The computer won") # print(f"Final Scores: Player... {player_wins} Computer... {computer_wins}")
true
077ad7e6d229c605fff056ef2d26b9872623c12f
Maninder-mike/100DaysWithPython
/basic/if_elif_else.py
1,336
4.4375
4
# Basic style of if...else if not True: print("it's not True!") else: print("it's True!") # ------------------------------------------------------------------ x = False if x: print('x is True.') else: print('x is False.') # ------------------------------------------------------------------ location = 'bank' if location == 'shop': print('you are in shop now.') elif location == 'bank': print(f'you are in {location} now') elif location == 'airport': print('at the airport') else: print('not desination set yet on list.') # ------------------------------------------------------------------ x = 25 y = 35 z = 25 if x < y: print('x is less than y') else: print('x is greater than y') # ------------------------------------------------------------------ # Short hand if..else print("X") if x < y else print("Y") print('X') if x > y else print('=') if x == y else print('Y') # ------------------------------------------------------------------ # And, Or if y > x and z < y: print('Both are true') if y > x or z > y: print('one statement is true.') if x > 10: print('Above Ten.') if x > 20: print('also above 20') else: print('not above 20') # ------------------------------------------------------------------ # pass statement if y > x: pass
true
f05852287bc22b6f9ee3617ac826f26eed7a52d1
JennyBethCornell/DnaScripts
/check_dna.py
325
4.40625
4
#!/usr/bin/env python3 """ This script checks whether a DNA sequence has any undefined bases ('n' or 'N'). """ dna = input('Enter DNA sequence:') if 'n' in dna or 'N' in dna: nbases=dna.count('n')+dna.count('N') print("dna sequence has %d undefined bases " % nbases) else: print("dna sequence has no undefined bases")
true
5d19159a82986fb1342cae0c802eb31b4c4201b9
iqzar/Word_doc-Assignments-
/Task34.py
425
4.125
4
#Input a text and count the occurrences of vowels and consonant: text=input("Write your text here: ") vowels =0 consonants =0 for i in text: if (i=='a' or i=='o' or i=='e' or i=='u' or i=='i' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U') : vowels=vowels+1 else: consonants=consonants+1 print("Vowels in sentence is: ",vowels) print("Consonants in sentence is:",consonants)
false
108d1f762beb643e41428da5f2ecaade2a97e1a9
iqzar/Word_doc-Assignments-
/Task40.py
472
4.125
4
#Write a Python program that accepts a string and calculate the number of digits and letters Sample Data : Python 3.2, Expected Output : Letters 6, Digits 2: data=str(input("Enter your data here: ")) digits=0 letters=0 for i in data: if i=='0' or i=='1' or i=='2' or i=='3' or i=='4' or i=='5' or i=='6' or i=='7' or i=='8' or i=='9': digits=digits+1 else: letters=letters+1 print("Digits:", digits) print("Letters:",letters)
true
9321195077da8f7e1807b4f2ed9f854c04f4cd7b
domnicmel/python-LR
/Dist and dir.py
1,396
4.28125
4
from math import * print("Program to calculate distance and direction between positions A and B") print() print("Enter coordinates of position A:") lata = radians(float(input("Give latitude in degrees (North is positive):"))) longa = radians(float(input("Give longitude in degrees (East is positive):"))) print() print("Enter coordinates of position B:") latb = radians(float(input("Give latitude in degrees (North is positive):"))) longb = radians(float(input("Give longitude in degrees (East is positive):"))) R = 6371. #distance dist = R*acos(cos(lata)*cos(latb)*cos(longb -longa) + sin(lata)*sin(latb)) #direction A to B - eastbound A to B = alpha - westbound A to B = 360 -alpha alpha = acos(cos(lata)*sin(latb) - sin(lata)*cos(latb)*cos(longb - longa)) #direction B to A alphb = acos(cos(latb)*sin(lata) - sin(latb)*cos(lata)*cos(longa - longb)) print() print ("Distance is {:.2f} km".format(dist)) if ((longb-longa)> 0): #eastbound A to B AND westbound B to A print ("Direction from A to B = {:.2f} degrees.".format(degrees(alpha))) print ("Direction from B to A = {:.2f} degrees.".format((360-degrees(alphb)))) else: #westbound A to B AND eastbound B to A print ("Direction from A to B = {:.2f} degrees.".format((360-degrees(alpha)))) print ("Direction from B to A = {:.2f} degrees.".format(degrees(alphb)))
false
257173957405ad088ed339b837574df633f20848
sgupta304/data-structures-and-algorithms
/tests/test_challenges/test_array_reverse.py
886
4.1875
4
from data_structures_and_algorithms.challenges.day_1.array_reverse import reverse_list def test_int_array(): arr = [1, 3, 4, 5, 6, 8] actual = reverse_list(arr) expected = [8, 6, 5, 4, 3, 1] assert actual == expected def test_int_array_negative(): arr = [89, 2354, 3546, 23, 10, -923, 823, -12] actual = reverse_list(arr) expected = [-12, 823, -923, 10, 23, 3546, 2354, 89] assert actual == expected def test_int_array_empty(): arr = [] actual = reverse_list(arr) expected = [] assert actual == expected def test_int_array_single_element(): arr = [1] actual = reverse_list(arr) expected = [1] assert actual == expected def test_int_array_text(): arr = ["One", "Two", "Three", "Four", "Five"] actual = reverse_list(arr) expected = ["Five", "Four", "Three", "Two", "One"] assert actual == expected
false
bb0b463b50ff99ea37e6a3d0ecfb0c240b0e8675
cnicogd/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/6-print_comb3.py
265
4.1875
4
#!/usr/bin/python3 for number in range(0, 100): decimal = number / 10 unit = number % 10 if decimal < unit and decimal != unit and number != 89: print("{:02d}, ".format(number), end='') if number == 89: print("{}".format(number))
false
a8e15ce150b1177f6b3ab69a288862d3fb9bd0cb
ibarkay/codewars
/first-word-simplified.py
448
4.28125
4
# coding=utf-8 ''' You are given a string where you have to find its first word. This is a simplified version of the First Word mission. Input string consists of only english letters and spaces. There aren’t any spaces at the beginning and the end of the string. Input: A string. Output: A string. Precondition: Text can contain a-z, A-Z and spaces ''' def first_word(txt): txt = txt.split() return txt[0] first_word("Hello world")
true
78b8032f056d4c53a4d72827c60833c6a5fb95b8
rafaelm229/PythonCrashCourse
/Basics/13.TryYourself.py
2,005
5.0625
5
""" 3-8. Seeing the World: Think of at least five places in the world you’d like to visit. • Store the locations in a list. Make sure the list is not in alphabetical order. • Print your list in its original order. Don’t worry about printing the list neatly, just print it as a raw Python list. • Use sorted() to print your list in alphabetical order without modifying the actual list. • Show that your list is still in its original order by printing it. • Use sorted() to print your list in reverse alphabetical order without chang- ing the order of the original list. • Show that your list is still in its original order by printing it again. • Use reverse() to change the order of your list. Print the list to show that its order has changed. • Use reverse() to change the order of your list again. Print the list to show it’s back to its original order. • Use sort() to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed. • Use sort() to change your list so it’s stored in reverse alphabetical order. Print the list to show that its order has changed. 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use len() to print a message indicating the number of people you are inviting to dinner. 3-10. Every Function: Think of something you could store in a list. For example, you could make a list of mountains, rivers, countries, cities, languages, or any- thing else you’d like. Write a program that creates a list containing these items and then uses each function introduced in this chapter at least once. """ # 3-8. Seeing the World: print("3-8. Seeing the World:\n") #lista places = ['Toronto', 'New York', 'Dubai', 'Tel Aviv', 'Berlin'] print(places) print("\n Sorted") print("\n", sorted(places)) print("\n Original") print(places) print("\nReverse Ordered") places.sort(reverse = True) print(places) print("\n Original") places.reverse() print(places)
true
c5da8816659b4f5b7b88fbb9d0d44ef110d4dfbd
rafaelm229/PythonCrashCourse
/Basics/10.motorcycles.py
575
4.3125
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) # para adicionar items em uma lista basta usar o metodo append() motorcycles.append('ducati') print(motorcycles) #para remover bastar usar o metodo "del" motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[0] print(motorcycles) # podemos usar o metodo pop() para remover tambem motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) popped_motorcycle = motorcycles.pop() print(motorcycles) print(popped_motorcycle)
false
84892c2de2db5bdb8478b64b562f85b23041c767
hafizpatwary/pytest_testing
/python_exercise/factorial.py
574
4.25
4
def factorial(num): divide = 2 negative = False try: if num < 0: num *= -1 negative = True if num == 1 or num == 0: print(1) elif num > 1 and type(num) is int: while num > 1: num /= divide divide += 1 if num == 1: if negative: divide *= -1 return divide+1 return(divide-1) else: return("none") except TypeError as e: print("none")
false
aea6ac82bf3c5ee9e65ce20c29479ecfc6d0f038
ElenaVasyltseva/Beetroot-Homework
/lesson_ 4/task_4_3.py
673
4.375
4
# Task 3 # Words combination # Create a program that reads an input string and then creates and # prints 5 random strings from characters of the input string. # For example, the program obtained the word ‘hello’, so it should # print 5 random strings(words) that combine characters # ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ … # Tips: Use random module to get random char from string) import random random_word = list(input('Please, enter a word:')) i = 1 while i <= 5: random.shuffle(random_word) shuffled_word = ''.join(random_word) print(str(i) + '. ' + shuffled_word) i += 1
true
1fd633178046ee40df03f373e7fa714f6807a476
ElenaVasyltseva/Beetroot-Homework
/lesson_11/task_2.py
2,345
4.3125
4
# Task 2 # Mathematician # Implement a class Mathematician which is a helper class for doing math operations on lists # The class doesn't take any attributes and only has methods: # square_nums (takes a list of integers and returns the list of squares) # remove_positives (takes a list of integers and returns it without positive numbers # filter_leaps (takes a list of dates (integers) and removes those that are not 'leap years' class Mathematician: def if_list_of_numbers_empty(self, list_of_numbers): """Checking parameter list of numbers, if list is empty - raise ValueError""" if len(list_of_numbers) != 0: return list_of_numbers else: raise ValueError('List of numbers is empty') def square_nums(self, list_of_numbers): """takes a list of integers and returns the list of squares""" self.if_list_of_numbers_empty(list_of_numbers) square_nums_list = [] for i in list_of_numbers: square_nums_list.append(i * i) return square_nums_list def remove_positives(self, list_of_numbers): """takes a list of integers and returns it without positive numbers""" self.if_list_of_numbers_empty(list_of_numbers) remove_positives_list = [] for i in list_of_numbers: if i < 0: remove_positives_list.append(i) return remove_positives_list def filter_leaps(self, list_of_numbers): """takes a list of dates (integers) and removes those that are not 'leap years'""" self.if_list_of_numbers_empty(list_of_numbers) leap_years_list = [] for i in list_of_numbers: if (i % 4 == 0) and (i % 100 != 0) or (i % 400 == 0): leap_years_list.append(i) return leap_years_list m = Mathematician() print(m.square_nums([7, 11, 5, 4])) # [49, 121, 25, 16] # print(m.square_nums([])) # test print(m.remove_positives([26, -11, -8, 13, -90])) # [-11, -8, -90] # print(m.remove_positives([])) # test print(m.filter_leaps([2001, 1884, 1995, 2003, 2020])) # [1884, 2020] # print(m.filter_leaps([])) # test
true
120b0351585460e895b1c0985a784439c1164bd0
ElenaVasyltseva/Beetroot-Homework
/lesson_3/task_3.py
601
4.34375
4
# Task 3 # The name check. # Write a program that has a variable with your name stored (in lowercase) # and then asks for your name as input.The program should check if your input # is equal to the stored name even if the given name has another case, e.g., # if your input is “Anton” and the stored name is “anton”, it should return True. my_name = 'elena' while True: check_name = input('Do you know my name? Please, enter:') if my_name == check_name.lower(): print('It\'s true') break else: print('No, try again!') continue
true
660b72bc36ac1120efea2641503eb8108fa62322
JLevins189/Python
/Labs/Lab4/Lab9Ex9.py
426
4.21875
4
def insert_string_middle(my_str1,add_string): str = "" half = len(my_str1) // 2 for counter in range(0,half): str += my_str1[counter] str+=add_string for counter in range(half,len(my_str1)): str += my_str1[counter] print(str) my_str1 = input("Input a string") add_string = input("Input a string to be added in the middle") insert_string_middle(my_str1,add_string)
true
c22215fed36d96c9203d8831329c0922d9c397a1
JLevins189/Python
/Labs/Lab5/Lab12Ex2.py
939
4.375
4
def safe_input(prompt, type): input_var = '' while True: try: if type == 'int': input_var = input(prompt) int(input_var) return input_var elif type == 'string': input_var = input(prompt) return input_var elif type == 'float': input_var = input(prompt) float(input_var) return input_var else: print("Incorrect type entered! \n") except ValueError or TypeError: if input_var is not type1: print(type, "not detected! Input correct type") input_var = input() else: break type1 = input("Enter the type of input you wish to display\n int float or string\n") prompt1 = input("Enter the prompt to display") output = safe_input(prompt1, type1) print(output)
true
c1bf1c99dac866939621ea3330f587a11fd031b9
JLevins189/Python
/Labs/Lab5/Lab11Ex6.py
1,276
4.375
4
def tuple_sort(tuple1, tuple2, tuple3): new_list = [] if tuple1[1] > tuple2[1]: if tuple1[1] > tuple3[1]: # Tuple1 >Tuple 2+3 new_list.append(tuple1) if tuple2[1] > tuple3[1]: new_list.append(tuple2) new_list.append(tuple3) else: new_list.append(tuple3) new_list.append(tuple2) elif tuple2[1] > tuple3[1]: # Tuple 2>Tuple1+3 new_list.append(tuple2) if tuple1[1] > tuple3[1]: new_list.append(tuple1) new_list.append(tuple3) else: new_list.append(tuple3) new_list.append(tuple1) elif tuple3[1] > tuple1[1]: # Tuple 3>Tuple1+2 new_list.append(tuple3) if tuple1[1] > tuple2[1]: new_list.append(tuple1) new_list.append(tuple2) else: new_list.append(tuple2) new_list.append(tuple1) return new_list t1a = 'item1' t1b = float(input("Enter a float for item1\n")) t2a = 'item2' t2b = float(input("Enter a float for item2\n")) t3a = 'item3' t3b = float(input("Enter a float for item3\n")) tuple1 = (t1a, t1b) tuple2 = (t2a, t2b) tuple3 = (t3a, t3b) answer = tuple_sort(tuple1, tuple2, tuple3) print(answer)
false
80478f6e25e4eb037268be07221a52cef7866925
blackhumdinger/LPTHW
/LPTHW_EXER/e18.py
1,218
4.59375
5
print("EXRECISE 18: NAMES VARIABLES AND FUNCTIONS") print(""" the properties of functions can be listed as follows: 1. they name pieces of code the same way variables name strings and numbers 2. they take arguments the same way we pass argv to the script 3. using #1 and #2 we can generate mini pieces of code or tiny commands """) from sys import argv def print_two(*args): arg1, arg2 = args print ("arg1, %r, arg2, %r" %(arg1, arg2)) def print_two_again(arg1, arg2): print("arg1,%r , arg2, %r" %(arg1, arg2)) #ths takes only one argument def print_one(arg1): print("this is the only argument %r" %arg1) def print_none(): print("nothing!") print_two("zedd", "shawn") print_two_again("nicky","skrillex") print_one("asd") print_none() #define is given by def.. #on the sanme line as def we give the function name the function name can be anything exceot it should give us the correct functionality # *args are lot like argv except they are defined for functions rather than the commandline # the fucntion ends with a colon and after that we get indentation of 4 spaces #to demonstrate how it works we can print these arguments just like in a script
true
b9926d02bf8f727b6dcd2d8a818178b634b23c11
tranphibaochau/LeetCodeProgramming
/Medium/amazon_fresh.py
2,078
4.53125
5
""" Amazon Fresh is running a promotion in which customers receive prizes for purchasing a secret combination of fruits. The combination will change each day, and the team running the promotion wants to use a code list to make it easy to change the combination. The code list contains groups of fruits. Both the order of the groups within the code list and the order of the fruits within the groups matter. However, between the groups of fruits, any number, and type of fruit is allowable. The term "anything" is used to allow for any type of fruit to appear in that location within the group. Consider the following secret code list: [[apple, apple], [banana, anything, banana]] Based on the above secret code list, a customer who made either of the following purchases would win the prize: orange, apple, apple, banana, orange, banana apple, apple, orange, orange, banana, apple, banana, banana Write an algorithm to output 1 if the customer is a winner else output 0. Input The input to the function/method consists of two arguments: codeList, a list of lists of strings representing the order and grouping of specific fruits that must be purchased in order to win the prize for the day. shoppingCart, a list of strings representing the order in which a customer purchases fruit. Output Return an integer 1 if the customer is a winner else return 0. Note" 'anything' in the codeList represents that any fruit can be ordered in place of 'anything' in the group. 'anything' has to be something, it cannot be "nothing." 'anything' must represent one and only one fruit. If secret code list is empty then it is assumed that the customer is a winner. """ def is_af_winner(codelist, basket): if len(codelist) == 0: return 1 if len(basket) == 0: return 0 match = False for subgroup in codelist: if helper(subgroup, basket) == -1: return 0 else: basket = basket[helper(subgroup, basket):] return 1 codelist = [['apple', 'apple'], ['apple', 'apple', 'banana']] shoppingCart = ['apple', 'apple', 'apple', 'banana'] print(is_af_winner(codelist, shoppingCart))
true
0382a4225ff66b3dbd205a5c0167410de25dce57
tranphibaochau/LeetCodeProgramming
/Medium/atoi.py
2,301
4.375
4
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Example 1: Input: "42" Output: 42 """ def myAtoi(str): INT_MIN = -2147483648 INT_MAX = 2147483647 result = 0 digit_found = False sign_found = False for i, c in enumerate(str): if digit_found == False and c not in '+- ' and c != '+' and not c.isdigit(): return result elif digit_found == False and c in '+-' and i+1 < len(str) and not str[i+1].isdigit(): return result elif digit_found == False and c.isdigit(): if i > 0 and (str[i-1] == '-'): sign_found = True digit_found = True result+= int(c) elif digit_found == True and c.isdigit(): result = result * 10 + int(c) if sign_found and result*(-1) <= INT_MIN: return INT_MIN elif result > INT_MAX: return INT_MAX elif digit_found == True and not c.isdigit(): if sign_found: return max(result*(-1), INT_MIN) else: return min(result, INT_MAX) if sign_found: return max(result*(-1), INT_MIN) else: return min(result, INT_MAX)
true
c9b3aea95dba4570348b1cab51f595031b1f8e75
tranphibaochau/LeetCodeProgramming
/Easy/balanced_binary_tree.py
2,426
4.125
4
#################################################################################################################################### # Given a binary tree, determine if it is height-balanced. #For this problem, a height-balanced binary tree is defined as: # a binary tree in which the left and right subtrees of every node differ in height by no more than 1. #################################################################################################################################### class Solution: #Top-down recursive def height (self, root): if not root: return -1 else: return (1 + max(self.height(root.left), self.height(root.right))) def isBalanced(self, root: TreeNode) -> bool: if not root: return True return abs(self.height(root.left) - self.height(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right) #Bottom-up recursive def isBalancedHelper(self, root): # An empty tree is balanced and has height -1 if not root: return True, -1 # Check subtrees to see if they are balanced. leftIsBalanced, leftHeight = self.isBalancedHelper(root.left) if not leftIsBalanced: return False, 0 rightIsBalanced, rightHeight = self.isBalancedHelper(root.right) if not rightIsBalanced: return False, 0 # If the subtrees are balanced, check if the current tree is balanced # using their height return (abs(leftHeight - rightHeight) < 2), 1 + max(leftHeight, rightHeight) def isBalanced(self): return self.isBalancedHelper(root)[0] #Iterative solution def isBalanced(self, root): stack, node, last, depths = [], root, None, {} while stack or node: if node: stack.append(node) node = node.left else: node = stack[-1] if not node.right or last == node.right: node = stack.pop() left, right = depths.get(node.left, 0), depths.get(node.right, 0) if abs(left - right) > 1: return False depths[node] = 1 + max(left, right) last = node node = None else: node = node.right return True
true
4dc49144996433c5c97ec3c5409096622cd99bf4
petersobhi/Xth-prime-number
/xth_prime_number.py
506
4.125
4
def get_xth_prime_number(x): # initial prime number list prime_numbers = [2] num = 3 while len(prime_numbers) < x: for prime_number in prime_numbers: if num % prime_number == 0: break else: prime_numbers.append(num) num += 2 # return last prime number return prime_numbers[-1] def main(): print("Generate X'th prime number") x = int(input("Enter a number: ")) print(get_xth_prime_number(x)) main()
false
63e551e85b7d631ce723a4c6f23aad39a65afba8
QuakeTheDuck/LearningPython
/Week-1 If Elif Else.py
1,287
4.15625
4
## M/D/Y 04/24/2017 ## Disclaimer: These are all personal notes. +=1 member - Thank you sentdex ## Python 3.6.1 # Adding more logic! x = 5 y = 10 z = 22 if x > y: # IT IS NOT print('x is greater than y') elif x < z: # IT IS print('x is less than z') # SO THIS IS RAN # Since the above 'elif' statement is ran it breaks/stops the rest of the code from being ran # Once an 'elif' finds something thats true it wont keep searching elif 5 > 2: print('5 is greater than 2') else: print('if an elif(s) never ran') #! Same code as above except noted out and some '>' and '<' were changed # Remove the note and run it ''' x = 5 y = 10 z = 22 if x > y: # IT IS NOT print('x is greater than y') elif x == z: # IT IS print('x is less than z') # SO THIS IS RAN # Since the above 'elif' statement is ran it breaks/stops the rest of the code from being ran # Once an 'elif' finds something thats true it wont keep searching elif 5 == 2: print('5 is greater than 2') else: print('if an elif never ran') ''' #! QUESTION # What will the output be? #! Don't run this code until you think you have the answer ''' if 1 > 2 > 3: print('#1') elif 3 > 2 > 1: print('#2') if 1 < 3: print('#3') '''
true
83fd08870cb361a1ced57ab9e8b65ec6b4901aef
QuakeTheDuck/LearningPython
/Week-1 Variables.py
2,122
4.375
4
## M/D/Y 04/23/2017 ## Disclaimer: These are all personal notes. +=1 member - Thank you sentdex ## Python 3.6.1 #! Errors are included, ignore them until you reach that part in the lesson ''' Variables are used to store information to be referenced and manipulated in a computer program They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves It is helpful to think of variables as containers that hold information Their sole purpose is to label and store data in memory This data can then be used throughout your program ''' # You define a variable in python by typing it out # Below 'exampleVar' is the variable it can be written like 'EXAMPLE_VAR', 'Example_Var', 'exampleVar' nearly any way you like # Remember be consistent # The exampleVar is camelCasing, because new words or abbreviations are capitalized, or bigger, like a camels hump # You cannot start a variable with a number exampleVar = 58 print(exampleVar) # Above we have the integer '55' which has been put into the variable 'exampleVar' print(exampleVar + 55) # Since it is an integer stored inside a variable it can be added as if it were an integer # # Variables are very powerful and are used !a lot! there are many thing you can do with them newVar = 9+33 print(newVar) print(newVar + exampleVar) # 'print()' is a function, variables can contain functions crazyVar = print('whoa') anotherVar = print(5+9) print('CLEAR') print('CLEAR') ''' Unpacking varibles ''' # Both 'x' and 'y' are variables # The '5' and '3' and a list # The program will read this as 'x = 5' and 'y = 3' x,y = (5,3) print(x) print(y) print(x+y) print(x-y) # ERROR # Below shows two variables with a list containing three different digits # This will cause 'ValueError: too many values to unpack' # For now debug the code, more debugging will be covered further in the future # Just remember the amount of variables and the amount of items in a list must be equal x,y = (5,3,8) print(x) print(y) print(x+y) print(x-y)
true
a157f86902345bd8d43928535feca33cdc28004c
ShreyaRawal97/Problems-vs-algorithms
/problem_1.py
935
4.375
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number == 0 or number == 1: return number if number < 0: return None s = 1 e = number/2 while s <= e: mid = (s+e)//2 if (mid*mid == number): return mid if mid*mid < number: s = mid+1 res = mid else: e = mid - 1 return res #Test Case 1 print ("Pass" if (3 == sqrt(9)) else "Fail") #pass #Test Case 2 print ("Pass" if (0 == sqrt(0)) else "Fail") #pass #Test Case 3 print ("Pass" if (4 == sqrt(16)) else "Fail") #pass #Test Case 4 print ("Pass" if (1 == sqrt(1)) else "Fail") #pass #Test Case 5 print ("Pass" if (5 == sqrt(27)) else "Fail") #pass print ("Pass" if (None == sqrt(-9)) else "Fail") #pass
true
eb295a23b0680359194dc6dbda24687c48a7a689
alaguraja006/pythonExcercise
/stringEx.py
772
4.40625
4
ex = 'this is a string' print(ex) ex = "string examples" print(ex) print(r'C:\some\name') s = ' You are awesome ' #accessing index value print(s[0]) #appending string no of times print(s*3) #lenght of String print(len(s)) #slicing String print(s[0:]) print(s[:-1]) print(s[-3:-1]) #0 starting index ,9 ending index , 2 interval travesal value print(s[0:9:2]) #reverse a string print(s[::-1]) print(s[3:0:-1]) #remove leading spaces print(s.strip()) print(s.lstrip()) print(s.rstrip()) #find substring index #it couldn't find substring return -1 print(s.find("awe")) print(s.find("awe"),0,len(s)) print(s.find("awe",0,len(s))) #count and replace print(s.count("a")) print(s.replace("awesome","super",0)) print(s.upper()) print(s.lower()) print(s.title())
true
1ebd7073df85458c1ca5d25fe74fc45f7e9921b0
atchyutn/python_tutorial_practise
/word_frequency.py
450
4.40625
4
''' This program is used to count the occurances of a word in a given set of words ''' user_input = input('Please enter a comma seperated list of words:') def word_frequency(user_input): word_count = {} word_array = user_input.split(',') for word in word_array: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 for key, value in word_count.items(): print(key,value) word_frequency(user_input)
true
f9a16dd7d15ab8e1983b882f130e28380d9b4138
atchyutn/python_tutorial_practise
/min_max_sort.py
540
4.4375
4
''' This program is to find the min, max, sorted list of stocks based on the value ''' #creating dictonary with key, value pairs of company and its share value STOCKS = { 'SBI' : 239, 'Infosys': 1190, 'Airtel': 390, 'wipro' : 500 } ''' To find the min or max or sorted values of a dict, we need to zip. ''' min_stock = min(zip(STOCKS.values(), STOCKS.keys())) print(min_stock) max_stock = max(zip(STOCKS.values(), STOCKS.keys())) print(max_stock) sorted_stocks = sorted(zip(STOCKS.values(), STOCKS.keys())) print(sorted_stocks)
true
87114bbb62a10ed277992485cba21fdfdd10ec3e
raykirichenko/card-game
/game.py
630
4.1875
4
import random winning = True score = 0 while winning: hidden = random.randrange(1, 13) print("My card is: " + str(hidden)) guess = int(input("Type 1 to draw or 2 to quit: ")) if guess == 1: mycard = random.randrange(1, 13) print("Your card is: " + str(mycard)) if mycard > hidden: print("You win!") score = score + 100 print("Your score: " + str(score) + "\n") else: print("You lose!") print("Final score: " + str(score) + "\n") winning = False else: print("Good game!") winning = False
true
59a07064c5e062594461c3a0304dd3d3011529f2
rdsilvalopes/python-exercise
/Q04.py
651
4.25
4
#! usr/bin/env python3 # Faça um Programa que verifique se uma letra digitada é vogal ou consoante. def verificarLetra(): # lista vogais vogal = ['a', 'e', 'i', 'o', 'u'] # lista consoantes consoantes = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'l', 'm', 'n', 'k', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z', 'y'] letra = input("Informe uma letra:") if letra.lower() in vogal: print ("Letra %s é uma vogal!" % letra.upper()) elif letra.lower() in consoantes: print ("Letra %s é um consoante!" % letra.upper()) else: print ("Por favor, informe somente uma letra!") verificarLetra()
false
dc84d04a85dc097e1e04ab27d867be8999770ce7
nstudenski/project_euler
/e5.py
1,221
4.21875
4
#is divisible checks whether num is divisible by every integer between divisor and max_divisor #num is the number to check the divisibility of #divisor is the first number to check divisibility by (usually 2) #max divisor is the highest number that num must be divisible by #the function checks divisibility by every number between divisor and max divisor #True is returned if num is divisible by all divisors def is_divisible(num,divisor,max_divisor): if divisor == max_divisor+1: return True if num % divisor == 0: return is_divisible(num,divisor+1,max_divisor) else: return False #find_lowest returns the smallest integer for which is_divisible returns true #num is the first number to check, if is_divisible returns false, #we continue to increment num by 1 until True is returned def find_lowest(num,divisor,max_divisor): if is_divisible(num,divisor,max_divisor) == True: return num else: return find_lowest(num+1,divisor,max_divisor) #for i in range(12252240,1000000000): # if is_divisible(i,2,19): # print(i) #the answer is 232792560 #I cheated a bit by multiplying the answer for 18 by 19 to save computation time print(12252240*19)
true
1591e8a20491745c1545ac1b8cac6468970e921d
kholm-umc/Electric_Bike_Class
/main.py
2,515
4.34375
4
# Ken Holm # Purpose: Demonstrate how to use a subclass # we created from a superclass # Importing ElectricBike instead of Bike # from bike import Bike from electricbike import ElectricBike try: # Instantiate our new ElectricBike # Number of gears: 5 # Number of wheels: 3 # Brake type: electric # I must create an instance of an ElectricBike, not a Bike myBike = ElectricBike(5, 3) # Print our some bike info print("Our new bike") print(f"Gears: {myBike.getNumberOfGears()}") print(f"Number of Wheels: {myBike.getNumberOfWheels()}") print(f"Brake Type: {myBike.getBrakeType()}") print(f"Current Gear: {myBike.getCurrentGear()}") print(f"Current Charge: {myBike.getCharge()}") input("Continue") print() # Set our current gear to 3 print("Setting the current gear to 3") myBike.setCurrentGear(3) print(f"Current Gear: {myBike.getCurrentGear()}") input("Continue") print() # Increase the gear (to 4) print("Increasing the current gear") myBike.increaseGear() print(f"Current Gear: {myBike.getCurrentGear()}") input("Continue") print() # Increase the gear, again (to the max: 5) print("Increasing the current gear, again") myBike.increaseGear() print(f"Current Gear: {myBike.getCurrentGear()}") input("Continue") print() # Increase the gear, once more, past the max print("Trying to go past the max gear") myBike.increaseGear() print(f"Current Gear: {myBike.getCurrentGear()}") print("NOTE: We do not allow that to happen") input("Continue") print() # Prepare to go below the minimum gear print("Resetting our gear to 2") myBike.setCurrentGear(2) print(f"Current Gear: {myBike.getCurrentGear()}") input("Continue") print() # Decrease the gear (to 1) print("Decreasing our current gear") myBike.decreaseGear() print(f"Current Gear: {myBike.getCurrentGear()}") input("Continue") print() # Try to bypass the minimum gear print("Trying to decrease our current gear below 1") myBike.decreaseGear() print(f"Current Gear: {myBike.getCurrentGear()}") print("NOTE: We do not allow that to happen") input("Continue") print() # Set the brake type to "electric" print("Trying to set the brake type to 'hand'") myBike.setBrakeType("hand") print(f"The brake type is now: {myBike.getBrakeType()}") print() except Exception as e: print(f"Error message: {e}")
true
fb6554295c729d7b92bed8a08a91f860b2b2a500
manjuprasadshettyn/pythonprogramming
/bitwise.py
336
4.15625
4
#Bitwise operations a=10 b=7 c=a&b d=a ^ b e= a | b print ('The result of 10 and 7 operation is', c) print ('The result of 10 exclusive or 7 operation is' , d) print ('The result of 10 or 7 operation is', e) g=a<<2 print ('Left shifting - Multiplying 10 by 4 becomes:' , g) h=a>>1 print ('Right shifting - Dividing 10 by 2 becomes:',h)
false
512548460cfdc475604cbd5ccb090253121e9ce0
manjuprasadshettyn/pythonprogramming
/tailrecursive.py
307
4.40625
4
# Tail recursive factorial program def fact(x): return facthelper(x,1) def facthelper(n,result): if n==0: return result elif n==1: return result else: return facthelper(n-1,n*result) print("Enter the number to find the factorial") num=int(input()) print("The factorial of ",num,"is",fact(num))
true
0668d2bf5bcaf886141a50f0bc1699b9bdf2102b
manjuprasadshettyn/pythonprogramming
/functionsum.py
286
4.1875
4
# function to find the sum of series def sum1(a,b): sum=0 for i in range(a,b+1) : sum+=i return sum print("the sum of integers from 1 to 10 is ", sum1(1,10)) print("the sum of integers from 20 to 37 is ", sum1(20,37)) print("the sum of integers from 35 to 49 is ", sum1(35,49))
true
c13d331a726f8752f41d1d00b968c5947b2b58a5
megane22/dungeon
/dungeon-v2.py
2,376
4.15625
4
dungeon = [['Rm 101', 'Rm 102', 'Rm 103', 'Rm 104', 'Elevator'], ['Rm 201', 'Rm 202 (my room)', 'Rm 203', 'Rm 204', 'Elevator'], ['Rm 301', 'secret stairs', 'Rm 303', 'Rm 304', 'Elevator'], ['Rm 401', 'secret stairs', 'maintenance closet', 'Rm 404', 'dead end']] #tell me what room I should move to def move_left_from(room_number): print("You want to move left! OK. I don't know how to do that yet.") def move_right_from(room_number): print("You want to move right! OK. I don't know how to do that yet.") def move_up_from(floor_number): print("You want to move up! OK. I don't know how to do that yet.") def move_down_from(floor_number): print("You want to move down! OK. I don't know how to do that yet.") #FOR THURSDAY, 7/27: #Here is a "game loop" that asks for user input and calls the correct #functions. The key is the while(True) loop, and also that #exit() gets called on some input. See if you can adapt this for your #social network back-end! def main(): print("Welcome to the dungeon! Muahahaha.") floor_number = 1 room_number = 1 print("You start at" + dungeon[floor_number][room_number]) #this is equivalent to "forever": since True is true forever! while True: #ask for what the user wants to do user_action = input("What do you want to do?\n \ You can move up (u), down (d), left (l), or right(r),\n \ or you can quit (q). ") if user_action == 'q': print("Sorry to see you go!") exit() #elif = else if. So, if the user action was NOT q, now check if it's u elif user_action == 'u': move_up_from(floor_number) elif user_action == 'd': move_down_from(floor_number) elif user_action == 'r': move_right_from(room_number) elif user_action == 'l': move_left_from(room_number) #else here means, if the user action was ANYTHING else #besides q, u, d, r, or l. else: print("Um, I don't know what that means. Please ask again.") #at the end of the if/else statements, print a line of stars #to help the user separate the previous action from the next action print("**********************\n") #end of the main method #call the main method, so our program runs main()
true
76c47d22c9ec19c46e763ff47eff2fccf5cf4bfe
freakyindiancoder/List_Game
/List Game.py
1,768
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #Function to Displays The current Game List def display_game(game_list): print('The current game list is :') print(game_list) # In[2]: #Function to Choose the position to update def pos_choice(): choice = 'Wrong choice' while choice not in ['0','1','2']: choice = input('Enter your choice (0,1,2) ') if choice not in ['0','1','2']: print(f'choice should be either (0,1,2): ') else: return int(choice) # In[3]: #Function to update game_list def replacement(game_list,position): replace = input('Enter the string to be replaced: ') game_list[position] = replace print(game_list) return game_list # In[4]: #Function to continue game or to end game def continue_game(): choice = 'wrong' while choice not in ['y','n']: choice = input('Do you wish to continue the game (y or n): ') if choice not in ['y','n']: print('the choice should be y or n') if choice == 'y': return True else: return False # In[5]: #Now lets Build Logic of the Game game_on = True game_list = [0,1,2] #Unless the game_on == False the game will be continued: while game_on: #display the game list display_game(game_list) #Assing the position to pos_choice or you can call directly position = pos_choice() #Update the Game list Using the Position Chosen and Value given as input game_list = replacement(game_list,position) #Ask user to continue or not and assign that boolean to game_on:(if true then game continue,if it is false game exits) game_on = continue_game() # In[ ]:
true
e7651e31febe3b77054ef662a70e2d836821d760
ComradYuri/Complex_Data_Structures-Trees_Wilderness_Escape
/script.py
2,812
4.21875
4
print('Once upon a time...') class TreeNode: def __init__(self, story_piece): self.story_piece = story_piece self.choices = [] # add new branches to the story def add_child(self, node): self.choices = self.choices + [node] # initiates story from root. Takes input to traverse story lines def traverse(self): # sets init value to story node story_node = self # prints variable story piece from self. Which is the starting/root story in this case print(story_node.story_piece) # iterates through list of choices until empty while len(story_node.choices) > 0: choice = input("Enter 1 or 2 to continue the story: ") # checks if input is valid. If input is not valid it starts again at the top of the while loop if choice not in ['1', '2']: print('Enter a valid choice. 1 or 2.') # in this case the input is valid else: # index numbers are 0 and 1. Choices are 1 and 2. This corrects for that chosen_index = int(choice) - 1 # this inputs index into new variable chosen child chosen_child = story_node.choices[chosen_index] print(chosen_child.story_piece) # shifts tree one level/branch down. Which shortens the choices list story_node = chosen_child story_root = TreeNode(""" You are in a forest clearing. There is a path to the left. A bear emerges from the trees and roars! Do you: 1 ) Roar back! 2 ) Run to the left... """) choice_a = TreeNode(""" The bear is startled and runs away. Do you: 1 ) Shout 'Sorry bear!' 2 ) Yell 'Hooray!' """) choice_b = TreeNode(""" You come across a clearing full of flowers. The bear follows you and asks 'what gives?' Do you: 1 ) Gasp 'A talking bear!' 2 ) Explain that the bear scared you. """) story_root.add_child(choice_a) story_root.add_child(choice_b) choice_a_1 = TreeNode(""" The bear returns and tells you it's been a rough week. After making peace with a talking bear, he shows you the way out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """) choice_a_2 = TreeNode(""" The bear returns and tells you that bullying is not okay before leaving you alone in the wilderness. YOU REMAIN LOST. """) choice_a.add_child(choice_a_1) choice_a.add_child(choice_a_2) choice_b_1 = TreeNode(""" The bear is unamused. After smelling the flowers, it turns around and leaves you alone. YOU REMAIN LOST. """) choice_b_2 = TreeNode(""" The bear understands and apologizes for startling you. Your new friend shows you a path leading out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """) choice_b.add_child(choice_b_1) choice_b.add_child(choice_b_2) # start story story_root.traverse()
true
a41bc6aa6f5faafed65515bba0d843a0ea380901
sudita07/if-else-statements
/class10part3ifelsecondition.py
506
4.1875
4
# program to find odd or even numbers # x=int(input("enter your number")) # r=x%2 # if(r==0): # print("even") # else: # print("odd") # x=int(input("enter first number")) # if x>=0: # print("is positive") # else: # print("is negative") # x=int(input("enter age")) # if x>=60: # print("senior citizen") # else: # print("is young") v=int(input("enter num")) b=int(input("enter 2nd num")) if v<b: print("v is smaller") else: print("b is smaller")
false
8c589f2a914bf587b845c5c1bcb5983c7aface5f
meccs/CSSI
/cssi-labs/python/labs/word-frequency-counter/classPet.py
1,255
4.46875
4
class Pet: '''__init__() is a method of the class Pet .A method is a function that belongs to a class instance. All methods of a class first parameter is self''' def __init__(self,name,age,animal="dog"): '''self.name and self.age are instance attributes or data members of the class Pet. Instance attributes are unique in every occurance (instance) of a Pet object''' self.name = name self.age = age self.animal = animal self.is_hunger = False self.mood = "Happy" def eat (self): self.is_hunger = False def __str__(self): return "{0} {1}".format(self,name,age,animal) '''The pet class has the members age,name,count,__init()__self. To call the __init__() function we use the class name with the respective parameters within parenthesis''' def madeHunger(pet): pet.is_hunger = True #o is an object of Pet o = Pet("Dog", 3) #t is another object of Pet t = Pet("Cat", 4) print "Before call to makeHunger()" print o.name, o.age, o.count print t.name, t.age, t.count makeHunger(o) print "After call to makeHunger() and before call to eat()" print o.name, o.age, o.count print t.name, t.age, t.count o.eat print o.name, o.age, o.count print t.name, t.age, t.count
true
cc61e3065275655156b8ee62731bbf5070971467
lavenus/PythonLearn
/Note/1.1circumference.py
892
4.46875
4
# -*- coding: utf-8 -*- ## 计算圆周长和面试的程序 ## 问题:已知圆半径,计算圆周长和面积.所用到的数学公式有: ## 圆周长 = 2 * pi * r ## 圆面积 = pi * r * r ##-------------------- ## 中文算法 # (1) 提示用户输入圆的半径. # (2) 利用上面公式进行计算圆的周长和面积. # (3) 把计算得出的周长和面积输出结果 ##---------------------- ## English algorithm # calculate the area and circumference of a circla from its radius # Step 1: prompt for a radius # Step 2: apply the area formula # Step 3: Print out the results import math radiusString = raw_input("Enter the radius of your circle: ") radiusInteger = int(radiusString) circumference = 2 * math.pi * radiusInteger area = math.pi * (radiusInteger ** 2) print "The circumference is: ",circumference,", and the area is: ",area
false
d0c3a107620ce26ad0ec0c666df94a548b5caff1
aa-iakupova/my_python
/4 lesson/str_op.py
1,180
4.1875
4
s = "У лукоморья 123 дуб зеленый 456" #1) Определить, встречается ли в строке буква 'я'. Вывести на экран ее позицию (индекс) в строке. #2) Определить, сколько раз в строке встречается буква 'у'. #3) Определить, состоит ли строка из букв, ЕСЛИ нет, ТО вывести строку в верхнем регистре. #4) Определить длину строки. ЕСЛИ длина строки превышает 4 символа, ТО вывести строку в нижнем регистре. #5) Заменить в строке первый символ на 'О'. Результат вывести на экран #1 if s.find('я')==-1: print ('Не содержит') else: print(s.index('я')) #2 print(s.count('у')) #3 if s.isalpha()==False: print(s.upper()) #4 if (s.__len__()>4)==True: #почему нельзя без нижних подчеркиваний? print (s.lower()) #5 print(s.replace(s[0],'О'))
false
ae9b36cbcc1288714e8a121ee3689c5233a54d5f
chenwei90/IDG
/TestPython/examples/example40_字符串和列表反转.py
444
4.15625
4
# -*- coding: utf-8 -*- ''' 将一个数组逆序输出。 ''' def main(): test_string = "1234abcd" test_list = [1, 2, 3, 4, 'a', 'b', 'c', 'd'] # [::-1] 对于string和list是通用的 print test_string[::-1] print test_list[::-1] # 反转列表还有一种方法: reversed, 但是必须要转一下(转成list, 强转, 跟int有点像) print list(reversed(test_list)) if __name__ == '__main__': main()
false
6a2240186fae9d9ddeac367f1e2fad62ac0ca109
ShubhangiDabral13/Pythonic_Lava_Coding_Question
/GeeksForGeeks/gfg-Flipkart/Find The Middle Element From Linked List/Finding_Middle_Element_In_Linked_List.py
1,900
4.21875
4
class Node: def __init__(self,data): self.data = data self.next = None class Linked_List: def __init__(self): self.head = None def insert(self,data): new_node = Node(data) if self.head == None: self.head = new_node else: new_node.next = self.head self.head = new_node def middle_element(self): temp = self.head slow_temp = self.head if temp == None: print("There is no element in the linked list") return if temp.next == None: temp = temp.next print("the middle element in the linked list is {}".format(temp.data)) return else: while(temp != None and temp.next != None): #prev_slow = slow_temp slow_temp = slow_temp.next temp = temp.next.next print("The middle element in the linked list is {}".format(slow_temp.data)) def display(self): temp = self.head while temp != None: print(temp.data,end = " ") temp = temp.next ll = Linked_List() ch = 0 while(ch != 4): print("""Enter 1 to insert a node at front in Linked_List Enter 2 to display the middle element of the linked list Enter 3 to print the linked List Enter 4 to to quit """) ch = int(input()) if ch == 1: print("Enter the data you want to insert in the linked list") a = int(input()) ll.insert(a) elif ch == 2: ll.middle_element() elif ch == 3: ll.display() elif ch == 4: print("We will quit") else: print("Wrong choice")
true
70eecaf97a35acc83f6e691447db0f17c3a0ed4c
sabeeh99/Batch-3
/mohammed_asif.py
1,001
4.34375
4
# import turtle package import turtle # Mohammed_Asif-3-Chess Board (turtle) # create turtle object pen = turtle.Turtle() # hides the pointer of turtle pen.hideturtle() # Increases drawing speed pen.speed(100) # setting up the beginning position pen.penup() pen.goto(-200, -150) pen.pendown() def draw(): """This function will draw a square""" for k in range(4): pen.right(90) pen.forward(50) # looping for getting a board for i in range(1, 9): # drawing squares as row for j in range(1, 9): # set position for new square pen.forward(50) # calling function to draw each square draw() # checks whether the board is drawn . if drawn breakes the loop if i == 8: break # repositioning the pointer to draw the next row else: pen.backward(50 * 8) pen.left(90) pen.forward(50) pen.right(90) # stops execution turtle.done()
true
b7c5004d83f4ba84ca539b137c723bdf7b1626b6
cauegraciolip/class_projects
/class_tests_2.py
506
4.25
4
print("""Para formar um triângulo, precisamos de trê retas. Digite três valores e veja se eles formam um triângulo.""") a = float(input('Primeira reta: ')) b = float(input('Segunda reta: ')) c = float(input('Terceira reta: ')) abs1 = abs(b - c) abs2 = abs(a - c) abs3 = abs(a - b) soma1 = b + c soma2 = a + c soma3 = a + b if abs1 < a < soma1 and abs2 < b < soma2 and abs3 < c < soma3: print('Com esses valores se forma um triângulo.') else: print('Não é possível formar um triângulo.')
false
6947612714a7ae80e2d8541ba9f146a0189c39af
jorgemira/Hackerrank
/frequency-queries.py
1,290
4.25
4
""" https://www.hackerrank.com/challenges/frequency-queries/ """ import os from collections import defaultdict def freqQuery(queries): """You are given q queries. Each query is of the form two integers described below: -1 x : Insert x in your data structure. -2 y : Delete one occurence of y from your data structure, if present. -3 z : Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0. :type queries: list[list[int]] :rtype: list[str] """ items = defaultdict(int) freqs = defaultdict(int) result = [] for op, v in queries: if op == 1: freqs[items[v]] -= 1 items[v] += 1 freqs[items[v]] += 1 elif op == 2: if items[v] > 0: freqs[items[v]] -= 1 items[v] -= 1 freqs[items[v]] += 1 elif op == 3: result.append(1 if freqs[v] else 0) return result if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) ans = freqQuery(queries) fptr.write('\n'.join(map(str, ans))) fptr.write('\n') fptr.close()
true
e2d6cfb733a7dc35668a25b0f9b2fd18805d0a31
jorgemira/Hackerrank
/standardize-mobile-number-using-decorators.py
835
4.40625
4
""" https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/ Let's dive into decorators! You are given N mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have +91, 91 or 0 written before the actual 10 digit number. Alternatively, there may not be any prefix at all. """ def fix_number(n): if len(n) == 12: n = f"+{n}" elif len(n) == 11: n = f"+91{n[1:]}" elif len(n) == 10: n = f"+91{n}" return f"{n[:3]} {n[3:8]} {n[8:13]}" def wrapper(f): def fun(l): f([fix_number(n) for n in l]) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l)
true
c3e419708a95101645da770ef982e58ac1283bf3
jorgemira/Hackerrank
/python-arithmetic-operators.py
615
4.1875
4
""" https://www.hackerrank.com/challenges/python-arithmetic-operators/ """ def arithmetic_operators(a, b): """Read two integers from STDIN and print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. :type a: int :type b: int :rtype: tuple[int, int, int] """ return a + b, a - b, a * b if __name__ == '__main__': a = int(input()) b = int(input()) print('\n'.join(str(i) for i in arithmetic_operators(a, b)))
true
a321ac29c88644ceeb6fdc0735ab160e0e8281bc
elishatam/python-projects
/programming_foundations/inheritance/inheritance.py
1,116
4.3125
4
class Parent(): def __init__(self, last_name, eye_color): print("Parent Constructor Called") self.last_name = last_name self.eye_color = eye_color def show_info(self): print("Last Name - "+self.last_name) print("Eye Color - "+self.eye_color) class Child(Parent): #class Child inherits from class Parent and gets everything public from Class Parent def __init__(self, last_name, eye_color, number_of_toys): print("Child Constructor Called") Parent.__init__(self, last_name, eye_color) #To initialize the variables that are inherited from Class Parent self.number_of_toys = number_of_toys billy_cyrus = Parent("Cyrus", "blue") #print(billy_cyrus.last_name) billy_cyrus.show_info() miley_cyrus = Child("Cyrus", "blue", 5) # print(miley_cyrus.last_name) # print(miley_cyrus.number_of_toys) miley_cyrus.show_info() # def show_info(self): # Child's method will override Parent's method # print("Last Name - " + self.last_name) # print("Eye Color - " + self.eye_color) # print("Number of Toys - " + str(self.number_of_toys))
true
efd21546d605ef679e397d5c42695dd0aca5c241
mohitsharma14/HackerRank-Python-Solutions
/Easy/countApplesAndOranges.py
1,824
4.125
4
""" Finding how many apples or oranges fell with in a particular range Given the value of for apples and oranges, determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range )? For example, Sam's house is between and . The apple tree is located at and the orange at . There are apples and oranges. Apples are thrown units distance from , and units distance. Adding each apple distance to the position of the tree, they land at . Oranges land at . One apple and two oranges land in the inclusive range so we print Output 1 2 """ # Approach 1 def countApplesAndOranges(s, t, a, b, apples, oranges): applesDistCount = [] orangesDistCount = [] for i in range(0, len(apples)): tempVal = a + apples[i] if(tempVal in range(s, t+1)): applesDistCount += 1 for i in range(0, len(oranges)): tempVal = a + oranges[i] if(tempVal in range(s, t+1)): orangesDistCount += 1 print(len(applesDistCount)) print(len(orangesDistCount)) s = 7 t = 10 a = 4 b = 12 apples = [10, 3, -4] oranges = [ 3, -7] countApplesAndOranges(s, t, a, b, apples, oranges) # Approach - 2 def countApplesAndOranges(s, t, a, b, apples, oranges): applesDist = [] orangesDist = [] for i in range(0, len(apples)): applesDist.append(a + apples[i]) for i in range(0, len(oranges)): orangesDist.append(b + oranges[i]) finalDistApples = list(filter(lambda x: (x >= 7) and (x <= 10), applesDist)) finalDistOranges = list(filter(lambda x: (x <= -7) and (x >=- 10), orangesDist)) print(len(finalDistApples)) print(len(finalDistOranges)) countApplesAndOranges(s, t, a, b, apples, oranges)
true
ffd41929a427c995332668b124875c9db63d82a6
Santi-ago222/programacion3semestre
/Clases2021-1/ejemploswhyleclase6.py
887
4.28125
4
#---entradas---# MENSAJEBIENVENIDA= "Muy buenos dias, despierte que esta en clase de 6 " PREGUNTAMENU= '''ingrese 1- para mostrar los numeros del 1 al 5 2- para preguntar tu nombre 3- para mostrarte el año en que estamos 4- para salir ''' MENSAJE_ERROR= "Por favor ingresa una opcion valida" PREGUNTANOMBRE= "Como te llamas? : " #---CODIGOS---# print(MENSAJEBIENVENIDA) entrada= 1 while(entrada>=1 and entrada<=3): entrada= int(input(PREGUNTAMENU)) if(entrada==1): print("1,2,3,4,5") elif (entrada==2): print(PREGUNTANOMBRE) elif(entrada==3): print("el año en que estamos es el 2021") elif(entrada==4): print('muchas gracias por usar este programa, feliz dia dormilon') else: entrada=1 print(MENSAJE_ERROR)
false
4360f24bcc3755c8a726c63f8f22716a9e942de5
YanHengGo/python
/36_OOP/lesson.py
407
4.125
4
#加载类 from Turtle import * tu=Turtle() tu.eat() #封装 例子:list list1=[2,1,3,7,5] list1.sort() print(list1) list1.append(9) print(list1) #继承 class Mylist(list): pass list2=Mylist() list2.append(5) list2.append(3) list2.append(8) list2.sort() print(list2) #多态 class A: def fun(self): print("a") class B: def fun(self): print("b") a=A() b=B() a.fun() b.fun()
false
31a0c4ee9f83c3f8769b13dfd7781bb314dfa36b
aviato/programming_for_everyone
/5.2.py
508
4.21875
4
#~~~~~~~~~~~~~~~~~~Coursera assignment 5.2~~~~~~~~~~~~~~~~~~~~ largest = None smallest = None while True: prompt = raw_input("Please enter a number: ") try: num = float(prompt) if smallest == None or num < smallest: smallest = num elif largest == None or num > largest: largest = num except: if prompt == 'done': break else: print "Invalid input (not a number)." print "Maximum", largest print "Minimum", smallest
true
7d5f4f106608093047b90b7a99168d3cab112c09
aviato/programming_for_everyone
/8.5.py
331
4.25
4
#~~~~~~~~~~~~~~~~~~~Coursera Assignment 8.5~~~~~~~~~~~~~~~~~~~ prompt = raw_input("please enter filename: ") open_file = open(prompt) count = 0 for line in open_file: s_line = line.split() if "From" in s_line: print s_line[1] count += 1 print "There were %d lines in the file with From as the first word" % count
true
a8f4b98db5cfd5085a3dc528bf6e8ed84890c926
upendra431/python3
/CH03 Conditionals/Conditionals/conditional-operators.py
2,370
4.28125
4
''' Comparison Operators == a==b Equal != a!=b Not Equal < a<b Less Then > a>b Grater Then <= a<=b Less Then or Equal >= a>=b Grater Then or Equal ''' print("---------------------------------------------------") print("--------------Comparison Operators-----------------") print("---------------------------------------------------\n") print("-----------------------Equal-----------------------") a=10 b=10 if a==b: print(" a={} and b={} a==b is true ".format(a,b)) print("---------------------------------------------------") print("-------------------Not Equal-----------------------") a=10 b=100 if a!=b: print(" a={} and b={} a!=b is true ".format(a,b)) print("---------------------------------------------------") print("-------------------Less Then-----------------------") a=10 b=100 if a<b: print(" a={} and b={} a<b is true ".format(a,b)) print("---------------------------------------------------") print("-----------------Grater Then-----------------------") a=1000 b=100 if a>b: print(" a={} and b={} a>b is true ".format(a,b)) print("--------------------------------------------------------") print("------------------Less Then or Equal--------------------") a=100 b=100 if a<=b: print(" a={} and b={} a<=b is true ".format(a,b)) print("----------------------------------------------------------") print("-----------------Grater Then or Equal--------------------") a=1000 b=1000 if a>=b: print(" a={} and b={} a>=b is true ".format(a,b)) print("----------------------------------------------------------") ''' Logical Operators ''' print("##########################################################") print("==================Logical Operators=======================") print("##########################################################") print("######################## and #############################") if True and True: print(" both the conditions true only and will execute ") print("######################## or #############################") if True or False: print(" any conditions true only and will execute ") print("######################## not #############################") if not False: print(" both are not conditions true only and will execute ") print("##########################################################")
false
feee17204f8321cfe3f2f058deac57df16efc578
Raseckuat/LearningPython
/edadesEstudiantes.py
1,698
4.125
4
print("Se cuenta con la siguiente información:") print("Las edades de 5 estudiantes del turno mañana.") print("Las edades de 6 estudiantes del turno tarde.") print("Las edades de 11 estudiantes del turno noche.") print("Las edades de cada estudiante deben ingresarse por teclado.") print("a) Obtener el promedio de las edades de cada turno (tres promedios)") print("b) Imprimir dichos promedios (promedio de cada turno) ") print("c) Mostrar por pantalla un mensaje que indique cual de los tres turnos tiene un promedio de edades mayor.") temp=0 pmanana=0 ptarde=0 pnoche=0 print("Estudiantes de la manana:") for i in range(1,6): temp+=int(input(f"Please enter the Edad {i}:")) pmanana=temp/5 print(f"El promedio de edades de los estudiantes de manana es={pmanana}") print("*****************************************************************") print("Estudiantes de la Tarde:") temp=0 for i in range(1,7): temp+=int(input(f"Please enter the Edad {i}:")) ptarde=temp/6 print(f"El promedio de edades de los estudiantes de manana es={ptarde}") print("*****************************************************************") print("Estudiantes de la Noche:") temp=0 for i in range(1,12): temp+=int(input(f"Please enter the Edad {i}:")) pnoche=temp/6 print(f"El promedio de edades de los estudiantes de manana es={pnoche}") if pmanana > ptarde and pmanana > pnoche: print(f"El promedio de edades de la manana es mayor, ya que es:{pmanana}") elif ptarde > pnoche: print(f"El promedio de edades de la tarde es mayor, ya que es:{ptarde}") else: print(f"El promedio de edades de la noche es mayor, ya que es:{pnoche}") input("Presione cualquier tecla para terminar.")
false
84f30a5c262663a94ad03aad015e481febc4640b
Derekjames93/Python102
/vowels.py
584
4.28125
4
# Create a word string user_question = ("Please enter your name!") # Create var to make it all upper user_question = str.upper(user_question) # create a list of all the vowels # vowels = ["A", "E", "I", "O", "U"] # Create a while loop to prompt user to enter correct string while True : try : user_input = input('').lower user_input = int(user_input) print('Please enter a string!') except ValueError : break #Extend Vowels by 5 #ex_vowels = vowels * 5 # Create IF statement to extend vowel by 5 # Print output #print(ex_vowels)
true
af11d5984fee14878de666b38e4004fc676c288e
devanwong/web-335
/week 8/wong_calculator.py
627
4.28125
4
# # ============================================ # ; Title: Exercise 8.3 # ; Author: Devan Wong # ; Date: 2 December 2020 # ; Description: Python in Action # ;=========================================== # # addition def add(a,b): return a + b # subtract def subtract(a,b): return a - b # divide def divide(a,b): return a / b # print statements print(add(1,2)) print(subtract(4, 1)) print(divide(8, 2)) # if/elses statement num1 = 0 num2 = 0 # logic if num1 > num2: print("num1 greater than num2") elif num1 == num2: print("num1 is equal to num2") else: print("num1 is not greater than num2")
true
275ceedde4a3ab954e32d8d3e3b06eed463a0ede
thenriq/GMIT-DataAnalitics
/W7_Read_a_text_File.py
1,210
4.3125
4
# Thiago Lima # This program ask for a file name (file must be in the same folder), then it asks for a # desired character to be seek throughout the program and outputs the number of this character occurence def readfile(filename,character): # function definitions: it asks for a filename and the seek character f = open(filename,'r') # user will input file name count =0 # this will summarize the number of the seek character for line in f: #get the line #for word in line.split(): # split the line into words for letter in list(line): # split the word into characters if (letter == character): # compares whether or not each character is equal to the seek character count = count + 1 # if character is found, it is summarized with count return count # result of this function ############################################################### filename = str(input("Type the file name: ")) character = str(input("Which character are you looking for? ")) # the line below will print and call the funcion "readfile" at the same time print('Found', (readfile(filename,character)), 'occurrences of ',"'",character,"'" 'character')
true
2ce50ce0f8ba02de539cc3eaa41d696a9fd9ddfc
CarlosCortes2020/PenCompPython
/freeloops.py
1,213
4.21875
4
def run(): ext_counter = 0 int_counter = 0 frutas = ['manzana','pera','mango','platano'] estudiantes = { 'Mexico' : 10, 'colombia' : 15, 'Puerto Rico' : 4, } while ext_counter <= 3: while int_counter <= 3: print(ext_counter,int_counter) int_counter += 1 ext_counter += 1 int_counter = 0 input('Presiona enter para frutas') for fruta in frutas: print(fruta) input('Presiona enter para looper') looper = iter(frutas) next(looper) input('Presiona enter') next(looper) input('Presiona enter') next(looper) input('Presiona enter') next(looper) input('Presiona enter') input('Presiona enter pais 1') for pais in estudiantes: print(pais) input('Presiona enter pais 2') for pais in estudiantes.keys(): print(pais) input('Presiona enter estudiantes 1') for num_estudiantes in estudiantes.values(): print(num_estudiantes) input('Presiona enter juntos') for pais,num_estudiantes in estudiantes.items(): print(pais,num_estudiantes) if __name__ == "__main__": run()
false
b516d84a6015665efe2bc8602f2f7d4a84118342
RAM-droi/StructuredPrograming2A
/unit1/activity.01.py
250
4.15625
4
num1 = 0 num2 = 0 result_add = 0 result_m = 0 num1 = int( input( "Enter number1:" ) ) num2 = int( input( "Enter number2: ")) result_add = num1 + num2 result_m = num1 * num2 print("This is the add:",result_add) print("This is the mult:",result_m)
false
5d42b156d3a778fbf385aea99195ee7f05b35270
alicesilva/P1-Python-Problemas
/exemplo17.py
728
4.21875
4
#coding: utf-8 numero1 = int(raw_input()) numero2 = int(raw_input()) numero3 = int(raw_input()) if numero1<numero2 and numero2<numero3 and numero2<numero3: print numero1 print numero2 print numero3 elif numero1<numero2 and numero2<numero3 and numero3<numero2: print numero1 print numero3 print numero2 elif numero2<numero1 and numero2<numero3 and numero1<numero3: print numero2 print numero1 print numero3 elif numero2<numero1 and numero2<numero3 and numero3<numero1: print numero2 print numero3 print numero1 elif numero3<numero1 and numero3<numero2 and numero1<numero2: print numero3 print numero1 print numero2 else: print numero3 print numero2 print numero1 print print numero1 print numero2 print numero3
false
1a15c5ab19d228cdcc76cb084ca2e5fcc5d0fcb1
andresSaldanaAguilar/Python
/functions.py
2,728
4.125
4
def saludar(): print("hola k tal") #una observacion con el uso de variables es que una variable a ser usada en la funcion #debe ser definida no necesariamente antes de la definicion de la funcion pero si antes de #su llamada #el tipo de retorno es de aquel objeto retornado # def suma(): # lista=[1,2,3,4] # return lista #print(suma()) #podemos hacer cosas como las siguiente # def arreglo(): # return "cadena", 1,[1,2,3] # c,n,l=arreglo() # print(c, n,l) #para mandar parametros hacemos los siguiente: #los valores nulos son valores por default cuando no se mandan argumentos # def suma(a=None,b=None): # return a[0]+b # print(suma([1,2,3],3)) # print(suma(b=4,a=[5,2])) #las listas son llamadas a las funciones por referencia, es decir, su valor original si es modificado # a diferencia de una variable simple, que su valor no es modificado al ser llamado a una funcion, se pasa por valor a la funcion #una lista puede recibir parametros infdefinidos haciendo uso de la palabra "args", guardandolos en una tupla # def arg_indeterminados(*args): # for arg in args: # print(arg) # arg_indeterminados(1,"hola",[1,2,3]) #una numero indeterminado de argumentos tambien puede ser guardado en un diccionario # def arg_indeterminados(*args,**kwargs): # print(args,kwargs) # arg_indeterminados(1,"hola",[1,2,3],n=1,s="hola",l=[1,2,3]) #factorial # def factorial(n): # if n==1 or n==0 : # return 1 # else: # return n*factorial(n-1) # num=int(input("ingrese el numero a encontrar su factorial:")) # print(factorial(num)) #------------------------------------------------------funciones integradoras c="esto es una texto" + str(10) + str(2.333) #convierte de decimal a binario binario=bin(9) #convierte de decimal a hexadecimal hexa=hex(21) #convierte de una base a decimal # print(int('1110', 2)) # print(int('0XA', 16)) #encuentra el valor absoluto #print(abs(-4)) import math #Return the ceiling of x as a float, the smallest integer value greater than or equal to x. #print(math.ceil(3.33)) #Return x factorial. Raises ValueError if x is not integral or is negative. #print(math.factorial(5)) #Return the floor of x as a float, the largest integer value less than or equal to x. #print(math.floor(5.99)) #si se pone el tipo "global" antes de una variable en una funcion, significa que le haremos referencia #a una variable fuera de la funcion, pasando asi su valor por referencia def ordenar(lista): lpar=[] limpar=[] for elemento in lista: if elemento%2 == 0: lpar.append(elemento) else: limpar.append(elemento) return lpar,limpar l1,l2=ordenar([1,2,3,4,5,6,7,8,9]) print(l1) print(l2)
false
9989ef6fe66bb2e266a7433e22341a2f696aa65a
IanRiceDev/Age-program
/Age.py
1,501
4.375
4
# Gets time import datetime # Getting and storing user age from user strInputDate = input("Enter your year of birth:") # Variable for testing if the user input is a number boolTestDigit = strInputDate.isdigit() # A loop to test if the input is a number and print to it to screen while True: # if false will print tell user the the input was a invalid if boolTestDigit is False: print("\n") print("That is an invalid number") break # if true will enter if block if boolTestDigit is True: # Variable for turning user input string into a integer intUserBirth = int(strInputDate) # Variable for getting current year on computer intYear = int(datetime.datetime.now().year) # Tests if user input is more then the current year if true if intUserBirth > intYear: # Tells user to enter number that is less then the current date print("\n") print("Plese enter a number that is less then the current date") break #Variable sets final print message by subtracting year by user input intUserAge = intYear - intUserBirth #Takes user input and turns it to string and prints the users age to screen strUserPrint = str(intUserAge) print("\n") print("Your age is " + strUserPrint) break #Uses input() method to pause program input()
true
7527515d7c479f2e50e1d27ddb301a6b227068c7
bkoehler2016/cs-module-project-algorithms
/product_of_all_other_numbers/product_of_all_other_numbers.py
1,046
4.15625
4
''' Input: a List of integers Returns: a List of integers ''' def product_of_all_other_numbers(arr): # Your code here index = 0 # make a copy of the arr passed in copy_arr = [arr[i] for i in range(0, len(arr))] while index < len(arr): product = 1 # loop through the copy array for i in range(0, len(copy_arr)): # skip over the index that is in line with the copied array if index == i: continue # multiply it product *= copy_arr[i] # set that index in the array to the product of all other indicies arr[index] = product index += 1 return arr if __name__ == '__main__': # Use the main function to test your implementation # arr = [1, 2, 3, 4, 5] arr = [2, 6, 9, 8, 2, 2, 9, 10, 7, 4, 7, 1, 9, 5, 9, 1, 8, 1, 8, 6, 2, 6, 4, 8, 9, 5, 4, 9, 10, 3, 9, 1, 9, 2, 6, 8, 5, 5, 4, 7, 7, 5, 8, 1, 6, 5, 1, 7, 7, 8] print(f"Output of product_of_all_other_numbers: {product_of_all_other_numbers(arr)}")
true
206c78f05513318682072eee2171b1d3f08e2dea
CodewithOs/pythonwithOs
/Python Basica.py
1,052
4.3125
4
#Exercise 1 print ("Hello World") print ("How are you?") #Exercise 2 #You can assign the input tag to a variable to a #variable so you don't need to keep reusing it whatIsYourName = "What is your name? " name = input(whatIsYourName) name2 = input(whatIsYourName) print ("Hello " + name + "! How are you?") print("Hello " + name2 +"! How are you?") #Exercise 3 a = 3 - 4 + 10 b = 5 * 6 c = 7.0/8.0 print ("These are the values:", a, b, c) print ("Increment", a, "by one: ") a = a + 1 print (a) print ("The sum of", a, "and", b, "is") d = a + b print (d) number = int( input("Input a number ") ) r = number * 2 print ("your number times 2 is", r) number = int(input("Input a number ")) number2 = (((number + 3) * 2) - 4) - 2 * number + 3 print(number2) #additional tasks 1 length = int(input("Input a number ")) width = int(input("Input a number ")) print (length * width) #additional tasks 2 originalTemp = int(input("Input a temperature ")) print ((originalTemp * 1.8) + 32)
true
2ef7ecb39fbe5366fef6f3db0cf66db8e66aabc1
RafaelSerrate/C-digos-Python
/Exercicios/Aula 7 - exercicios/Exercicio 006.py
333
4.21875
4
num = int(input('Coloque um numero: ')) d = num * 2 t = num * 3 r = pow(num, 1/2) print('O dobro do numero {} é {}, \no triplo é {}, \ne sua raiz quadrada é {:.2f}.'.format(num, d, t, r)) print('\n') print('O dobro do numero {} é {}, \no triplo é {}, \ne sua raiz quadrada é {:.2f}.'.format(num, num*2, num*3, pow(num, 1/2)))
false
f877a00fc9a5df3f1bdffdf9a8924c64ac539388
RafaelSerrate/C-digos-Python
/Exercicios/Aula 12 - exercicios/Exercicio 037.py
634
4.15625
4
num = int(input('Coloque um numero inteiro: ')) while not num == int(num): input('Coloque um numero inteiro: ') print('1) Binário') print('2) Octal') print('3) Hexadecimal') conversor = int(input('Escolha um dos conversores acima: ')) while not conversor == 1 or not conversor == 2 or not conversor == 3: conversor = int(input('Escolha um dos conversores acima: ')) if conversor == 1: print('seu numero sera convertido em binario') elif conversor == 2: print('Seu numero sera convertido em octal') else: print('Seu numero sera convertido em hexadecimal') print('A conversao do seu número vai ser: {}'.format())
false
9351831011539b586054af8ed5fcc9c76dde2e53
johnnydotdev/practice
/2-3.py
674
4.15625
4
#!/usr/bin/python from classes.LinkedList import * linked_list = create_rand_list(15) # Implement an algorithm to delete a node in the middle of a singly linked list, # given only access to that node def delete_middle_node(node): node.value = node.next.value node.next = node.next.next return start = linked_list.head trail = linked_list.head interval = 0 while start.next != None: start = start.next if (interval == 2): trail = trail.next interval = 0 interval += 1 print("Random Linked List: " + str(linked_list)) print("Middle Node value: " + unicode(trail)) delete_middle_node(trail) print("New List: " + str(linked_list))
true
8c8a3176ed8f544966f0254f6f65255de5feffda
acharyasandeep/Lab_Works
/Lab_Works/DSA _Lab/Algorithms/newtonRaphson.py
773
4.1875
4
''' calculating square root using newton raphson method. f(x)=x^2-a(given number) f'(x)=2x we make a guess x then update the guess if f(x)!=0 update logic: x=x-f(x)/f'(x) ''' def improve(update, close, guess = 1): while not close(guess): guess = update(guess) return guess #basically x is guess here def approx_eq(x,y,tol=1e-15): return abs(x-y)<tol def newton_update(f,df): def update(x): return x - f(x)/df(x) return update def find_zero(f,df): def close_zero(x): return approx_eq(f(x),0) return improve(newton_update(f,df),close_zero) def square_root_newton(a): def f(x): return x*x - a def df(x): return 2*x return find_zero(f,df) print(square_root_newton(256))
true
479f18c1bf1ee787f501ccad79881604cfd03df3
RussellJi/algorithm
/PyAl/DC/max_square.py
1,217
4.28125
4
''' 问题描述:在一个给定了边长的长方形中,求可以将长方形等分的最大的正方形 解决思路: 小区域中满足条件的最大的正方形也是整个区域中满足条件的正方形; 分治,将整个区域划分为由以宽为边长的正方形组成的长方形,以及剩余部分的长方形; 递归求剩余长方形中的满足条件的正方形。 基准条件(跳出递归的条件):长和宽相等。 tip: list = [] list.append() [2,3].append() //error ''' def max_square(x): if x[0] == x[1]: return x[0] elif x[0] > x[1]: return max_square((x[0]-x[1]),x[1]) else: return max_square(((x[1]-x[0]),x[0])) def max_square2(x): if x[0] == x[1]: return x[0] elif x[0] > x[1]: list = [] list.append(x[0]-x[1]) list.append(x[1]) return max_square2(list) else: list = [] list.append(x[1]-x[0]) print("1:",list) list.append(x[0]) print("list:",list) return max_square2(list) tuple = (4,6) list = [640,1680] print(max_square2(list))
false
5be6d86900e5c18e524c02fae5583d74450f0b30
Alumet/Codingame
/Easy/Mars_Lander-Niveau_1.py
1,178
4.125
4
''' Author Alumet 2015 https://github.com/Alumet/Codingame ''' surface_n = int(input()) # the number of points used to draw the surface of Mars. for i in range(surface_n): # land_x: X coordinate of a surface point. (0 to 6999) # land_y: Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars. land_x, land_y = [int(j) for j in input().split()] # game loop while 1: # h_speed: the horizontal speed (in m/s), can be negative. # v_speed: the vertical speed (in m/s), can be negative. # fuel: the quantity of remaining fuel in liters. # rotate: the rotation angle in degrees (-90 to 90). # power: the thrust power (0 to 4). x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()] # rotate power. rotate is the desired rotation angle. power is the desired thrust power. if y>2500: print(rotate,power) else: if v_speed<-20 and power<4: power+=1 print(rotate,power) elif v_speed>-20 and power>0: power-=1 print(rotate,power) else: print(rotate,power)
true
f34308978046f79cd3a0ef3f71c70e80fef77c1c
Eeswar21/Python-Programs
/area_calculation.py
1,269
4.5
4
#Find the area of rectangle, square, circle and triangle from math import pi print("Area calculation") def rectangle_area(): '''this function is for finding area of rectangle''' length=float(input("Enter the length value : ")) breadth=float(input("Enter the breadth value : ")) area = length * breadth print('Area of Rectangle: %0.2f\n' %(area)) def square_area(): '''this function is for finding area of square''' side=float(input("Enter the side value : ")) area = side*side print('Area of Square: %0.2f\n' %(area)) def circle_area(): '''this function is for finding area of circle''' radius=float(input("Enter the radius value : ")) area = pi * radius**2 print('Area of Circle: %0.2f\n' %(area)) def triangle_area(): '''this function is for finding area of triangle''' base=float(input("Enter the base value : ")) height=float(input("Enter the height value : ")) area = 1/2 * base * height print('Area of Triangle: %0.2f\n' %(area)) while True: print("1.Rectangle\n2.Square\n3.Circle\n4.Triangle\n5.Quit\n") choice = int(input("Choose your option : ")) if choice==1: rectangle_area() elif choice==2: square_area() elif choice==3: circle_area() elif choice==4: triangle_area() else: break
true
2a85c724e4fe49a07af7971b844915940b611e89
Eeswar21/Python-Programs
/factorial.py
255
4.3125
4
#Find the factorial value of the given number print("Factorial") print("---------") def factorial(n): if n<1: return 1 else: return n*factorial(n-1) number = int(input("Enter the number : ")) print(factorial(number))
true
352797165e90cc35e15f071da18d38415ad942b1
nicaibuzhao/day05
/10-公共的运算符和公共的关键字.py
302
4.15625
4
# 练习1: + 完成两个列表的合并 list1 = [1,2,3,4] list2 = [5,6,7,8] print(list1 + list2) # 练习2: * 完成字符串的数据复制成3份 print("你猜" * 3) # 练习3:使用in判断字典中是否有张三这个值 if "张三" in list1: print("存在") else: print("不存在")
false
7524367129551bc3a20aeb849ebd5b7842f9cca7
manuchzhua/Geekbrains
/lesson_3/dz3_02.py
1,019
4.40625
4
""" 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. """ def data_user(name, last_name, year_of_birth, city, email, tel): print( f"Имя:{name} Фамилия:{last_name} Год рождения:{year_of_birth} Год рождения:{city} Email:{email} Телефон:{tel}" ) m = [ input("Имя: "), input("Фамилия: "), input("Год рождения: "), input("Город проживания: "), input("Email: "), input("Телефон: ") ] data_user(name=m[0], last_name=m[1], year_of_birth=m[2], city=m[3], email=m[4], tel=m[5])
false
954c5abf0515b6d4f032b883d4a39771f023f8b9
NM20XX/Python
/Prime_number.py
1,010
4.1875
4
# A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number ########################################################################### #To determine if a number in prime or not num = int(input("Enter the number\n")) if num <= 1: print(str(num) + " is not a prime number") else: for i in range(2,num): if num%i == 0: print(str(num) + " is not a prime number") break else: print(str(num) + " is a prime number") ########################################################################### #To print all prime numbers in an interval: lower_limit = int(input("Enter the lower limit\n")) upper_limit = int(input("Enter the upper limit\n")) prime_list = [] for i in range(lower_limit, upper_limit+1): for num in range(2, i): if i % num == 0: break else: if i > 1: prime_list.append(i) print(prime_list)
true
03a07706818d574810ec935db21181a04033a556
thanhtungittlu/PythonTutorial
/05_tuple.py
1,595
4.25
4
# Được sắp xếp theo thứ tự và không thể thay đổi, được viết bằng dấu ngoặc tròn mytuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) onetuple = ("apple",) # khi khai báo tuple duy nhất 1 phần tư thì cần thêm dấu phẩy cuối cùng print(type(onetuple)) # tuple không thể thay đổi, nên khi muốn thay đổi thì thể convert sang list rồi thay đổi, sau đó convert lại tuple x = ("apple", "banana", "cherry") y = list(x) # convert to list y[1] = "kiwi" x = tuple(y) print(x) thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) #cách 2: thêm tuple và 1 tuple khác thistuple = ("apple", "banana", "cherry") y = ("orange",) thistuple += y print(thistuple) fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits #unpack Số lượng biến phải bằng với số lượng phần tử của tuple print(green) print(yellow) print(red) #nếu ít hơn có thể dùng dấu * ở biến cuối cùng để hiện thị dưới dạng danh sách: #(green, yellow*) = fruits # Nếu * ở giữa fruits = ("apple", "mango", "papaya", "pineapple", "cherry") (green, *tropic, red) = fruits print(green) print(tropic) print(red) fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 print(mytuple) thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) x = thistuple.count(5)# Đếm số lần xuất hiện y = thistuple.index(8) #trả về index đầu tiền xuất hiện 8 print(x) print(y)
false
38165a62d836584de0031572a7d41d4b5a1bf771
YanaNina/Stanford-CS106A
/Assignment2/khansole_academy.py
1,023
4.21875
4
""" File: khansole_academy.py ------------------------- Good practice adding two 2-digit integers """ import random MIN_NUMBER = 10 MAX_NUMBER = 99 CORRECT_IN_A_ROW = 3 def khan_academy(): corr_num = 0 while corr_num < CORRECT_IN_A_ROW: # looping until which 3 corrections num1 = random.randint(MIN_NUMBER, MAX_NUMBER) num2 = random.randint(MIN_NUMBER, MAX_NUMBER) print("What is " + str(num1) + " + " + str(num2) + "?") user_answer = int(input("Your answer: ")) right_answer = num1 + num2 if user_answer == right_answer: corr_num += 1 print("Correct! You've gotten " + str(corr_num) + " correct in a row.") else: corr_num = 0 print("Incorrect. The expected answer is " + str(right_answer)) print("Congratulations! You mastered addition.") def main(): khan_academy() # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
e9c1363c2956e0bdd52ba53d1730b74b910ac7a5
vijgan/HackerRank
/Sort/insertion_sort1.py
699
4.15625
4
#!/usr/bin/python import sys import string def insertion_sort_1(elements,length): insert_elem=int(elements[-1]) for i in range(len(elements)-2,-1,-1): if int(elements[i])>insert_elem: elements[i+1]=elements[i] print (''.join(str(elem)+' ' for elem in elements)) else: elements[i+1]=insert_elem print (''.join(str(elem)+' ' for elem in elements)) break if insert_elem not in elements: elements[0]=insert_elem print (''.join(str(elem)+' ' for elem in elements)) length=int(input()) elements=list(input().split()) elements=[int(x) for x in elements] insertion_sort_1(elements,length)
true
2b66437ddccb24d8085d504142378c34f2cc7cae
TheYk98/DataStructuresAndAlgorithms
/Linear DS/arrays.py
892
4.15625
4
''' Arrays are sequential ds they are allocated with contiguous memory blocks you can simply use the implementation below as * Stack * Queue ''' # this is how we declare in python arr=[] arr= [1,2,3,4,5] # index 0 1 2 3 4 ''' # STACK * PUSH visual idx | 7 | <- 3 (newly pushed) ----- | 8 | <- 2 ----- | 6 | <- 1 ----- | 5 | <- 0 ----- * POP | 8 | <- 2 ----- | 6 | <- 1 ----- | 5 | <- 0 ----- | 7 | <- 3 (popped elem) ----- Stack follows LIFO. Last In First Out - Think of plates stacked on top of each other . You'd always pick the topmost plate ''' n = int(input()) plates = [] # push for _ in range(n): plate = int(input()) print("Plate {} is pushed".format(plate)) plates.append(plate) # pop for _ in range(n): removedPlate = plates.pop(-1) print("Plate {} is popped remaining plate {}".format(removedPlate,plates))
true