blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1fb65c1293b19fbb6155629a223213801eae2068 | 3to80/Algorithm | /LeetCode/Leet#339/Leet#339.py | 2,039 | 4.15625 | 4 | # Define f(element, level).
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger(object):
# def __init__(self, value=None):
#
# def isInteger(self):
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
# f(element, level):
# #Exception
# if not element:
# return 0
# #Default
# if element is singleIntger:
# return element * level
# #Recursion
# ret = 0
# for i in element:
# ret +=f(i, level+1)
# return ret
# [[1,1],2,[1,1]]
# [Nested, Nested, Nested]
# [[],[]],[]]
class Solution(object):
def f(self, element, level):
# Exception
# Default
if not isinstance(element, list):
if not element.isInteger():
return 0
return element.getInteger() * level
# Recursion
ret = 0
for i in element:
if i.getList():
ret += self.f(i.getList(), level + 1)
else:
ret += self.f(i, level + 1)
return ret
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
return self.f(nestedList, 0) | true |
f84f43287cc6d1538fb6b6a9d5b1b9451c833199 | sgn255/programs | /IS 3/bots/mybot/mybot.py | 2,797 | 4.125 | 4 | """
RandomBot -- A simple strategy: enumerates all legal moves, and picks one
uniformly at random.
"""
# Import the API objects
from api import State, util, Deck
import random
class Bot:
def __init__(self):
pass
def get_move(self, state):
# type: (State) -> tuple[int, int]
"""
Function that gets called every turn. This is where to implement the strategies.
Be sure to make a legal move. Illegal moves, like giving an index of a card you
don't own or proposing an illegal mariage, will lose you the game.
TODO: add some more explanation
:param State state: An object representing the gamestate. This includes a link to
the states of all the cards, the trick and the points.
:return: A tuple of integers or a tuple of an integer and None,
indicating a move; the first indicates the card played in the trick, the second a
potential spouse.
"""
# All legal moves
''' moves = state.moves()
imp=[0,1,5,6,10,11,15,16]
high=[]
played_card = state.get_opponents_played_card()
if played_card is not None:
for move in moves:
if (move[0] in imp) & (move[0] < played_card):
return move
return max(moves)
else:
for move in moves:
if move[0] in imp:
high.append(move)
if len(high)>0:
return min(high)
else:
return max(moves)'''
moves = state.moves()
imp = [0, 1, 5, 6, 10, 11, 15, 16]
scores =[11,10,4,3,2]
high = []
played_card = state.get_opponents_played_card()
if played_card is not None:
for move in moves:
if ((move[0]%5) < (played_card % 5)) & (util.get_suit(move[0])==util.get_suit(played_card)):
return move
for move in moves:
if ((move[0]%5) < (played_card % 5)) & (state.get_trump_suit()==util.get_suit(move[0])):
return move
return max(moves)
else:
for move in moves:
if move[0]%5 < 1 & (state.get_trump_suit()!=util.get_suit(move[0])):
return move
for move in moves:
if move[0]%5 < 2 & (state.get_trump_suit()!=util.get_suit(move[0])):
return move
for move in moves:
if move[0]%5 < 2 & (state.get_trump_suit()==util.get_suit(move[0])):
return move
for move in moves:
if move[0]%5 >= 2 & (state.get_trump_suit()!=util.get_suit(move[0])):
return move
return max(moves)
| true |
2f0eb4e6d2fd9a8a3c45b87d60f670742c02a0ca | yamax87/NumberGuessApp | /numberGuess.py | 2,361 | 4.125 | 4 | """
GUESS THE NUMBER GAME
Welcome to game
random number generated
Think of number between x and y
Ask user to guess
Say if correct
Say if incorrect
Say "thanks for playing"
EXTRAS
ask user to set max/min vals
offer user clues
"""
import random
import time
def RandomNum():
randomNumber = random.randint(1,10)
return randomNumber
randomNumber=RandomNum()
def welcome():
print ("Welcome to Cesar's Number guess!")
def gameStart():
print("I am thinking of a number between 1 and 10.")
time.sleep(1)
print("Can you guess what it is?")
userInput(randomNumber)
def userInput(NumberToGuess):
try:
userGuess = int(input("Go on, enter a number between 1 and 10."))
if userGuess == NumberToGuess:
rightAnswer()
elif userGuess >10 or userGuess <1:
UserGuessOutOfBounds()
elif userGuess > NumberToGuess:
UserGuessHigh()
elif userGuess < NumberToGuess:
UserGuessLow()
except ValueError:
WrongInput()
def ByeBye():
time.sleep(0.5)
print("Thanks for playing!")
def WrongInput():
print("What you just typed in makes no sense, you useless clobberbat.")
userInput(randomNumber)
def UserGuessLow():
time.sleep(0.5)
print("That's too low! Try again.")
userInput(randomNumber)
def UserGuessHigh():
time.sleep(0.5)
print("That's too high! Try again.")
userInput(randomNumber)
def UserGuessOutOfBounds():
time.sleep(0.5)
print("I said between 1 and 10! How lucky did you bloody feel when you put finger to button?")
time.sleep(1)
print("Honestly, I suspect a problem exists between your chair and your keyboard...")
time.sleep(1)
print("Right...")
time.sleep(1)
print("Sigh...let's try that again...")
time.sleep(1)
userInput(randomNumber)
def rightAnswer():
time.sleep(0.5)
print("That's right, you bloody genius. How'd you get to be so clever?")
time.sleep(1)
playAgain()
def playAgain():
userPlayAgain=input("Would you like to play again? Enter 'yes' or 'no'.")
if userPlayAgain == "yes":
gameStart()
elif userPlayAgain =="no":
ByeBye()
elif userPlayAgain != "yes" or "no":
time.sleep(1)
print("Speak slowly and carefully. 'yes', or 'no'?")
playAgain()
welcome()
gameStart()
| true |
3ff5fc1d7a2a31f7ba88f609debfc2252546ef1b | GraceDurham/Cracking_the_coding_interview | /is_permutation_grace_steph.py | 1,137 | 4.25 | 4 |
def is_permutation(s1, s2):
""" Checks if two strings are permutations of each other"""
# If the length of both strings is not the same,
# then they can not be Permutation
if (len(s1) != len(s2)):
return False
# Sort both strings
s1_sorted = " ".join(sorted(s1))
s2_sorted = " ".join(sorted(s2))
# Compare sorted strings index by index
for i in range(0, len(s1), 1):
if (s1_sorted[i] != s2_sorted[i]):
return False
return True
print(is_permutation("dog", "gdd"))
def is_permu_2(str_1, str_2):
""" Checks if two strings are permutations of each other"""
if str_1 == str_2:
return "Yay, we have permitation with string '{}'' and '{}'.".format(str_1, str_2)
else:
str_1_sorted = "".join(sorted(str_1))
str_2_sorted = "".join(sorted(str_2))
if str_1_sorted != str_2_sorted:
return "Sooo sorry, we do not have permitation with string '{}'' and '{}'.".format(str_1,str_2)
return "Yay, we have permitation with string '{}'' and '{}'.".format(str_1, str_2)
print(is_permu_2("dog", "god"))
| true |
6e19226227986f87058aa237d13c311624d47354 | Inventrixx/datascience-exercises | /exercises/improving_website.py | 1,901 | 4.53125 | 5 | """ III. Statistics
3.1 Improving a website
A coworker performed an A/B test to improve the revenue of your company's website. He created two different flows and registered the amount of money that each customer expended.
The test is finished and your colleague uploaded all the data to a spreadsheet.
He asked you to analyze the data and help him to decide whether the alternative configuration is better than control. Also, since this is going to be presented at the management, you need to find a way to explain and show (justifying from the data) how this change could potentially impact company revenue.
Some notes about how data was collected:
- Users were randomly assigned to each config from the minute they entered the website.
- It is a representative sample.
- All the variables were properly controlled.
"""
# Solve this problem here
'''
Due to the fact that the data was randomly assigned to each config from the
minute they entered the website, it is a representative sample and all
the variables were properly controlled, we can conclude that it is convenient
to choose group B since it will bring higher profits and benefits.
As you can see in the graph the amount spent by group B is greater than the
amount spent by group A.
'''
import requests
import matplotlib.pyplot as plt
def dataframe_creator(url):
response = requests.get(url)
open('ab_testing.csv', 'wb').write(response.content)
amount_a = 0.0
amount_b = 0.0
with open('ab_testing.csv') as f:
for line in f.readlines():
elements = line.strip().split(',')
if elements[1] == 'A':
amount_a += float(elements[2])
elif elements[1] == 'B':
amount_b += float(elements[2])
data = [amount_a, amount_b]
plt.bar(['group A', 'group B'], data)
plt.show()
dataframe_creator("https://www.dropbox.com/s/1a5ss6oknp93bku/ab_website.csv?dl=1") | true |
bd1cf52c9db6e26cc7c07a0589d4c5e136387b4d | haakoneh/TDT4110 | /Oving_5/Oving5_5.py | 294 | 4.15625 | 4 | def fibonacci_loop(n):
for i in range (0, n):
if(i == 0):
sum = 0
elif(i == 1):
sum = 1
n_1 = 1
else:
n_2 = sum
sum += n_1
n_1 = n_2
return sum
def main():
while True:
n = int(input('Skriv inn antall ledd '))
#fib_list = []
print(fibonacci_loop(n))
main()
| false |
7586a044737e2480ae44a669014f5a1280343aa3 | armenjuhl/ATM-Machine | /src/atm.py | 2,554 | 4.125 | 4 | from src.AtmClass import ATM
def main():
atm = ATM()
command = ''
while command.lower() != 'exit':
command = input('What would you like to do (deposit, withdraw, check balance, history)\n$ ')
# Case: Deposit
if command == 'deposit':
amount = 0
deposit = False
while deposit is False:
try:
amount = input('How much would you like to deposit\n$ ')
if amount.lower() == 'exit':
break
amount = int(amount)
atm.deposit(amount)
response = input('Thank you for your business. Would you like to do anything else? (y/n)\n')
if response.lower == 'yes' or response == 'y':
withdraw = True
else:
print('Have a great day')
return True
break
except Exception as TypeError:
print('Must enter a valid number. Enter exit to go back.')
# Case: Withdraw
if command == 'withdraw':
amount = 0
withdraw = False
while withdraw is False:
try:
amount = input('How much would you like to withdraw\n$ ')
if amount == 'exit':
break
amount = int(amount)
withdrawal = atm.withdraw(amount)
response = input('Thank you for your business. Would you like to do anything else? (y/n)\n')
if response.lower == 'yes' or response == 'y':
withdraw = True
else:
print('Have a great day')
return withdrawal
except Exception as TypeError:
print('Must enter a valid number. Enter exit to go back.')
# Case: Check balance
if command.lower() == 'check balance' or command.lower() =='balance':
balance = atm.check_balance()
print(f"Balance: ${balance}")
response = input('Thank you for your business. Would you like to do anything else? (y/n)\n')
if response.lower != 'yes' or response != 'y':
continue
else:
print('Have a great day')
return True
# Case: History
if command.lower() == 'history':
atm.print_transactions()
| true |
3500e45202e6f367eb039b442072fa96bd080ab3 | clay-beach/Python_Programs | /Sorting Algorithms/Sorting.py | 2,478 | 4.1875 | 4 | # Import Statements
import random
import time
# Question 10/11 Bubble sort algorithm
def bubbleSort(ll):
for i in range(len(ll)-1, 0, -1):
for j in range(i):
if ll[j] > ll[j + 1]:
ll[i] = ll[j]
ll[j] = ll[j + 1]
ll[j + 1] = ll[i]
# End BubbleSort
# Question 12 Implement the selection sort using simultaneous assignment.
def selectionSort(ll):
for i in range(len(ll)-1, 0, -1):
max = 0
for location in range(1, i + 1):
if ll[location] > ll[max]:
max = location
temp = ll[i]
ll[i] = ll[max]
ll[max] = temp
# End selectionSort
# Question 14 Implement the mergeSort function without using the slice operator.
def mergeSort(ll):
if len(ll) > 1:
# find midpoint of list
mid = len(ll) // 2
# Splits list to left and right of mid
left = ll[:mid]
right = ll[mid:]
# Calls mergeSort Function on splits
mergeSort(left)
mergeSort(right)
# Ordering the lists
# K is counter, I is left, j is right
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
ll[k] = left[i]
i += 1
else:
ll[k] = right[j]
j += 1
k += 1
while i < len(left):
ll[k] = left[i]
i += 1
k += 1
while j < len(right):
ll[k] = right[j]
j += 1
k += 1
# Main
n = 1000
min, max = 0, n
trials = 10
sumTime = 0
exe = 0
random.seed(1234)
for i in range(trials):
testList = [random.randint(min, max) for num in range(n)]
start = time.time()
bubbleSort(testList)
end = time.time()
exe = end - start
sumTime += exe
print("Sorting took exe%.2f" % exe + "Seconds on average for BubbleSort")
for j in range(trials):
testList = [random.randint(min, max) for number in range(n)]
start = time.time()
selectionSort(testList)
end = time.time()
exe = end - start
sumTime += exe
print("Sorting took exe%.2f" % exe + "Seconds on average for selectionSort")
for k in range(trials):
testList = [random.randint(min, max) for numeral in range(n)]
start = time.time()
mergeSort(testList)
end = time.time()
exe = end - start
sumTime += exe
print("Sorting took exe%.2f" % exe + "Seconds on average for mergeSort")
| true |
a22d61c5996b488621b038728de8c2a84f402632 | buzsb/PythonExample | /BackwardString.py | 658 | 4.40625 | 4 | # Program that asks the user for a long string containing multiple words
# Print back to the user the same string, except with the words in
# backwards order
def user_string():
your_string = raw_input("Print your long string: ")
you_revers_str = backwards_string(your_string)
return you_revers_str
def backwards_string(your_string):
if not isinstance(your_string, basestring):
raise TypeError
split_string = your_string.split()
revers_str = ' '.join(split_string[::-1])
return revers_str
if __name__ == '__main__':
try:
print user_string()
except TypeError:
print 'Your input not a string'
| true |
e0d1d8898b267ab95fdc092cc906c4f22beb66b6 | codio-content/ms-m12-conditionals-and-repetition | /.guides/content/ExampleInput.py | 362 | 4.28125 | 4 | #Note - for the purpose of this example driving age is assumed at 16 years
name = input( 'What is your name?' )
age = int(input('What is your age?'))
if age ==16:
print ('%s, you can get your license' % name)
elif age < 16:
print ('%s,you are too young to get your license' % name)
else:
print ('%s,you already have your license' % name)
| true |
ca80bb3caf3f1eb40eca5df9e575fd540dfdd77b | SaadAbdullah11/Internship-coding | /product and sum.py | 284 | 4.21875 | 4 |
#Given two integer numbers return their product. If the product is greater than 1000, then return their sum
a=int(input("Please enter a number:"))
b=int(input("Please enter another number:"))
product=a*b
print("Product=", product)
if product>1000:
sum=a+b
print("Sum=", sum)
| true |
f0ed74cedd86d6a56e8bfc78066d3c78f21a6304 | JhanielCC/Python-CursoUdemy | /08-funciones/main.py | 2,951 | 4.1875 | 4 | """
FUNCION
Es un conjunto de instrucciones agrupadas bajo
un nombre concreto que pueden reutilizarce invocando a
la funcion tantas veces como sea necesario
def nombre_funcion(parametros):
# Bloque / conjunto_de_instrucciones
nombre_funcion(parametro)
"""
########## Ejemplo 1 ######### Invocar una función
def muestra_nombre():
print("Usuario 1")
print("Usuario 2")
print("Usuario 3")
#muestra_nombre()
########## Ejemplo 2 ######### Paso de parametros
def mostrartunombre(name,age):
print(f"Tu nombre es: {name}")
if age >=18:
print("Eres mayor de edad")
else:
print("Aun no eres mayor de edad")
nm = "Juan" #str(input("Como te llamas?: "))
edad= 18 #int(input("Dame tu edad: "))
#mostrartunombre(nm,edad)
########## Ejemplo 3 #########
def tabla(numero):
print(f"Tabal del {numero}")
for c in range(1,11):
print(f"{numero} X {c} = {numero*c}")
print("\n")
tbnum = 5# int(input("Dame un numero: "))
#tabla(tbnum)
########## Ejemplo 3 ######### Tablas de multiplicar
"""
for c in range(1,11):
tabla(c)
"""
########## Ejemplo 4 ######### Parametros opcionales
def getEmpleado(nombre,dni = None):
print("EMPLEAADO")
print(f"Nombre: {nombre}")
if dni != None:
print(f"DNI: {dni}")
#getEmpleado("Jhaniel","77788999")
#getEmpleado("User")
########## Ejemplo 5 ######### Parametros opcionales return
"""
def saludame(nombre):
saludo = f"Hola nuevo usuario {nombre}"
return saludo
print(saludame("Jhaniel"))
"""
########## Ejemplo 6 ######### Parametros opcionales return
def calculadora(num1,num2,basicas=False):
suma = num1 + num2
resta = num1 - num2
multi = num1 * num2
divi = num1 // num2
cadena = " "
#cadena +="Suma: " + str(suma) +"\nResta: "+str(resta)+"\nMultiplicación: "+str(multi)+"\nDivisión: "+str(divi)
if basicas != False:
cadena +="Suma: " + str(suma) +"\nResta: "+str(resta)
else:
cadena +="\nMultiplicación: "+str(multi)+"\nDivisión: "+str(divi)
return cadena
#print(calculadora(98,12,True))
########## Ejemplo 7 ######### Funcion que llama funcion
def getNombre(nombre):
texto=f"El nombre del usuario es {nombre}"
return texto
def getApellidos(apellidos):
texto=f"Los apellidos del usuario son {apellidos}"
return texto
def regresaTodo(nombre,apellidos):
texto = getNombre(nombre) + "\n"+ getApellidos(apellidos)
return texto
#print(getNombre("Usuario"))
#print(getApellidos("Apellidos Usuario"))
#print(regresaTodo("Jhaniel","Coronel C"))
########## Ejemplo 8 ######### Funciones anonimas lambda
"""
Una función lambda es una función anonima, una funcion que no tiene nombre
Funciones que sirven para tareas simples y pequeñas pero que pueden llegar a ser
repetitivas y que todo su contenido se traduce en una linea de codigo
"""
dime_el_year = lambda year:f"El año es {year}"
#print(dime_el_year(2021)) | false |
0df21bd1334e9d4a278021589cb3def350d8b3f5 | JhanielCC/Python-CursoUdemy | /02.py | 1,611 | 4.40625 | 4 | """
Variables y tipos
Una variables es un contenedor de información
que dentro guardará, un dato, se pueden crear
muchas variables y que cada una tenga un dato distinto.
"""
#Python es debilmente tipado, no hay que indicar el tipo de dato que va a ser solo interpreta el tipo de dato con el contido de este
texto = "Curso de Python"
#texto = 1
texto2 = 'en Udemy'
numero = 2
decimal = 6.7
#print(texto)
"""
Concatenar
Mostrar varias variables juntas
"""
nombre = 'Nombre Usuario'
apellidos = 'C C'
git = 'https://github.com/JhanielCC'
print("Hola yo soy"+nombre+" "+apellidos)
print(f"Hola soy {nombre} {apellidos}")
print("Hola soy {} {} y mi GH es: {}".format(nombre,apellidos,git))
print("-----------------------TIPOS DE DATOS-----------------------------------")
"""
Tipos de datos
"""
nada = None
cadena = "Soy una cadena"
entero = 99
flotante = 4.2
boleano = True #True/False
lista = [00,10,20,30,40,50,60,70,80,90]
listaStr = [12,"Uno",44,"Cien"]
tupla = ("Curso", "en", "Python")#Es una lista de datos que no pueden cambiar
diccionario = {
"nombre":"Jhaniel",
"apellido": "CC",
"edad":26
}#Es un tipo de Array asociativo / Documento json. Colección de datos Clave y Valor
rango = range(9)
dato_byte = b"Test"
print(dato_byte)
#Mostrar tipo de dato
print(type(dato_byte))
print("--------------------------CONVERTIR TIPO DE DATO--------------------------------")
"""
Convertir tipo de datos a otro
"""
txt = "Soy un texto"
num = str(5) #Convertir a str
print(type(num))
print(txt+" "+num)
num = int(5) #Convertir a int
print(type(num))
num = float(5) #Convertir afloat
print(type(num))
| false |
40c2dd8b71910df84d7dd0a9f91919a9c35860a0 | MikeOnAMission/Password_Cracker | /password_cracker.py | 1,626 | 4.375 | 4 | from sys import argv
import string
alphabet = ''
alphabet += string.ascii_letters
alphabet += string.digits
alphabet += string.punctuation
"""A program that generates every possible combination of a string using '*' for unknown characters."""
script, string = argv
def first_character():
"""Returns list containing first letter or possible first letters"""
next_letter = []
if '*' in string[:1]:
for letter in alphabet:
next_letter.append(letter)
return next_letter
else:
next_letter.append(string[:1])
return next_letter
def next_character(slice1, slice2, current_letter):
"""Iterates over existing letter(s), appending all possible letter combinations"""
next_letter = []
if '*' in string[slice1:slice2]:
for letter in current_letter:
for alphabet_letter in alphabet:
combination = f'{letter}{alphabet_letter}'
next_letter.append(combination)
return next_letter
else:
for letter in current_letter:
existing_letter = string[slice1:slice2]
combination = f'{letter}{existing_letter}'
next_letter.append(combination)
return next_letter
def main():
"""Returns an index of possible letter combinations"""
slice1 = 1
slice2 = 2
current_letter = first_character()
for i in range(len(string)):
next_letter = next_character(slice1, slice2, current_letter)
current_letter = next_letter
slice1 += 1
slice2 += 1
for index, i in enumerate(current_letter):
print(index, i)
main()
| true |
f073054b5fe340e6c08c48a58ae352259f77c442 | sachisabya28/Python-Basics | /Functions/functions.py | 2,318 | 4.3125 | 4 | # A function is a set of statements that take inputs, do some specific computation and
# produces output. The idea is to put some commonly or repeatedly done task together and
# make a function, so that instead of
# writing the same code again and again for different inputs, we can call the function.
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print ("even")
else:
print("odd")
# Driver code
evenOdd(2)
evenOdd(3)
##############################
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)
############################
def myFun(x):
# After below line link of x with previous
# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]
# Driver Code (Note that lst is not modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)
###############################
def python_food():
width = 80
text = "Spam and eggs"
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
################################
def centre_text(*args, sep=' '):
text = ""
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)) // 2
return " " * left_margin + text
##############################
def swap(x, y):
temp = x;
x = y;
y = temp;
# Driver code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
##############################
# with open("centred", mode='w') as centred_file:
# call the function
# s1 = centre_text("spam and eggs")
# print(s1)
# s2 = centre_text("spam, spam and eggs")
# print(s2)
# s3 = centre_text(12)
# print(s3)
# s4 = centre_text("spam, spam, spam and spam")
# print(s4)
# s5 = centre_text("first", "second", 3, 4, "spam", sep=":")
# print(s5)
with open("menu", "w") as menu:
s1 = centre_text("spam and eggs")
print(s1, file=menu)
s2 = centre_text("spam, spam and eggs")
print(s2, file=menu)
print(centre_text(12), file=menu)
print(centre_text("spam, spam, spam and spam"), file=menu)
s5 = centre_text("first", "second", 3, 4, "spam", sep=":")
print(s5, file=menu)
| true |
4531d8830c97595c267937b50f723740484811d2 | audalogy/Distributed-Computing | /SQL/hw9a.leung.py | 1,514 | 4.5 | 4 |
import sqlite3
import re
# connect operation makes a “connection” to the database stored in the file
# in the current directory. If the file does not exist, it will be created.
conn = sqlite3.connect('contacts.db')
# A cursor is like a file handle that we can use to perform operations on the data stored in the database.
# Calling cursor() is very similar conceptually to calling open() when dealing with text files.
cur = conn.cursor()
#create a small SQLite database that contains the names, phone numbers, and address of four made-up people.
cur.execute('DROP TABLE IF EXISTS Contact ')
cur.execute('CREATE TABLE Contact (name TEXT, phone INTEGER, address TEXT)')
cur.execute('INSERT INTO Contact (name, phone, address) VALUES ( ?, ?, ?)', ( 'Tiffany', 4088650225, '50 Merritt Way' ))
cur.execute('INSERT INTO Contact (name, phone, address) VALUES ( ?, ?, ?)', ('Linus',6509069885,'2468 California St'))
cur.execute('INSERT INTO Contact (name, phone, address) VALUES ( ?, ?, ?)', ('Rachel',4082561324,'201 Folsom St'))
cur.execute('INSERT INTO Contact (name, phone, address) VALUES ( ?, ?, ?)', ('Jonathan',7142805888,'One Marina Way'))
conn.commit()
# Add some more Python code to execute an SQL query on your database that grabs the address of
# everyone whose name begins with a letter between M and Z inclusive.
print 'Contact:'
cur.execute('SELECT name, address FROM Contact')
for row in cur:
for name in row[0]:
if re.match("[M-Z]",name):
print row[1]
conn.commit()
cur.close()
| true |
992f88a4c7125bf99a9379a9d8511a5025fc951f | tyronedamasceno/Daily-Coding-Problem | /src/problem_23/solution.py | 2,380 | 4.3125 | 4 | """
You are given an M by N matrix consisting of booleans that represents a board.
Each True boolean represents a wall. Each False boolean represents a tile you
can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the
minimum number of steps required to reach the end coordinate from the start.
If there is no possible path, then return null. You can move up, left, down,
and right. You cannot move through walls. You cannot wrap around the edges
of the board.
For example, given the following board:
[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum
number of steps required to reach the end is 7, since we would need to go
through (1, 2) because there is a wall everywhere else on the second row.
"""
"""
Time complexity is O(n*m) and space complexity is O(n*m)
"""
import unittest
import queue
def solve(board, start, end):
n = len(board)
m = len(board[0])
visited = {(x, y): False for x in range(n) for y in range(m)}
visited[start] = True
q = queue.Queue()
q.put((*start, 0))
while not q.empty():
x, y, k = q.get()
if (x, y) == end:
return k
visited[(x, y)] = True
if x > 0 and not visited[(x-1, y)] and not board[x-1][y]:
q.put((x-1, y, k+1))
if y > 0 and not visited[(x, y-1)] and not board[x][y-1]:
q.put((x, y-1, k+1))
if x < n - 1 and not visited[(x+1, y)] and not board[x+1][y]:
q.put((x+1, y, k+1))
if y < m - 1 and not visited[(x, y+1)] and not board[x][y+1]:
q.put((x, y+1, k+1))
return None
class Tests(unittest.TestCase):
def test_example(self):
board = [
[False, False, False, False],
[True, True, False, True],
[False, False, False, False],
[False, False, False, False]
]
start = (3, 0)
end = (0, 0)
ans = solve(board, start, end)
self.assertEqual(ans, 7)
def test_no_way(self):
board = [
[False, False, False, False],
[True, True, True, True],
[False, False, False, False],
[False, False, False, False]
]
start = (3, 0)
end = (0, 0)
ans = solve(board, start, end)
self.assertEqual(ans, None)
| true |
94aa073ab65cc19957607d1dd838c6152d271fce | redcican/Python-Exercise | /14_palindrome_check.py | 946 | 4.25 | 4 | # check a given string is a palindrome or not
# A palindrome is a word or sentence that’s spelled the same way both forward and backward,
# ignoring punctuation, case, and spacing.
# You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols)
# and turn everything lower case in order to check for palindromes.
import re
def palindrome(string):
pattern = r'[\W_]'
smallString = re.sub(pattern, "", string.lower())
reversedString = ''.join(list(reversed(smallString)))
if reversedString == smallString:
return True
return False
print(palindrome("eye"))
print(palindrome("_eye"))
print(palindrome("race car"))
print(palindrome("not a palindrome"))
print(palindrome("A man, a plan, a canal, Panama"))
print(palindrome("never odd or even"))
print(palindrome("nope"))
print(palindrome("almostomla"))
print(palindrome("My age is 0, 0 si ega ym."))
print(palindrome("0_0(:/-\:)0-0"))
| true |
c879d610d7b181d3e9f343e4c9f656c4127fe5ce | kiransurendra/python | /bank_data/hai.py | 914 | 4.28125 | 4 | ''' sum of all elements in a list '''
# a=[1,2,3,4,5]
# b=a[0]+a[1]+a[2]+a[3]+a[4]
# print(b)
# a=[1,2,3]
# for item in a:
# print(a[0]+a[1]+a[2])
# break
#
# def list(item):
# sum =0
# for x in item:
# sum += x
# return sum
# print(list([1,2,3,10]))
''' multiples of all elements in a list '''
# def list(item):
# multiple =1
# for x in item:
# multiple *= x
# return multiple
# print(list([1,2,3,10]))
'''3. Write a Python program to get the largest number from a list'''
#
# def max_list(item):
# max = item[0]
# for a in item:
# if a > max:
# max = a
# return a
# print(max_list([1,5,2,6,7]))
'''4. Write a Python program to get the smallest number from a list.'''
def small_list(item):
min = item[0]
for a in item:
if a < min:
min = a
return min
print(small_list([1,2,3,4,0,-1]))
| false |
6d315e862df1a9268371762bb1298d8b3b55b8ae | harriswohl/Python-Practice | /hw_diagonal.py | 328 | 4.46875 | 4 | #takes user input as a string and displays
#the string diagonally, 3 characters at a time
userinput = input("text: ")
def main(text):
i = 0
numspaces = 0
while i < (len(text)-2):
line = numspaces * " " + text[i:i + 3]
print(line)
i += 1
numspaces += 3
main(userinput)
| true |
7f403c9bb1d4a5061ddbcd53d43017adb0e2c6c3 | anshdholakia/Full-Voice-Assistant-Application | /Functions/files.py | 398 | 4.40625 | 4 | # Name: files.py
# Purpose: It takes the name and type of the file to create as input from the user and creates a new file.
# Version: Python 3.9.5
# 15-04-2021
# Saquib Baig
# Dependencies: no module is required
file_type = input("What file type would you like to create - word or txt: ")
filename = input("What would you like to name the file: ")
f = filename + '.' + file_type
f= open(f, "w+")
| true |
1fe3867c2797493b8be4f734646e3d15bdbefac9 | anshdholakia/Full-Voice-Assistant-Application | /Functions/time_shravya.py | 545 | 4.3125 | 4 | #Time Function
#Purpose: Returns the current time when prompted to
#Version: Python 3.9
#02-28-2021
#Shravya Bingi
#Dependencies: datetime, pytz modules, main.py
#Get the modules from python
'''
This part of the code was acquired from "https://www.pythonprogramming.in/get-current-time-in-mst-est-utc-and-gmt.html"
'''
from datetime import datetime
import pytz
tz = pytz.timezone('America/New_York')
time_1 = datetime.now(tz)
''' The part of the code that was acquired ends here'''
time = time_1.strftime("%I:%M")
print("The current time is:", time)
| true |
bba451c0d19f946814a24cd307f59ecaf11f78e9 | anshdholakia/Full-Voice-Assistant-Application | /Functions/calculator.py | 1,120 | 4.1875 | 4 | # Function for addition
def add(num1, num2):
return num1 + num2
# Function for subtraction
def subtract(number1, number2):
return number1 - number2
# Function for multiplying
def multiply(number1, number2):
return number1 * number2
# Function for dividing
def divide(number1, number2):
return number1 / number2
print("Operations calculator can perform:")
print("Add")
print("Subtract")
print("Multiply")
print("Divide")
# Take input from the user
select = input("Select operations form:")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
if select == 'add':
print(number_1, "+", number_2, "=",
add(number_1, number_2))
elif select == 'Subtract':
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 'Multiply':
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 'Divide':
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid operation") | true |
c6c2b3045ee618e6f8b0b99edd9a5d3151cc6cdc | annapeterson816/PythonPrograms | /Comp Sci Labs-2018/lab2problem2.py | 1,156 | 4.25 | 4 |
age = int(raw_input("Please input your age: "))
max_heart_rate = 220-age
print "Your Maximum Heart Rate (MHR) is : " + str(max_heart_rate) + "\n"
objective = float(raw_input("Please indicate your exercise objective as follows \n 1 = weight loss, building endurance \n 2 = weight management, improving cardio fitness \n 3 = interval workouts \n \n input your objective: "))
def THRzones(max_heart_rate, objective) :
top_beat= 0
bottom_beat = 0
if (objective ==1) :
bottom_beat = max_heart_rate *.6
top_beat = max_heart_rate * .7
return "Your Target Heart Rate zone is: " + str(bottom_beat) + " - " + str(top_beat) + " beats per minute"
if (objective ==2) :
bottom_beat = max_heart_rate *.7
top_beat= max_heart_rate *.8
return "Your Target Heart Rate zone is: " + str(bottom_beat) + " - " + str(top_beat) + " beats per minute"
if(objective==3) :
bottom_beat= max_heart_rate *.8
return "Your Target Heart Rate zone is: " + str(bottom_beat) + " and beyond beats per minute"
return bottom_beat
print THRzones(max_heart_rate,objective)
| false |
c365f9f2929224d432113613daeae9c181eb39fd | pghrogue/Sorting | /src/iterative_sorting/iterative_sorting.py | 2,197 | 4.1875 | 4 | test_array = [7, 2, 45, 1, 90, 54, 23, 12, 9, 14]
def insertion_sort(arr):
# loop through elements
for i in range(1, len(arr)):
temp = arr[i]
j = i
while j > 0 and temp < arr[j - 1]:
# shift left until correct position is found
arr[j] = arr[j-1]
j -= 1
arr[j] = temp
return arr
# print("insertion_sort:", end=" ")
# print(insertion_sort(test_array))
# TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
# TO-DO: swap
temp = arr[smallest_index]
arr[smallest_index] = arr[cur_index]
arr[cur_index] = temp
return arr
# print("selection_sort: ", end='')
# print(selection_sort(test_array))
# TO-DO: implement the Bubble Sort function below
def bubble_sort( arr ):
swaps = 1
while swaps > 0:
swaps = 0
for i in range(0, len(arr)-1):
# Swap if wrong positions
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
swaps += 1
return arr
# print("bubble_sort: ", end='')
# print(bubble_sort(test_array))
test_array = [9,3,1,5,7,2,5,8,2,5,9,5,1,4,7,9,4,2,3,6]
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=10 ):
# Array is 0 - 9. Initialize empty values
count = [0 for i in range(0, maximum)]
# count the numbers we have in the array:
for i in range(0, len(arr)):
if arr[i] < 0:
return "Error, negative numbers not allowed in Count Sort"
count[arr[i]] += 1
new_arr = [0 for i in range(0, len(arr))]
j = 0
for i in range(0, maximum):
while count[i] > 0:
new_arr[j] = i
count[i] -= 1
j += 1
return new_arr
# print(count_sort(test_array)) | true |
bdb849818319e5c482f5baedc28970e25f4daeab | danxie1999/python_test | /age.py | 339 | 4.15625 | 4 | #!/usr/bin/env python3
city=str(input('Please input the city you came from:'))
age=int(input('Please input your age:'))
if age > 18 and city == 'BeiJing':
print ('You are a BeiJing adult')
elif age <= 18 and city == 'BeiJing':
print ('You are a teenager in BeiJing')
else:
print ('You are',age,'years old and live in',city ) | false |
cd87b3d414f2aacea9e242a58a59410fc5c67914 | danxie1999/python_test | /power.py | 430 | 4.375 | 4 | #!/usr/bin/env python3
def power(x,n):
s=1
while n >0:
n=n-1
s=s*x
return s
num1=input('Please input a number:')
num2=input('Please input power you want to add:')
try:
num1=float(num1)
except ValueError:
print('%s is not a number' % num1)
exit()
try:
num2=float(num2)
except ValueError:
print('%s is not a number' % num2)
exit()
print('The result is %s' % power(num1,num2)) | true |
76071ec59e384570a0aa69c95b456e2e084a5c97 | GaloisLovWind/Python-CoreProgram | /4_class/1_build_in_func/question.py | 1,751 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Galois
# @Date: 2019/10/22 19:39
# @File: question.py
# @Software: Program
# @Desc: question
"""
cmd: python app.py --file_name=4_class
enter keyboard : 1
"""
from typing import TypeVar
Number = TypeVar('Number', int, float, complex, str)
def displayNumberType(num: Number) -> None:
""" type() """
print(num, "is", end=" ")
if type(num) == type(0):
print("an integer")
elif type(num) == type(0.0):
print("an float")
elif type(num) == type(0 + 0j):
print("an complex")
else:
print("not a number at all")
def displayNumberType2(num: Number) -> None:
""" type() """
print(num, "is", end=" ")
if type(num) == int:
print("an integer")
elif type(num) == float:
print("an float")
elif type(num) == complex:
print("an complex")
else:
print("not a number at all")
def displayNumberType3(num: Number) -> None:
""" type() """
print(num, "is", end=" ")
if isinstance(num, int):
print("an integer")
elif isinstance(num, float):
print("an float")
elif isinstance(num, complex):
print("an complex")
else:
print("not a number at all")
def test1() -> None:
""" build-in function """
print("-" * 20, " type()")
displayNumberType(1)
displayNumberType(2.2)
displayNumberType(1 + 1j)
displayNumberType("a")
print("-" * 20, " types module")
displayNumberType2(1)
displayNumberType2(2.2)
displayNumberType2(1 + 1j)
displayNumberType2("a")
print("-" * 20, " isinstance()")
displayNumberType3(1)
displayNumberType3(2.2)
displayNumberType3(1 + 1j)
displayNumberType3("a")
| false |
6a08bc89fe74a56cf2a0da28fba9e9983354611f | christianbrotherson/BottegaDiner | /bottega_diner.py | 2,852 | 4.21875 | 4 | from random import choice
from time import sleep
breakfast_menu = {
'Pancakes': 7.49,
'French Toast': 7.99,
'Omlet': 6.99,
'Country Fried Steak': 10.99
}
breakfast_menu_sides = {
'Bacon': .99,
'Sausage': 1.49,
'Eggs': 1.49,
'Hash Browns': 1.49,
}
lunch_menu = {
'Steak': 15.99,
'Hamburger': 12.99,
'Pasta': 11.99,
'Ribs': 13.99
}
lunch_menu_sides = {
'Fries': .49,
'Salad': .19,
'Onion Rings': 1.49,
'Baked Potato': .99
}
dinner_menu = {
'Steak': 20.99,
'Hamburger': 15.99,
'Pasta': 16.99,
'Ribs': 17.49
}
dinner_menu_sides = {
'Fries': 1.49,
'Salad': 1.19,
'Onion Rings': 1.99,
'Baked Potato': 1.49
}
def greeting(time, waiter_name):
print(f"Thanks for coming in to Bottega Diner! We have the best {time} in town!")
sleep(1)
print(f"\nMy name is {waiter_name} and I'll be serving you today.")
sleep(2)
name = input(f"\nWhat's your name?")
sleep(1)
print(f"\nIt is nice to meet you, {name}! Here is your menu!")
menu(time)
sleep(2)
more_time = (input("\nWould you like more time to order?")).lower()
if more_time == 'yes':
sleep(5)
return name
def random_waiter_name():
waiter_name = choice(['Sam', 'Martha', 'Rosie', 'Mark'])
return waiter_name
def menu(time):
print(f"~Bottega Diner~\n\n--{time.capitalize()} Menu--\n")
print("---Entrees---")
if time == 'breakfast':
for food, price in breakfast_menu.items():
print(f"{food}: ${price}")
print("\n---Sides---")
for food, price in breakfast_menu_sides.items():
print(f"{food}: ${price}")
elif time == 'lunch':
for food, price in lunch_menu.items():
print(f"{food}: ${price}")
print("\n---Sides---")
for food, price in lunch_menu_sides.items():
print(f"{food}: ${price}")
else:
for food, price in dinner_menu.items():
print(f"{food}: ${price}")
print("\n---Sides---")
for food, price in dinner_menu_sides.items():
print(f"{food}: ${price}")
def time_of_day():
time = choice(['b', 'l', 'd'])
if time == 'b':
return 'breakfast'
elif time == 'l':
return 'lunch'
else:
return 'dinner'
def order():
entree = input("\nWhat can I get for you? Let's start with your entree!")
side_one = input("And your first side?")
side_two = input("And your second side?")
correct = input(f"\nAlright, you want the {entree} with {side_one} and {side_two}?").lower()
if correct == 'yes':
print("\nI'll get that order right in for you!")
else:
print("\nI'm pretty sure that's what you said and that's what you get...")
def waitress_comments():
return
class Chef_Special():
def __init__():
return
def random_entree():
return
def random_sides():
return
class Bill():
def __init__():
return
def entree_price():
return
def sides_prince():
return
def main():
main() | true |
1821203583f295e84288655690a363a4ec03ab32 | PengZhao-GitHub/PythonStudy | /PythonPrograms/squareRoot.py | 383 | 4.125 | 4 |
c = input('please enter a number')
x = float(c)
epsilon = 0.01
step = epsilon**3
numGuesses = 0
ans = 0.0
while abs(x- ans**2) >= epsilon and ans**2 <= x:
ans += step
"""print(ans)"""
numGuesses += 1
print('numGuesses =', numGuesses)
if abs(ans**2 - x) >= epsilon:
print('Failed on square root of', x, ans)
else:
print(ans, ' is close to squre root of', x)
| true |
8a007721aa6c404e3478bb73b55e66fd322fce2c | nithyasubbu/Using-Python-s-turtle-graphics-framework-to-create-some-fun-Art- | /flowerFromTriangles.py | 884 | 4.28125 | 4 | import turtle
#Draw a triangle
def draw_square():
#brad is the person/point or contact
brad = turtle.Turtle()
#second instance turtle shape is arrow
brad.shape("arrow")
#second instance turtle color is red, yellow - pen/fill color
brad.color("blue")
#second instance turtle speed is 5 - average
brad.speed(7)
#Draw a flower with multiple triangles starting and ending a point until 360 degrees
#for deg in range(1,37,1):
#draw a triangle
for i in range(1,36,1):
brad.right(120)
brad.forward(100)
brad.right(120)
brad.forward(100)
brad.right(120)
brad.forward(100)
#brad.right(120)
brad.right(10)
brad.left(80)
brad.forward(-500)
def drawArt():
#window is basically the canvas where the square is drawn
window = turtle.Screen()
#the color of the screen is red
window.bgcolor("lightgreen")
draw_square()
window.exitonclick()
drawArt()
| true |
0bf2ffaf6b4225c9164d03d6a29af2de54f6bb29 | Usenbaev1090/HomeWork2 | /elements.py | 810 | 4.1875 | 4 | # Ваше задание здесь создать функцию, которая получает массив
# и возвращает набор с 3 элементами - первым, третьим, вторым с конца.
# Входные данные: Набор длинной не менее 3 элементов.
# Выходные данные: Набор элементов.
def easy_unpack(elements: list) -> list:
l = [0, 2, -2]
elements = [elements[i] for i in l]
return elements
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert easy_unpack([1, 2, 3, 4, 5, 6, 7, 9]) == [1, 3, 7]
assert easy_unpack([1, 1, 1, 1]) == [1, 1, 1]
assert easy_unpack([6, 3, 7]) == [6, 7, 3]
print('Done! Go Check!') | false |
a353346ddd0b0dedfddc350da04ac571de485fbc | KrishnaRauniyar/Python_assignment | /venv/num5.py | 528 | 4.625 | 5 | # Write a Python program to add 'ing' at the end of a given string (length should
# be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the
# string length of the given string is less than 3, leave it unchanged.
# Sample String : 'abc'
# Expected Result : 'abcing'
# Sample String : 'string'
# Expected Result : 'stringly'
str = input("Enter a string:")
result = " "
if len(str) < 3:
result = str
elif str[-3:] == "ing":
result = str + "ly"
else:
result = str + "ing"
print(result) | true |
4ad44b546ab641a575b0c4fcf206f4461d7cf3da | KrishnaRauniyar/Python_assignment | /fun6.py | 250 | 4.15625 | 4 | # Write a Python function to check whether a number is in a given range.
def check_number(n):
if n in range(1,10):
print("%s is between 1 and 10" %str(n))
else:
print("%s is not in between 1 and 10" %str(n))
check_number(5) | true |
ccd46ebf5b52ca596f7a3274e524673de2583fe0 | russellsmith/Project-Euler | /Problem37.py | 1,493 | 4.125 | 4 | """
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""
def remove_digits(number):
from maths.misc import get_digits, digit_list_to_num
digits = get_digits(number)
num_digits = len(digits)
for i in xrange(1, num_digits):
# Remove digits from the right
yield digit_list_to_num(digits[:i])
# Remove digits from the left
yield digit_list_to_num(digits[i:])
if __name__ == "__main__":
matching_primes = []
from maths.misc import is_prime
from maths.sequences import prime_numbers
exclusion_set = (2, 3, 5, 7)
# Start prime search at 10
for prime_number in prime_numbers(limit = None, start = 10):
if len(matching_primes) > 10:
break
found_prime = True
for n in remove_digits(prime_number):
if n is 1 or not is_prime(n):
found_prime = False
break
if found_prime:
matching_primes.append(prime_number)
print('Matching primes: %s'%matching_primes)
print('The sum of matching primes is %d'%sum(matching_primes))
| true |
e230f36bac4ee592ca767af18f9d5d0879024042 | liujinguang/pystudy | /PythonStudy/attributes/power_descriptor.py | 959 | 4.21875 | 4 | #/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2017年6月20日
@author: bob
To do the same with descriptors, we define the attributes with complete classes. Note
that these descriptors store base values as instance state, so they must use leading underscores
again so as not to clash with the names of descriptors
'''
class DescSquare(object):
def __get__(self, instance, owner):
return instance._square ** 2
def __set__(self, instance, value):
instance._square = value
class DescCube(object):
def __get__(self, instance, owner):
return instance._cube ** 3
class Powers(object):
square = DescSquare()
cube = DescCube()
def __init__(self, square, cube):
self._square = square
self._cube = cube
if __name__ == '__main__':
X = Powers(3, 4)
print(X.square) # 3 ** 2 = 9
print(X.cube) # 4 ** 3 = 64
X.square = 5
print(X.square) # 5 ** 2 = 25 | true |
a9b625522ba06f81704c203c81638d312e96ade0 | liujinguang/pystudy | /PythonStudy/attributes/person.py | 1,819 | 4.46875 | 4 | '''
Created on May 27, 2017
@author: bob
Normally, attributes are simply names for objects; a person’s name attribute, for example,
might be a simple string, fetched and set with basic attribute syntax:
person.name # Fetch attribute value
person.name = value # Change attribute value
In most cases, the attribute lives in the object itself, or is inherited from a class from
which it derives. That basic model suffices for most programs you will write in your
Python career.
Sometimes, though, more flexibility is required. Suppose you’ve written a program to
use a name attribute directly, but then your requirements change—for example, you
decide that names should be validated with logic when set or mutated in some way
when fetched. It’s straightforward to code methods to manage access to the attribute’s
value (valid and transform are abstract here):
However, this also requires changing all the places where names are used in the entire
program—a possibly nontrivial task. Moreover, this approach requires the program to
be aware of how values are exported: as simple names or called methods. If you begin
with a method-based interface to data, clients are immune to changes; if you do not,
they can become problematic.
'''
class Person(object):
def valid(self):
return True
def transform(self, val):
return val
def getName(self):
if not self.valid():
raise TypeError('cannot fetch name')
else:
return self.name.transform()
def setName(self, value):
if not self.valid():
raise TypeError('cannot change name')
else:
self.name = self.transform(value)
if __name__ == '__main__':
person = Person()
person.getName()
person.setName('value') | true |
a007efba781fe95a5eba1026cf17ac44da2bba93 | chicocheco/automate_the_boring_stuff | /add_loot.py | 1,727 | 4.15625 | 4 | #! python3
# add_loot - Add loot from a dragon to your inventory.
"""
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None,
so that this method never raises a KeyError.
setdefault(key[, default]) - more common to use!! (faster)
If key is in the dictionary, return its value. If not, insert key with a value of default and return default.
default defaults to None.
Al says: setdefault() will do nothing if the key already exists,
you can call it on every iteration of the for loop without a problem.
"""
def add_to_inventory(inventory, added_items):
for item in added_items:
inventory[item] = inventory.setdefault(item, 0) + 1
# inv['gold coin'] = 42
# inv.get('gold coin', 0) = 42
# inv.setdefault('gold coin', 0) = 42
# inv.get('dagger', 0) = 0
# inv.setdefault('dagger', 0) = 0
# examples of the dict.get(key, default-value) and dict.setdefault(key, default-value) methods:
# 'dagger' didn't exist yet, assign '0' to the key 'dagger' in the first iteration (to avoid exceptions)
# 'dagger already existed, add '+1' to its value (second iteration would be 0 + 1)
return inventory
def display_inventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print('Total number of items: ' + str(item_total))
inv = {'gold coin': 42, 'rope': 1, 'sword': 1}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby', 'ruby',
'ruby', 'gold coin', 'sword', 'bow', 'junk ']
inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)
| true |
5fe10b03ca71cfdaaf4733d3e4ead373fd6d9513 | chicocheco/automate_the_boring_stuff | /mul_table.py | 229 | 4.21875 | 4 | #! python3
# mul_table.py - Multiplies an input number by a number in range from 1 to 10
def mul_table(y):
print([(x, x * y) for x in range(1, 11)])
print('Multiplication table for number:')
y = int(input())
mul_table(y)
| true |
699263321df88b542b8462804b33c54da6ee8579 | friedoutkombi/Python | /Ex 1 - CharacterInput.py | 627 | 4.15625 | 4 | #http://www.practicepython.org/exercise/2014/01/29/01-character-input.html
#Character input
#Create a program that asks the user
#to enter their name
#and their age. Print out a message
#addressed to them that
#tells them the year that they will turn
#100 years old
#(str,num)->str,num
#MY SOLUTION
name=input("Enter your name ")
age=int(input("Enter your age "))
hundred=(100-age)+2017
print(name+" you will turn 100 in the year "+str(hundred))
#THEIR SOLUTION
name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2017 - age)+100)
print(name + " will be 100 years old in the year " + year)
| false |
65f026dab67ffbaf3d6e706b6143bf5cfa007f34 | varshajoshi36/practice | /leetcode/python/easy/reverseWord.py | 361 | 4.15625 | 4 | """
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
reverse1 = s[::-1]
reverse2 = ""
"""for i in reversed(s):
reverse2 += i"""
return reverse1
| true |
f625d2851036e0fb28ea0ca5ff8c0394b8e2820a | varshajoshi36/practice | /leetcode/python/easy/firstUniqueChar.py | 495 | 4.21875 | 4 | '''
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
'''
def firstUniqChar(s):
return_index = -1
for index in range(len(s)):
ch = s[index]
if ch not in s[index + 1:] and ch not in s[:index]:
return_index = index
break
return return_index
s = 'loveleetcode'
print firstUniqChar(s)
| true |
b73f8b720af6ca2dd621c9435db76de8e69135b4 | varshajoshi36/practice | /leetcode/python/easy/isRotation.py | 607 | 4.3125 | 4 | #! /usr/bin/python
"""Assume you have a method isSubstring which checks if one word is a
substring of another. Given two strings, si and s2, write code to check if s2 is
a rotation of si using only one call to isSubstring (e.g.,"waterbottle"is a rota-
tion of "erbottlewat")."""
def is_substring(s1, s2):
if s1 in s2:
return True
else:
return False
def is_rotation(s1, s2):
if len(s1) is len(s2):
starting_index = s1.index(s2[0])
s2s2 = s2 + s2
if is_substring(s1, s2s2):
return True
else:
return False
s1, s2 = 'waterbottlew', 'bottlewwater'
print s1, s2
print is_rotation(s2, s1)
| true |
740e52e86cf7abc8318986258c8372ef962f56de | varshajoshi36/practice | /leetcode/python/medium/factorialTrailingZeros.py | 422 | 4.125 | 4 | """
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
"""
def trailingZeroes(n):
five = 5
no_fives = n/5
no_zeros = 0
while no_fives > 0:
no_zeros += no_fives
five *= 5
no_fives = n/five
return no_zeros
def main():
print trailingZeroes(int(raw_input()))
if __name__ == '__main__':
main()
| true |
592d1e57963cae6e6fe7d4b63e63b0977f0bc5d2 | romandadkov/Data-Structures-and-Algorithms | /Algorithms on Strings/pa3_suffix_trees/kmp/kmp.py | 823 | 4.125 | 4 | # python3
import sys
def find_pattern(pattern, text):
"""
Find all the occurrences of the pattern in the text
and return a list of all positions in the text
where the pattern starts in the text.
"""
result = []
if len(pattern) > len(text):
return result
string = pattern + '$' + text
s = [0] * len(string)
border = 0
for i, symbol in list(enumerate(string))[1:]:
while border > 0 and symbol != string[border]:
border = s[border - 1]
a = 1 if symbol == string[border] else 0
border += a
s[i] = border
if s[i] == len(pattern):
result.append(i - 2 * len(pattern))
return result
if __name__ == '__main__':
pattern = sys.stdin.readline().strip()
text = sys.stdin.readline().strip()
result = find_pattern(pattern, text)
print(" ".join(map(str, result)))
| true |
50639553b90318e0775e748df28e6d275fa2de8d | shreyashetty270/pythonbootcampinternship | /task 21.py | 503 | 4.21875 | 4 | #To create merged list of tuples
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']
new_list = list(zip(list1, list2))
print(new_list)
#To merge the list and range together
lst1=["A", "B", "C", "D", "E", "F", "G","H","I"]
x= range(1,9)
lst=list(zip(lst1,x))
print(lst)
#To sort the list in ascending order
numbers = [6, 9, 3, 1]
x= sorted(numbers)
print(x)
#To filter even numbers from the list
x= [ 1, 2, 4, 5, 7, 8, 9, 10, 12,34,76,57]
y= filter(lambda x: x % 2 == 1, x)
print("The new list:",list(y))
| true |
e215f9ad3b56e10d453f6982f5533fc73722f02f | SlyesKimo123/ComputadoraScience2 | /Files and Dictionaries/Dictionaries_Prob#12:19.py | 1,214 | 4.125 | 4 |
mydict = {}
mydict['sir'] = 'matey'
mydict['hotel'] = 'fleabag inn'
mydict['student'] = 'swabbie'
mydict['boy'] = 'matey'
mydict['madam'] = 'proud beauty'
mydict['professor'] = 'foul blaggart'
mydict['restaurant'] = 'galley'
mydict['your'] = 'yer'
mydict['excuse'] = 'arr'
mydict['are'] = 'be'
mydict['lawyer'] = 'foul blaggart'
mydict['the'] = "th'"
mydict['restroom'] = 'head'
mydict['my'] = 'me'
mydict['hello'] = 'avast'
mydict['is'] = 'be'
mydict['man'] = 'matey'
user_input = str(input("Enter a random sentence and I will change it to Pirate language.\n"))
list_user_input = [] # Creates a new list of user_input
words = user_input.split() # This splits up each word in the user_input
for word in words: # This iterates thru each item of list_user_input, changing the key in mydict to the value
if word in mydict:
list_user_input.append(mydict[word]) # This singles out the word that is to be changed into Pirate
print()
else: # This is a list of the words that do not change to Pirate
list_user_input.append(word)
#for k in mydict.items():
# user_input = list_user_input.replace(k, mydict[k])
#print(user_input)
print(" ".join(list_user_input))
| false |
508059d7968d224d95270f8569d4c691a2654f76 | pezy/python_test | /hardway/input.py | 813 | 4.21875 | 4 | # raw_input : input anything will look as string
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So you're %r old, %r tall and %r heavy." % (age, height, weight)
# other useage
# input to string
id = raw_input("input some text: ")
print "your text len is %r" % len(id)
# 0x
nHex = int(raw_input("input hex value(like 0x20): \n"), 16)
print "nHex = %x, nDec = %d\n" % (nHex, nHex)
# 0
nOct = int(raw_input("input orc value(like 020): \n"), 8)
print "nOrc = %o, nDec = %d\n" % (nOct, nOct)
# my own
name = raw_input("what is your name? ")
where = raw_input("where are you from? ")
aim = raw_input("what is your aim? ")
print "Hi, %r, %r is a great place, and %r will be better!" % (name, where, aim)
| false |
54b6b179c1129ebed4f72bbf3471f60bb2ec2e97 | ilirmaci/advent-of-code-2020 | /day01/day01.py | 1,493 | 4.25 | 4 | #!/usr/bin/env python3
# Solutions to https://adventofcode.com/2020/day/1
from typing import Tuple, Sequence
def find_adding(x: Sequence[int], total=2020) -> Tuple[int, int]:
'''
Return the two entries from `x` that add up to `total`.
`x` needs to be sorted in ascending order.
'''
x_desc = reversed(x)
x_iter = iter(x)
second = next(x_iter)
for first in x_desc:
while first + second <= total:
if (first + second == total) and (first != second):
return first, second
try:
second = next(x_iter)
except StopIteration:
return None, None
return None, None
input_raw = open('day01_input.txt')
entries = (int(_.strip()) for _ in input_raw)
entries_asc = sorted(entries)
first, second = find_adding(entries_asc)
answer1 = first*second
print(f"The answer to the first puzzle is {answer1}")
def find_adding_three(x: Sequence[int], total=2020) -> Tuple[int, int, int]:
'''
Return the three entries from `x` that add up to `total`.
`x` needs to be sorted in ascending order.
'''
for first in x:
remainder = 2020 - first
x_wo_first = [_ for _ in x if _ != first]
second, third = find_adding(x_wo_first, remainder)
if second is not None:
return first, second, third
first, second, third = find_adding_three(entries_asc)
answer2 = first*second*third
print(f"The answer to the second puzzle is {answer2}")
| true |
f8b3f1e06c845ff05353a078500cec7fad8f7912 | Liam1809/Testing_Built-in_Python | /String_methods.py | 2,794 | 4.65625 | 5 | # Python comes with built-in string methods that gives you the power to perform complicated tasks on strings very quickly and efficiently.
# These string methods allow you to change the case of a string, split a string into many smaller strings, join many small strings together into a larger string, and allow you to neatly combine changing variables with string outputs.
# In the previous lesson, you worked len(), which was a function that determined the number of characters in a string.
# This, while similar, was NOT a string method. String methods all have the same syntax:
# py string_name.string_method(arguments)
# Unlike len(), which is called with a string as it’s argument, a string method is called at the end of a string and each one has its own method specific arguments.
# These methods will not affect special characters, which are any non-alphabetical and non-numeric characters and
# will only apply to case-based characters, which include essentially all the alphabetical characters.
# # FORMATTING STRING METHODS
# .lower() returns the string with all lowercase characters.
# .upper() returns the string with all uppercase characters.
# .title() returns the string in title case, which means the first letter of each word is capitalized.
favorite_song = 'SmOoTH'
favorite_song_lowercase = favorite_song.lower()
print(favorite_song)
print(favorite_song_lowercase)
poem_title = "spring storm"
poem_title_fixed = poem_title.title()
print(poem_title)
print(poem_title_fixed)
poem_author = "William Carlos Williams"
poem_author_fixed = poem_author.upper()
print(poem_author)
print(poem_author_fixed)
highlighted_poems = "Afterimages:Audre Lorde:1997, The Shadow:William Carlos Williams:1915, Ecstasy:Gabriela Mistral:1925, Georgia Dusk:Jean Toomer:1923, Parting Before Daybreak:An Qi:2014, The Untold Want:Walt Whitman:1871, Mr. Grumpledump's Song:Shel Silverstein:2004, Angel Sound Mexico City:Carmen Boullosa:2013, In Love:Kamala Suraiyya:1965, Dream Variations:Langston Hughes:1994, Dreamwood:Adrienne Rich:1987"
# print(highlighted_poems)
highlighted_poems_list = highlighted_poems.split(",")
# print(highlighted_poems_list)
highlighted_poems_stripped = [element.strip() for element in highlighted_poems_list]
# print(highlighted_poems_stripped)
highlighted_poems_details = [element.split(":") for element in highlighted_poems_stripped]
# print(highlighted_poems_details)
titles = []
poets = []
dates = []
titles = [element[0] for element in highlighted_poems_details]
poets = [element[1] for element in highlighted_poems_details]
dates = [element[2] for element in highlighted_poems_details]
for i in range(len(titles)):
title, poet, date = titles[i], poets[i], dates[i]
print("The poem {t} was published by {p} in {d}".format(t = title, p = poet, d = date)) | true |
ba65be5ab1af65056e9a3d2165bf299e8aa23986 | Liam1809/Testing_Built-in_Python | /Clear.py | 258 | 4.15625 | 4 | # clear() :- This function is used to erase all the elements of list. After this operation, list becomes empty.
# initializing list 1
list1 = [2, 1, 3, 5]
# initializing list 1
list2 = [6, 4, 3]
list1.clear()
list2.clear()
print(list1)
print(list2) | true |
6ee8e42d6e172062173c416e6780c69e40e5f477 | victorsaad00/ed_python_study | /Linked_List.py | 1,741 | 4.21875 | 4 | # Not finished
class Node(object):
def __init__(self):
self.data = None
self.next = None
class List: # Simple linked list
def __init__(self):
self.cur_node = None
self.size = 0
#####################
'''
# Only for ordered list
def insertFirst(self, data):
pass
def insertNext(self, data):
pass
def deleteMid(self, data):
pass
def deleteLast(self,data):
pass
def deleteFirst(self, data):
pass
'''
######################
def insert(self, data):
new_node = Node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
self.size += 1
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print(str(node.data))
node = node.next
def delete(self, data):
if not self.isEmpty():
if self.exist_rec(data, self.cur_node):
pass # Search node, unlink it and link the prev with the next.
else:
print('List is empty!')
def exist(self, data):
node = self.cur_node
while node:
if node.data == data: return True
else: node = node.next
return False
def exist_rec(self, data, node):
if self.isEmpty(): return False
elif node.data == data: return True
else: return self.exist_rec(data, node.next)
def isEmpty(self):
return self.size == 0
| true |
9fed8be0130f801d95811cfde17350f2179b619b | MontrealCorpusTools/PolyglotDB | /polyglotdb/syllabification/maxonset.py | 1,249 | 4.15625 | 4 | def split_ons_coda_maxonset(string, onsets):
"""
Finds the split between onset and coda in a string
Parameters
----------
string : iterable
the phones to search through
onsets : iterable
an iterable of possible onsets
Returns
-------
int
the index in the string where the onset ends and coda begins
"""
if len(string) == 0:
return None
for i in range(len(string) + 1):
cod = tuple(string[:i])
ons = tuple(string[i:])
if ons not in onsets:
continue
return i
return None
def split_nonsyllabic_maxonset(string, onsets):
"""
Finds split between onset and coda in list with no found syllabic segments
Parameters
----------
string : iterable
the phones to search through
onsets : iterable
an iterable of possible onsets
Returns
-------
int
the index in the string where the onset ends and coda begins
"""
if len(string) == 0:
return None
for i in range(len(string), -1, -1):
ons = tuple(string[:i])
cod = tuple(string[i:])
if ons not in onsets:
continue
else:
return i
return None
| true |
df2c98fa66e59a1a086f7767a7b5fbf352b9bed0 | LarryWachira/andela-boot-camp-XIV | /git-training/commiting.py | 232 | 4.21875 | 4 | print('This is a calculator that multiplies two numbers.\n')
a = int(input('Input your first number: \n>'))
b = int(input('Input the second number: \n>'))
def multiply(a,b):
return a*b
print("The answer is: ", multiply(a,b))
| true |
2008e39d58249687a704d79a1048c2886c7fc5d1 | ypliu/leetcode-python | /src/208_implement_trie/208_implement_trie.py | 1,492 | 4.21875 | 4 | class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_word = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for ch in word:
if ch not in node.children:
return False
node = node.children[ch]
return node.is_word
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return True
# debug
# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert("apple")
print obj.search("apple")
print obj.search("app")
print obj.startsWith("app")
obj.insert("app")
print obj.search("app")
| true |
d4899ecdde06cb989de7c08a737dc1f6cd29325f | DikranHachikyan/CPYT211004 | /ex62_zan9.py | 716 | 4.15625 | 4 | # 1. дефиниция на класа
class Point():
def __init__(self, x=0, y=0, *args, **kwargs):
print('Point Ctor')
# данни обекта
self.x = x
self.y = y
def draw(self):
print(f'draw point at ({self.x},{self.y})')
def move_to(self, dx, dy):
self.x += dx
self.y += dy
if __name__ == '__main__':
# 2. променлива от тип Point
# клас - типа, обект - променлива от типа, представител на класа
p1 = Point()
p2 = Point(30, 50)
print(f'Point:({p1.x},{p1.y})')
p1.draw()
p2.draw()
p2.move_to(30, -10)
p2.draw()
print('---') | false |
7025a27445ab530ac355ca20de6f6c0d5a349ef9 | YogeshPhuyal/myprojects | /validation.py | 424 | 4.15625 | 4 | name=input("enter your name")
while name.isalpha()==False:
name=input("error")
age=(input("enter your age"))
while age < 19:
age= (input("enter your correct age "))
mobile=input ("enter your mobile number")
while len(mobile)!= 10 or mobile.isalpha == True:
mobile=input("enter your correct mobile number")
print("your name is ",name)
print("your age is ",age)
print("your mobile number is ",mobile)
| false |
872a0f5a06b2a787f2a805be075f730c7b144193 | EDalSanto/DS-Algos | /bradfield/dynamic_programming/lattice.py | 1,301 | 4.21875 | 4 | # Compute number of shortest paths from top left to bottom right
def num_paths_recursive(height, width):
"""
same problem of fib with O(2^N) time complexity and O(N) space
"""
# Straight line can only ever have 1
if height == 0 or width == 0:
return 1
else:
return num_paths_recursive(height - 1, width) + num_paths_recursive(height, width - 1)
print(num_paths_recursive(2, 2) == 6)
"""
Initial State
[
[ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ],
]
Final State
[
[ 1, 1, 1 ],
[ 1, 2, 3 ],
[ 1, 3, 6 ]
]
"""
def num_paths_dynamic(height, width):
"""
solve subproblems of number of points to the left and above to derive how many paths to point
left and top points by definition of problem have only 1 path to them
"""
# Create matrix of height by width
memo = [ [1] * (width + 1) for _ in range(height + 1) ]
for row_idx, row in enumerate(memo):
for col_idx, col in enumerate(row):
# Skip leftmost col and top most row
if row_idx == 0 or col_idx == 0:
continue
else: # Add top and left points
memo[row_idx][col_idx] = memo[row_idx][col_idx - 1] + memo[row_idx - 1][col_idx]
return memo[-1][-1]
print(num_paths_dynamic(2, 2) == 6)
| true |
6cfba2077689111ecd6d5aadfc97143b1a6a2a34 | diegocdl/cc1-refuerzo-2020 | /20200418/ejemplo3.py | 869 | 4.34375 | 4 | # definir un diccionario vacio
diccionario = {}
# definir un diccionario con elementos
diccionario = {'Julio': 123456, 'Jorge': 654321}
# modificar un valor
diccionario['Julio'] = 1234567
# agregar una llave:valor
diccionario['Saida'] = 987654
# consultar un valor segun una llave leida del teclado
try:
llave = input("Ingrese una llave: ")
print(diccionario[llave])
except KeyError:
print("No se encontro la llave en el diccionario.")
# mostrar todos los elementos del diccionario
for llave, valor in diccionario.items():
print(llave, "->", valor)
# mostrar todas las llaves del diccionario
print("-------------------")
print("Llaves del diccionario")
for llave in diccionario.keys():
print(llave)
# mostrar todos los valores
print("-------------------")
print("Valores del diccionario")
for valor in diccionario.values():
print(valor) | false |
78c3e1023f43e18ebea3acbb08bfab9c7472f665 | cognizant1503/Assignments | /PF/day4/Assignment31.py | 326 | 4.21875 | 4 | #PF-Assgn-31
def check_palindrome(word):
reverse_word=word[::-1]
status=False
if(reverse_word==word):
status=True
else:
status=False
return status
status=check_palindrome("malayalam")
if(status):
print("word is palindrome")
else:
print("word is not palindrome") | false |
671a67f031a9806af994df65ed02535da92999cc | heachou/python-learning | /src/str.py | 1,241 | 4.15625 | 4 | # 字符串学习
# Unicode
print(ord('A')) # 65
print(ord('高')) # 39640
print(chr(66)) # B
# 引号创建字符串
# 创建多行字符串
a = """
this is multiple line
this is multiple line
this is multiple line
"""
print(a)
print(len(a))
# 转义字符
# \(在行尾时) 续行符
# \\ \
# \' '
# \* *
# \b 退格符 Backspace
# \n 换行
# \t 横向制表符
# \r 回车
a = 'i\nlove\nyou'
print(a)
# 字符串拼接
# + 或空格
a = 'hell' + 'o'
print(a)
a = 'hello' 'test'
print(a)
# 字符串复制
a = 'hello ' * 3
print(a)
# 不换行打印
print("test1", end='')
print("test2", end='$$$')
print("test3", end='\n')
# 从控制台读取字符串
# my_name = input("请输入name:")
# print(my_name)
# str 转换为字符串
print(type(str(5.13))) # <class 'str'>
print(str(True)) # True
# []
a = 'abcd'
print(a[0]) # a
print(a[-1]) # d
# replace 替换字符串
a = 'hello'
b = a.replace('l', 'u')
print(a) # hello
print(b) # heuuo
# slice 切片
a = 'abcdefg'
print(a[1:5]) # bcde
print(a[1:5:2]) # bd
print(a[:]) # abcdefg
print(a[2:]) # cdefg
print(a[:2]) # ab
print(a[-3:]) # efg
print(a[::-1]) # gfedcba 倒序
a = 'to be or not to be'
b = a.split()
print(a.split())
print('$'.join(a))
| false |
2c6fb3d00c2168f81a9a25a119de6d9aec0b7a00 | remilekunajisebutu/Election_Analysis | /Python_practice.py | 1,904 | 4.40625 | 4 | print("Hello World")
counties = ["Arapahoe","Denver","Jefferson"]
for county in counties:
print(county)
numbers = [0, 1, 2, 3, 4]
for num in numbers:
print(num)
for i in range(len(counties)):
print(counties[i])
counties_tuple = ("Arapahoe1","Denver1","Jefferson1")
for i in range(len(counties_tuple)):
print(counties_tuple[i])
for county in counties_tuple:
print(county)
# iterating through a dictionary to get key or values or both
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
#another way to get value
for county in counties_dict.values():
print(county)
# another way to get values
for county in counties_dict:
print(counties_dict[county])
#another way to get values
for county in counties_dict:
print(counties_dict.get(county))
for county, voters in counties_dict.items():
#print(county,voters)
print("county {} county has voters {} registered voters".format(county, voters))
print(county + " county has " + str(voters) + " registered voters.")
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}]
#for county_dict in voting_data:
# print(county_dict)
for county_dict in voting_data:
for value in county_dict.values():
print(value)
#my_votes = int(input("How many votes did you get in the election? "))
#total_votes = int(input("What is the total votes in the election? "))
#print(f"I received {my_votes / total_votes * 100}% of the total votes.")
#prints out the key and value within text - useful for assignment
counties_dict = {"Arapahoe1": 422829, "Denver2": 463353, "Jefferson3": 432438}
for county in counties_dict:
voters = counties_dict[county]
print("{} county has {:,} registered voters.".format(county, voters)) | false |
653d53af35c62bbc24475992d12c092f7a1ebc6f | dkhaosanga/class_python_labs_031218 | /numbers.py | 1,361 | 4.375 | 4 | # Integers: Integers are whole numbers,
# Floating numbers are numbers with decimals. Both
# positive and negative numbers
#Arithmetic operators:
# addition +, integers and floats can be mixed and matched
# subtraction -, integers and floats mixed and matched
# multiplication *, mixed and matched, you can mutiply variable with integers
# division /, will always print as a floats
# floor division //, rounds down, takes off everything after the decimal
# modulus operators %, gives you the remainder, helpful to determine even or odds print % 2
# print(20 % 4)
# print(40 % 9)
# Exponents **, print(20 ** 3), cubed
# +=, -=, *= so you don't have to reassign a variable
# number = 10
# number += 5
# print(number) will equal 15
#lab 3 - hammer
# When asking for time with hour and am or pm ask with this: (HH:AM/PM)
# meridan is the AM/PM
time = input("what time is it? ")
time_split = time.split(':') #automatically if you put just () it will be a space
hour = int(time_split[0])
meridian = (time_split[1]) #.lower(), you can put in after input
if hour in range (7,10):
if meridian == 'am':
print("it's breakfast")
else:
print("it's dinner") #taking hours and then if theres any other meridian it will print dinner
elif hour in range (10,12) and meridian == "pm" or (hour == 12 or hour in range (1,5) and meridian == "am"):
| true |
5a1c0dc17bdb3dff97357e2ebde1379e2741d8ee | dkhaosanga/class_python_labs_031218 | /condlab.py | 479 | 4.125 | 4 | grade = input('What percentage is your grade?: ')
grade = int(grade)
if grade >= 90:
if grade > 96:
print("A+")
elif grade > 93 and grade <= 96:
print("A")
elif grade >= 90:
print("A-")
elif grade >= 80:
if grade > 86:
print("B+")
elif grade > 83 and grade <= 86:
print("B")
elif grade >= 80:
print("B-")
elif grade >= 70:
print("C")
elif grade >= 60:
print("D")
else:
print(F)
# 50 < n < 100
| false |
4e62283caf7b3ecfbb2b91a917e39f81e66a78a8 | BhathiyaVandebona/python-quick-reference | /oop/class.py | 2,087 | 4.4375 | 4 | #classes are user define data types that allows us to map real world entities into datatypes that we can manipulate
#this is how to create a simple class
# class is a like a mold or a template out of this you can model actual objects
class Employee:
#the builtin datatypes are used to represent attribute of the employee
#here the slf must always be the first parameter of the parameter list
def __init__(self, name, age, address, gender, branch, emp_type):#this is known as an initialize function and it is like a constructor in Java
#the variables given inside of the parathensis acts as attributes of this class
#self is like the this key word in Java or this-> in cpp this means it is refering to the current object
self.name = name
self.age = age
self.address = address
self.gender = gender
self.branch = branch
self.emp_type = emp_type
#this is a class function
def details(self):# here the slef is a must because an argument is passed by default to check this remove the self and give this a try
print("The name of the employee is :"+self.name)
print("The age of the employee is :"+str(self.age))
print("The address of the employee is :"+self.address)
print("The gender of the employee is :"+self.gender)
print("The branch of the employee is :"+self.branch)
print()
#this is the actual object or the instance
e1 = Employee("John", 40, "Address", "M", "NEW", "PROGRAMMER")
#here you don't have to pass a value to the self parameter it is automatically referred
#to access the atributes in this object
print("The name of the employee is :"+e1.name)
print("The age of the employee is :"+str(e1.age))
print("The address of the employee is :"+e1.address)
print("The gender of the employee is :"+e1.gender)
print("The branch of the employee is :"+e1.branch)
print("The emp_type of the employee is :"+e1.emp_type)
#and you can create as much employees from this template
#you can even assign e1 another new employee object as well
e1.details()
| true |
0dfa17ef6cc625b39638f07f05ea0375908b1d48 | Saurav-Shrivastav/py4e | /Chapter_6 Strings/Manipulating_Strings.py | 2,294 | 4.25 | 4 | #Concatenating strings
a = 'Hello'
b = a + 'There'
print(b) #prints "HelloThere"
b = a + ' ' + 'There'
print(b) #prints "Hello There"
#using in as a logical operator (other use is in for loop)
#The in expression returns True or False
fruit = 'banana'
if 'a' in fruit :
print('Found it!')
# '==' is used to compare strings
#Strings are objects
#For now objects are variables that have capabilities grafted or built into them
greet = 'Hello Saurav'
zap = greet.lower() # This is,run a function lower() that's part of the string object, of the string class, that is going to give us back a lowercase copy.
#So what this functionally does, it says, make a copy of greet but all lowercase and return it to us, and then we're going to store that into zap.
print(zap)
print(greet)
#This part of code has to be typed in the console
type(greet) #returns <class 'str'>
dir(greet) #returns the methods of class string
#This link gives a detail ofvarious methods of strigs - "https://docs.python.org/3/library/stdtypes.html#string-methods"
#capitalize()
a = fruit.capitalize()
print(a) #capitalizes the first letter of the word
b = 'ABC'.capitalize()
print(b) #returns Abc
#find() - to find a letter or a bunch of letters within a string - gives the index of the position
#if a letter is not foundit return -1
#upper() & lower() are used to change the case
#This can be used while comparing two strings, they have to be of the same case even if they are the same woords for the equality to return True
#replace() - saercha word in a string and replace it with another letter
nstr = greet.replace('Saurav', 'saulav')
#lstrip() and rstrip() remove spaces from the left or right resp.
#strip() removes beginning and ending spaces
greet = ' Hello Saurav '
print(greet)
print(greet.lstrip())
print(greet.rstrip())
print(greet.strip())
#prefixes - startswith()
line = 'Please have a nice day'
if line.startswith('Please') :
print('HI')
#parsing and extracting
data = "From sauravsrivastav@gmail.com sat Jan 5"
#we are going to extract the site address
atpos = data.find("@")
sppos = data.find(' ', atpos) #this finds a space after the atpos index
host = data[atpos+1: sppos]
print (host)
#in python 3 all strings are unicode
| true |
64b095b6dfa56875eadc2d68b411fb2ba5d0829a | Saurav-Shrivastav/py4e | /Chapter_3/assi_3.1.py | 264 | 4.21875 | 4 | #we are assuming that the user enters correct data
hrs = input("Enter Hours:")
rate = input("Enter the rate per hour:")
hrs = float(hrs)
rate = float(rate)
if hrs <= 40 :
s = hrs*rate
print(s)
elif hrs>40 :
s = 40*rate + (hrs-40)*rate*1.5
print(s)
| true |
3287ed065e82ada84d80a85f8c64edd5f6b40e33 | tattudc/pythonestudos | /Python Curso - Udemy de Leonardo Moura/2 - Tipos de dados.py | 568 | 4.25 | 4 | #Tipos de dados
print("Isso é uma String ou cadeia de caracteres")
print("-"*50)
print("Quando tem numero decimal é float ")
print(0.55)
print("-"*50)
print("Quando tem numero inteiro é inteiro ou int ")
print(32)
print("-"*50)
print("Quando tem True ou False é boolean ")
print(True)
print("-"*50)
lista=[1, "asd", 3, 4.5]
print("Quando tem uma sequência é lista")
print(lista)
print("-"*50)
print("Quando vem seguido de chaves e com um indice para cada sentença é dicionário")
dicion = {"Primeiro": "Hoje", "Segundo": "Amanhã"}
print(dicion)
print("-"*50)
| false |
80971bc9aac94b3dc03b6049a88a4e343f5b9b27 | renukadeshmukh/LearningPython | /14. PrintGrade.py | 695 | 4.5 | 4 | # 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range,
# print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
# Score Grade
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# If the user enters a value out of range, print a suitable error message and exit. For the test,
# enter a score of 0.85.
input = raw_input("Enter grade value between 0.0 and 1.0")
fVal = float(input)
if fVal > 1.0:
print "Error"
elif fVal >= 0.9 :
print "A"
elif fVal >= 0.8:
print "B"
elif fVal >= 0.7:
print "C"
elif fVal >= 0.6:
print "D"
elif fVal < 0.6:
print "F"
else :
print "Error! Input out of range"
| true |
4875c5628048580d9834eacd345b0b2277af3952 | renukadeshmukh/LearningPython | /13. PayRate2.py | 687 | 4.28125 | 4 | # 3.1 Write a program to prompt the user for hours and rate per hour using raw_input
# to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the
# hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50
# per hour to test the program (the pay should be 498.75). You should use raw_input
# to read a string and float() to convert the string to a number. Do not worry about
# error checking the user input - assume the user types numbers properly.
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Rate:")
r = float(rate)
diff = h - 40
if diff <= 0 :
print h * r
else :
print (40 * r) + (1.5 * diff * r)
| true |
fc1ad784c5f7dc8f22051df10065eaf6b0f34ea1 | lesteveinix/bywave-python-training | /exer_003.py | 754 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Exercise #3
Write a program that accepts a comma separated sequence of words as input
and prints the words in a comma-separated sequence after sorting them
alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
Hint:
String join() method
"""
# your name and email address here
__author__ = 'xXLXx <leo@bywave.com.au>'
if __name__ == '__main__':
while 1:
try:
x = input("Enter comma separated string: ")
x = x.replace(" ", "")
x = x.split(',')
x = sorted(x)
x = ','.join(x)
print(x)
except:
print('Oops, something went wrong XD')
| true |
f61145297166297087497e77dd0b356b2846b17d | farhankhan25/fork-this-junk | /add two bit string.py | 1,382 | 4.34375 | 4 | # Python3 program for above approach
# adds the two-bit strings and return the result
# Helper method: given two unequal sized bit strings,
# converts them to same length by adding leading 0s
# in the smaller string. Returns the the new length
def makeEqualLength(str1, str2):
len1 = len(str1) # Length of string 1
len2 = len(str2) # length of string 2
if len1 < len2:
str1 = (len2 - len1) * '0' + str1
len1 = len2
elif len2 < len1:
str2 = (len1 - len2) * '0' + str2
len2 = len1
return len1, str1, str2
def addBitStrings( first, second ):
result = '' # To store the sum bits
# make the lengths same before adding
length, first, second = makeEqualLength(first, second)
carry = 0 # initialize carry as 0
# Add all bits one by one
for i in range(length - 1, -1, -1):
firstBit = int(first[i])
secondBit = int(second[i])
# boolean expression for sum of 3 bits
sum = (firstBit ^ secondBit ^ carry) + 48
result = chr(sum) + result
# boolean expression for 3 bits addition
carry = (firstBit & secondBit) | \
(secondBit & carry) | \
(firstBit & carry)
# if overflow, then add a leading 1
if carry == 1:
result = '1' + result
return result
# Driver Code
if __name__ == '__main__':
str1 = '1100011'
str2 = '10'
print('Sum is', addBitStrings(str1, str2))
# This code is contributed by farhan
| true |
50c493fd61963ee96593da8defd3a14176f5fe97 | Brudicon/Experiments-Tutorials | /MachineLearningPython/TrainTest.py | 1,559 | 4.125 | 4 | import numpy
import matplotlib.pyplot as plt
numpy.random.seed(2)
#Measure the accuracy of a model
#Train the model means create the model.
#Test the model means test the accuracy of the model.
#start with the data set we will test, 100 customers in a shop
x = numpy.random.normal(3, 1, 100) #x = minutes before making purchase
y = numpy.random.normal(150, 40, 100) / x #y = money spent on the purchase
#Display the OG data
plt.scatter(x, y)
plt.show()
#Split into train and test
train_x = x[:80] #Training set should be a random set of 80% of the OG data
train_y = y[:80]
test_x = x[80:] #Testing set should be the remaining 20%
test_y = y[80:]
#Display the Training set
plt.scatter(train_x, train_y)
plt.show()
#Display the Testing set
plt.scatter(test_x, test_y)
plt.show()
#For this set it looks like the best course of action to fit the data set is polynomial regression, so let's do that.
#Let's fit a line to the training data using poly reg
mymodel = numpy.poly1d(numpy.polyfit(train_x, train_y, 4))
myline = numpy.linspace(0, 6, 100)
plt.scatter(train_x, train_y)
plt.plot(myline, mymodel(myline))
plt.show()
#R2/R-squared value from 0 to 1 for how well the Training data fits in a polynomial regression
r2 = r2_score(train_y, mymodel(train_x))
print(r2)
#Same for Testing data
r2 = r2_score(test_y, mymodel(test_x))
print(r2)
#Predicting a future value, in this case how much money will a customer spend if they stay in the shop for 5 minutes?
print(mymodel(5)) | true |
2de72ade19926c8cfeb91ed1bb735ff6cb707b10 | krunopz/Intro_to_functions | /main.py | 272 | 4.1875 | 4 | def name_format(name, lname):
name.split()
lname.split()
name.lower()
lname.lower()
f_name=name.capitalize()
l_name=lname.capitalize()
return print(f"{f_name} {l_name}\n")
name=input("Your name: ")
lname=input("Your last name:")
name_format(name, lname)
| false |
134b42038b16d370bcfc8ac285dad95092210684 | NN88/python_for_everybody | /07_lists/e06.py | 733 | 4.1875 | 4 | # Exercise 6: Rewrite the program that prompts the user for a list of numbers
# and prints out the maximum and minimum of the numbers at the end when the
# user enters "done". Write the program to store the numbers the user enters
# in a list and use the max() and min() functions to compute the maximum and
# minimum numbers after the loop completes.
lyst = []
try:
while True:
inp = input("Enter a number: ")
if inp != 'done':
lyst.append(float(inp))
continue
else:
break
except Exception as e:
print("Error is: ", e)
exit()
if len(lyst) > 0:
maximum = max(lyst)
minimum = min(lyst)
print("Maximum: ", maximum)
print("Minimum: ", minimum)
| true |
64b4faf57655a7747760d6ea98c9ff885d49ef34 | NN88/python_for_everybody | /04_iteration/e02.py | 608 | 4.25 | 4 | # Exercise 2: Write another program that prompts for a list of numbers as above
# and at the end prints out both the maximum and minimum of the numbers instead
# of the average.
try:
arr = []
while True:
num = input("Enter a number: ")
if num != 'Done' and int(num):
print(num)
arr.append(int(num))
continue
if num == "Done":
smallest = min(arr)
largest = max(arr)
print("Smallest: ", smallest)
print("Largest: ", largest)
break
except Exception as e:
print("Error is: ", e)
| true |
52c27c05f36e2a81fc4f7664e6fdb9f3ab3e345f | NN88/python_for_everybody | /08_dictionary/e01.py | 623 | 4.1875 | 4 | # Exercise 1: Write a program that reads the words in words.txt and stores
# them as keys in a dictionary. It doesn't matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is in
# the dictionary.
try:
fhand = open(input("Input file name: ") or "_files/words.txt")
except Exception as e:
print("Error is: ", e)
count = 0
dic = dict()
for line in fhand:
words = line.split()
for word in words:
count += 1
if word in dic:
continue
dic[word] = count
if 'Python' in dic:
print('Python EXISTS!')
else:
print('NOPE!')
| true |
9d4edeeacd826896c16c4b72f8899bca3d89c683 | NN88/python_for_everybody | /10_regular_expressions/e02.py | 833 | 4.125 | 4 | # Exercise 2: Write a program to look for lines of the form
# `New Revision: 39772`
# and extract the number from each of the lines using a regular expression and
# the findall() method. Compute the average of the numbers and print out
# the average.
# Enter file:mbox.txt
# 38549.7949721
# Enter file:mbox-short.txt
# 39756.9259259
import re
summ = []
try:
fhand = open(input("Input file name: ") or "_files/mbox-short.txt")
except FileNotFoundError:
print('File cannot be opened: ', fname)
exit()
for line in fhand:
line = line.rstrip()
match = re.findall('^New Revision: ([0-9.]+)', line)
if len(match) > 0:
for val in match:
val = float(val)
summ = summ + [val]
total_sum = sum(summ)
count = float(len(summ))
average = total_sum / count
print(average)
| true |
00a4c05fd67e35a032cee4e90f5c661b84ed7cad | NN88/python_for_everybody | /07_lists/e05.py | 1,206 | 4.3125 | 4 | # Exercise 5: Write a program to read through the mail box data and when you find
# line that starts with "From", you will split the line into words using the
# split function. We are interested in who sent the message, which is the
# second word on the From line.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line and print out the second word for each From line,
# then you will also count the number of From (not From:) lines and print out
# a count at the end.
# This is a good sample output with a few lines removed:
# python fromcount.py
# Enter a file name: mbox-short.txt
# stephen.marquard@uct.ac.za
# louis@media.berkeley.edu
# zqian@umich.edu
# [...some output removed...]
# ray@media.berkeley.edu
# cwen@iupui.edu
# cwen@iupui.edu
# cwen@iupui.edu
# There were 27 lines in the file with From as the first word
try:
fhand = open(input("What is the file name?: ") or "_files/mbox.txt")
except Exception as e:
print("Error is: ", e)
exit()
count = 0
for line in fhand:
if line.startswith("From"):
words = line.split()
if len(words) > 1:
print(words[1])
if words[0] == "From":
count = count + 1
print("There were:" , count, 'lines in the file with the From as the first word')
| true |
c74427fecf307d22a7d796a24e59a87455cdb388 | Yema94/Python-Projects | /controlstatements/gradecalculator.py | 507 | 4.21875 | 4 | #Grade Calculation
"""Subjects: Maths, Physics, Chemistry
Pass Marks : 35
if Avg <=59 grade C
if Avg <=69 grade B
if Avg >69 grade A """
subjects = input("Enter the names of 3 subjects: ").split()
marks = [float(mark) for mark in input("Enter 3 subjects marks:").split(',')]
if marks[0]>=35 and marks[1]>=35 and marks[2]>=35 :
print( "passed ")
avg = sum(marks)/len(marks)
if avg <=59 : print ("Grade C")
elif avg <=69 : print("Grade B")
else : print ("Grade A")
else : print("Failed!") | true |
832247fd70e02223242f97a091530dd0a5d4af0b | eluvishis/SSMIF_Coding_Assignment | /question3.py | 2,705 | 4.21875 | 4 | """
program: question3_SSMIF.py
author: Eden Luvishis
In order to complete this logic question more efficiently, I have
defined 2 functions. The main one, sum_ssmif, expects a nested list
as an input and iterates through it, sorting the list by even and odd
indices. In order to make the function more efficient, I have defined
a second function, get_sum, that is executed 3 times in the main. I
realized that all 3 steps in the instructions follow a very similar
pattern. They have a start and end value and a multiplier that determines
the modified lists' values. In the final case, if 4 and 5 are present,
this muliplier is just 0. Therefore, for lists with an even index, I call
the get_sum function with the values 9, 6, and 2, while for odd I call
it with 7,4, and 3.
Within the get_sum function, I parce through the list and find the total
sum of the normal list to begin with. Then, if the start value is present,
I create a new list that begins with the start value and contains the
rest of the list. I then search for the end value in the remaining list.
If it exists, the list is ammended to just contain values beginning from
the start value and ending at the first occurence of the ending index.
This list is then multiplied by the (multiplier - 1) because one case of
each value was already accounted for in the total sum at the beginning
of the function. In the case of 0 being the multiplier, the total sum
is first found and then the "special" list is subtracted from the total
sum by multiplying its values by -1.
"""
def get_sum(l ,start, end, multiplier):
"""Returns sum of each inner-list depending on multiplier"""
#one instance is already accounted for in totSum
multBy = multiplier - 1
totSum = sum(l)
#creates a new list in start and end are in the original list
if start in l:
startIndex = l.index(start)
remainingList = l[startIndex:]
if end in remainingList:
endIndex = remainingList.index(end)
#includes the end value
totSum += sum(remainingList[:endIndex + 1 ]) * multBy
return totSum
def sum_ssmif(l):
"""Returns the ssmif_sum of a nested list"""
#new list to append values to
myList = []
for i in range(len(l)):
#even indices
if i % 2 == 0:
evenResult = get_sum(l[i], 9, 6, 2)
myList.append(evenResult)
#odd indices
else:
oddResult = get_sum(l[i], 7, 4, 3)
myList.append(oddResult)
#final list checks for 4 and 5
finList = get_sum(myList, 4, 5, 0)
return finList
test = [[1,2,3,9,2,6,1], [1,3], [1,2,3], [7,1,4,2], [1,2,2]]
print(sum_ssmif(test))
| true |
32efb1d94032e8af57a8fff368937c8916c0cc2b | Rohitkumar3796/Factorial-Number | /FACTORIAL.py | 614 | 4.15625 | 4 | #import time module
# USE NESTED FUNTION TO PRINT FACTORIAL NUMBER WITH TIME
import time
# here,function define
def fact_time(fa_ti):
def inside():
begin = time.time()
fa_ti(int(input('enter the number')),1)
end = time.time()
print('total time taken:',fa_ti.__name__,end-begin) #use name for to print its real name means factorial
return inside
#here I write code of factorial and use sleep funtion for hold 2 sec
def factorial(x,a):
for i in range(1,x+1):
time.sleep(2)
a=a*i
print(a)
time_fact=fact_time(factorial)
time_fact() | true |
9d8ddeb23f283af5f9d08fda827b2cf0019d68f1 | kentronnes/python_crash_course | /python_work/Python Crash Course Chapter 9/9-5 login attempts.py | 1,359 | 4.25 | 4 | class User():
"""Creating a class for user attributes."""
def __init__(self, first_name, last_name, username, email, location):
"""Initiliaze the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location
self.login_atttempts = 0
def describe_user(self):
"""Display a summary of a user's information."""
print("\n" + self.first_name + " " + self.last_name)
print(" Username: " + self.username)
print(" Email: " + self.email)
print(" Location: " + self.location)
def greet_user(self):
"""Display a personalized greeting to the user."""
print("\nWelcome back, " + self.username + "!")
def incremental_login_attempts(self):
"""Track the number of subsequent login attempts by a user."""
self.login_atttempts += 1
def reset_login_attempts(self):
"""Reset a user's login attempts to 0."""
self.login_attempts = 0
ken = User('ken', 'tronnes', 'ktronnes', 'ktronnes@aol.com', 'fiji')
ken.describe_user()
ken.greet_user()
print("\nMaking 3 login attempts...")
ken.incremental_login_attempts()
ken.incremental_login_attempts()
ken.incremental_login_attempts()
print(" Login attempts: " + str(ken.login_atttempts))
print("\nResetting login attempts...")
ken.reset_login_attempts()
print(" Login attempts: " + str(ken.login_attempts)) | true |
ba6e9fc1a2e4859411af00d63fc195c74b9cf194 | gandalf/exercises | /problem4.py | 599 | 4.25 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(num):
text = str(num)
reversed_text = text[::-1]
if text == reversed_text:
return True
else:
return False
l_palindrome = 0
numbers = range(100, 1000)
for n in range(100, 1000):
for number in numbers:
p = n * number
if is_palindrome(p) and p > l_palindrome:
l_palindrome = p
print l_palindrome
| true |
5b259ed9d92ecfe15b6dc6fab3d4e81523e351d3 | yhellow/webdev.fast | /lecture/01grammar/section07-2.py | 2,456 | 4.78125 | 5 | # Section07-2
# class, inheritance
# basics
# superclass(parent) / subclass(child) -> child can use all attributes and methods of the parent
# code can be reused by inheriting class + reduce repetition
# e.g.1
class Computer():
"""parent class"""
def __init__(self, ty, color):
self.ty = ty
self.color = color
def show(self):
return 'Computer Class "show method"'
class samsung(Computer): # using Computer class as parent
"""subclass"""
def __init__(self, computer_name, ty, color):
super().__init__(ty, color)
self.computer_name = computer_name
def show_model(self):
return "your computer is: %s" % self.computer_name
class apple(Computer): # using Computer class as parent
"""subclass"""
def __init__(self, computer_name, ty, color):
super().__init__(ty, color)
self.computer_name = computer_name
def show_model(self):
return "your computer is: %s" % self.computer_name
def show(self):
print(super().show())
return 'car info: %s %s %s' %(self.computer_name, self.ty, self.color)
model1 = samsung('ios', 'air', 'spacegrey')
# general use
print(model1.color) # super
print(model1.ty) # super
print(model1.computer_name) # sub
print(model1.show()) # super
print(model1.show_model()) # sub
print(model1.__dict__)
print()
# method overriding use
model2 = apple('window', 'galaxy', 'neonpurple')
print(model2.show()) # subclass 'show()' has overrided superclass 'show()'
print()
# parent method call
model3 = apple('ios', 'pro', 'gold')
print(model3.show()) # calling super method through 'super().function()'
print()
# inheritance info
# '.mro()' : returns the inheritance info as a list format
# source return
print(apple.mro()) # [<class '__main__.apple'>, <class '__main__.Computer'>, <class 'object'>]
print(samsung.mro()) # from right to left <-- (object(super of all) -> Computer -> apple)
print()
# e.g.2
# multiple inheritance
class X(object): # object is the super of the py doc
pass
class Y():
pass
class Z():
pass
class A(X, Y):
pass
class B(Y, Z):
pass
class F(B, A, Z):
pass
print(F.mro()) # multiple inheritance of class X, Y, Z, A, B
print(A.mro()) | true |
6352da89401bca418210887eb762e6f4a5518f71 | TDysart1/CS1030 | /TiearnDysart_002_01_01.py | 2,207 | 4.3125 | 4 | #Convert a height to meters
#prompt user to input height in feet and inches
# userFt = int(input('What is you height in feet? '))
# userIn = int(input('In inches? '))
# userSumIn = (((userFt) * 12) + userIn)
#users inputs are then gathered as int values to be converted to intches total
userFt = (input('What is your height in feet? ')) #ask user to input height in feet
try: #try/except was used to make sure that if the input is
#anything but an integer it will throw error
userFt == int(userFt)
except ValueError:
print('Not a number value!')
raise SystemExit
userIn = (input('Any inches? '))
try: #Same try/except for the inches input that was used for the feet
userFt == int(userFt) and userFt == int(userFt)
#creating the variable that int values of feet and inches are then
#turned into the sum of inches. Feet times 12 + whatever inches where added
userSumIn = ((int(userFt) * 12) + int(userIn))
except ValueError:
print('Not a number value!')
raise SystemExit
#functon doing the formula to return the
# vaule of users summed inches(userSumIn) and turns into userM(eters)
def heightMeters (userSumIn):
userCm = int(userSumIn * 2.54)
userM = userCm / 100
return userM
#FUNCTION THAT CONVERTS ALL VALUES INTO METERS ^^^
#not to convert it all into a string to make a sentence
# takes the userSumIn as the value...
def convert_to_string(userSumIn):
if userSumIn > 0 and userSumIn <= 95: #if the value is between 0 and 95
fT = str(userFt) #convert userFt to a string
iN = str(userIn) #conver userIn to a string
mM = str(round(heightMeters(userSumIn),2)) #taking the heightMeters value we
#use round to take the value to 2 decimals places.
print('Original height is ' + fT + ' feet and ' + iN + ' inches. That converts to ' + mM + ' meters tall!')
#our sentence will return all values properly spaced
else:
print ('you are really tall!')
#prints the statement if you are just tall
convert_to_string(userSumIn)
#calls are function so we can print our sentences
#WHILE THE VAULES REMAIN WILL BREAK
| true |
e18766afed5c076fe41110229f7bdf129e59a1eb | mageshrocky/PycharmProjects | /pythonProject/interview qns/palindrome.py | 591 | 4.3125 | 4 | # checking the string is palindrome or not
'''string = "madam"
rev_string = string[::-1]
if string == rev_string:
print("palindrome")
else:
print("non palindrome")
# checking the number is palindrome or not
num = int(input("enter the number:"))
string = str(num)
rev_string = string[::-1]
if string == rev_string:
print("palindrome")
else:
print("non palindrome")'''
# alternate method
n = int(input("enter the number:"))
temp = n
sum = 0
while n>0:
sum = n % 10 + sum*10
n = n // 10
if sum == temp:
print("palindrome")
else:
print("not a palindrome")
| true |
ebe8c21ad2f21fcf7d0d20b65cff9fbc14361468 | DanielPascualSenties/practicePython | /Exercise 33.py | 639 | 4.25 | 4 | birthdays = {
"Irene": "20 de febrero",
"Mama": "27 de julio",
"Papa": "16 de febrero",
"Javier": "19 de julio",
"Roberto": "15 de enero",
"Pablo": "17 de septiembre",
"Enriquito": "14 de abril",
"Irene Sentíes": "31 de agosto"
}
def listar(dict):
print(">>> Hola, estos son los cumpleaños disponibles:")
for i in dict:
print(i)
def show_birthday(dict, k):
v = dict[k]
print("El cumpleaños de {} es el {}.".format(k, v))
def main():
listar(birthdays)
while True:
name = input(">>>¿Qué cumpleaños quiere saber?\n ")
show_birthday(birthdays, name)
main()
| false |
b2bc500ddd6d563d76f8ef19d76b8d735dda9a11 | Bama-S/python_intro | /ex1.py | 262 | 4.3125 | 4 | #count the number of vowel in the string
name = input("Enter the string \n")
print ("The string you entered is: ", name)
count = 0
for s in name:
if (s=="a" or s=="e" or s=="i" or s=="o" or s=="u"):
count +=1
print ("The number of vowels: ", count)
| true |
cad2aee285dfd11de8715029f7bfaebe531d6d71 | Bama-S/python_intro | /intro2.py | 232 | 4.40625 | 4 | #Get the input from the user
# get the input as integer
number = input("Enter the number")
print "The number you entered is", number
#get the input as string
name = raw_input("enter your name")
print "The name you entered is", name
| true |
1a2236f937805dec2b4d3823fc00c394cce293c3 | ShinHyoHaeng/Learn-Python | /Ch11_Object-Oriented/11-03-constructor.py | 916 | 4.125 | 4 |
## 객체지향: 생성자
# 클래스 정의 부분
class Car : # 클래스 생성
# 필드 선언
color = ""
speed = 0
# 생성자: 인스턴스를 생성하면 무조건 호출
def __init__(self):
self.color = "빨강"
self.speed = 0
# 메소드 선언
def upSpeed(self, value): # self: 클래스 자신 --> 필드의 speed 변수 / 실제 넘겨 받는 매개변수는 value 한 개
self.speed += value
def downSpeed(self, value): # self: 클래스 자신 --> 필드의 speed 변수
self.speed -= value
# 메인 코드 부분
# 생성자 호출 --> 인스턴스에 필드 값 대입 필요 X
myCar1 = Car()
myCar2 = Car()
print("자동차1의 색상은 %s이며, 현재속도는 %d km입니다." % (myCar1.color, myCar1.speed))
print("자동차2의 색상은 %s이며, 현재속도는 %d km입니다." % (myCar2.color, myCar2.speed))
| false |
d40522cd3a664688bd5b65820c4ea0a7929ee862 | LaisQualtieri/exerciciosPython | /exercicios.py/3.py | 1,393 | 4.3125 | 4 | #formato antigo, talvez por não ser um código bonito
#print("hora da calculadora, primeiro soma")
#n1=int(input("digite um número:"))
#n2=int(input("digite outro número:"))
#soma=n1+n2
#print("a soma entre", n1,"e", n2,"é" soma)
print("hora da calculadora, primeiro soma")
n1=int(input("digite um número:"))
n2=int(input("digite outro número:"))
soma=n1+n2
print("a soma vale",soma)
#formato atual e mais atualizado por motivos óbvios
print("agora subtração")
n1=int(input("digite um número:"))
n2=int(input("digite outro número:"))
subtração=n1-n2
print("a subtração entre {} e {} é {}".format(n1, n2, subtração))
print("agora multiplicação")
n1=int(input("digite um número:"))
n2=int(input("digite outro número:"))
multiplicação=n1*n2
print("a multiplicação entre {} e {} é {}".format(n1, n2, multiplicação))
print("agora divisão")
n1=int(input("digite um número:"))
n2=int(input("digite outro número:"))
divisão=n1/n2
print("a divisão entre {} e {} é {}".format(n1, n2, divisão))
print("potência")
n1=int(input("digite a base:"))
n2=int(input("digite o expoente:"))
potência= n1**n2
print("a potência de {} ao {} é {}".format(n1, n2, potência))
#ou
print("potência")
n1=int(input("digite a base:"))
n2=int(input("digite o expoente:"))
print("o resultado é:", pow(n1, n2))
print("parabéns pelo exercicio concluido :)")
| false |
0cae3bb0b00a8356c46c508c049821d017d75923 | papargyri/BMI_Calculator | /bmi.py | 1,354 | 4.28125 | 4 | height=float(input("Please enter your height in centimeters: "))
weight=float(input("Please enter your Weight in Kg: "))
height = height/100
BMI=weight/(height*height)
print("Your Body Mass Index (BMI) is: ",round(BMI,2)) #Printing BMI with 2 decimal points
if(BMI>0):
if(BMI<=16):
print("According to the World Health Organization(WHO) you belong to the Severe Thinness category.")
elif(BMI<=17):
print("According to the World Health Organization(WHO) you belong to the Moderate Thinness category.")
elif(BMI<=18.5):
print("According to the World Health Organization(WHO) you belong to the Mild Thinness category.")
elif(BMI<=25):
print("According to the World Health Organization(WHO) you belong to the Normal category.")
elif(BMI<=30):
print("According to the World Health Organization(WHO) you belong to the Owergeight category.")
elif(BMI<=35):
print("According to the World Health Organization(WHO) you belong to the Obese Class I category.")
elif(BMI<=40):
print("According to the World Health Organization(WHO) you belong to the Obese Class II category.")
else:
print("According to the World Health Organization(WHO) you belong to the Obese Class III category.")
else:("The details you have entered are not correct. Please try again")
| false |
8346b57f0f1abbf6f3807c4572e958bd1c1ed76a | mika-okamoto/intropython | /hw6project3.py | 1,129 | 4.25 | 4 | #! /usr/bin/python
# Exercise No. 3
# File Name: hw6project3.py
# Programmer: Mika Okamoto
# Date: July 5 2020
#
# Problem Statement: Write a program that prints the lyrics to the ten verses of "The Ants go Marching"
#
# Overall Plan:
# 1. Define lists to use when looping.
# 2. Loop 10 times and print out the lyrics, formatting with the lists.
count = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
ants = ['suck his thumb', 'tie his shoe', 'get stung by a bee', 'eat more', 'smell the bee hive', 'eat cake mix', 'go into heaven', 'check and mate', 'be sublime', 'play with stick men']
for i in range(10):
print('The ants go marching {} by {}, hurrah! hurrah!'.format(count[i], count[i]))
print('The ants go marching {} by {}, hurrah! hurrah!'.format(count[i], count[i]))
print("The ants go marching {} by {},".format(count[i], count[i]))
print("The little one stops to " + ants[i])
print('And they all go marching down...')
print('In the ground...')
print("To get out...")
print("Of the rain.")
print('Boom! Boom! Boom!') | true |
8b87a42bd7c54502f1b739a0bd5611abcfac56d0 | mika-okamoto/intropython | /hw7project2.py | 871 | 4.46875 | 4 | #! /usr/bin/python
# Exercise No. 2
# File Name: hw7project2.py
# Programmer: Mika Okamoto
# Date: July 9 2020
#
# Problem Statement: Write a program that takes the gender of a child and the parents heights and calculates the height of the child as an adult.
#
# Overall Plan:
# 1. Take the gender and parents heights as inputs.
# 2. Calculate the height in inches with the formulas.
# 3. Print the height of the child.
import math
gender = input('What is the gender of the child? >> ')
momHeight = eval(input("What is the mother's height in inches? >> "))
dadHeight = eval(input("What is the father's height in inches? >> "))
if gender == 'female':
inches = round(((dadHeight*12/13)+momHeight)/2)
else:
inches = round(((momHeight*13/12)+dadHeight)/2)
print('The child is {} feet {} inches.'.format(inches//12, inches%12)) | true |
8b9546839f48cd3ae52848433a2822baef6f03c7 | nikhil-shukla/GitDemo | /pythonProject/List (Ordered collection of Objects)/ListDemo4.py | 247 | 4.15625 | 4 | list1=[12,89,58,66,52,0,3,6,8]
print(list1)
list1.reverse() #reverse order
print(list1)
list1.sort() #sorting
print(list1)
#lists of list
myList=[10,9,20,["Nikhil","Python","Selenium"]]
print(myList)
print(myList[3][::-1]) #access using indexing | true |
bbbbbfde54ec857244e49539419db777926c3aaf | Aidaralievh/Aidaraliev | /pythonProject/1homework калькулятор.py | 895 | 4.15625 | 4 |
a = float(input("Введите первое число:"))
b = float(input("Введите второе число:"))
adi = input("выберите какой знак будете использовать +, -, /, *:")
if adi == "+":
c = a + b
print("\n результат:" + str(c))
print("спасибо что выбрали нас -_-")
elif adi == "-":
c = a - b
print("\n результат:" + str(c))
print("спасибо что выбрали нас -_-")
elif adi == "*":
c = a * b
print("\n результат:" + str(c))
print("спасибо что выбрали нас -_-")
elif adi == "/":
c = a / b
print("\n результат:" + str(c))
print("спасибо что выбрали нас -_-")
else:
print("\n Введен неправильный символ,", "попытайтесь еще раз-_-")
| false |
ebd028af58b49ed5c263dc75237ee5f136a5365b | danielmmetz/euler | /euler009.py | 629 | 4.40625 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def answer(sumval):
""" returns the product of a Pythagorean triplet whose sum equals sumval """
for a in xrange(1, sumval):
for b in xrange(a, sumval):
c = sumval - a - b
if c > 0 and c ** 2 == a ** 2 + b ** 2:
return a * b * c
raise Exception, 'no triplet exists'
if __name__ == '__main__':
print answer(1000)
| true |
980594b37a93e9bdf475dc650ce6a55089c04acd | danielmmetz/euler | /euler004.py | 719 | 4.21875 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
from itertools import combinations
def answer(n_digits):
"""
finds the largest palindrome made from the project of two numbers, each
composed of n_digits
"""
best = 0
pairs = combinations(xrange(10 ** (n_digits - 1), 10 ** (n_digits)), 2)
for (x, y) in pairs:
prod = str(x * y)
if prod == prod[::-1]:
best = max(best, x * y)
return best
if __name__ == '__main__':
assert answer(2) == 9009, 'failed small test'
print answer(3)
| true |
2775b2ea71a9ed895aff16a93513fde3aad66e1d | 3uxeca/Bitcamp-AI-study | /flask/fk16_sqlite.py | 1,295 | 4.125 | 4 | # 모듈
import sqlite3
# test.db 연결(SQLite 는 없으면 자동으로 생성) >> SQLite는 내 PC에서만 사용 가능
conn = sqlite3.connect("test.db", isolation_level=None)
cursor = conn.cursor()
# 테이블이 없다면 해당 테이블을 생성
cursor.execute("""CREATE TABLE IF NOT EXISTS supermarket(Itemno INTEGER, Category TEXT,
FoodName TEXT, Company TEXT, Price INTEGER)""")
# 테이블의 내용을 모두 지우기
# sql = "DELETE FROM supermarket"
# cursor.execute(sql)
# 데이터를 2건 입력
sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)"
cursor.execute(sql, (1, '과일', '자몽', '마트', 1500))
sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)"
cursor.execute(sql, (2, '음료수', '망고주스', '편의점', 1000))
# 입력된 데이터를 조회
sql = "select Itemno, Category, FoodName, Company, Price from supermarket"
cursor.execute(sql)
# 데이터를 모두 가져오기
rows = cursor.fetchall()
# 가져온 내용을 한 줄씩 가져와서, 각 컬럼의 내용을 공백으로 구분해 출력
for row in rows:
print(str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4]))
# 연결 닫기
conn.close() | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.