blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0a9b497336921b58e470654e06fb4e4275f9b7ea | bishalbar77/Python-Bootcamp | /class-13.py | 1,273 | 4.40625 | 4 | # import turtle
# turtle.
from turtle import *
# from <Package_name> import <what_functions_you_need>
marker = Turtle()
# Create a object from Turtle class
# Screen operations
window = Screen()
# Create a object from Screen class
window.title("My Turtle Project")
# To change window title
# This is how we make an object
marker.shape('turtle')
# To change the of marker
# Some shapes :- 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'
marker.turtlesize(1)
# To increase the size of marker by some percent
marker.speed(1)
marker.color("#EEEEEE")
# To change the speed if the marker
# 'fastest' : 0
# 'fast' : 10
# 'normal' : 6
# 'slow' : 3
# 'slowest' : 1
marker.color("yellow")
marker.begin_fill()
marker.forward(100)
# To move the marker in forward direction
marker.left(90)
# To move the marker angle to left by 90
marker.forward(100)
marker.left(90)
marker.forward(100)
marker.left(90)
marker.forward(100)
marker.left(90)
marker.end_fill()
marker.color("#ADD8E6")
marker.begin_fill()
# Next bottom sqaure
marker.forward(100)
marker.right(90)
marker.forward(100)
marker.right(90)
marker.forward(100)
marker.right(90)
marker.forward(100)
marker.right(90)
marker.end_fill()
window.bgcolor("green")
# To change the background color
done() | true |
06f66d901babcbf520d43cda056623ed328822e1 | jankeromnes/Python-Calc | /algeb/median.py | 471 | 4.21875 | 4 | def median3():
numbers1 = input("What numbers are we finding the median of?: ")
numbers1 = numbers1.split(",")
num = []
for i in numbers1:
i = float(i)
n = num.append(i)
n1 = num.sort()
z = len(num)
if z % 2 == 0:
median1 = num[z//2]
median2 = num[z//2-1]
median = (median1 + median2)/2
else:
median = num[z//2]
median = float(median)
print(f"The Median is: {median}")
median3()
| false |
4acfbaefecbe304c2cc727276d7777c4ae3e73a1 | jankeromnes/Python-Calc | /misc/gpa.py | 1,267 | 4.25 | 4 | values = {
"A+": 4.33,
"A": 4.0,
"A-": 3.7,
"B+": 3.33,
"B": 3,
"B-": 2.7,
"C+": 2.33,
"C": 2.0,
"C-": 1.7,
"D+": 1.33,
"D": 1,
"D-": 0.7,
"F": 0,
}
def gpa():
c = 0
while c == 0: # For the infinite loop
x = int(input('How grades do you have?: ')) # This sets a limit
x = x - 1 # this is to account for the computers understanding that 0 is included in the number's value
r = [] # helps maintain the limit
while len(r) <= x: # same with this one
m = input('Input a grade: ').upper()
if m in values: # if the grade input by the user is n the table it adds that corresponding value to the list
r.append(values[m])
else:
print('Sorry yum must have mistyped something. Please try again :(')
sum_of_num = sum(r) # the equation for gpa is sum/length this takes the sum of the list we made and stores it in a variable
length = len(r) # this takes the length of the list and once again stores it in a variable
gpa = sum_of_num / length # this is the actual equ
print(f'Your gpa is {gpa}')
break
gpa()
| true |
ed4f00e8ba45bbb96633644f8bbd7c0490801450 | HenryXin/PythonExamples | /tests/collatz.py | 486 | 4.21875 | 4 | #!/usr/bin/env python3
def collatz(Number):
if Number%2 == 0:
print(Number//2)
return Number//2
else:
print(Number*3+1)
return Number*3+1
if __name__ == '__main__':
print("Please input a number:")
try:
NewNumber = int(input())
except ValueError:
print("You have to input an integeter number")
else:
NewNumber = collatz(NewNumber)
while NewNumber != 1:
NewNumber = collatz(NewNumber)
| true |
39a2026c54502ea4511574beac9b8056a2c89349 | KamalDGRT/Hackerrank_Problems | /Week_01/Question_01/question_01.py | 476 | 4.1875 | 4 | #!/bin/python3
# Staircase Problem
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
steps = n - 1
charcount = 1
while steps >= 0:
for space in range(steps):
print(' ', end='')
for number in range(charcount):
print('#', end='')
print('')
steps -= 1
charcount += 1
if __name__ == '__main__':
n = int(input())
staircase(n)
| true |
5fca4884de84a5123196f9dceec5ebc837bc7eb1 | hannahkwong/lps_compsci | /multiples.py | 386 | 4.1875 | 4 | print("For what number would you like multiples?")
my_num = int(raw_input())
num = 0
multiples = float(my_num * num)
while multiples < 1000:
print(str(num) + " " + "times" + " " + str(my_num) + " " + "equals" + " " + str(multiples))
num = num + 1
multiples = float(my_num * num)
print("Those are all of the multiples of" + " " + str(my_num) + ", thank you for existing!")
| true |
c01b69a5dc58f5068b38c4a0e03f9b7b76d24686 | ikramsalim/chatbots | /chatbots-101/adding-variety.py | 1,462 | 4.3125 | 4 | """
Great job! Adding some variety makes your bot much more fun to talk to. Now, hit 'Run Code' and use send_message()
(which utilizes the new respond() function) to ask the bot "what's your name?" 3 times.
"""
# Import the random module
import random
name = "Greg"
weather = "cloudy"
# Define a dictionary containing a list of responses for each message
responses = {
"what's your name?": [
"my name is {0}".format(name),
"they call me {0}".format(name),
"I go by {0}".format(name)
],
"what's today's weather?": [
"the weather is {0}".format(weather),
"it's {0} today".format(weather)
],
"default": ["default message"]
}
# Use random.choice() to choose a matching response
def respond(message):
if message in responses:
bot_message = random.choice(responses[message])
else:
bot_message = random.choice(responses["default"])
return bot_message
"""
ELIZA
"""
import random
def respond(message):
# Check for a question mark
if message.endswith("?"):
# Return a random question
return random.choice(responses["question"])
# Return a random statement
return random.choice(responses["statement"])
# Send messages ending in a question mark
send_message("what's today's weather?")
send_message("what's today's weather?")
# Send messages which don't end with a question mark
send_message("I love building chatbots")
send_message("I love building chatbots")
| true |
d0ab10f37476540cad14b085dba3c648350b7fb1 | fmillerwork/TutoratPython | /Codes/RecapIF.py | 1,670 | 4.34375 | 4 | print("\n-----------if-----------")
print("introduction :")
a = eval(input("a = "))
b = eval(input("b = "))
if a < b :
print("a < b")
elif a == b: #Python ne regarde la condition d'un elif que si aucune condition d'un if ou elif situé au dessus n'a été Vraie.
print("a = b")
else : # => elif a > b
print("a > b")
print("\nelif VS if :")
a = 2
b = 6
if a != b :
print("a != b")
elif a < b : #on n'entre pas dans ce elif car la condition du if au dessus est vraie (True)
print("elif")
if a < b :
print("if")
print("\nOpérateurs :")
print("Opérateurs de comparaison possibles :", "<", ">", "<=", ">=", "== (égal à ...) | attention à la confusion avec =", "!= (différent de ...)", sep="\n\t")
print("Opérateurs supplémentaires :", "and (ET logique : toutes les conditions doivent être vraies)", "or (OU logique => 'et/ou' : au moins 1 condition doit être vraie)", "not (négation de la condition)", sep="\n\t")
a = 5
b = 8
nb = eval(input("nb = "))
if nb < b and nb > a:
print("a < nb < b (and)")
if nb < b or nb > a:
print("nb < b OU nb > a OU a < nb < b (or)")
if nb < b and nb > a or nb == 10: # => if (nb < b and nb > a) or nb == 10 Les and sont traités avant les or. Donc si besoin de traiter les or en premier, il faut mettre des parenthèses (comme pour les calculs). Dans le doute, toujours parenthèser, c'est plus clair.
print("a < nb < b OU nb = 10")
print("\nType booléen (boolean en anglais) :")
a = True #ON, 1, vrai, ...
b = False #OFF, 0, faux, ...
if a: # if a == True
print("a est Vrai")
else:
print("a est Faux")
if b: # if b == True
print("b est Vrai")
else:
print("b est Faux") | false |
6a413102db054443e4fb9ed5d344016b956c7d0f | anatekar/Programming-Samples | /Python/samples_from_tutorials/week2/program_15.py | 739 | 4.3125 | 4 | # pylint: disable=C0103
'''
Program to reverse/inverse a dictionary
'''
def inverse_key_values(original_dict):
''' Function to inverse key:value pairs of a dictionary'''
new_dict = {}
keys = original_dict.keys()
values = original_dict.values()
num_items = 0
for value in values:
new_dict[value] = keys[num_items]
num_items += 1
return new_dict
def inverse_key_values_using_zip(original_dict):
''' Function to inverse key:value pairs of a dictionary'''
keys = original_dict.keys()
values = original_dict.values()
return dict(zip(values,keys))
d = {1:'a', 2:'b', 3:'b'}
print 'Original dictionary is : ', d
print 'Inverse dictionary is :', inverse_key_values_using_zip(d)
| true |
f8d29879cfdc60e06a60244c38c9263700319b73 | jibon969/Python-Problem-Solving | /Math/06-calculate-surface-volume.py | 524 | 4.1875 | 4 |
"""
Write a Python program to calculate surface volume and area of a sphere
একটি গোলকের পৃষ্ঠের পরিমাণ এবং ক্ষেত্রফল গণনা করুন /
Formula :
1. The area of a sphere is A = 4*π*r2
2. radius of the sphere V = 4/3*π*r3
"""
import math
pi = math.pi
radian = float(input("Enter Radius of sphere : "))
sur_area = 4 * pi * radian **2
volume = (4/3) * (pi * radian ** 3)
print("Surface Area is :", sur_area)
print("Volume is : ", volume)
| false |
d531eb603436f7f361ee7bec3b2a27b57226f21c | Studies-Alison-Juliano/geek_university_curso_python | /pep3.8/argumentos_somente_posicionais.pyi | 919 | 4.15625 | 4 | """
Argumentos Somente Posicionais
"""
# valor = "67.7"
# print(float(valor))
"""
def cumprimenta(nome):
return f"Olá {nome}"
print(cumprimenta("Geek"))
print(cumprimenta(nome="Geek"))
"""
"""
def cumprimenta_v2(nome, /):
return f"Olá {nome}"
print(cumprimenta_v2("Geek"))
print(cumprimenta_v2(nome="Geek"))
"""
"""
def cumprimenta_v3(nome, /, mensagem="Olá"):
return f"{mensagem} {nome}"
print(cumprimenta_v3("Geek"))
print(cumprimenta_v3("University", mensagem="Helo"))
print(cumprimenta_v3("University", "Bem-Vinda"))
print(cumprimenta_v3("University", nome="Teste"))
"""
"""
def cumprimenta_v4(*, nome):
return f"Olá {nome}"
print(cumprimenta_v4(nome="Alison"))
print(cumprimenta_v4("Alison"))
"""
def cumprimentar_v5(nome, /, mensagem="Olá", *, mensagem2):
return f"{mensagem} {nome} {mensagem2}"
print(cumprimentar_v5("Geek", mensagem="Heelo", mensagem2="tenha um bom dia"))
| false |
0a20d6916b42df1f0ecf10ae28d1bc2bf7d59d06 | Studies-Alison-Juliano/geek_university_curso_python | /secao4_variaveis_e_tipos_de_dados/escopo_variaveis.py | 820 | 4.4375 | 4 | """
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais
- Variáveis globais sao reconhecidas, ou seja, se o escopo compreende todo o programa
2 - Variáveis locais
- São reconhecidas apenas nos blocos onde foram declaradas, ou seja, seu escopo está limitado
ao bloco onde foi declarada.
Para declarar variáveis em python, fazemos:
nome_da_variavel = valor_da_variavel
Python é uma linguagem de tipagem dinâmica. Isso significa que ao declararmos uma variável nos não colocamos
o tipo de dado dela. Esse tipo é inferido ao atribuirmos o valor a mesma
Exemplo em java:
int numero = 42;
"""
numero = 41
print(numero)
print(type(numero))
if numero < 42:
novo = numero + 10 # A variável 'novo' está declarada localmente dentro do bloco IF, por tanto é local
print(novo)
| false |
1f7c35f01d30ca5062ab83930c12f10a75bdcdb4 | Studies-Alison-Juliano/geek_university_curso_python | /secao3_introducao_a_linguagem/pep8.py | 1,914 | 4.15625 | 4 | """
PEP8 - Python Enhancement Proposal
São propostas de melhorias para a linguagem python
A ideia da PEP8 é para que possamos escrever codígos pythonicos.
[1] Utilize camel case para nome de classes.
class Calculadora:
pass
class CalculadoraCientifica:
pass
[2] Utilizar nomes em minúsculo, separados por underline para funções e variáveis.
def soma():
pass
def soma_dois():
pass
numero = 4
numero_impar = 4
[3] Utilize 4 espaços para indentação! (Não utilize tab)
if 'a' in 'banana':
print('tem')
[4] Linhas em branco (Parágrafos em branco)
-Separar funções e definições da classe com 2 parágrafos (2 linhas em branco)
-Métodos dentro de uma classe devem ser separados por apenas 1 parágrafo
[5] Imports:
-Imports devem sempre ser feitos em linhas separadas:
# Import errado
import sys, os
# Import certo
import sys
import os
# Não há problemas em utilizar:
from types import StringType, ListType
# Caso tenha muitos imports de um mesmo pacote, recomenda-se:
from types import (
StringType,
ListType,
SetType,
outrotype
)
# Imports devem ser sempre colocados no topo do arquivo, logo depois de quaisquer comentários ou docstrings
# e antes de constantes ou variáveis globais.
[6] Espaços em instruções e expressões:
# Não correto:
spam( ham[ 1 ], { eggs: 2 } )
algo (1)
# Correto
spam(ham[1], {eggs: 2})
algo(1)
[7] Termine sempre uma instrução com uma nova linha
"""
| false |
3c45ae9e7e16ff5ac033e0123403174be05903be | Studies-Alison-Juliano/geek_university_curso_python | /secao8_funcoes/args.py | 2,846 | 4.375 | 4 | """
Entendendo o *args
- O *args é um parâmetro como outro qualquer. Isso significa que você podera chamar de qualquer coisa, desde que comece
com * (asterisco)
Exemplo:
*xis
Mas por convenção, utilizamos o *args para defini-lo
O que é o *args
O parâmetro *args utilizado em uma função, coloca os valores extras informados como entrada em uma tupla. Então desde ja
lembre-se que tuplas são imutaveis
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Exemplo
def soma_todos_numeros(num1=1, num2=2, num3=3, num4=4):
return num1 + num2 + num3
print(soma_todos_numeros(4, 6, 9))
print(soma_todos_numeros(4, 6))
print(soma_todos_numeros(4, 6, 9, 10))
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Entendendo o *args
def soma_todos_numeros(nome, sobrenome, *args):
return sum(args)
print(soma_todos_numeros('Angelina', 'Jolie'))
print(soma_todos_numeros('Angelina', 'Jolie', 1))
print(soma_todos_numeros('Angelina', 'Jolie', 1, 2))
print(soma_todos_numeros('Angelina', 'Jolie', 1, 2, 3))
print(soma_todos_numeros('Angelina', 'Jolie', 1, 2, 3, 4))
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Outro exemplo de utilização de *args
def verifica_info(*args):
if 'Geek' in args and 'University' in args:
return 'Bem Vindo Geek'
return 'Eu não tenho certeza de quem você é'
print(verifica_info())
print(verifica_info(1, True, 'University', 'Geek'))
print(verifica_info(1, 'University', 3.145))
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
"""
def soma_todos_numeros(*args):
return sum(args)
# print(soma_todos_numeros())
# print(soma_todos_numeros(3, 4, 5, 6))
lista = [1, 2, 3, 4, 5]
# Desempacotador
print(soma_todos_numeros(*lista))
# OBS: O *(asterisco) serve para que informemos ao Python que estamos passando como argumento uma coleção de dados.
# Desta forma ele saberá quer precisará desempacotar os dados
| false |
5137b04443442223d62a780f0e4404f5d365ba56 | Studies-Alison-Juliano/geek_university_curso_python | /secao4_variaveis_e_tipos_de_dados/string_cursso.py | 933 | 4.125 | 4 | """
Tipo String
Em Python, um dado é considerado String sempre que:
-Estiver entre aspas simples => 'uma string', '234', 'a', 'True', '43.3'
-Estiver entre aspas duplas => "
-Estiver entre aspas simples triples => '''
-Estiver entre aspas duplas triplas =>
nome = 'Angelina \nJolie' # \n no caso está pulando uma linha
print(nome)
print(type(nome))
nome = "Angelina \" Jolie" # '\' character de escape
print(nome)
print(type(nome))
nome = "Angelina Jolie"
print(nome)
print(nome.split()) # Transforma em uma lista de strings
# [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
# ['A', 'n', 'g', 'e', 'l', 'i', 'n', 'a', ' ', 'J', 'o', 'l', 'i', 'e']
nome = "Angelina Jolie"
print(nome[0:8]) # Slice de string
# [ 0 , 1 ]
# ['Angelina', 'Jolie']
print(nome.split()[0])
"""
nome = 'Angelina Jolie'
"""
::-1 -> comece do primeiro elemento, vá ate o ultimo elemento e inverta
"""
print(nome[::-1]) # Inverssão da string
| false |
6ae80e0bb445351a31a58117d60334f3ddbf8fd7 | Studies-Alison-Juliano/geek_university_curso_python | /secao10_expressões_lambdas_e_funções_Integradas/min_e_max.py | 1,927 | 4.3125 | 4 | """
Min e Max
max() -> Retorna o maior valor de um iterável ou o maior de dois ou mais elementos.
# Exemplos
lista = [1, 8, 4, 99, 35, 129]
print(max(lista)) # 129
tupla = (1, 8, 4, 99, 35, 129)
print(max(lista)) # 129
set = {1, 8, 4, 99, 35, 129}
print(max(set)) # 129
dicionario = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 35, 'f': 129}
print(max(dicionario.values())) # 129
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Faça um programa que receba doi valores do usuário e mostre o maior
val1 = int(input('n :'))
val2 = int(input('n2 :'))
print(max(val1, val2))
print(max(4, 67, 82)) # 82
print(max('a', 'ab', 'abc')) # abc
print(max('a', 'b', 'c', 'g')) # g
print(max(3.145, 5.789)) # 5.789
print(max('Geek University')) # y
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
min() -> Retorna o menor valor em um iterável ou o menor de dois ou mais elementos
{ mesma coisa que max() só que o inverso }
# Outros exemplos
nomes = ['Arya', 'Simom', 'Dora', 'Tim', 'Olivander']
print(max(nomes)) # Tim
print(min(nomes)) # Arya
print(max(nomes, key=lambda nome: len(nome))) # Olivander
print(min(nomes, key=lambda nome: len(nome))) # Tim
"""
musicas = [
{'titulo': 'Thunderstruck', 'tocou': 3},
{'titulo': 'Dead Skin Mask', 'tocou': 2},
{'titulo': 'Back in Black', 'tocou': 4},
{'titulo': 'Too old to rock, to yong to die', 'tocou': 32}
]
print(max(musicas, key=lambda musica: musica['tocou']))
print(min(musicas, key=lambda musica: musica['tocou']))
# DESAFIO!
print(max(musicas, key=lambda musica: musica['tocou'])['titulo'])
print(min(musicas, key=lambda musica: musica['tocou'])['titulo'])
| false |
90eeeb83afbaeab4e445e92fe6c3478fb76f8416 | Codex-Mayrie/Password-Locker | /user.py | 1,203 | 4.15625 | 4 | import pyperclip
# from user import User
class User:
"""
This is a User class that creates new instances of other users
"""
user_details= []
def __init__(self, first_name, second_name, password):
self.first_name= first_name
self.second_name= second_name
self.password= password
#saving user details
def save_user(self):
"""
A save method that saves the details of the user
"""
User.user_details.append(self)
#deleting user's account
def delete_account(self):
"""
A delete method that tries to check whether the user's account is deletable
"""
self.user_details.remove(self)
#finding user by firstname
@classmethod
def find_by_first_name(cls,first_name):
"""
A method that finds the user using their first name
Args:
user: user to search for
returns:
Name of the user searched for
"""
for user in cls.user_details:
if user.first_name == first_name:
return user
#displaying user
@classmethod
def display_user(cls):
"""
A function that displays the user
"""
return cls.user_details
| true |
8125c497535e30cc1ceb121942c7433b8449edf8 | Eliah7/Practice-Python | /Recursion/reverse_list.py | 274 | 4.25 | 4 | """This function reverses the list given recursively """
def reverse_list(the_list):
if len(the_list) == 1: # Base case
return(the_list)
else:
return(reverse_list(the_list[1:]) + [the_list[0]])
print(reverse_list([1,2,3,4,5,6,7,8,9,10,11]))
| true |
e04fa0e1a0782f0e36ee7f1cce3a4d7b4627bf92 | Meowu/data-structures-and-algorithms-in-python | /Object-Orient Programming/hierarchy_of_numeric_progressions.py | 2,111 | 4.28125 | 4 | #!/usr/env/bin python3
class Progression:
"""Iterator producing a generic progression.
Default iterator produces the whole numbers 0, 1, 2...
"""
def __init__(self, start=0):
"""Initialize current to the first value of the progression."""
self._current = start
def _advance(self):
"""Update self._current to a new value.
This should be overridden by a subclass to customize progression.
By convention, if current is set to None, this designates the end of a finite progression.
"""
self._current += 1
def __next__(self):
"""Return the next element or else raise StopIteration error."""
if self._current is None:
raise StopIteration()
else:
answer = self._current
self._advance() # advance to prepare for next time
return answer
def __iter__(self):
return self
def print_progression(self, n):
"""Print next n values of the progression."""
print(' '.join(str(next(self)) for j in range(n)))
def print_current(self):
"""Print the current"""
print(self._current)
class ArithmeticProgression(Progression):
def __init__(self, step=1, start=0):
super().__init__(start)
self._step = step
def _advance(self):
self._current += self._step
class GeometricProgression(Progression):
def __init__(self, base=2, start=1):
super().__init__(start)
self._base = base
def _advance(self):
self._current *= self._base
class FibonacciProgression(Progression):
def __init__(self, first=0, second=1):
super().__init__(first)
self._prev = second - first
def _advance(self):
self._prev, self._current = self._current, self._prev + self._current
if __name__ == "__main__":
print("exec progression: ")
pg = Progression()
print("first value: {0}".format(next(pg)))
print("next 9 value")
pg.print_progression(9)
pg.print_current()
fp = FibonacciProgression(0, 1)
print(str(next(fp)))
| true |
99cc57b4c457193aad5c0dd1630379a4e1b6cc3f | thanhsonlpc97/-i-u-ki-n-if-then-else | /BT1.py | 226 | 4.125 | 4 | score = int(input('Input score'))
if score >= 90:
print('Grade is A')
elif score >= 80:
print('Grade is B')
elif score >= 70:
print('Grade is C')
elif score >= 60:
print('Grade is D')
else: print('Grade is F')
| false |
9b5472a53b1a894707b9b2bdd98cc0589c30914b | shivakomat/PractisePython | /average_length_of_words.py | 377 | 4.28125 | 4 | list_of_words="What is the difference between coronavirus and COVID-19".split(' ')
print(list_of_words)
def lengths(list_of_words):
total_length=0
for word in list_of_words:
total_length = len(list(word)) + total_length
return total_length
number_of_letters = lengths(list_of_words)
number_of_words = len(list_of_words)
print(number_of_letters / number_of_words)
| true |
bb9959ef4ea3ddc05b3dc24ba0bd27b72fa2b3b1 | drreynolds/Math4315-codes | /CubicSplines/BackwardSubTri.py | 1,266 | 4.15625 | 4 | # BackwardSubTri.py
#
# Daniel R. Reynolds
# SMU Mathematics
# Math 4315
# imports
import numpy
def BackwardSubTri(U,y):
"""
usage: x = BackwardSubTri(U,y)
Row-oriented backward substitution to solve the upper-triangular, 'tridiagonal'
linear system
U x = y
This function does not ensure that U has the correct nonzero structure. It does,
however, attempt to catch the case where U is singular.
Inputs:
U - square n-by-n matrix (assumed upper triangular and 'tridiagonal')
y - right-hand side vector (n-by-1)
Outputs:
x - solution vector (n-by-1)
"""
# check inputs
m, n = numpy.shape(U)
if (m != n):
raise ValueError("BackwardSubTri error: matrix must be square")
p = numpy.size(y)
if (p != n):
raise ValueError("BackwardSubTri error: right-hand side vector has incorrect dimensions")
if (numpy.min(numpy.abs(numpy.diag(U))) < 100*numpy.finfo(float).eps):
raise ValueError("BackwardSubTri error: matrix is [close to] singular")
# create output vector
x = y.copy()
# perform forward-subsitution algorithm
for i in range(n-1,-1,-1):
if (i<n-1):
x[i] -= U[i,i+1]*x[i+1]
x[i] /= U[i,i]
return x
# end function
| true |
2b16a2a2c1a1f90da30863820858d0d04ab46295 | ellnika/PythonCourses | /Trainings/WebExercises/exercise2.py | 1,041 | 4.40625 | 4 | '''
Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
Hint: how does an even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).
If check divides evenly into num, tell that to the user. If not, print a different appropriate message.
'''
def odd_even():
number_one=int(input('Please enter any number '))
if number_one % 2 == 0:
print('The number you entered is even')
if number_one % 4 == 0:
print('the number is multiply of 4')
else:
print('The number you entered is odd')
#odd_even()
def number_check():
num=int(input('Enter first number '))
check=int(input('Enter second number'))
if check%num == 0:
print('first number dives by second')
else:
print('first number does not divide by second')
number_check()
| true |
375bbb71ee8ffb14112853b3bb7a803a9e2d58f0 | sowmiyashakthi/python-prgm | /beginner/power of n number.py | 245 | 4.53125 | 5 | number = int(input(" Enter the positive integer "))
exponent = int(input("Enter the exponent integer "))
power = 1
for i in range(1, exponent + 1):
power = power * number
print("result of {0} power {1} = {2}".format(number, exponent, power))
| true |
71efc1a293bf743efcc397e1f763524ad98e7aaa | dingweihua/PythonCertSpring | /schedule_speakers.py | 903 | 4.21875 | 4 | #! /usr/bin/env python
#
# This prorgram reads in a list of students from a file, and sorts them in
# random order
#
import sys
import random
import string
import csv
date_students = {0:"Oct 16th", 3:"Oct 23rd", 6:"Oct 30th", 9:"Nov 6th", \
12:"Nov 13th", 16:"Nov 20th", 20:"Nov 27th", 24:"Dec 4th",
28:"Dec 11th" }
filename = "Student_list.csv"
f = open(filename,"r")
raw_student_list = csv.reader(f, delimiter='\t', quotechar='"')
student_list = []
for a_line in raw_student_list:
# Column 0 is the student last name, Column 1 is the student first name
# student's name (last name first)
student_list.append( string.strip( a_line[0]+" "+a_line[1] ) )
random.shuffle( student_list, )
counter = 0
for n in student_list :
if counter in date_students.keys() :
print "----", date_students[counter]
counter += 1
print counter, n
print "----"
| true |
08bb986425e7ec1842f21516712928adace8f56f | dingweihua/PythonCertSpring | /week-03/code/decorators/p_wrapper_solution.py | 2,340 | 4.4375 | 4 | """
Python decorator example
simple decorator that turns any function that returns a string
into one that returns that string wrapped in the html <p> tag:
@p_wrapper
def func():
" simplest example possible"
return "this is the returned string"
func()
"""
# the simple decorator
def p_wrapper(func):
def function(*args, **kwargs):
result = func(*args, **kwargs)
return "<p>" + result + "</p>"
return function
# fancy one using a class:
# this lets you make a decorator with some custom input
# the argument to the __init__ sets what tag you want
# this creates a custom decorator
# the __call__ method is the decorator itself.
class tag_wrapper(object):
def __init__(self, tag='p' ):
"""
inititilze the decorator class with the tag you want
"""
self.open_tag = "<%s>"%tag
self.close_tag = "</%s>"%tag
def __call__(self, func, *args, **kwargs):
"""
The actual decorator function.
using lambda - 'cause why not?
"""
return lambda *args, **kwargs: self.open_tag + func(*args, **kwargs) + self.close_tag
# give it a try:
if __name__ == "__main__":
def func():
" simplest example possible"
return "this is the returned string"
print "the raw version"
print func()
# now add the decorator:
@p_wrapper
def func():
" simplest example possible"
return "this is the returned string"
print "the decorated version"
print func()
# try it with another function
@p_wrapper
def func2(x,y):
return "the sum of %s and %s is %s"%(x, y, x+y)
# call it:
print func2(3,4)
# and one with keyword arguments
@p_wrapper
def func2(x, y=4, z=2):
return "the sum of %s and %s and %s is %s"%(x, y, z, x+y+z)
# call it:
print func2(3)
print func2(3, 5)
print func2(3, 5, 7)
## and try the class version:
@tag_wrapper('h1')
def func2(x, y=4, z=2):
return "the sum of %s and %s and %s is %s"%(x, y, z, x+y+z)
print func2(3,4)
@tag_wrapper('div')
def func2(x, y=4, z=2):
return "the sum of %s and %s and %s is %s"%(x, y, z, x+y+z)
print func2(5,6,7)
| true |
821870fae54f1cf42e6d5d61c8b8a011b73dc05c | rayhond/projecteuler | /MultiplesOf3And5/MultiplesOf3And5.py | 239 | 4.1875 | 4 | #!/usr/bin/env python2
#Find the sum of all the multiples of 3 or 5 below 1000
# - Find multiples of 3 or 5 below 1000
sum = 0
for i in xrange(1000):
if ((i % 3)==0) or ((i % 5)==0):
print i
sum = sum + i
print sum
| true |
90c4267961255f41f53e4d9106532a1538fd7ec0 | AntonyXXu/Learning | /Python practice/LeetCode/dec-binary_Nums.py | 1,229 | 4.125 | 4 | # A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros.
# For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.
# Given a string n that represents a positive decimal integer,
# return the minimum number of positive deci-binary numbers needed so that they sum up to n.
# Example 1:
# Input: n = "32"
# Output: 3
# Explanation: 10 + 11 + 11 = 32
# Example 2:
# Input: n = "82734"
# Output: 8
# Example 3:
# Input: n = "27346209830709182346"
# Output: 9
n1 = "32"
n2 = "82734"
n3 = "27346209830709182346"
def deciBinary(arr):
max = 0
for i in range(len(arr)):
if max < int(arr[i]):
max = int(arr[i])
return max
def alternate(arr):
nums = [1]*len(arr)
lst = [int(i) for i in arr]
counter = 0
while True:
changes = False
for i in range(len(arr)):
if lst[i] == 0:
nums[i] = 0
if lst[i] > 0:
changes = True
lst[i] -= nums[i]
if not changes:
return counter
counter += 1
print(deciBinary(n1))
print(deciBinary(n3))
print(deciBinary(n2))
print(alternate(n1))
print(alternate(n3))
print(alternate(n2)) | true |
5f1b83efd53b917f88073d88f231769b72f0b13d | freebritneyspears/multichoicequiz | /v1/v1_assembled.py | 933 | 4.125 | 4 | #version one full
#Ask for name
def greet():
global name
while True:
name = input("Please enter your name: ")
if name.isalpha():
break
print("Enter a - z only")
greet()
print("you will be given 10 questions, and three options")
print("one of the options is correct")
print("for each question you get correct you will get one point")
#question 1
print("\nQuestion: 1|score:{}".format(score))
ans=input("What is the capital of New Zealand?\na.London\nb.Wellington\nc.Auckland \nYour answer: ").lower()
if ans == 'b' or ans == 'B' or ans == 'wellington' or ans == 'Wellington':
print("Correct")
score+=1
print("Your score is", score)
else:
print("Oops incorrect the correct answer is _____!")
if score <=0:
score = 0
print("Your score is", score)
print("final score is", score)
| true |
f25bf62406505e934b2c5cef9983b4b6bd190ce3 | sumitkjm/python-learning | /IfElse.py | 225 | 4.125 | 4 | if True:
print ("Manasvi is my daughter")
if 2>3:
print ("Dishu is very cute")
elif 1>5:
print("Manshu is very cute")
else:
print ("Manshu and Dishu both are very cute")
if not 20<10:
print("It worked") | true |
6eb808a2bfd20106fdf5baffc9e96edb015f835d | KevinAnd0/NLP-law | /Backend/NLPBackend/dbConnect.py | 1,956 | 4.15625 | 4 | import sqlite3
'''
Usage:
The class initializes a connection by default.
The class methods use this when you call the methods.
In the API, you define an object and connect to the database
through that object.
For example:
databasCon = Database()
databaseCon.get_all_rows_in_texts()
databaseCon.close()
(Always close the connection after use)
'''
'''
Methods:
- Text - table
get_all_rows_in_texts() - Gets all rows in the text field
get_text_by_id(id) - Gets text by id
- Keywords - table
get_all_keywords() - Gets all rows in keywords
get_specific_keyword(word) - Finds all posts with a specific word
'''
class Database:
def __init__(self):
self.db_name = "nlpdatabase.db"
self.connection = sqlite3.connect(self.db_name)
self.cur = self.connection.cursor()
def get_keywords_by_search(self, word):
results = []
self.cur.execute("SELECT * FROM keywords WHERE LOWER(keyword) LIKE ('%'||?||'%')", (word,))
rows = self.cur.fetchall()
for row in rows:
obj = {
self.cur.description[0][0]: row[0],
self.cur.description[1][0]: row[1]
}
results.append(obj)
return results
def get_texts_by_keywords(self, keyword):
results = None
self.cur.execute('''SELECT DISTINCT * FROM texts JOIN keywords, keywordsXtexts
ON texts.id = keywordsXtexts.texts AND keywords.id = keywordsXtexts.keywords
WHERE LOWER(keyword) LIKE ('%'||?||'%')''', (keyword,))
rows = self.cur.fetchall()
for row in rows:
results = {
self.cur.description[0][0]: row[0],
self.cur.description[1][0]: row[1],
self.cur.description[2][0]: row[2]
}
return results
def close(self):
self.connection.commit()
self.connection.close()
| true |
a5cf96ac89169261b34e8a14df052064c097b443 | sandhyachowdary/Python | /venv/Global Variable.py | 1,221 | 4.21875 | 4 | #Global Variable
#The variable which is declared inside the python file and outside the function or class are called as global variable
#The Global variable will get memory while running the program
# The scope of global variable is any where .It means we can use through at the python file and another python fine aslo
#Example
a = 100 # Global Variable
def show():
print("Hello")
b= 200 # Local Variable
print(a+b)
c = 300 #Global Variable
print(a+c)
show()
print(a+c)
print("-----------")
#Global and Local Variable
a = 300
def display():
a= 200
print(a)
print(a)
display()
print(a)
print("-----------")
#Declaring global variable inside a function
#To declare global variable inside a function we use "global" keyword
a = "sandhya" #Global Variable
def show():
print(a)
global b
b = 300
c = 400
print(b) #Global Variable
print(b+c) #Local Variable
print(a)
show()
print(a)
print(b)
print("---------")
#The global variable which is declared inside a function will get memory when function is called
#ex: modify global variable inside a function
a = 10
def display():
global a
a = 20
print(a)
print(a)
display()
print(a)
#parameters file after these
| true |
0f89f8a882c8ad8e1fe57622c5e882730fc6bb12 | sagarsitap596/python_learnings | /ListDemo.py | 1,241 | 4.125 | 4 |
#create empty list two ways
list1=[]
list2=list()
names=["aa","bb","cc","dd","dd"]
print(names)
#Added new value
names.append("ee")
print(names)
#delete value
del names[1]
#find count
names.count("dd")
#insert at specific position
names.insert(0,"zz")
print(names)
#get value at index
print(names[3])
lettesr_list=list("Welcome to python")
print(lettesr_list)
menu=[]
menu.append(["food1","food2"])
menu.append(["food1","food3"])
menu.append(["food5","food3","food4"])
menu.append("foo10")
for meal in menu:
if "food1" not in meal:
print(meal)
book_list=["book1","book2","book3","book4","book5"]
book_itr=iter(book_list)
for book in range(0,len(book_list)):
print(next(book_itr))
print("+"*30)
List_1=[2,6,7,8]
List_2=[2,6,7,8]
print(List_1[-2])
print(List_2[2])
print(List_1[-2] + List_2[2])
print("="*80)
# define a list
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
for item in my_iter:
print(item)
print("="*80)
list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma']
list2 = ['one', 'two', 'three']
test = zip(list1, list2) # zip the values
testList = list(test)
a, b = zip( *testList )
print('The first list was ', list(a));
print('The second list was ', list(b));
| true |
5bbcc35ef07cefb1e8ede2da5ce95085cbf89298 | agrawalshivam66/python | /lab2/q3.py | 420 | 4.34375 | 4 | sideA,sideB,sideC=eval(input("Enter three sides "))
if(sideA<sideB+sideC and sideB<sideA+sideC and sideC<sideB+sideA):
print("The triangle is valid ",end="")
if(sideA**2==sideB**2+sideC**2) or (sideB**2==sideA**2+sideC**2) or (sideC**2==sideB**2+sideA**2):
print("and form a Pythagorean Triplet")
else:
print("but do not form a pythagorean Triplet")
else:
print("Not a valid triangle")
| true |
7b148fc3d8cae15cf59c6a64577bb5383fd7e821 | carlosmspk/GitHubCopilotShowcase | /2-BouncingBall.py | 1,697 | 4.40625 | 4 | """
This program will simulate a bouncing ball, given initial position and velocity. The result will be printed as a plot in x and y
"""
import matplotlib.pyplot as plt
def simulate_bouncing_ball (x0, y0, vx0, vy0, steps, dt, coefficient_of_restitution = 0.2, g = 9.83) -> list:
""">>>
Simulate the bouncing ball. Gravity affects the y coordinate only. When it its the floor on the y axis, it bounces back
:param x0: initial x position
:param y0: initial y position
:param vx0: initial x velocity
:param vy0: initial y velocity
:param steps: number of steps
:param dt: time step
:param g: gravity constant
:param coefficient_of_restitution: coefficient of restitution of each bounce
:return: list of positions
"""
x_positions = [x0]
y_positions = [y0]
vx = vx0
vy = vy0
for i in range(steps):
x_positions.append(x_positions[-1] + vx * dt)
y_positions.append(y_positions[-1] + vy * dt)
if y_positions[-1] < 0:
vy = -vy * coefficient_of_restitution
y_positions[-1] = 0
else:
y_positions[-1] = y_positions[-1] + vy * dt
vy = vy - g * dt
return x_positions, y_positions
#>>> set initial x and y positions to 1.0
x0 = 1.0
y0 = 1.0
#>>> set initial x and y velocities to 1.0
x0 = 1.0
y0 = 1.0
#>>> set number of time steps to 250
steps = 250
# set time step
dt = 0.01
#>>> set coefficient of restitution to 0.8
coefficient_of_restitution = 0.8
# set gravity constant
g = 9.8
#>>> test function
x_positions, y_positions = simulate_bouncing_ball(x0, y0, x0, y0, steps, dt, coefficient_of_restitution, g)
plt.plot(x_positions, y_positions)
plt.show() | true |
df59f66cc712c06a11c7aee247edeb15c1344848 | Bharti1601/Python_Coding | /Leap-year.py | 588 | 4.375 | 4 | # program to find leap year
year = int(input(" Enter the year :")) # it takes year as an input
# check the conditions of the leap year , if all match then print leap year else not a leap year.
if (x % 4) == 0 :
if(year % 100) == 0 :
if(year % 400) == 0 :
print ("Year is Leap Year")
else:
print("Year is not a leap year")
else:
print("Year is a leap year")
else:
print("Year is not leap year")
# output will be :
# Enter the year :2000
#Year is Leap Year
| true |
a8b9238885ae44f9ca50f62afbb013af1ccaf9fb | jevinkeffers/DC-Repos-Week-1 | /KJ_Python_101_lessons/Medium/HOW_MANY_COINS.py | 503 | 4.21875 | 4 | # 3. How many coins?
# Write a program that will prompt you for how many coins you want. Initially you have no coins. It will ask you if you want a coin? If you type "yes", it will give you one coin, and print out the current tally. If you type no, it will stop the program.
coins = 0
answer = "yes"
while answer == "yes":
print("You have %s coins." % coins)
answer = input("Do you want another? ")
if answer == "yes":
coins +=1
if answer == "no":
print("Bye")
# #SOLVED | true |
91206859d093a90e44ea246e69bac006414da44d | binonguyen1090/PythonExercises | /test.py | 1,209 | 4.15625 | 4 | # num1 = float(input("Enter number: "))
# op = input("+ - * /: ")
# num2 = float(input("Enter number: "))
#
# if op == "+":
# print(num1+num2)
# elif op == "-":
# print(num1-num2)
# elif op == "*":
# print(num1*num2)
# elif op == "/":
# print(num1/num2)
# else:
# print("Invalid Input")
# secret = "Hello"
# guess = ""
# count = 0
# guessLeft = True
# while guess != secret and guessLeft:
# if count < 3:
# guess = input("Enter guess: ")
# count += 1
# else:
# guessLeft = False
# if guessLeft == False:
# print("You lose")
# else:
# print("You win")
p1 = "Which one is a ? \na = a\nb = b\nc = c"
p2 = "Which one is b ? \na = a\nb = b\nc = c"
class Question:
def __init__(self, promp, answer):
self.promp = promp
self.answer = answer
example1 = Question(p1, "a")
example2 = Question(p2, "b")
questions = [example1, example2]
def run_test(questions):
score = 0
for question in questions:
print(question.promp)
user = input("Enter the pick: ")
if user == question.answer:
score += 1
print("You got " + str(score) + "/" + str(len(questions)))
run_test(questions)
| false |
32ba064a32222cee90b9890ab698425a5cfaad54 | Extomvi/GDGUnilag | /inPython/datastructures/queue_dequeue.py | 733 | 4.1875 | 4 | """ Queue-DeQueue-EnQueue"""
class Queue:
def _init_(self):
self.s1 = []
self.s2 = []
# EnQueue item to the queue
def enQueue(self, x):
self.s1.append(x)
# DeQueue item from the queue
def deQueue(self):
# if both the stacks are empty
if len(self.s1) == 0 and len(self.s2) == 0:
print("Q is Empty")
return
# if s2 is empty and s1 has elements
elif len(self.s2) == 0 and len(self.s1) > 0:
while len(self.s1):
temp = self.s1.pop()
self.s2.append(temp)
return self.s2.pop()
else:
return self.s2.pop()
| false |
39e465c6830341f8b9554419a5c452d0b09dd359 | Extomvi/GDGUnilag | /inPython/palindrome_checker.py | 327 | 4.21875 | 4 | def is_palindrome(string):
first = 0
last = len(string) - 1
while first <= last:
if string[first] == string[last]:
first += 1
last -= 1
else:
return False
print("{} is a palindrome".format(palindrome))
palindrome = 'Mallam'
is_palindrome(palindrome.lower())
| true |
6b7b92bf28c4de8ddf4787ca8d433f229744548a | Extomvi/GDGUnilag | /Algorithms&DataStructures/reverse_integer.py | 278 | 4.1875 | 4 | """Reverse an Integer"""
def reverse_integer(n):
reversed_num = 0
while n>0:
remainder = n%10
reversed_num = reversed_num*10 + remainder
n = n//10
return reversed_num
if __name__ == "__main__":
n = 54321
print(reverse_integer(n)) | false |
32468cdbb9017db99433bc36711fc53182dff2f3 | Extomvi/GDGUnilag | /Algorithms&DataStructures/Palindrome.py | 301 | 4.1875 | 4 | """Palindrome Checker"""
def is_palindrome(str): #One liner code
return str==''.join(str[::-1])
def isPalindrome(str):
reversed_string = str[::-1]
if str == reversed_string:
return True
return False
if __name__ == "__main__":
str = "madam"
print(isPalindrome(str)) | false |
99a154d29312a92fe512af8c1f9ca41345e9e315 | niki4/leetcode_py3 | /easy/1480_running_sum_of_1d_array.py | 2,016 | 4.34375 | 4 | """
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
"""
from itertools import accumulate
from typing import List
class Solution:
"""
Runtime: 36 ms, faster than 85.31% of Python3
Memory Usage: 14.1 MB, less than 96.97% of Python3
Time complexity: O(n)
Space complexity: O(n)
"""
def runningSum(self, nums: List[int]) -> List[int]:
prev_sum = 0
result = []
for n in nums:
prev_sum += n
result.append(prev_sum)
return result
class Solution2:
"""
Runtime: 40 ms, faster than 63.50% of Python3
Memory Usage: 14.5 MB, less than 10.28% of Python3
Time complexity: O(n)
Space complexity: O(n)
"""
def runningSum(self, nums: List[int]) -> List[int]:
return list(accumulate(nums))
class Solution3:
"""
Runtime: 88 ms, faster than 5.32% of Python3
Memory Usage: 14.5 MB, less than 10.28% of Python3
Time complexity: O(n)
Space complexity: O(1). Note we update nums list in place (so changes are seen outside of the function).
"""
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] = sum(nums[i - 1:i + 1])
return nums
if __name__ == '__main__':
solutions = [Solution(), Solution2(), Solution3()]
tc = (
([1, 2, 3, 4], [1, 3, 6, 10]),
([1, 1, 1, 1, 1], [1, 2, 3, 4, 5]),
([3, 1, 2, 10, 1], [3, 4, 6, 16, 17]),
)
for sol in solutions:
for inp_nums, exp_nums in tc:
assert sol.runningSum(inp_nums) == exp_nums
| true |
2b1b453c1074c3f6e1fc3b7448510d1b490529ce | niki4/leetcode_py3 | /medium/658_find_k_closest_elements.py | 2,492 | 4.125 | 4 | """
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array.
The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr is sorted in ascending order.
-104 <= arr[i], x <= 104
"""
from typing import List
class Solution:
"""
Sort With Custom Comparator
Time complexity: O(N logN) + (K logK)
Space complexity: O(n)
"""
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# sort using custom comparator, denoting closest numbers first
sorted_arr = sorted(arr, key=lambda num: abs(x - num))
# take only k closest numbers
result = sorted_arr[:k]
# return elements sorted in ascending order
return sorted(result)
class Solution2:
"""
Binary Search To Find The Left Bound
Algorithm idea: "If the element at arr[mid] is closer to x than arr[mid + k], then that means arr[mid + k], as
well as every element to the right of it can never be in the answer. This means we should move our right pointer
to avoid considering them. The logic is the same vice-versa - if arr[mid + k] is closer to x, then move the left
pointer."
Runtime: 272 ms, faster than 96.24% of Python3
Memory Usage: 15.4 MB, less than 90.19% of Python3
Time complexity: O(log(N-k) + k)
Space complexity: O(1)
"""
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# init binary search bounds
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) // 2
if x - arr[mid] > arr[mid + k] - x:
# left distance greater than right one
left = mid + 1
else:
right = mid
return arr[left:left + k]
if __name__ == '__main__':
solutions = [Solution(), Solution2()]
tc = (
([1, 2, 3, 4, 5], 4, 3, [1, 2, 3, 4]),
([1, 2, 3, 4, 5], 4, -1, [1, 2, 3, 4]),
)
for sol in solutions:
for inp_arr, inp_k, inp_x, exp_res in tc:
assert sol.findClosestElements(inp_arr, inp_k, inp_x) == exp_res
| true |
c4f1bde006560cddc2c8ab7b5f141badacb997bb | niki4/leetcode_py3 | /easy/246_strobogrammatic_number.py | 1,995 | 4.34375 | 4 | """
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: num = "69"
Output: true
Example 2:
Input: num = "88"
Output: true
Example 3:
Input: num = "962"
Output: false
"""
class Solution:
"""
Build rotated string and compare with the source string. Strobogrammatic strings shall equal.
Runtime: 28 ms, faster than 80.88% of Python3
Memory Usage: 14.3 MB, less than 12.53% of Python3
Time / Space complexity: O(n)
"""
def isStrobogrammatic(self, num: str) -> bool:
strob = {"0": "0", "1": "1", "6": "9", "9": "6", "8": "8"}
rev_num = list()
for n in num:
if n in strob:
rev_num.append(strob[n])
else:
return False
return num == "".join(reversed(rev_num))
class Solution2:
"""
Two-pointers approach
Runtime: 28 ms, faster than 80.88% of Python3
Memory Usage: 14 MB, less than 99.05% of Python3
Time complexity: O(n) as we need to check all the digits in num
Space complexity: O(1) as we use constant extra space for "strob" dict
"""
def isStrobogrammatic(self, num: str) -> bool:
strob = {"0": "0", "1": "1", "6": "9", "9": "6", "8": "8"}
i, j = 0, len(num) - 1
while i <= j:
if num[i] not in strob or strob[num[i]] != num[j]:
return False
i += 1
j -= 1
return True
if __name__ == '__main__':
solutions = [Solution(), Solution2()]
tc = (
("69", True),
("88", True),
("962", False),
("1", True),
("2", False),
("101", True),
)
for s in solutions:
for inp, exp in tc:
res = s.isStrobogrammatic(inp)
assert res is exp, f"{s.__class__.__name__}: for input {inp} expected {exp}, got {res}"
| true |
65810884845a310bd3fae63f4b7f423fa3133b5f | niki4/leetcode_py3 | /hard/004_median_of_two_sorted_arrays.py | 922 | 4.21875 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
class Solution:
"""
Runtime: 56 ms, faster than 88.08% of Python3.
Memory Usage: 13.4 MB, less than 49.16% of Python3.
"""
def findMedianSortedArrays(self, nums1: list, nums2: list) -> float:
src = sorted(nums1 + nums2)
med_idx = len(src) // 2
median = ((src[med_idx-1] + src[med_idx]) / 2) if len(src) % 2 == 0 else src[med_idx]
return median
if __name__ == "__main__":
s = Solution()
assert s.findMedianSortedArrays([1, 3], [2]) == 2
assert s.findMedianSortedArrays([1, 2], [3, 4]) == 2.5
| true |
a799617001770c25ddd79cb89034f934bd669903 | niki4/leetcode_py3 | /medium/957_prison_cells_after_n_days.py | 2,709 | 4.125 | 4 | """
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant,
then the cell becomes occupied.
* Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the
row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way:
cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days
(and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]
Note:
cells.length == 8
cells[i] is in {0, 1}
1 <= N <= 10^9
"""
class Solution:
"""
Runtime: 36 ms, faster than 98.49% of Python3.
Memory Usage: 13.2 MB, less than 29.68% of Python3.
Algoritm idea:
1. The first and last cells become (and left) 0 after the first iteration, so
we don't count on them.
2. Having cells.length == 8 and first and last cells out of count, we could have 2**6=64
possible states for cells. In fact, loop happens earlier and we can spot it,
this would require from us using some sort of hash map/set to detect if we've seen the result
of cells modification before. The length of set before the initial state and the state
with the same value is the length of loop. This is why 14 in 'N = (N - 1) % 14'.
"""
def prisonAfterNDays(self, cells: list, N: int) -> list:
while N > 0:
new_cells = [0] * len(cells)
for i in range(1, len(cells)-1):
new_cells[i] = 1 if cells[i-1]==cells[i+1] else 0
cells = new_cells
N = (N - 1) % 14
return cells
if __name__ == "__main__":
s = Solution()
assert s.prisonAfterNDays([0,1,0,1,1,0,0,1], 7) == [0,0,1,1,0,0,0,0]
assert s.prisonAfterNDays([1,0,0,1,0,0,1,0], 1000000000) == [0,0,1,1,1,1,1,0]
assert s.prisonAfterNDays([0,0,0,0,1,1,1,1], 503) == [0,1,0,0,0,0,1,0]
assert s.prisonAfterNDays([1,0,0,1,0,0,0,1], 826) == [0,1,1,0,1,1,1,0]
| true |
146e8046eee1174467a49b651bd51c4f2e19f2ea | niki4/leetcode_py3 | /easy/359_logger_rate_limiter.py | 2,481 | 4.15625 | 4 | """
Design a logger system that receives a stream of messages along with their timestamps.
Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will
prevent other identical messages from being printed until timestamp t + 10).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger class:
Logger() Initializes the logger object.
bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given
timestamp, otherwise returns false.
"""
class Logger:
"""
Runtime: 144 ms, faster than 65.48% of Python3
Memory Usage: 20.1 MB, less than 75.42% of Python3
Time Complexity: O(1). The lookup and update of the hashtable takes a constant time.
Space Complexity: O(M) where M is the size of all incoming messages.
Over the time, the hashtable would have an entry for each unique message that has appeared.
"""
def __init__(self):
"""
Initialize your data structure here.
"""
self.records = dict()
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity.
"""
if message not in self.records:
self.records[message] = timestamp
return True
old_ts = self.records[message]
if timestamp >= old_ts + 10:
self.records[message] = timestamp
return True
return False
if __name__ == '__main__':
logger = Logger()
assert logger.shouldPrintMessage(1, "foo") is True # next allowed timestamp for "foo" is 1 + 10 = 11
assert logger.shouldPrintMessage(2, "bar") is True # next allowed timestamp for "bar" is 2 + 10 = 12
assert logger.shouldPrintMessage(3, "foo") is False # 3 < 11
assert logger.shouldPrintMessage(8, "bar") is False # 8 < 12
assert logger.shouldPrintMessage(10, "foo") is False # 10 < 11
assert logger.shouldPrintMessage(11, "foo") is True # 11 >= 11, next allowed timestamp for "foo" is 11 + 10 = 21
assert logger.shouldPrintMessage(100, "bug") is True
assert logger.shouldPrintMessage(100, "bug") is False # two equal messages at the same ts is not allowed
| true |
b27117e6864709dc200c5b282da00ecaec38f7e1 | niki4/leetcode_py3 | /easy/1684_count_the_number_of_consistent_strings.py | 1,861 | 4.21875 | 4 | """
You are given a string allowed consisting of distinct characters and an array of strings words.
A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
Example 1:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
"""
from typing import List
class Solution:
"""
For each word iterate over it and check all letters are in allowed (consistent).
Runtime: 248 ms, faster than 51.48% of Python3
Memory Usage: 16.2 MB, less than 13.60% of Python3
Time complexity: O(n*k) where n is the length of the words list and k is the median length of word.
Space complexity: O(1)
"""
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
consistent = 0
for word in words:
if all(ltr in allowed for ltr in word):
consistent += 1
return consistent
class Solution2:
"""
Using hash set, for each word compare (letters) difference between a word and allowed.
Runtime: 288 ms, faster than 18.49% of Python3
Memory Usage: 16 MB, less than 92.44% of Python3
Time complexity: O(n*k)
Space complexity: O(1)
"""
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
consistent = 0
for word in words:
if len(set(word).difference(allowed)) == 0:
consistent += 1
return consistent
if __name__ == '__main__':
solutions = [Solution(), Solution2()]
tc = (
("ab", ["ad", "bd", "aaab", "baa", "badab"], 2),
("abc", ["a", "b", "c", "ab", "ac", "bc", "abc"], 7),
("cad", ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"]),
)
| true |
6fffdf887853022684d1b784119161ddc4e03764 | niki4/leetcode_py3 | /easy/1002_find_common_characters.py | 1,366 | 4.125 | 4 | """
Given an array A of strings made only from lowercase letters,
return a list of all characters that show up in all strings within
the list (including duplicates). For example, if a character occurs 3 times
in all strings but not 4 times, you need to include that character three times
in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
"""
class Solution:
"""
Runtime: 40 ms, faster than 99.37% of Python3.
Memory Usage: 13.2 MB, less than 58.30% of Python3.
Casting to 'set' is the best way to find unique items in Python.
"""
def commonChars(self, A: list) -> list:
if len(A) == 1:
return list(A[0])
init_word = A[0]
letters = set(init_word)
for idx in range(1, len(A)):
letters.intersection_update(A[idx])
result = []
for ltr in letters:
result += [ltr] * min(word.count(ltr) for word in A)
return result
if __name__ == "__main__":
s = Solution()
assert sorted(s.commonChars(["bella","label","roller"])) == sorted(["e","l","l"])
assert sorted(s.commonChars(["cool","lock","cook"])) == sorted(["c","o"])
| true |
369062e63df3e88621ac853388a96e52d06a2edd | dallinhumphrey/Python | /test_ch1.py/march_seventeenth_chapter_4.py | 1,315 | 4.25 | 4 | twoRivers = ['Rand', 'Perrin', 'Faile', 'Mat', 'Egwene', 'Nynaeve']
visit = ['new zealand', 'fuji', 'costa rica', 'bali', 'lake powell']
for character in twoRivers:
print(character.title() + ", killed a trolloc!")
print("I can't wait to see you do it again, " + character.title() + "\n")
print("Thank you everyone! That was a great show!")
pizzas = ['cheese', 'veggie', '4 cheese', 'pineapple']
for pizza in pizzas:
print(f"""I love {pizza.title()} pizza!""")
print(f"""
Pizza is my favorite food in the whole world, and I think {pizzas[2]} is my favorite. {pizzas[-1]} is super close too!
""")
numbers = list(range(1, 11, 2))
print(numbers)
squares = []
for value in range(1, 11):
square = value**2
squares.append(square)
print(squares)
house_members = ['kort', 'dallin', 'lincoln', 'lily']
for house_member in house_members:
print(f"""{house_member.title()} is super cool \n""")
print(f"""We have fun here""")
squares = []
for value in range(1, 11, 2):
squares.append(value**2)
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
numbers = range(3, 31, 3)
for numb in numbers:
print(numb)
numbers = list(range(3, 31, 3))
print(numbers)
for numb in numbers:
numb = list(range(3, 31, 3))
print(numb)
| true |
ef5044a0876b085c08523b0c42fa6544585124fd | EdgarOrnelas/Re_Start-Week9 | /password.py | 1,446 | 4.375 | 4 | #19. Write a Python program to check the validity of a password input by users
import re
print ("Hello, I will guide you to create a secure password for this site.")
print ("Your password can be anything you like, but it has to include the following elements:")
print ("It has to be between 6 and 16 characters")
print ("At least ONE lower-cap ('a' to 'z') and ONE Cap letter ('A' to 'Z')")
print ('At least ONE number')
print ("Aaaand... at least ONE of these special characters: '$', '#', '@'")
print ("That is it! I hope you have a good password in mind. Please input your password below:")
p = input(' ')
incorrectPassword = True
while incorrectPassword:
if len(p) < 6:
print ("Your password is too short")
p = input("Try again: ")
break
elif len(p) > 16:
print ("Your password is too long")
p = input("Try again: ")
break
elif not re.search('[a-z]', p):
print ("You missed a lower-cap letter")
p = input("Try again: ")
break
elif not re.search('[A-Z]', p):
print ("You missed a CAPS letter")
p = input("Try again: ")
break
elif not re.search('[0-9]', p):
print ("You missed a number")
p = input("Try again: ")
break
elif not re.search ('[$#@]', p):
print ("You missed one of the special characters")
p = input("Try again: ")
break
else:
print ("Great! Your password has been stored")
incorrectPassword = False
break
if incorrectPassword:
print ("The password you entered is not valid")
| true |
9a8f1df5003d4c8b63f1a64ff1471d490116a7d5 | EdgarOrnelas/Re_Start-Week9 | /multiplyall.py | 212 | 4.3125 | 4 | #7. Write a Python function to multiply all the numbers in a list
def multiall(l):
result = 1
for n in l:
result *= n
return result
multiplyTheseNumbers = [2, 4, 6, 8]
print(multiall(multiplyTheseNumbers)) | true |
cd661d476ee2c26251affa2b68f04f6158bfcc84 | imperialisticwaffle/Python | /freeCodeCamp_Learn_Python_in_4_Hours/getting_inputs_from_users.py | 605 | 4.34375 | 4 | # To obtain input from users we use input().
# Inside the parentheses we type the string prompt.
# input("Enter your name: ")
# We can then put this into a variable.
name = str(input("Enter your name: "))
print("Hello, " + name + " !")
# Note that string variables can combine with strings, but number variables cannot combine with strings.
# VSCode requires that you put quotations around the name string. Numbers are fine themselves.
# Continuing...
name = str(input("Enter your name: "))
age = str(input("Please enter your age: "))
print("Hello, " + name + "! You are " + age + " years of age.") | true |
98756fc2b515808461206b3ccb2c5be5719f8a6a | imperialisticwaffle/Python | /CodeWars Challenges/digital_root.py | 1,798 | 4.15625 | 4 |
n = int(input("Please input a random positive integer. "))
def digital_root(n):
if n < 10:
print(n)
return
else:
sum_of_digits = 0
for digit in str(n):
sum_of_digits += int(digit) # Up until here in the code, it works. 98 doesn't work, for example.
if sum_of_digits >= 10:
new_sum = 0
while sum_of_digits >= 10:
for digit_2 in str(sum_of_digits):
new_sum += int(digit_2)
print(new_sum)
return
else:
print(sum_of_digits)
return sum_of_digits
digital_root(n)
n = int(input("Please input a random positive integer. "))
def digital_root(n):
if n < 10:
print(n)
return
else:
sum_of_digits = 0
for digit in str(n):
sum_of_digits += int(digit) # Up until here in the code, it works. 98 doesn't work, for example.
if len(str(sum_of_digits)) >= 2:
print("loop enter") # infinite loop test
while len(str(sum_of_digits)) >= 2:
for digit in str(sum_of_digits):
sum_of_digits += int(digit)
if len(str(sum_of_digits)) == 1:
break
print("loop exit") # infinite loop test
print(sum_of_digits)
return sum_of_digits
return
digital_root(n)
# TIL n mod 9 is the digital root. If n divisible by 9, DR is 9.
n = int(input("Please input a random positive integer. "))
def digital_root(n):
if n % 9 == 0 and not n == 0:
print("The digital root of", n, "is 9")
elif n % 9 > 0:
print("The digital root of", n, "is", n % 9)
elif n == 0:
print("The digital root of", n, "is 0")
return
digital_root(n)
| true |
9132c74c23f53018904e0bb1778e1b2b7a87a5cd | imperialisticwaffle/Python | /freeCodeCamp_Learn_Python_in_4_Hours/exponent_function.py | 724 | 4.78125 | 5 | # Double multiplication signs are exponents.
print(2**3) # This gives 8.
# We can make exponent functions also with for loops.
def raise_power(base_num, pow_num): # We could do base_num * base_num...etc. but we don't know what pow_num is.
result = 1
for index in range(pow_num):
result = result * base_num # base_num * 1 = base_num; base_num * base_num = base_num ^ 2; ... base_num ^ (pow_num - 1) * base_num
return result
print(raise_power(3, 3))
def raise_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
base_num = input("Input a base number. ")
pow_num = input("Input an exponent. ")
print(raise_power(base_num, pow_num)) | true |
485c4bc20310ebe93bf709f26a6050868e9209b1 | Myneequaye/python | /hours_rate.py | 430 | 4.28125 | 4 | # Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or bad user data.
hrs = input("Enter Hours:")
rate = input("Enter rates:")
pay = int(hrs) * float(rate)
print("Pay:", pay) | true |
ed2b84f0ce967f5d85f89748d40c9f28d626d7eb | Duelmaster09/PythonForEverybody | /Using Python to Access Web Data/Week5_Assignment1.py | 1,073 | 4.15625 | 4 | '''In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py.
The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data,
compute the sum of the numbers in the file.
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
Sample data: http://py4e-data.dr-chuck.net/comments_42.xml (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comments_1108397.xml (Sum ends with 54)'''
from urllib.request import urlopen
import xml.etree.ElementTree as et
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url=input('Enter URL: ')
xml_string=urlopen(url,context=ctx).read().decode()
tree=et.fromstring(xml_string)
all_comments=tree.findall('comments/comment')
total=0
for comment in all_comments:
total+=int(comment.find('count').text)
print("Sum:",total) | true |
bd2cdb6dc537e3d439d99addf844439087e4f2d0 | bvictori0927/Python | /caesarcipher.py | 1,485 | 4.25 | 4 | '''
Caesar Cipher program
CaesarCipher.py
BMeadows
Used to encry/decrypt data
'''
#Bringing in the String library to generate character base
import string
#Prompt the user
message= input("Enter the message or phrase to be encrypted or decrypted: ")
#Get the key from the user
while True:
try:
key = int(input('Please enter your key size: '))
break
except ValueError as error:
print(error)
print('Please enter an integer for the key and try again.')
#getting the mode setting
mode=input('Please enter E for encrypt and D for decrypt!')
#Create my character base
SYMBOLS= string.ascii_letters + string.punctuation + string.digits + " "
#to store translated message
translated= ''
#Code to encrypt/decrypt
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
## The shift
if mode in['e','E','ENCRYPT','encrypt']:
translatedIndex = symbolIndex + key
elif mode in ['DECRYPT','decrypt','D','d']:
translatedIndex = symbolIndex - key
#What do I do when it wraps around? There's a script for that!
if translatedIndex >= len(SYMBOLS):
translatedIndex -= len(SYMBOLS)
elif translatedIndex <= 0:
translatedIndex += [len(SYMBOLS)]
translated += SYMBOLS[translatedIndex]
else:
translated += symbol
print(translated)
| true |
aba22f4aa520bbd0a25c85b156b555eb288506ed | chakri63/Calculator-progaram-in-python | /calculator.py | 828 | 4.3125 | 4 | from functions import *
while True:
print("What is your required operation : ")
print("Enter 1 for Addition")
print("Enter 2 for Subtraction")
print("Enter 3 Multiplication")
print("Enter 4 for Division")
print("Enter 5 for power operation")
print("Enter Q to exit")
choice =input("Enter your choice:")
if choice == 'q' or choice == 'Q':
break
num1 = float(input("Enter the Number 1 : "))
num2 = float(input("Enter the number 2 : "))
if choice == '1':
addition(num1, num2)
elif choice == '2':
substraction(num1, num2)
elif choice == '3':
multiplication(num1, num2)
elif choice == '4':
division(num1, num2)
elif choice == '5':
power(num1, num2)
else:
print("Invalid Choice") | true |
bec717329b39f06e54d02bba853456cb772cf0d2 | drmirk/dcoder | /area_of_circle.py | 294 | 4.1875 | 4 | #python 3.4
def area_of_circle():
'''
radius is given, find the area of a circle,
if radius negative return zero
'''
user_inp = float(input())
if(user_inp <= 0):
return 0
else:
PI = 3.14
area = PI * (float(user_inp)**2.0)
return('{0:.2f}'.format(area))
print(area_of_circle()) | true |
6d913d6052ebb78dad0084b44477281980d52cc1 | mcode36/Python_Class | /Save_for_later/number_guessing_game.py | 1,499 | 4.375 | 4 | # Example: Number guessing game
# - Python Indentation
# - input()
# - if
my_answer = 67
your_answer = input("Give me a number (from 0 to 100): ")
while (int(your_answer) != my_answer):
if int(your_answer) > my_answer:
print("Too big, try again...")
else:
print("Too small, try again...")
your_answer = input("Give me a number (from 0 to 100): ")
print("You got it!! The answer is ",my_answer)
'''
## version 0: Buggy version
my_answer = 67
your_answer = input("Give me a number (from 0 to 100): "):
while (your_answer != my_answer):
if your_answer > my_answer:
print("Too big, try again...")
else
print("Too small, try again...")
your_answer = input("Give me a number (from 0 to 100): ")
'''
'''
## version 2: Reducing two input() statements to one
my_answer = 67
your_answer = 1
while (your_answer != my_answer):
your_answer = input("Give me a number (from 0 to 100): ")
if your_answer > my_answer:
print("Too big, try again...")
else:
print("Too small, try again...")
'''
'''
## version 3: Endless loop? (hint: wrong data type)
my_answer = 67
your_answer = input("Give me a number (from 0 to 100): ")
while (int(your_answer) != my_answer):
if int(your_answer) > my_answer:
print("Too big, try again...")
else:
print("Too small, try again...")
your_answer = input("Give me a number (from 0 to 100): ")
print("You got it!! The answer is ",my_answer)
'''
| true |
a22105c637df3a624f58dbd9f08c92ad5cafecd2 | Tezza1/P0_TS | /Task1.py | 1,232 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
# UNDERSTAND INPUTS
# get all sent numbers from texts
# get all received numbers from texts
# get all sent numbers from calls
# get all received number from calls
# UNDERSTAND THE OUTPUTS
# get a list of all unique numbers
# count the list to get a final number
# CONSIDER SYSTEMATICALLY HOW A HUMAN SOLVES THE PROBLEM
# go through the list and make a list of new numbers
# each time a number comes up, compare it to the list
# if the number exists, ignore it
# if it is new, add it to the list
# initialize my_set
num_set = set()
def getData(data):
for i in data:
num_set.add(i[0])
num_set.add(i[1])
getData(texts)
getData(calls)
print(f"There are {len(num_set)} different telephone numbers in the records.")
# def test():
# print("Tests finished")
# test()
| true |
33139a5557e52998ea8bb89cf7dfb360f278036d | Achyutha18/College_Sample_2 | /Sample2_1.py | 229 | 4.21875 | 4 | #Python Program to Find the Largest Number in a List
import random
ran=int(input("Enter the range"))
lis = []
for i in range(ran):
lis.append(random.randint(1,100))
print(lis)
lis.sort()
print("Largest number is ",lis[-1])
| true |
b3a740dc664e120cbb19b45bc4306b4484414efa | Achyutha18/College_Sample_2 | /Sample2_7W.py | 524 | 4.21875 | 4 | #Python Program to find union and intersection of lists without repetition
list1=[]
list2=[]
list3=[]
n1=int(input("Enter the range"))
for i in range(n1):
list1.append(input("Enter the values"))
print("Second List Starts")
n2=int(input("Enter the range"))
for i in range(n2):
list2.append(input("Enter the values"))
print(list1)
print(list2)
list3 =(set(list1)|set(list2))
print("The union of numbers are: ",set(list3))
list4=(set(list1)&set(list2))
print ("The intersection of two lists are : ", set(list4))
| true |
3972dcbd93b9e996d5980e9e42ab3e77df3f6573 | yadav-vikas/python-object-oriented-programming | /python-DS/nodes/n_element_in_linked_list.py | 1,313 | 4.1875 | 4 | from linked_list import LinkedList
# Complete this function:
def nth_last_node(linked_list, n):
current = None
tail_seeker = linked_list.head_node
count = 1
while tail_seeker.get_value() is not None:
tail_seeker = tail_seeker.get_next_node()
count += 1
if count >= n + 1:
if current is None:
current = linked_list.head_node
else:
current = current.get_next_node()
return current
#time complexity is O(n) and space complexity is O(1)
# ------------------------------------- alternate solution----------------------------------------------------------------
# def list_nth_last(linked_list, n):
# linked_list_as_list = []
# current_node = linked_list.head_node
# while current_node:
# linked_list_as_list.append(current_node)
# current_node = current_node.get_next_node()
# return linked_list_as_list[len(linked_list_as_list) - n]
#time complexity is O(n) and space complexity is O(n)
def generate_test_linked_list():
linked_list = LinkedList()
for i in range(50, 0, -1):
linked_list.insert_beginning(i)
return linked_list
# Use this to test your code:
test_list = generate_test_linked_list()
print(test_list.stringify_list())
nth_last = nth_last_node(test_list, 4)
print(nth_last.value)
| true |
a0741da2fec2fb3aeeec8f57c9c5351b85d4990d | abedford/devops-exercises | /FizzBuzz/FizzBuzz.py | 2,263 | 4.125 | 4 |
def divisibleBy(number, rule):
if (number % rule == 0):
return True
return False
def print_number(number, rules):
divisibleBy3bool = divisibleBy(number, 3) and 3 in rules
divisibleBy5bool = divisibleBy(number, 5) and 5 in rules
divisibleBy7bool = divisibleBy(number, 7) and 7 in rules
divisibleBy11bool = divisibleBy(number, 11) and 11 in rules
divisibleBy13bool = divisibleBy(number, 13) and 13 in rules
divisibleBy17bool = divisibleBy(number, 17) and 17 in rules
resultString =""
if (divisibleBy11bool):
if (divisibleBy13bool):
resultString += "Fezz"
resultString += "Bong"
elif (divisibleBy3bool or divisibleBy5bool or divisibleBy7bool or divisibleBy13bool or divisibleBy17bool):
ruleStrings = []
if (divisibleBy3bool):
ruleStrings.append("Fizz")
if (divisibleBy13bool):
ruleStrings.append("Fezz")
if (divisibleBy5bool):
ruleStrings.append("Buzz")
if (divisibleBy7bool):
ruleStrings.append("Bang")
if (divisibleBy17bool):
index = len(ruleStrings) - 1
while(index >= 0):
resultString += ruleStrings[index]
index -= 1
else:
for ruleString in ruleStrings:
resultString += ruleString
else:
resultString = number
print(number, " ", resultString)
print("Welcome to the Fizz Buzz exercise program.")
max_number = input("Enter max number to calculate to:")
print("Enter which rules you'd like to use, options are 3, 5, 7, 11, 13, 17, anything else will run the program.")
run_program = False
possibleRules = [3, 5, 7, 11, 13, 17]
user_rules = []
while not(run_program):
rule = input("Type a rule, or press any other key to stop inputting rules and run the program: ")
try:
ruleNumber = int(rule)
if (ruleNumber in possibleRules):
user_rules.append(ruleNumber)
else:
run_program = True
except:
print("That is not a valid rule, starting program.")
run_program = True
for index in range(0, int(max_number)):
print_number(index, user_rules)
| false |
b81ca3c1f0313dbf11f1b3d0eb0832e6c03626e3 | cjonsmith/algorithms | /sorting-algorithms/selection_sort.py | 917 | 4.53125 | 5 | def selection_sort(a_list):
"""Sorts a given list in place using the selection sort algorithm.
:param a_list: The list to sort.
:return: The sorted list."""
end_position = len(a_list) # The position to swap with largest found value
while end_position != 0:
# Traverse the unsorted portion of the list to find the largest value in it.
# Save the largest value and its position in the list as well.
largest = a_list[0], 0
for i, value in enumerate(a_list[:end_position]):
if value > largest[0]:
largest = value, i
# Preseve the element at end of the unsorted portion of the list, then swap
# it with the largest element.
a_list[largest[1]], a_list[end_position - 1] = \
a_list[end_position - 1], largest[0]
end_position -= 1 # Decrease the size of the unsorted array
return a_list
| true |
2c486e98585ddacc9f9becbe45d3829a3a100e0f | MohitBis/Python_Learnings | /programing_practice_problems/word_order.py | 911 | 4.125 | 4 | """
You are given n words. Some words may repeat. For each word, output its number of occurrences.
The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
Input Format:
------------
The first line contains the integer, n.
The next n lines each contain a word.
Output Format:
-------------
Output 2 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Sample Input
------------
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
"""
d = {}
n =int(input())
for _ in range(n):
x = input()
if x in d:
d[x] = d[x]+1
else:
d[x] = 1
l = []
for k,v in d.items():
l.append(str(v))
y = " ".join(l)
print(n)
print(y) | true |
8051fa330e65af901ff57bad40124b327e74c828 | PiyushChaturvedii/flamingo-woodpecker-attainU | /Solutions/Week 5/Day 5/w5d5cc1.py | 2,652 | 4.21875 | 4 | # Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Linked List class
class LinkedList:
def __init__(self):
self.head = None
self.end = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
self.end = new_node
else:
self.end.next = new_node
self.end = self.end.next
def reverse(self): # Time complexity O(n)
prev_node = None
curr_node = self.head
if curr_node is None:
return curr_node
while curr_node is not None:
next_node, curr_node.next = curr_node.next, prev_node
prev_node, curr_node = curr_node, next_node
self.end = self.head
self.head = prev_node
def display(self):
curr_node = self.head
while curr_node is not None:
print('\033[46m', curr_node.data, '\033[41m', end=" --\033[0m-->")
curr_node = curr_node.next
else:
print('\033[44m', "None", '\033[0m')
print()
ll = LinkedList()
lis = [18, 5, 11, 30, 5]
for i in lis:
ll.append(i)
ll.display()
ll.reverse()
ll.display()
# ------------------------------- explanation [reverse()] -----------------------------------------
# Input
# Head
# 18 --> 5 --> 11 --> 30 --> 5 --> None
# Inside reverse()
# Prev Curr/Head
# None 18 --> 5 --> 11 --> 30 --> 5 --> None
# Loop - PASS - 1
# P C/H Next
# None <-- 18 5 --> 11 --> 30 --> 5 --> None
# P/H C/Next
# None <-- 18 5 --> 11 --> 30 --> 5 --> None
# Loop - PASS - 2
# P/H C N
# None <-- 18 <-- 5 11 --> 30 --> 5 --> None
# H P C/N
# None <-- 18 <-- 5 11 --> 30 --> 5 --> None
# Loop - PASS - 3
# H P C N
# None <-- 18 <-- 5 <-- 11 30 --> 5 --> None
# H P C/N
# None <-- 18 <-- 5 <-- 11 30 --> 5 --> None
# Loop - PASS - 4
# H P C N
# None <-- 18 <-- 5 <-- 11 <-- 30 5 --> None
# H P C/N
# None <-- 18 <-- 5 <-- 11 <-- 30 5 --> None
# Loop - PASS - 5
# H P C N
# None <-- 18 <-- 5 <-- 11 <-- 30 <-- 5 None
# H P C/N
# None <-- 18 <-- 5 <-- 11 <-- 30 <-- 5 None
# Loop breaks
# E H/P
# None <-- 18 <-- 5 <-- 11 <-- 30 <-- 5
# Output
# Head
# 5 --> 30 --> 11 --> 5 --> 18 --> None
| true |
483e5b0fb8c400a73378def6e4441828b49f42e5 | smikes/MasterMind-Python | /main.py | 2,337 | 4.21875 | 4 | from random import randint
import mastermind
answer = [-1]*3
guess = [-1]*3
print ("What would you like to do?")
print ("1. Testing Version")
print ("2. Mastermind Game")
choice = (int)(input(""))
if choice==1:
print ("For answer:")
answer[0] = (int)(input("What is the first number? "))
answer[1] = (int)(input("What is the second number? "))
answer[2] = (int)(input("What is the third number? "))
while True:
print("\n")
print ("For guess:")
guess[0] = (int)(input("What is your first digit? "))
guess[1] = (int)(input("What is your second digit? "))
guess[2] = (int)(input("What is your third digit? "))
print ( mastermind.analyze_guess (answer, guess) )
continue_loop = input("Would you like to continue? ")
if continue_loop=="no":
break
else:
answer = mastermind.generate_num(answer)
attempts = 1
hasWon = False
while attempts < 11:
print("\n")
print ("Guessing:")
guess[0] = (int)(input("What is your first digit? "))
guess[1] = (int)(input("What is your second digit? "))
guess[2] = (int)(input("What is your third digit? "))
print("")
print ("Turn %s: Your Guess: %s" % (attempts, str(guess)) )
#print ("Answer: %s, Your Guess: %s" % (answer, guess))
analysis = mastermind.analyze_guess(answer,guess)
print (analysis)
if analysis=="green, green, green":
hasWon = True
break
attempts += 1
if hasWon:
print("You won! The computer's number was %s" % ( str(answer)) )
else:
print("You lost. The computer's number was %s" % ( str(answer)) )
'''
Test Evaluations (Answer is 123):
Guess Evaluation Attempts
134 green, yellow 1 //notice no red
213 green, yellow, yellow 2 //notice the green is first, always
312 yellow, yellow, yellow 3
143 green, green 4
300 yellow 5
555 red 6 //red will only appear here
114 green 7 //notice that there is no yellow for the second 1
123 green,green,green 7 //correct answer
Computer number is 242
Guess is 213
Correct evaluation: Green
Incorrect Evaluation: Green, Yellow
Computer number is 242
Guess is 443
Correct evaluation: Green
Incorrect Evaluation: Green, Yellow
'''
| true |
7266e4ae6b1f14eb754584facfd65ca66d342750 | lafabo/i-love-tutorials | /thinkpython/6-fibonacci.py | 329 | 4.125 | 4 | def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n+1)
def factorial(n):
if not isinstance(n, int):
print 'n isnt int'
return None
elif n < 0:
print 'n is < than 0'
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
print factorial(12)
| false |
a210e5b5ba381e4e39366bfa25e2a46fc19951be | lafabo/i-love-tutorials | /a_bite_of_python/37-str-methods.py | 293 | 4.21875 | 4 | name = 'Boris'
if name.startswith('Bor'):
print('Yeah, string starts with "Bor"')
if 'a' in name:
print('"a" in name')
if name.find('ris') != -1:
print('Yeah, string have "ris"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
| false |
a7e43bc014de235d2b37188fea6653edc9b0d662 | lafabo/i-love-tutorials | /a_bite_of_python/48_ispalindrome.py | 639 | 4.3125 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input('Input some text: ')
something = something.replace(' ','')
something = something.replace(',','')
something = something.replace('.','')
something = something.replace('-','')
#all -> .?!:;-—()[]...’“”/,
#forbiden = ('.','?','!',':',';','-','—','(',')','[',']','.','.','.','’','“','”','/,)
#something = something.replace(forbiden, '')
#for i in bla bla bla
something = something.lower()
print(something)
if (is_palindrome(something)):
print('Yeah it\'s palyndrom')
else:
print('Not a palyndrom')
| false |
391d5e3da42c683d2c05c510b35515adacd7ea39 | lafabo/i-love-tutorials | /thinkpython/1.3-run.py | 318 | 4.125 | 4 | # print help('print')
dist = float(raw_input("Enter the distance: "))
time = str(raw_input("Enter the time (only M:S format allowed): "))
def time_to_sec(time):
m, s = time.split(':')
seconds = int(m)*60 + int(s)
return seconds
print 'You ran with speed: ', round(dist/(time_to_sec(time)/60), 2), 'km per minute' | true |
daeb32533c49f475d271d08279a05183594f6a51 | lafabo/i-love-tutorials | /a_bite_of_python/11-continue.py | 285 | 4.25 | 4 | while True:
s = input('Enter something(or "exit"): ')
if s == 'exit':
break
if len(s) < 3:
print('more than 3 chars, pls')
continue #used to skip all others comands in block
print('That\'s good len for string!')
| true |
8bd4efb8aea3d21d0cdf66798ee865ebf8f6dc98 | gazerhuang/PythonLearning | /05_Data/gz_01_list_base.py | 394 | 4.15625 | 4 | name_list = ["zhangsan", "lisi", "wangwu"]
# 1.取值和取索引
print(name_list[0])
print(name_list.index("zhangsan"))
# 2.修改
name_list[1] = "李四"
# 3.增加
name_list.append("王小二")
name_list.insert(1, "2222")
temp_list = ["a", "b", "c"]
name_list.extend(temp_list)
# 4.删除
name_list.remove("2222")
name_list.pop()
name_list.pop(3)
# name_list.clear()
print(name_list)
| false |
1817c20b344abd70a682aa4ce5dc2bde5ebb128a | sudo-tharun/abbreviation-adder-python | /abbreviation.py | 2,601 | 4.1875 | 4 | # abbreviation-adder
This is program to add the short forms with their abbreviations to a notepad file. Further extension can be writing to a word file.
import os
def duplicate(d,sf1):
temp=[]
index=0
m=0
with open(d , "r") as t:
for i in t:
temp.append(i)
for m in temp:
print("The first word:" + m[0])
#index=index+1
t.close()
return
def selectfromexisting(shortform,listoffullform):
arr=os.listdir('.')
l=(list(enumerate(arr)))
for i in l:
string=str(i)[1:-1]
string = string[:1] + ":" + string[1+1:]
print(string)
print("Does the file exitsts here in the above list? ")
a=input("1. Yes 2. No")
if a == "1":
index=int(input("Enter the index of file: "))
l=(list(enumerate(arr)))
filename=arr[index]
print(filename)
return filename
else:
findingfile(shortform,listoffullform)
def abbreviate():
word=input("Enter the short-form: (Ex: ABC or abc) ")
word=word.upper()
print(word)
m=list()
for i in word:
a=input("Give the fullform of " + i + " in " + word +": ")
m.append(a.capitalize())
findingfile(word,m)
def writetofile(name,sf2,l):
filename=name
duplicate(filename,sf2)
f=open(filename,"a")
f.write("\n")
f.write(sf2 + ": ")
for k in l:
f.write(k + " ")
f.close()
f=open(filename, "r")
print(f.read())
f.close()
print("Do you wish to write more? ")
choice=input("Yes(y) or No(n) ")
choice=choice.lower()
if choice == "y" or choice == "yes":
abbreviate()
else:
return
def findingfile(sf,l):
file=input("Enter the name of the file (case sensitive): ")
filename=file + ".txt"
try:
f=open(filename)
except FileNotFoundError:
print("\n File not found!! Kindly check the name!")
print("Not remembering the name? ")
c=input("Select your choice: \n 1. View all files in directory \n 2. Create new file ")
if c == "1":
filefromdir=selectfromexisting(sf,l)
writetofile(filefromdir,sf,l)
if c == "2":
f=open(filename, "x")
f.close()
writetofile(filename,sf,l)
abbreviate()
| true |
88316ac9edb6dcc731c54f4af74094d89dd7f82b | dilipksahu/django_class | /python_revision/HackerRank/swap_case_string.py | 763 | 4.375 | 4 | '''
You are given a string and your task is to swap cases.
In other words, convert all lowercase letters to uppercase letters and vice versa.
For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
'''
def swap_case(s):
string = str(s)
newstring = ""
for i in string:
if i.isupper():
newstring += i.lower()
elif i.islower():
newstring += i.upper()
elif i.isspace():
newstring += i
else:
newstring += i
return newstring
if __name__ == '__main__':
s = input("String=>")
result = swap_case(s)
print(result)
# ****************** 2nd method *******************************
string = input("String=>")
print(string.swapcase())
| true |
1b2301b1d3e5f15ec3c78755f8a9237d2fba6ac2 | dilipksahu/django_class | /python_revision/HackerRank/AppleandOrangeCount.py | 2,547 | 4.40625 | 4 | '''
Sam's house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where is the start point, and is the endpoint. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point , and the orange tree is at point .
Apple and orange(2).png
When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis. A negative value of means the fruit fell units to the tree's left, and a positive value of means it falls units to the tree's right.
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
1
2
Function Description
Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam's house, each on a separate line.
countApplesAndOranges has the following parameter(s):
s: integer, starting point of Sam's house location.
t: integer, ending location of Sam's house location.
a: integer, location of the Apple tree.
b: integer, location of the Orange tree.
apples: integer array, distances at which each apple falls from the tree.
oranges: integer array, distances at which each orange falls from the tree.
sample Input 0
7 11
5 15
3 2
-2 2 1
5 -6
Sample Output 0
1
1
'''
def countApplesAndOranges(s, t, a, b, apples, oranges):
app = []
org = []
for x in apples:
posapp = a + x
if s <= posapp <= t:
app.append(posapp)
for y in oranges:
posorg = b + y
if s <= posorg <= t:
org.append(b+y)
print(len(app),"\n",len(org))
if __name__ == '__main__':
st = input().split()
s = int(st[0])
t = int(st[1])
ab = input().split()
a = int(ab[0])
b = int(ab[1])
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
| true |
6301bfeaf45756f7de5adaca5df80d54c7ec209c | FelixTheC/hackerrank_exercises | /hackerrank/staircase.py | 388 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 09.05.20
@author: felix
"""
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
arr = [' ' for _ in range(n - 1)]
for i in range(1, n):
arr[-i] = '#'
print(''.join(arr))
if __name__ == '__main__':
n = int(input())
staircase(n)
| true |
61132296b1611a80b747186e8e9e5afefee44450 | Jason0221/backup | /HOME/笔记/考试/Python基础考试2-12.16/6.py | 2,561 | 4.25 | 4 | #!/usr/bin/python
#coding=utf-8
'''
6. 编写python程序: 实现一个双向循环链表,封装结点和其他方法。
要求至少实现创建和增删方法,并且要求实现其__getitem__和__setitem__两个魔法方法。
(如果你的__setitem__即可实现链表的插入那么可以不必写额外的插入方法)
'''
class Node(object):
def __init__(self,value,prior=None,next=None):
self.value = value
self.prior = prior
self.next = next
class Linklist(object):
def __init__(self,):
self.head = None
def initlist(self,data):
self.head = Node(0)
p = self.head
for i in data :
node = Node(i)
p.next = node
node.prior = p
p = p.next
p.next = self.head
self.head.prior = p
def show(self):
p =self.head.next
while p !=self.head:
print p.value,
p = p.next
print ""
def insert(self,index,value):
p = self.head
i = 0
while p.next != self.head and i < index:
i += 1
p = p.next
q = Node(value)
p.next.prior = q
q.next = p.next
p.next = q
q.prior =p
def delete(self,index):
p =self.head
i = 0
while p.next != self.head and i< index:
p =p.next
i += 1
p.next = p.next.next
p.next.prior = p
def is_empty(self):
if self.head == None:
print "空列表"
return True
else:
return False
def getitem(self,index):
p = self.head.next
i = 0
while p != self.head and i < index:
p = p.next
i += 1
return p.value
def __getitem__(self,index):
if self.is_empty():
print "Linklist is empty"
return
else:
p = self.head.next
i = 0
while p != self.head and i < index:
p = p.next
i += 1
return p.value
def __setitem__(self,index,value):
self.delete(index)
return self.insert(index,value)
if __name__ == "__main__":
l = Linklist()
print "创建一个双链表:"
l.initlist([1,2,3,5,3,6,8])
l.show()
print '删除下标为2的结点:'
l.delete(2)
l.show()
print "使用魔法方法__getitem__列出下标为1的结点:",l[1]
l.show()
print "使用魔法方法__setitm__修改链表:"
l[1] = 10
l.show()
| false |
e010eb40f5728465b68367f7f380d5757d1ed573 | Jason0221/backup | /HOME/笔记/python/Python基础代码-G/area.py | 483 | 4.1875 | 4 | #!/usr/bin/python
#conding=utf-8
a=int(raw_input("please input side a:"))
b=int(raw_input("please input side b:"))
c=int(raw_input("please input side c:"))
print "side a is:",a
print "side b is:",b
print "side c is:",c
if a+b>c and a+c>b and b+c>a:
s=(a+b+c) / 2
import math
area=int(math.sqrt(s*(s-a)*(s-b)*(s-c)))
print "the area is:",area
else:
print "please input correct length of three sides! the sum of any two side'lehgth must longer than the third one!"
| true |
7d9baa304713e3b1e5322b96470bfa2181af6c95 | PyKt/Python_Ejercicios | /Listas.py | 656 | 4.25 | 4 | # Las listas son un cojunto de mas de un elemento.
getLista: list = [5, 9, "Linux", -8, "ArchLinux"]
getLista.append(+5) # Agregara el numero 5 al ser una lista mixta.
GetList = getLista[0:]
print(GetList)
GetListNum: list = [1, 2, 3, 4, 5]
GetListNum.append(+20) # agragara el numero 20 a la lista
print(GetListNum)
GetAlfaBeto: list = ['A', 'B', 'C', 'D']
print(GetAlfaBeto)
GetAlfaBeto[:2] = ['Z', 'R'] #al usar esta orden lo que hace es sustituir los dos primero elementos
print(GetAlfaBeto)
#Una lista anidada se expresaria de esta manera.
Get1 = [1, 2, 3]
Get2 = [4, 5, 6]
Get3 = [7, 8, 9]
GetAnidadas = [Get1, Get2, Get3]
print(GetAnidadas)
| false |
19b990c27f15970d45cc7e95bcba0cb31a44c03a | PyKt/Python_Ejercicios | /Practica Mitad de Curso.py | 660 | 4.125 | 4 | print("Elije la opcion")
while True:
print("""Elija la opcion correcta
elije el numero de la opcion
1 - Quiero que me saludes.
2 - Deseo la tabla de multiplicar.
3 - Salir del programa""")
opcion = int(input())
if opcion == 1:
print("Hola usuario")
elif opcion == 2:
numero1 = float(input("Introduce el valor a multiplicar: "))
numero2 = float(input("Introduce el otro valor a multiplicar: "))
print("El resultado es:", numero1*numero2, )
elif opcion == 3:
print("Saliendo del programa")
exit("saliendo...")
else:
raise ValueError ("Rango incorrecto")
| false |
dccfdceed841d73464d0687441f4268326bb5db6 | araratkhachadurian/calculator-python | /model/operations.py | 605 | 4.125 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def power(x, y):
return x ** y
def calculate(x, y, operator):
# addition
if operator == '+':
return add(x, y)
# subtraction
elif operator == '-':
return subtract(x, y)
# multiplication
elif operator == 'x' or operator == '*':
return multiply(x, y)
# division
elif operator == '/' or operator == ':':
return divide(x, y)
# power
elif operator == '^':
return power(x, y)
| false |
b675fe87d1dcffff24de8d6f477679a2f44b0e9e | vishnuchauhan107/pythonBasicToAdvance | /python_notes_by_vishnu/vch/file_handling/file_handling1.py | 1,652 | 4.65625 | 5 | #Q4. To create multiple directories like sub1 in that sub2 in that sub3:
#import os
#os.makedirs("sub1/sub2/sub3")
#print("sub1 and in that sub2 and in that sub3 directories created")
# sub1 and in that sub2 and in that sub3 directories created
#Q5. To remove a directory:
'''import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")
out-mysub2 directory deleted '''
#Q6. To remove multiple directories in the path:
'''import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
# All 3 directories sub1,sub2 and sub3 removed'''
#Q7. To rename a directory:
'''import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")'''
# mysub directory renamed to newdir
# Q8. To know contents of directory:
# os module provides listdir() to list out the contents of the specified directory. It won't
# display the contents of sub directory.
import os
print(os.listdir(""))
#['newdir', 'hii', 'file_handling.py', 'files.zip', 'abc.txt', 'abcd.txt', 'file_handling1.py']
# Q9. To know contents of directory including sub directories:
# We have to use walk() function
import os
for dirpath,dirnames,filenames in os.walk(''):
print("Current Directory Path:",dirpath)
print("Directories:",dirnames)
print("Files:",filenames)
print()
# Current Directory Path: ./newdir
# Directories: []
# Files: []
#
# Current Directory Path: ./hii
# Directories: []
# Files: []
# Pickling and Unpickling of Objects:
# Sometimes we have to write total state of object to the file and we have to read total
# object from the file
# pickle.dump(object,file)
# obj=pickle.load(file)
| true |
900304553cb90550ad190a1f51c5f0048e9cc85b | rafinharamos/Exercicios-WTTD- | /Andressa/Desafio-com-test/notas_moedas.py | 1,274 | 4.34375 | 4 | """
Notas e moedas
Leia um valor de ponto flutuante com duas casas decimais. Este valor representa um valor monetário.
A seguir, calcule o menor número de notas e moedas possíveis no qual o valor pode ser decomposto.
As notas consideradas são de 100, 50, 20, 10, 5, 2. As moedas possíveis são de 1, 0.50, 0.25, 0.10, 0.05 e 0.01.
A seguir mostre a relação de notas necessárias.
Entrada
O arquivo de entrada contém um valor de ponto flutuante N (0 ≤ N ≤ 1000000.00).
Saída
Imprima a quantidade mínima de notas e moedas necessárias para trocar o valor inicial, conforme exemplo fornecido.
Obs: Utilize ponto (.) para separar a parte decimal.
"""
montante = float(input("Digite o valor para saber a quantidade respectiva de notas e moedas: "))
cedulas = [100, 50, 20, 10, 5, 2]
moedas = [1, 0.50, 0.25, 0.10, 0.05, 0.01]
print("Notas:")
for nota in cedulas:
qtd_nota = int(montante / nota)
print("{} nota(s) de R$ {:.2f}".format(qtd_nota, nota))
montante -= qtd_nota * nota
print("Moedas")
for moeda in moedas:
qtd_moeda = int(montante / moeda)
print("{} moeda(s) de R$ {:.2f}".format(qtd_moeda, moeda))
montante -= qtd_moeda * moeda
assert moeda >= 0.01 < 1
assert nota >= 2 < 100
assert qtd_nota >= 0
assert qtd_moeda >= 0
| false |
e0be7fbe200d385cf797235f1bc092490f0bca12 | rafinharamos/Exercicios-WTTD- | /FabioJacob/TV.py | 1,117 | 4.25 | 4 | """
Classe TV: Faça um programa que simule um televisor criando-o como um objeto.
O usuário deve ser capaz de informar o número do canal e aumentar ou diminuir
o volume. Certifique-se de que o número do canal e o nível do volume permanecem
dentro de faixas válidas.
"""
class TV:
def canal(self, num):
validos = ('2', '4', '5', '7', '9', '11', '13')
if str(num) in validos:
saida = str(num)
else:
saida = 'Canal não existe.'
return saida
def volume(self, vol):
v = 0
if vol in range(0, 101):
if vol < v:
v = vol
som = f'Vol {vol}'
else:
som = 'Volume fora da faixa.'
return som
# testes
tv = TV()
assert tv.canal(2) == '2'
assert tv.canal(3) == 'Canal não existe.'
assert tv.canal(13) == '13'
assert tv.canal(30) == 'Canal não existe.'
assert tv.volume(2) == 'Vol 2'
assert tv.volume(101) == 'Volume fora da faixa.'
assert tv.volume(-1) == 'Volume fora da faixa.'
# Programa principal
tv = TV()
print(tv.canal(132), tv.volume(20))
| false |
af11219570e4dec041972596d34da9708ec34daf | melanyantoniazzi/pythonaulaeexercicios | /aula5.py | 588 | 4.21875 | 4 | # quinto programa bloco de instruções
num1=int(input("Digite um número: "))
if (num1>10):
print("O valor é maior do que 10!")
if(num1<=15):
print("O valor é maior do que 10, mas menor do que 15.")
else:
if(num1<=50):
print("O valor é maior do que 10, mas menor do que 50.")
else:
print("O valor é maior do que 50.")
else:
if(num1>5):
print("O número é menor que 10 mas maior do que 5!")
if(num1==7):
print("O numero é igual a 7.")
else:
print("O valor é menor do que 5.") | false |
839b53b5d556a1651524647350cc5cc271b1809f | Dharsh-21/30DayCodeChallenge | /Day21-Program.py | 1,004 | 4.46875 | 4 | #Day21
#1 Write a program using zip() function and list() function,
# create a merged list of tuples from the two lists given.
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
#2 First create a range from 1 to 8. Then using zip,
# merge the given list and the range together to create a new list of tuples.
lst1=["Energy", "Agriculture", "Industry", "Technology", "Finance", "Forestry", "Transport"]
rng1=(1,8)
lst=zip(lst1,rng1)
print(lst)
#3 Using sorted() function, sort the list in ascending order.
a = (1, 11, 2)
x = sorted(a)
print(x)
#4 Write a program using filter function,
# filter the even numbers so that only odd numbers are passed to the new list.
numbers = [1,2,6,7,13,14,12,17,16,53,67,34,75,48]
def odd_numbers(num):
if(num%2 != 0):
return True
else:
return False
oddNums = filter(odd_numbers, numbers)
print('odd Numbers are:')
new_list =[]
for num in oddNums:
new_list.append(num)
print(new_list) | true |
5c6429690ec2512bb0b19cf40260261553eeda00 | fabiomassa/dojo | /problem1.py | 574 | 4.1875 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
class Natural:
def isMultiple(self, number):
return number % 3 == 0 or number % 5 == 0
def sum(self, sequence):
index = 0
sum = 0
while index < sequence:
index += 1
if self.isMultiple(index):
sum += index
return sum
if __name__ == '__main__':
print Natural().sum(999) | true |
87cde3a8d0b281da3c3a087831629b6ef0b66dc1 | frainfreeze/studying | /home/old/python/04__mojPosao.py | 507 | 4.28125 | 4 | # Replace "not ... bad" substring starting with NOT
# and ending with BAD) with "good" in the input.
# Input
# Sentence
# Output
# Sentence with replaced substring
# Example
# Input:
# This pizza is not too bad.
# Output:
# This pizza is good.
def processLine(inputLine):
_not = inputLine.find('not')
bad = inputLine.find('bad')
if bad > _not:
inputLine = inputLine.replace(inputLine[_not:(bad+3)], 'good')
return inputLine
print(processLine("This pizza is not too bad."))
#passed | true |
c5e213a736caf274bb60af6e7c07292a8a44a486 | Ashot-Sargsyan/home-wortk-python- | /lesspn7homework.py | 2,269 | 4.25 | 4 | # '''1)We write a program where we buy to a phone'''
# phone=input('Do you have iphone and samsung') == 'yes'
# model=input('Do you have iphone 11 pro max or iphone 12 pro') == 'yes'
# iphone=input('You are buying to iphone and green color')=='yes'
# result=phone and model and iphone
# if result:
# print('Buy to ')
# else:
# print('There is no phone in our store that suits you')
# '''2)We writen a program where a chek 5 question '''
# question1=input('Where you were born')=='Russia'
# question2=input('Where are you living now')== 'Armenia'
# question3=int(input('How old do you live in Armenia'))==15
# question4=input('Do you study')=='yes'
# question5=input('Do you a work')== 'yes'
# result=question1 and question2 and question3 and question4 or question5
# if result:
# print('Very well you are hired')
# else:
# print('Sorry but you do not fit us')
'''3)We writen a program where cheak age employee'''
# import random
# age=random.randint(17,25)
# result_age=age>=17 or age<=25
# print(age,result_age)
# higher_education=input('do you have higher_education? ')=='yes'
# work=input('do you experience?')=='yes'
# human=result_age and work or higher_education
# if human:
# print('Very well','\n','your age is :',age,'\n','you fit in our age in company:',result_age,'\n','your higher_education',higher_education,'\n','your experience is not bad',work)
# else:
# print('you didnt enter work our office')
'''4)We write a program buy to dream car'''
# cars ="BMW Mercedes-Benz Hundai Honda Audi Subaru Tesla"
# company=input('We have many different types of machines')
# if company in cars:
# print('Let is go,Buy to cars',company.upper())
# else:
# print('Unfortunately, we do not have such a car')
'''5)We write a program math (a+b)**3'''
# a=5
# b=6
# x=(a+b)**3
# print(x)
# x=a**3+3*a**2*b+3*a*b**2+b**3
# print(x)
'''6)We write a program '''
# import random
# computer=random.randint(1,10)
# human='1,2,6,8,10'#stringa
# res=str(computer) in human#tive bara darcnum str
# if res :
# print('my number is :',human ,'\n','number computer is :','\n',computer,'\n',res,)
# else:
# print('your number is FALSE EROR 5005',computer)
# '''7)Factorial'''
# import math
# number=int(input('My naumber is :'))
# print(math.factorial(number))
| true |
66220261d75e19543d0588f913384d2c9824892b | Mj-R/python-program | /exchange rate convention/Exchange rate converter.py | 1,832 | 4.125 | 4 | # Python lab program - 4/August/2020
# https://repl.it/join/nhgmhchi-manojkumarkuma6
# Python program to convert the currency of one currency value to that of another currency value
# Import the modules needed, Requests is a Python module that you can use to send all kinds of HTTP requests. It is an easy-to-use library with a lot of features ranging from passing parameters in URLs to sending custom headers and SSL Verification.
import requests
print("Python program to convert the currency of one currency value to that of another currency value")
print()
print("Note: please use Upper-case")
print("Example:- AUD, EUR, INR, USD, SUA")
print()
class Currency_convertor:
# Empty dictionary to store the exchange rates from json list
rates = {}
def __init__(self, url):
data = requests.get(url).json()
# Extracting the rates from the json list
self.rates = data["rates"]
# Function to do the amount conversion
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
if from_currency != 'EUR' :
amount = amount / self.rates[from_currency]
# Amount calculation and rounding it to 2 decimal places
amount = round(amount * self.rates[to_currency], 2)
#Output using format feature
print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))
# Driver code
if __name__ == "__main__":
# Public api to get updated exchange rate values
url = str.__add__('http://data.fixer.io/api/latest?access_key=', 'a0164515fffd9356e9370068636b2742' )
c = Currency_convertor(url)
from_country = input("From: ")
to_country = input("To : ")
amount = int(input("Amount: "))
# Calling convert fn from Currency_convertor class
c.convert(from_country, to_country, amount)
| true |
91f971f2d406080d51d8fd363741ed0d2a4917e7 | MariaAfanaseva/Tasks_Python | /OOP/task_1.py | 679 | 4.21875 | 4 | """
Check out the inheritance mechanism in Python.
To do this, create two classes. The first is the parent (ItemDiscount),
should contain static information about the product: name and price.
The second is a child (ItemDiscountReport),
should contain a function (get_parent_data) corresponding
for displaying product information in one line.
Check the operation of the program.
"""
class ItemDiscount:
def __init__(self):
self.name = 'Car'
self.price = 20000
class ItemDiscountReport(ItemDiscount):
def get_parent_data(self):
print(f'Product name: {self.name}, price: {self.price}')
shop = ItemDiscountReport()
shop.get_parent_data()
| true |
a89bbc47be15527dd50908e85c6b3ce0596f97ee | Subhraj07/Python_Tutorials | /DS Implement/Linear_Search.py | 385 | 4.125 | 4 | # https://www.thecrazyprogrammer.com/2017/05/python-linear-search.html#
# time complexity O (n)
items = [5, 7, 10, 12, 15]
print("list of items is", items)
x = int(input("enter item to search:"))
i = 0
flag = 0
while i < len(items):
if items[i] == x:
flag = 1
break
i = i + 1
if flag == 1:
print("found location ", i + 1)
else:
print("Not found")
| true |
e4386af08e649b307220b71f147ea5e5e57104a0 | BenKnowlson18/p02.1x | /sequences.py | 1,153 | 4.5 | 4 | """
Problem:
The function in_sequence takes in 3 inputs: a, b and t.
If t is present in the sequence a + b, it prints which term it is in
the sequence, otherwise it prints out "Not present".
For example:
in_sequence(3, 2, 14) is looking at the sequence 3n + 2.
The terms in this sequence are: 5, 8, 11, 14, 17, 20, ...
14 is the 4th term in this sequence so the function would print out 4.
in_sequence(7, -2, 25) is looking at the sequence 7n - 2.
The terms in this sequence are 5, 12, 19, 26, 33, ....
25 is not present in this sequence so the function would print "Not present"
Tests:
>>> in_sequence(3, 2, 14)
4
>>> in_sequence(5, -3, 37)
8
>>> in_sequence(-2, 20, 28)
Not present
>>> in_sequence(6, 3, 23)
Not present
>>> in_sequence(-3, 100, 1)
33
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this function
def in_sequence(a, b, n):
if (n - b) % a != 0 or (n - b) // a < 0:
print("Not present")
elif (n - b) % a == 0:
print((n - b) // a)
| true |
15f2cc7e2b734700542715c14d60317d32c7b1f7 | vega2k/python_basic | /mycode/10pythonic/list_comprehension.py | 1,376 | 4.15625 | 4 | # 일반적인 for + append
result = []
for val in range(10):
if val % 2 == 0:
result.append(val)
print(result)
# List Comprehensions
result2 = [val for val in range(10) if val % 2 == 0]
print(result2)
my_str1 = "Hello"
my_str2 = "World"
result = [i+j for i in my_str1 for j in my_str2 if not (i == j)]
print(result)
words = 'Arguments can be passed to functions in four different ways'.split()
print(words)
my_list = [[w.upper(), w.lower(), w.title(), len(w)] for w in words]
print(type(my_list), my_list)
for word in my_list:
print(word)
# enumerate 함수 - for loop 를 dict에 저장
for idx, w in enumerate(words):
print(idx, w)
print(enumerate(words), type(enumerate(words)))
print(list(enumerate(words)))
word_dict = {idx: w for idx, w in enumerate(words, 1)}
print(word_dict)
# zip 함수
my_list1 = [1, 2, 3]
my_list2 = [10, 20, 30]
my_list3 = [100, 200, 300]
print(zip(my_list1, my_list2, my_list3), type(zip(my_list1, my_list2, my_list3)))
print(list(zip(my_list1, my_list2, my_list3)))
for val in zip(my_list1, my_list2, my_list3):
print(type(val), val, sum(val))
result = [sum(val) for val in zip(my_list1, my_list2, my_list3)]
print(result)
result_dict = {idx: sum(val) for idx, val in enumerate(zip(my_list1, my_list2, my_list3)) }
print(result_dict)
a, b, c = zip(my_list1, my_list2, my_list3)
print(a)
print(b)
print(c)
| false |
91ab6c03c0766671edc17bef426794e10ba3eca1 | vega2k/python_basic | /mycode/7_8_function/average_function.py | 351 | 4.15625 | 4 | # list에 저장된 값의 평균을 계산하는 함수 정의
def my_average(numbers):
print(numbers)
total = 0
for num in numbers:
total += num
avg = total / len(numbers)
return int(avg)
def main():
my_list = [20, 50, 60, 100, 30]
result = my_average(my_list)
print('평균값은 {}'.format(result))
main() | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.