blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
bcf0ea0073f1ff6635e224542e025db935224de2
|
victor-da-costa/Aprendendo-Python
|
/Curso-Em-Video-Python/Mundo-3/EXs/EX079.py
| 413
| 4.15625
| 4
|
numeros = []
while True:
num = int(input('Digite um número: '))
if num in numeros:
print(f'O número {num} já existe na lista, portanto não será adicionado')
else:
numeros.append(num)
continuar = str(input('Quer adicionar mais um número na lista? S/N ')).upper()
if continuar == 'N':
break
numeros.sort()
print(f'Os números adicionado a lista foram: {numeros}')
| false
|
da100cf4a30bed21264a673ed585ce508ca89115
|
victor-da-costa/Aprendendo-Python
|
/Curso-Em-Video-Python/Mundo-2/EXs/EX037.py
| 579
| 4.1875
| 4
|
num = int(input('Digite um número inteiro qualquer: '))
print('''Escolha uma base de conversão:
[1] Converter para Binário
[2] Converter para Octal
[3] Converter para Hexadecimal''')
escolha = int(input('Converter para: '))
if escolha == 1:
print('{} convertido para Binário é igual a {}'.format(num, bin(num) [2:]))
elif escolha == 2:
print('{} convertido para Octal é igual a {}'.format(num, oct(num)[2:]))
elif escolha == 3:
print('{} convertido para Hexadecimal é igual a {}'.format(num, hex(num)[2:]))
else:
print('Escolha invalida, tente novamente!')
| false
|
9a16c181418ba0fb5d6118d89d95a179942b7f05
|
GitSmurff/LABA-2-Python
|
/laba6/laba1.py
| 1,002
| 4.21875
| 4
|
import abc
class Abstract(abc.ABC):
@abc.abstractmethod
def __init__(self, x):
self.x = 0
class Queen(Abstract):
def __init__(self):
self.x = int(input('Введите число от 1 до 9: '))
if self.x >= 1 and self.x <= 3:
s =str(input("Введите строку: "))
n = int(input("Введите число повторов строки: "))
i = 0
while i < n:
print (s)
i += 1
elif self.x >= 4 and self.x <= 6:
m = int(input("Введите степень, в которую следует возвести число: "))
print(self.x**m)
elif self.x >= 7 and self.x <= 9:
i = 0
while i < 10:
self.x += 1
i += 1
print(self.x)
else:
print("Ошибка ввода!")
return self.x
x = Queen()
| false
|
3ed6e13c885c7e666fd318e32e3b20278581df18
|
kaiyaprovost/algobio_scripts_python
|
/windChill.py
| 1,076
| 4.1875
| 4
|
import random
import math
def welcome():
print("This program computes wind chill for temps 20 to -25 degF")
print("in intervals of 5, and for winds 5 to 50mph in intervals of 5")
def computeWindChill(temp,wind):
## input the formula, replacing T with temp and W with wind
wchill = 35.74 + 0.6215*temp - 35.75*(wind**0.16) + 0.4275*temp*(wind**0.16)
return(wchill)
def main():
welcome() #Print a message that explains what your program does
#Print table headings:
for temp in range(20, -25, -5):
print "\t",str(temp),
print
#Print table:
for wind in range(5,55,5): #For wind speeds between 5 and 50 mph
print wind,"\t", #Print row label
for temp in range(20, -25, -5): #For temperatures between 20 and -20 degrees
wchill = computeWindChill(temp, wind)
print wchill,"\t", #Print the wind chill, separated by tabs
print #Start a new line for each temp
main()
| true
|
7f5e66623babc6919733bec982bbd4d4baa10176
|
Ojhowribeiro/PythonProjects
|
/exercicios/PycharmProjects/exepython/ex014.py
| 315
| 4.125
| 4
|
c = float(input('Qual a temperatura em c°:'))
f = float((c*1.8)+32)
k = float(c+273)
print('{}°C é igual a {:.2f}°F e {:.2f}°K'.format(c, f, k))
'''c = float (input('qual o valor em °c: '))
f = float (((9*c) /5 ) + 32)
k = float (c + 273)
print('{}°C é igual a {:.2f}°F e {:.2f}°K'.format(c, f, k))'''
| false
|
0369b41812b9cdd3bd66f2dacbd728497b6525c8
|
Ojhowribeiro/PythonProjects
|
/exercicios/PycharmProjects/exepython/ex006.py
| 370
| 4.15625
| 4
|
n = int(input('digite um numero: '))
dobro = int(n*2)
triplo = int(n*3)
raiz = float(n**(1/2))
print('O dobro de {} é {}, o triplo é {} e a raiz é {:.2f}'.format(n, dobro, triplo, raiz))
'''n = int(input('digite um numero: '))
mul = n*2
tri = n*3
rai = n**(1/2)
print('o dobro de {} é {}, o triplo é {} e a raiz quadrada é {:.3f}'.format(n, mul, tri, rai))'''
| false
|
d5db4d147d1a96ba1713d98198e9c596b6d9e84c
|
Ojhowribeiro/PythonProjects
|
/exercicios/PycharmProjects/exepython/ex008.py
| 396
| 4.21875
| 4
|
medida = float(input('Qual o valor em metros: '))
cm = float(medida*100)
mm = float(medida*1000)
km = float(medida/1000)
print('{} metros: \n{:.3f} cm \n{:.3f} mm\n{:.3f} km'.format(medida, cm, mm, km))
'''medida = float(input('qual a distancia em metros:'))
cm = medida * 100
mm = medida * 1000
km = medida / 1000
print('{} metros igual:\ncm: {}\nmm: {}\nkm: {}'.format(medida, cm, mm, km))'''
| false
|
9de3fd928aecb53938eb1ced384dfb9deeb3a5b9
|
lzaugg/giphy-streamer
|
/scroll.py
| 1,426
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Console Text Scroller
~~~~~~~~~~~~~~~~~~~~~
Scroll a text on the console.
Don't forget to play with the modifier arguments!
:Copyright: 2007-2008 Jochen Kupperschmidt
:Date: 31-Aug-2008
:License: MIT_
.. _MIT: http://www.opensource.org/licenses/mit-license.php
"""
from itertools import cycle
from sys import stdout
from time import sleep
def stepper(limit, step_size, loop, backward, bounce):
"""Generate step indices sequence."""
steps = range(0, limit + 1, step_size)
if backward:
steps.reverse()
if bounce:
list(steps).extend(reversed(steps))
if loop:
steps = cycle(steps)
return iter(steps)
def display(string):
"""Instantly write to standard output."""
stdout.write('\r' + string)
stdout.flush()
def scroll(message, window, backward=False, bounce=True,
loop=True, step_size=1, delay=0.1, template='[%s]'):
"""Scroll a message."""
string = ''.join((' ' * window, message, ' ' * window))
limit = window + len(message)
steps = stepper(limit, step_size, loop, backward, bounce)
try:
for step in steps:
display(template % string[step:window + step])
sleep(delay)
except KeyboardInterrupt:
pass
finally:
# Clean up.
display((' ' * (window + len(template) - 2)) + '\r')
if __name__ == '__main__':
scroll('Hello Sam!', 20)
| true
|
f8f775245f38f0553c139bf3253c449e7bf851d8
|
judeinno/CodeInterview
|
/test/test_Piglatin.py
| 941
| 4.15625
| 4
|
import unittest
from app.Piglatin import PigLatinConverter
""" These tests are for the piglatin converter"""
class TestConverter(unittest.TestCase):
"""This test makes sure that once the first letters are not vowels they are moved to the end"""
def test_for_none_vowel(self):
self.pig = PigLatinConverter(args='jude')
result = self.pig.pig_latin()
self.assertEqual(result, 'udejay')
"""This test makes sure that once the first letter is a vowel the word way is added to the end of the word"""
def test_for_vowel(self):
self.pig = PigLatinConverter(args='andela')
self.assertEqual(self.pig.pig_latin(), 'andelaway')
"""This test makes sure that an integer is not entered"""
def test_for_integers(self):
self.pig = PigLatinConverter(args= str(55))
self.assertEqual(self.pig.pig_latin(), 'Please enter a word')
if __name__ == '__main__':
unittest.main()
| true
|
5b2887021b660dfb5bca37a6b395b121759fed0a
|
Kontetsu/pythonProject
|
/example24.py
| 659
| 4.375
| 4
|
import sys
total = len(sys.argv) - 1 # because we put 3 args
print("Total number of args {}".format(total))
if total > 2:
print("Too many arguments")
elif total < 2:
print("Too less arguments")
elif total == 2:
print("It's correct")
arg1 = int(sys.argv[1])
arg2 = int(sys.argv[2])
if arg1 > arg2:
print("Arg 1 is bigger")
elif arg1 < arg2:
print("Arg 1 is smaller")
else:
print("Arg 1 and 2 are equal!")
# some methods how to check the user input pattern
print("string".isalpha())
print("string1".isalnum())
print("string".isdigit())
print("string".startswith('s'))
print("string".endswith('g'))
| true
|
e8310a33a0ee94dfa39dc00ff5027d61c74e6d94
|
Kontetsu/pythonProject
|
/example27.py
| 748
| 4.28125
| 4
|
animals = ["Dog", "Cat", "Fish"]
lower_animal = []
fruits = ("apple", "pinnaple", "peach")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#for anima in animals:
# lower_animal.append(anima.lower())
print("List of animals ", animals)
for animal in animals:
fave_animal = input("Enter yor favorite animal from the list: ")
#print("Animals {}".format(animal))
if animal == fave_animal:
print("Your favorite animal Catis :", animal)
break
#for fruit in fruits:
# print("Fruits {}".format(fruit))
#for vehicles in thisdict.items():
# print("Vehicles {} {}".format(vehicles[0], vehicles[1]))
#for k, v in thisdict.items(): # is better
# print("Vehicles {} {}".format(k, v))
| false
|
1688c93855bda769c0e21a5cbfb463cfe3cc0299
|
JimVargas5/LC101-Crypto
|
/caesar.py
| 798
| 4.25
| 4
|
#Jim Vargas caesar
import string
from helpers import rotate_character, alphabet_position
from sys import argv, exit
def encrypt(text, rot):
'''Encrypts a text based on a pseudo ord circle caesar style'''
NewString = ""
for character in text:
NewChar = rotate_character(character, rot)
NewString = NewString + NewChar
return NewString
def main(rot):
if rot.isdigit():
text = input("Type the message that you would like to encrypt: ")
#rot = int(input(Rotate by:))
rot = int(rot)
print(encrypt(text, rot))
else:
print("You need to enter an integer argument.")
exit()
if __name__ == '__main__':
if len(argv) <=1:
print("You need to enter an integer argument.")
exit()
else:
main(argv[1])
| true
|
b211b888702bbb1ebed8b6ee2b21fec7329a7b59
|
deyoung1028/Python
|
/to_do_list.py
| 1,738
| 4.625
| 5
|
#In this assignment you are going to create a TODO app. When the app starts it should present user with the following menu:
#Press 1 to add task
#Press 2 to delete task (HARD MODE)
#Press 3 to view all tasks
#Press q to quit
#The user should only be allowed to quit when they press 'q'.
#Add Task:
#Ask the user for the 'title' and 'priority' of the task. Priority can be high, medium and low.
#Delete Task: (HARD MODE)
#Show user all the tasks along with the index number of each task. User can then enter the index number of the task to delete the task.
#View all tasks:
#Allow the user to view all the tasks in the following format:
#1 - Wash the car - high
#2 - Mow the lawn - low
#Store each task in a dictionary and use 'title' and 'priority' as keys of the dictionary.
#Store each dictionary inside an array. Array will represent list of tasks.
#** HINT **
#tasks = [] # global array
#input("Enter your option")
tasks = [] #global array
def view_tasks():
print(tasks)
while True:
print("Please make a choice from the following menu:")
print("1 - Add Task")
print("2 - Delete Task")
print("3 - View all tasks ")
print("q to quit")
choice = input("Enter Choice:")
if choice == "q":
break
if choice == "1":
title = input("Please enter a task title:")
priority = input("Please enter priority : high, medium or low - ")
task = {"title": title, "priority": priority}
tasks.append(task)
if choice == "2":
view_tasks()
del_task = int(input("Chose a task to delete:" ))
del tasks[del_task - 1]
view_tasks()
if choice == "3":
view_tasks()
print(tasks)
| true
|
e41796d392658024498869143c8b8879a7916968
|
deyoung1028/Python
|
/dictionary.py
| 487
| 4.21875
| 4
|
#Take inputs for firstname and lastname and then create a dictionary with your first and last name.
#Finally, print out the contents of the dictionary on the screen in the following format.
users=[]
while True:
first = input("Enter first name:")
last = input("Enter last name:")
user = {"first" : first, "last": last}
users.append(user)
choice = input("Enter q to quit or any key to continue:")
if choice == "q":
break
print(users)
| true
|
74dee8921f4db66c458a0c53cd08cb54a2d1ba63
|
KritikRawal/Lab_Exercise-all
|
/4.l.2.py
| 322
| 4.21875
| 4
|
""" Write a Python program to multiplies all the items in a list"""
total=1
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total * list1[ele]
# printing total value
print("product of all elements in given list: ", total)
| true
|
d71d9e8c02f405e55e493d1955451c12d50f7b9b
|
KritikRawal/Lab_Exercise-all
|
/3.11.py
| 220
| 4.28125
| 4
|
""" find the factorial of a number using functions"""
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input('enter the number'))
print(factorial)
| true
|
53b8278af9a4a98b4de820d91054d80e9f1247f4
|
KritikRawal/Lab_Exercise-all
|
/3.8.py
| 393
| 4.125
| 4
|
"""takes a number as a parameter and check the number is prime or not"""
def is_prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
print('Start')
val = int(input('Enter the number to check prime:\n'))
ans = is_prime(val)
if ans:
print(val, 'Is a prime number:')
else:
print(val, 'Is not a prime number:')
| true
|
ae6ae8cfe7e655b1ffc9617eb8d87480a97e8f27
|
KritikRawal/Lab_Exercise-all
|
/4.2.py
| 635
| 4.4375
| 4
|
""". Write a Python program to convert temperatures to and from celsius,
fahrenheit.
C = (5/9) * (F - 32)"""
print("Choose the conversion: ")
print(" [c] for celsius to fahrenheit")
print(" [f] for fahrenheit to celsius")
ans = input()
conversion = 0
cs = ""
if ans == "c":
ans = "Celsius"
elif ans == "f":
ans = "Fahrenheit"
print(f"Enter your temperature in {ans}")
temp = int(input())
if ans == "Celsius":
conversion = temp * (9 / 5) + 32
cs = "Fahrenheit"
elif ans == "Fahrenheit":
conversion = (5 / 9) * (temp - 32)
cs = "Celsius"
print(f"{temp} ({ans}) is {conv} ({cs})")
print()
| true
|
b9e75d0b9d9605330c54818d1dd643cc764032cf
|
KritikRawal/Lab_Exercise-all
|
/2.5.py
| 277
| 4.21875
| 4
|
"""For given integer x,
print ‘True’ if it is positive,
print ‘False’ if it is negative and
print ‘zero’ if it is 0"""
x = int(input("Enter a number: "))
if x > 0:
print('positive')
elif x<0:
print('negative')
else:
print('zero')
| true
|
d0c28518a33bf41c9945d97690e3891eeba277ad
|
AANICK007/STEPPING_IN_PYTHON_WORLD
|
/programme_8.py
| 413
| 4.53125
| 5
|
# This is a programme to study bitwise operators in python
x =5 & 6 ; # this is and operator between bit numbers of 5 and 6
print ( x ) ;
x = 5 | 6 ;
print ( x ) ; # this is or operator between bit numbers of 5 and 6
x = ~ 5 ;
print ( x ) ; # this is not operator
x = 5 ^ 6 ;
print ( x ) ; # this is xor operator between bit numbers of 5 and 6
x = 99 >> 2 ;
print ( x ) ;
x = 5 << 3 ;
print ( x ) ;
| false
|
5a1e59a9c6fb569a22357aeabb61952d112f9e98
|
marvjaramillo/ulima-intro210-clases
|
/s021-selectivas/selectiva.py
| 713
| 4.28125
| 4
|
'''
Implemente un programa que lea la calificacion de un alumno y su cantidad de
participaciones. Si la cantidad de participaciones es mayor que 10, entonces
recibe un punto de bonificacion. Su programa debe mostrar en pantalla la
nota final
'''
def main():
nota = int(input("Ingrese nota: "))
participaciones = int(input("Ingrese participaciones: "))
#Si la cantidad de participaciones es mayor que 10
if(participaciones > 10):
#Incremento la nota en 1
print("Felicidades, tiene un punto de bonificacion")
nota = nota + 1
else:
print("Lamentablemente no tiene bonificacion")
print("Nota final:", nota)
if __name__ == "__main__":
main()
| false
|
2a5f44807795975b2d7d392a2295811399606980
|
marvjaramillo/ulima-intro210-clases
|
/s036-guia05/p06.1.py
| 711
| 4.375
| 4
|
'''
Estrategia:
1) Leemos el valor como cadena (con el punto decimal)
2) LLamamos a una funcion para quitar el punto decimal
3) aplicamos la funcion que maneja enteros para hallar la suma de digitos
'''
import p06
def convertir(numero):
res = ""
#Convertimos a cadena para procesarlo
numero = str(numero)
for caracter in numero:
if(caracter != "."):
res = res + caracter
#Convertimos la respuesta a entero
return int(res)
def main():
n = 49.89343
print("Numero original:", n)
n = convertir(n)
print("Numero convertido:", n)
suma_cifras = p06.suma_cifras(n)
print("Suma de cifras:", suma_cifras)
if __name__ == "__main__":
main()
| false
|
31f9b34ad89fdaafb0f232c5783a35fc811a1d70
|
marvjaramillo/ulima-intro210-clases
|
/s054-guia08/p08.py
| 1,030
| 4.25
| 4
|
'''
Formato de los datos (ambos son cadenas):
- clave: termino
- valor: definicion del termino
Ejemplo:
glosario = {"termino1": "El termino1 es <definicion>"}
'''
#Lee los valores del usuario y crea el diccionario
def leer_glosario():
res = {}
#Leemos la cantidad de terminos
n = int(input("Ingrese la cantidad de terminos: "))
for i in range(n):
#Por cada uno, leemos el termino y su definicion
termino = input("Ingrese termino del glosario: ")
definicion = input("Ingrese su definicion: ")
#Agregamos elemento al diccionario
res[termino] = definicion
return res
#Muestra los valores del glosario
def mostrar_glosario(dic_glosario):
lista_terminos = dic_glosario.keys()
for termino in lista_terminos:
print("*" * 30)
print("Termino:", termino)
print("Definicion:", dic_glosario[termino])
print("*" * 30)
if __name__ == "__main__":
dic_glosario = leer_glosario()
mostrar_glosario(dic_glosario)
| false
|
99e3a484814475a5ccc0627f5d875507a5213b0c
|
Mattias-/interview_bootcamp
|
/python/fizzbuzz.py
| 520
| 4.15625
| 4
|
# Using any language you want (even pseudocode), write a program or subroutine
# that prints the numbers from 1 to 100, each number on a line, except for every
# third number write "fizz", for every fifth number write "buzz", and if a
# number is divisible by both 3 and 5 write "fizzbuzz".
def fb():
for i in xrange(1, 100):
s = ""
if i % 3 == 0:
s = "fizz"
if i % 5 == 0:
s += "buzz"
if not s:
print i
else:
print s
fb()
| true
|
1aae789149cce977556e11683e898dc039bdb9ad
|
derek-baker/Random-CS-Stuff
|
/python/SetCover/Implementation.py
| 1,542
| 4.1875
| 4
|
# INSPIRED BY: http://www.martinbroadhurst.com/greedy-set-cover-in-python.html
# def test_that_subset_elements_contain_universe(universe, elements):
# if elements != universe:
# return False
# return True
def compute_set_cover(universe, subsets):
# Get distinct set of elements from all subsets
elements = set(el for setOfEls in subsets for el in setOfEls)
print('ELEMENTS:')
print(elements)
# if test_that_subset_elements_contain_universe(universe, elements) == False:
# return None
covered = set()
cover = []
# Add subsets with the greatest number of uncovered points
# (As a heuristic for finding a solution)
while covered != elements:
# This will help us to find which subset can cover at the least cost
compute_cost = lambda candidate_subset: len(candidate_subset - covered)
subset = max(subsets, key = compute_cost)
cover.append(subset)
print('\nSELECTED SUBSET: ')
print(subset)
print('COVERED: ')
print(covered)
# Perform bitwise OR and assigns value to the left operand.
covered |= subset
return cover
def main():
universe = set(range(1, 11))
subsets = [
set([1, 2, 3, 8, 9, 10]),
set([1, 2, 3, 4, 5]),
set([4, 5, 7]),
set([5, 6, 7]),
set([6, 7, 8, 9, 10]),
]
cover = compute_set_cover(universe, subsets)
print('\nLOW-COST SET COVER:')
print(cover)
if __name__ == '__main__':
main()
| true
|
e74add4e61a90087bb085b51a8734a718fd554f7
|
sador23/cc_assignment
|
/helloworld.py
| 602
| 4.28125
| 4
|
'''The program asks for a string input, and welcomes the person, or welcomes the world if nothing was given.'''
def inputname():
'''Keeps asking until a string is inputted'''
while True:
try:
name=input("Please enter your name!")
int(name)
print("This is not a string! Please enter a string")
except ValueError:
return name
def greeting(name):
'''Greets the person, depending on the name'''
if not name:
print("Hello World!")
else:
print("Hello " + str(name) + "!")
greeting(inputname())
| true
|
2abe2c2de6d54d9a44b3abb3fc03c88997840e61
|
maria1226/Basics_Python
|
/aquarium.py
| 801
| 4.53125
| 5
|
# For his birthday, Lubomir received an aquarium in the shape of a parallelepiped. You have to calculate how much
# liters of water will collect the aquarium if it is known that a certain percentage of its capacity is occupied by sand,
# plants, heater and pump.
# Its dimensions - length, width and height in centimeters will be entered by the console.
# One liter of water is equal to one cubic decimeter.
# Write a program that calculates the liters of water needed to fill the aquarium.
length_in_cm=int(input())
width_in_cm=int(input())
height_in_cm=int(input())
percentage_occupied_volume=float(input())
volume_aquarium=length_in_cm*width_in_cm*height_in_cm
total_liters=volume_aquarium*0.001
percentage=percentage_occupied_volume*0.01
liters=total_liters*(1-percentage)
print(f'{liters:.3f}')
| true
|
56a13bb22f6d53ef4e149941d2d4119cc8d4edd3
|
lagzda/Exercises
|
/PythonEx/intersection.py
| 450
| 4.125
| 4
|
def intersection(arr1, arr2):
#This is so we always use the smallest array
if len(arr1) > len(arr2): arr1, arr2 = arr2, arr1
#Initialise the intersection holder
inter = []
for i in arr1:
#If it is an intersection and avoid duplicates
if i in arr2 and i not in inter:
inter.append(i)
return inter
#Test
arr1 = [54,26,93,17,77,31,44,55,20]
arr2 = [54, 93, 93, 7]
print intersection(arr1, arr2)
| true
|
6f77c3a1e04eb47c490eb339cf39fc5c925e453c
|
rudiirawan26/Bank-Saya
|
/bank_saya.py
| 1,114
| 4.15625
| 4
|
while True:
if option == "x":
print("============================")
print("Selamat Datang di ATM saya")
print("============================")
print('')
option1 = print("1. Chek Uang saya")
option2 = print("2. Ambil Uang saya")
option3 = print("3. Tabung Uang saya")
print('')
total = 0
option = int(input("Silakan pilih Option: "))
if option == 1:
print("Uang kamu berjumlah: ",total)
elif option == 2:
ngambil_uang = eval(input("Masukan nominal uang yang akan di ambil: "))
rumus = total - ngambil_uang
if ngambil_uang <= total:
print("Selamat anda berhasil ngambil unang")
else:
print("Saldo anda tidak mencukupi")
elif option == 3:
menabung = eval(input("Masukan nominal uang yang kan di tabung: "))
rumus_menabung = menabung + total
print("Proses menabung SUKSES")
else:
print("Masukan tidak di kenali")
else:
print("Anda telah keluar dari program")
| false
|
2c9da507053689dee6cc34724324521983ea0c8c
|
miroslavgasparek/python_intro
|
/numpy_practice.py
| 1,834
| 4.125
| 4
|
# 21 February 2018 Miroslav Gasparek
# Practice with NumPy
import numpy as np
# Practice 1
# Generate array of 0 to 10
my_ar1 = np.arange(0,11,dtype='float')
print(my_ar1)
my_ar2 = np.linspace(0,10,11,dtype='float')
print(my_ar2)
# Practice 2
# Load in data
xa_high = np.loadtxt('data/xa_high_food.csv',comments='#')
xa_low = np.loadtxt('data/xa_low_food.csv',comments='#')
def xa_to_diameter(xa):
""" Convert an array of cross-sectional areas to diameters with
commensurate units."""
# Compute diameter from area
diameter = np.sqrt((4*xa)/np.pi)
return diameter
# Practice 3
# Create matrix A
A = np.array([[6.7, 1.3, 0.6, 0.7],
[0.1, 5.5, 0.4, 2.4],
[1.1, 0.8, 4.5, 1.7],
[0.0, 1.5, 3.4, 7.5]])
# Create vector b
b = np.array([1.1, 2.3, 3.3, 3.9])
# 1. Print row 1 (remember, indexing starts at zero) of A.
print(A[0,:])
# 2. Print columns 1 and 3 of A.
print(A[:,(0,2)])
# 3. Print the values of every entry in A that is greater than 2.
print(A[A > 2])
# 4. Print the diagonal of A. using the np.diag() function.
print(np.diag(A))
# 1. First, we'll solve the linear system A⋅x=bA⋅x=b .
# Try it out: use np.linalg.solve().
# Store your answer in the Numpy array x.
x = np.linalg.solve(A,b)
print('Solution of A*x = b is x = ',x)
# 2. Now do np.dot(A, x) to verify that A⋅x=bA⋅x=b .
b1 = np.dot(A,x)
print(np.isclose(b1,b))
# 3. Use np.transpose() to compute the transpose of A.
AT = np.transpose(A)
print('Transpose of A is AT = \n',AT)
# 4. Use np.linalg.inv() to compute the inverse of A.
AInv = np.linalg.inv(A)
print('Inverse of A is AInv = \n',AInv)
# 1. See what happens when you do B = np.ravel(A).
B = np.ravel(A)
print(B)
# 2. Look of the documentation for np.reshape(). Then, reshape B to make it look like A again.
C = B.reshape((4,4))
print(C)
| true
|
877150ed0d4fb9185a633ee923daee0ba3d745e4
|
nmessa/Raspberry-Pi
|
/Programming/SimplePython/name4.py
| 550
| 4.125
| 4
|
# iteration (looping) with selection (conditions)
again = True
while again:
name = raw_input("What is your name? ")
print "Hello", name
age = int(raw_input("How old are you? "))
newage = age + 1
print "Next year you will be ", newage
if age>=5 and age<19:
print "You are still in school"
elif age < 5:
print "You have not started school yet?"
elif age > 20:
print "You are probably out of high school now?"
answer = raw_input("Again (y/n)?")
if answer != 'y':
again = False
| true
|
cd0c13a1013724e1ec7920a706ee52e2aa0e9a96
|
Teslothorcha/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/0-add_integer.py
| 411
| 4.15625
| 4
|
#!/usr/bin/python3
"""
This function will add two values
casted values if necessary (int/float)
and return the addition
"""
def add_integer(a, b=98):
"""
check if args are ints to add'em'
"""
if not isinstance(a, (int, float)):
raise TypeError("a must be an integer")
if not isinstance(b, (int, float)):
raise TypeError("b must be an integer")
return (int(a) + int(b))
| true
|
353bb70b7acbbedf2381635d1d554d117edc6b7f
|
valoto/python_trainning
|
/aula2/strings.py
| 780
| 4.125
| 4
|
var = "PYT''\"HON"
var = 'PYTH"ON'
# TODAS MAIUSCULAS
print(var.upper())
# TODAS MINUSCULAS
print(var.upper())
# SUBSTITUI T POR X
print(var.replace('T', 'X'))
# PRIMEIRA LETRA MAIUSCULA0
print(var.title())
# CONTA QUANTIDADE DE LETRAS T
print(var.count('T'))
# PROCURAR POSIÇÃO DA LETRA T
print(var.find('T'))
# QUANTIDADE DE CARACTERES DA STRING
print(len(var))
# JUNTA UMA LISTA EM UMA STRING
print(', '.join(['a', 'b', 'c']))
# EXPLODE UMA STRING EM UMA LISTA
print(var.split(','))
nome = "Igor"
sobrenome = "Valoto"
idade = 24
print(nome + " " + sobrenome)
print("Meu nome é: %s e tenho %s anos" % (nome, idade))
print("Meu nome é: {0} e tenho {1} anos".format(nome, idade))
var10 = "Meu nome é: {0} e tenho {1} anos".format(nome[:2], idade)
print(var10)
| false
|
5e6e2e5e3d29dc46c9e5a9e7bc49a5172fbbb3cb
|
wbsth/mooc-da
|
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
| 935
| 4.1875
| 4
|
#!/usr/bin/env python3
import math
def main():
while True:
shape = input('Choose a shape (triangle, rectangle, circle): ')
if shape == '':
break
else:
if shape == 'rectangle':
r_width = int(input("Give width of the rectangle: "))
r_height = int(input("Give height of the rectangle: "))
print(f"The area is {r_height * r_width}")
elif shape == 'triangle':
t_base = int(input("Give base of the triangle: "))
t_height = int(input("Give height of the triangle: "))
print(f"The area is {0.5*t_base*t_height}")
elif shape == 'circle':
c_radius = int(input("Give radius of the circle: "))
print(f"The area is {math.pi * c_radius ** 2}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
| true
|
f613fa6f9dbf7713a764a6e45f29ef8d67a5f39c
|
abhishek0chauhan/rock-paper-scissors-game
|
/main.py
| 1,431
| 4.25
| 4
|
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
#print(scissors)
your_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors."))
random_computer_choice = random.randint(0,2)
#for computer
if random_computer_choice == 0:
print(f"{rock}\nComputer chose:")
elif random_computer_choice == 1:
print(f"{paper}\nComputer chose:")
elif random_computer_choice == 2:
print(f"{scissors}\nComputer chose:")
#for player
if your_choice == 0:
print(rock)
elif your_choice == 1:
print(paper)
elif your_choice == 2:
print(scissors)
# logic of game
if your_choice == random_computer_choice:
print('game tied')
elif your_choice == 0 and random_computer_choice == 1:
print("You lose")
elif your_choice == 0 and random_computer_choice == 2:
print('You win')
elif your_choice == 1 and random_computer_choice == 0:
print('You win')
elif your_choice == 1 and random_computer_choice == 2:
print('You lose')
elif your_choice == 2 and random_computer_choice == 0:
print("You lose")
elif your_choice == 2 and random_computer_choice == 1:
print("You win")
else:
print('You typed a invalid number!\nYou lose')
| false
|
a0516d0ca0791c8584b51cee2e354113f03a74f1
|
LFBianchi/pythonWs
|
/Learning Python/Chap 4/p4e6.py
| 839
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Exercise 5 of the Part IV of the book "Learning Python"
Function "addDict" - Returns a union of dictionaries
Created on Mon Nov 9 11:06:47 2020
@author: lfbia
"""
def addList(list1, list2):
return list1 + list2
def addDict(aurelio, michaellis):
D = {}
for i in aurelio.keys():
D[i] = aurelio[i]
for i in michaellis.keys():
D[i] = michaellis[i]
return D
def addListDict(A, B):
if type(A) == list: return addList(A, B)
else: return addDict(A, B)
print(addListDict({'edi': 1,
'noelia': 2,
'anselmo': 4},
{'nilcilene': 54,
'arlete': 55,
'sandra': 8}))
print(addListDict([1, 2, 3, 4, 5],
[5, 3, 4, 5]))
print(addListDict([5, 3, 4, 5],
[1, 2, 3, 4, 5]))
| false
|
d3e64c5bfe6b5508c458a2bc76e40fa6ef0f4019
|
nasrinsultana014/HackerRank-Python-Problems
|
/Solutions/Problem14.py
| 536
| 4.21875
| 4
|
def swap_case(s):
characters = list(s)
convertedCharacters = []
convertedStr = ""
for i in range(len(characters)):
if characters[i].isupper():
convertedCharacters.append(characters[i].lower())
elif characters[i].islower():
convertedCharacters.append(characters[i].upper())
else:
convertedCharacters.append(characters[i])
return convertedStr.join(convertedCharacters)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
| true
|
0f28ba6d84069ffabf1a733ca4f4980c28674290
|
ngoc123321/nguyentuanngoc-c4e-gen30
|
/session2/baiq.py
| 480
| 4.15625
| 4
|
weight = float(input('Your weight in kilos: ')) # <=== 79
height = float(input('Your height in meters: ')) # <=== 1.75
BMI = weight / height ** 2
BMI = round(BMI, 1)
if BMI < 16: result = 'Severely underweight.'
elif 16 < BMI <= 18.5: result = 'Underweight.'
elif 18.5 < BMI <= 25: result = 'Normal.'
elif 25 < BMI <= 30: result = 'Overweight.'
else: result = 'obese.'
print('Your BMI is', BMI, end = ', ')
print('that is', result) # ===> Your BMI is 25.8, that is overweight.
| true
|
7601d4e5c01fe1e0f377ae459465a4cb0a4f3edf
|
sam505/Median-of-3-integers
|
/Median.py
| 1,423
| 4.34375
| 4
|
# Obtains the median of three integers that the user inputs
def median():
Num_one = input ("Enter your first integer: ")
Num_two = input ("Enter your second integer: ")
Num_three = input("Enter the third integer: ")
if (int (Num_one) < int (Num_two) and int (Num_one) > int (Num_three)):
print ("The Median of the numbers is: " +Num_one)
elif (int (Num_one) > int (Num_two) and int (Num_one) < int(Num_three)):
print("The Median of the numbers is: " + Num_one)
elif (int (Num_two) < int (Num_one) and int (Num_two) > int (Num_three)):
print ("The Median of the numbers is: " +Num_two)
elif (int (Num_two) > int (Num_one) and int (Num_two) < int (Num_three)):
print("The Median of the numbers is: " + Num_two)
elif (int (Num_three) < int (Num_two) and int(Num_three) > int(Num_one)):
print("The Median of the numbers is: " + Num_three)
elif (int (Num_three) > int (Num_two) and int (Num_three) < int (Num_one)):
print("The Median of the numbers is: " + Num_three)
else:
print("Invalid")
# Using an array and sort function the program automatically spits out the median of the numbers
num = [0, 17, 3]
num[0] = input("Enter the first number: ")
num[1] = input("Enter the second number: ")
num[2] = input("Enter the third number: ")
print(num)
num.sort()
print(num)
print("The Median of the numbers is: " +num [1])
median()
| false
|
d63f3014189730c8afbe7f91add852ef729e22f0
|
inwk6312fall2019/dss-Tarang97
|
/Chapter12-Tuples/Ex12.2.py
| 1,579
| 4.21875
| 4
|
fin = open('words.txt')
# is_anagram() will take a single text from 'words.txt', sorts it and lower the cases and
# append the original word in the list which will be the default value of sorted_dict() values;
# but, the sorted_word will be in sorted_dict() dictionary along with its value.
def is_anagram(text):
sorted_dict = dict()
for line in text:
original_word = line.strip()
sorting_word = ''.join(sorted(list(original_word.lower())))
sorted_word = sorting_word
sorted_dict.setdefault(sorted_word, []).append(original_word)
anagrams = []
# This for loop will take key and value from sorted_dict() using dict.items().
# the length of no. of words spelled with those letters will be counted and will be stored in 'l'.
# If length > 1, then (count of words formed, key(original word) , value (The words created with letters))
# will append in anagrams[] list.
for k,v in sorted_dict.items():
l = len(v)
if l > 1:
anagrams.append((l,k,v))
return anagrams
def longest_list_anagrams(text):
anagrams = is_anagram(text)
longest_list_anagrams = []
for l,k,v in reversed(sorted(anagrams)):
longest_list_anagrams.append((l,k,v))
return longest_list_anagrams
longest_list_anagrams = longest_list_anagrams(fin)
print(longest_list_anagrams[:5])
# longest_list_anagrams() will take the anagrams from is_anagram() and gets the anagrams[] list
# then it will get reversed and sorted and then it will append in longest_list_anagrams[].
| true
|
c65858019b12bc00cc9733a9fa2de5fd5dda8d14
|
asadali08/asadali08
|
/Dictionaries.py
| 1,662
| 4.375
| 4
|
# Chapter 9. Dictionaries
# Dictionary is like a set of items with any label without any organization
purse = dict()# Right now, purse is an empty variable of dictionary category
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
print(purse['candy'])
purse['money'] = purse['money'] + 8
print(purse)
lst = list()
lst.append(21)
lst.append(3)
print(lst)
print(lst[1])
abc = dict()
abc['age'] = 21
abc['course'] = 146
print(abc)
abc['age'] = 26
print(abc)
# You can make empty dictionary using curly brackets/braces
print('ccc' in abc)
# When we see a new entry, we need to add that new entry in a dictionary, we just simply add 1 in the dictionary under that entry
counts = dict()
names = ['ali', 'asad','ashraf','ali','asad']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print(counts)
if name in counts:
x = counts[name]
else:
counts.get(name, 0)
print(counts)
# Dictionary and Files
counts = dict()
print('Enter a line of text: ')
line = input('')
words = line.split()
print('Words:',words)
print('Counting.........')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts',counts)
# The example above shows how many words are there in a sentence and how many times each word has been repeated in a sentence
length = {'ali': 1, 'andrew': 20, 'jayaram': 32}
for key in length:
print(key, length[key])
print(length.keys())
print(length.values())
for abc,ghi in length.items():
print(abc,ghi)
stuff = dict()
print(stuff.get('candy', -1))
| true
|
f8327a56682bd0b9e4057defb9b016fd0b56afdd
|
karagdon/pypy
|
/48.py
| 671
| 4.1875
| 4
|
# lexicon = allwoed owrds list
stuff = raw_input('> ')
words = stuff.split()
print "A TUPLE IS SIMPLY A LIST YOU CANT MODIFY"
# lexicon tuples
first_word = ('verb', 'go')
second_word = ('direction', 'north')
third_word = ('direction', 'west')
sentence = [first_word, second_word, third_word]
def convert_numbers(s):
try:
return int(s):
except ValueError:
return None
print """
Create one small part of the test I give you \n
Make sure it runs and fails so you know a test is actually confirming a feature works. \n
Go to your source file lexicon.py and write the code that makes this test pass \n
Repeat until you have implemented everything in the test
"""
| true
|
80a5137b9ab2d2ec77805ef71c2513d8fcdf81a0
|
karagdon/pypy
|
/Python_codeAcademy/binary_rep.py
| 1,384
| 4.625
| 5
|
#bitwise represention
#Base 2:
print bin(1)
#base8
print hex(7)
#base 16
print oct(11)
#BITWISE OPERATORS#
# AND FUNCTION, A&B
# 0b1110
# 0b0101
# 0b0100
print "AND FUNCTION, A&B"
print "======================\n"
print "bin(0b1110 & 0b101)"
print "= ",bin(0b1110&0b101)
# THIS OR THAT, A|B
#The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1.
# 0b1110
# 0b0101
# ======
# 0b1111
print "OR FUNCTION, A|B"
print "======================\n"
print "bin(0b1110|0b0101)"
print "= ",bin(0b1110|0b0101)
# XOR FUNCTION, A^B
#XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both.
# 1 1 1 0
# 0 1 0 1
# = = = =
# 1 0 1 1 thus 0b1011 should appear
print "XOR FUNCTION"
print "======================\n"
print "bin(0b1110 ^ 0b101)"
print "=", bin(0b1110 ^ 0b101)
# XOR FUNCTION, ~A
#The bitwise NOT operator (~) just flips all of the bits in a single number.This is equivalent to adding one to the number and then making it negative.
print "NOT FUNCTION, ~A"
print "======================\n"
print "~1 =", ~1
print "~2 =", ~2
print "~3 =", ~3
print "~42 =", ~42
print "~123 =", ~123
| true
|
729099b198e045ce3cfe0904f325b62ce3e3dc5e
|
karagdon/pypy
|
/diveintopython/707.py
| 579
| 4.28125
| 4
|
### Regex Summary
# ^ matches
# $ matches the end of a string
# \b matches a word boundary
# \d matches any numeric digit
# \D matches any non-numeric character
# x? matches an optional x character (in other words, it matches an x zero or one times)
# x* matches x zero or more times
# x+ matches x one or more times
# x{n,m} matches an x character atleast n times, but not more than m times
# (a|b|c) matches either a or b or c
# (x) in general is a remembered group. You can get the value of what matched by using the groups() method of the object returned by re.search
| true
|
bd00c3566cf764ca82bba1a4af1090581a84d50f
|
f1uk3r/Daily-Programmer
|
/Problem-3/dp3-caeser-cipher.py
| 715
| 4.1875
| 4
|
def translateMessage(do, message, key):
if do == "d":
key = -key
transMessage = ""
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
if symbol.islower():
if num > ord("z"):
num -= 26
elif num < ord("a"):
num += 26
transMessage += chr(num)
else:
transMessage += symbol
return transMessage
do = input("Do you want to (e)ncrypt or (d)ecrypt? ")
message = input("Type your message : ")
key = int(input("Enter a key number between -26 and 26: "))
translated = translateMessage(do, message, key)
print("Your translated message is : " + translated)
| true
|
e2b0a7d7bc76ef3739eace98f62081e78df24b67
|
f1uk3r/Daily-Programmer
|
/Problem-11/Easy/tell-day-from-date.py
| 540
| 4.5
| 4
|
# python 3
# tell-day-from-date.py #give arguments for date returns day of week
# The program should take three arguments. The first will be a day,
# the second will be month, and the third will be year. Then,
# your program should compute the day of the week that date will fall on.
import datetime
import calendar
import sys
def get_day(day, month, year):
date = datetime.datetime(int(year), int(month), int(day))
print(calendar.day_name[date.weekday()])
if __name__ == '__main__':
get_day(sys.argv[1], sys.argv[2], sys.argv[3])
| true
|
c452668b786727a3438a06c22230e08c3eb01914
|
Eunbae-kim/python
|
/basic9.py
| 850
| 4.1875
| 4
|
# 파이썬
# 튜플 (Tuple) : 리스트(list)와 비슷하지마, 다만 한번 설정되면 변경 불가
# 튜플은 변경 불과
tuple = (1, 2, 3)
print(tuple ," : tuple type ", type(tuple))
# 리스트는 하나의 원소로 취급가능하기 때문에 리스트를 튜플의 각 원소로 사용가능
list1 = [1,3,5]
list2 = [2,4,6]
tuple2 = (list1, list2)
print(tuple2) #2개의 리스트가 각각 원소로 들어감
print(tuple2[0][1])
#하지만, 튜플은 변경불가능 하기 떄문에 tuple[0] = 1하면 오류
#cf) tuple2[0][1] = 3는 가능. 이건 리스트를 바꾸는 거니까
# 리스트와 특성이 비슷하기 때문에
# 인덱싱, 슬라이싱 가능
tuple3 = (0,1,2,3,4,5,6,7,8,9)
print(tuple3[0:5])
print(tuple3[-1])
print(tuple3[:-1])
print(tuple3[0:-1:2])
print(tuple3[0:3]*2) #[0,3) 까지 2번 반복 출력
| false
|
d2417f9b2a06ca9447d554ecc34998fac1f1d59d
|
yossef21-meet/meet2019y1lab1
|
/turtleLab1-Yossi.py
| 1,457
| 4.5
| 4
|
import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
#E
turtle.penup()
turtle.forward(50)
turtle.pendown()
turtle.forward(100)
turtle.backward(100)
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.backward(100)
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
#Second E
turtle.penup()
turtle.right(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(50)
turtle.pendown()
turtle.forward(100)
turtle.backward(100)
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.backward(100)
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
#T
turtle.penup()
turtle.forward(50)
turtle.pendown()
turtle.forward(150)
turtle.backward(75)
turtle.right(90)
turtle.forward(200)
# ...and end it before the next line.
turtle.mainloop()
# turtle.mainloop() tells the turtle to do all
# the turtle commands above it and paint it on the screen.
# It always has to be the last line of code!
| false
|
8d888e53b71da82ae029c0ffc4563edc84b8283d
|
EdwardMoseley/HackerRank
|
/Python/INTRO Find The Second Largest Number.py
| 661
| 4.15625
| 4
|
#!/bin/python3
import sys
"""
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
Find the second largest number in a list
"""
#Pull the first integer-- we don't need it
junk = input()
def secondLargest(arg):
dat = []
for line in arg:
dat.append(line)
dat = dat[0].split(' ')
i = 0
while i < len(dat):
dat[i] = int(dat[i])
i += 1
dat.sort()
#Find the first integer that is not the maximum integer while decrementing
for j in reversed(range(len(dat))):
if dat[j] is not max(dat):
return dat[j]
print(secondLargest(sys.stdin))
| true
|
bbe8b6100246aa2f58fca457929827a0897e9be5
|
arickels11/Module4Topic3
|
/topic_3_main/main_calc.py
| 1,637
| 4.15625
| 4
|
"""CIS 189
Author: Alex Rickels
Module 4 Topic 3 Assignment"""
# You may apply one $5 or $10 cash off per order.
# The second is percent discount coupons for 10%, 15%, or 20% off.
# If you have cash-off coupons, those must be applied first, then apply the percent discount coupons on the pre-tax
# Then you add tax at 6% and shipping according to these guidelines:
#
# up to $10 dollars, shipping is $5.95
# $10 and up to $30 dollars, shipping is $7.95
# $30 and up to $50 dollars, shipping is $11.95
# Shipping is free for $50 and over
def calculate_order(price, cash_coupon, percent_coupon):
if price < 10.00:
if (price - cash_coupon)*(1 - (percent_coupon / 100)) < 0:
return 5.95 # if coupons get price to under zero, customer only pays shipping costs
else:
return round((((price - cash_coupon)*(1 - (percent_coupon / 100)))*1.06) + 5.95, 2)
elif 10.00 <= price < 30.00:
return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 7.95, 2)
elif 30.00 <= price < 50.00:
return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 11.95, 2)
elif price >= 50.00:
return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06), 2)
else:
print("Please correct your input")
if __name__ == '__main__':
initial_price = float(input("What is the price?"))
cash = float(input("What is the cash discount, $5 or $10?"))
percent = float(input("What is the percent discount, 10%, 15%, or 20%?"))
final_price = float(calculate_order(initial_price, cash, percent))
print(final_price)
| true
|
27006f8290968a5d89a8d0d25355538212718075
|
Manny-Ventura/FFC-Beginner-Python-Projects
|
/madlibs.py
| 1,733
| 4.1875
| 4
|
# string concatenation (akka how to put strings together)
# # suppose we want to create a string that says "subscribe to ____ "
# youtuber = "Manny Ventura" # some string variable
# # a few ways...
# print("Subscribe to " + youtuber)
# print("Subscribe to {}".format(youtuber))
# print(f"subscribe to {youtuber}")
adj = input("Adjective: ")
verb1 = input("Verb: ")
verb2 = input("Verb: ")
famous_person = input("Famous Person: ")
noun1 = input("Noun: ")
noun2 = input("Noun: ")
place = input("Make a name for a place: ")
number = input("Number : ")
madlib = f"My time on earth is absolutely {adj}! All i want to do is {verb1} \n\
and {verb2} because I miss my home planet. Back home in the land of {place}, \n\
we had {noun1}'s running around all the time. Not only that, but some {noun2}'s \n\
even got along with the them! It was a crazy time, and I want to go back... \n\
I just... I miss my kids man. \n\
I wasn't there for them like I should have. Heck, LOOK WHERE I AM NOW. \n\
Its a scary feeling not being sure if I ever will be a good dad man, or ever was. \n\
Its not like wanting to be is enough. And its not fair to try and explain \n\
The hardships I go through to be there for them. There kids you know? \n\
Im supposed to not make it seem so scary, but what's scary is that \n\
They probably learned that life is scary and sometimes those that \n\
want to be there for them wont. Tough as nails, but it breaks my heart, \n\
cause its not fair to them. They should not have to tough BECAUSE of me. \n\
I hope at least they know I do love them, and that I am just a bad father \n\
I owe them at least that. Love all {number} of ya, \n\
\n\
Pops"
print(madlib)
| true
|
de25e31fa817bc6347566c021edc50f1868de959
|
gohjunyi/RegEx
|
/google_ex.py
| 1,167
| 4.125
| 4
|
import re
string = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', string)
# If-statement after search() tests if it succeeded
if match:
print('found', match.group()) # 'found word:cat')
else:
print('did not find')
# i+ = one or more i's, as many as possible.
match = re.search(r'pi+', 'piiig') # found, match.group() == "piii"
# Finds the first/leftmost solution, and within it drives the +
# as far as possible (aka 'leftmost and largest').
# In this example, note that it does not get to the second set of i's.
match = re.search(r'i+', 'piigiiii') # found, match.group() == "ii"
# \s* = zero or more whitespace chars
# Here look for 3 digits, possibly separated by whitespace.
match = re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx') # found, match.group() == "1 2 3"
match = re.search(r'\d\s*\d\s*\d', 'xx12 3xx') # found, match.group() == "12 3"
match = re.search(r'\d\s*\d\s*\d', 'xx123xx') # found, match.group() == "123"
# ^ = matches the start of string, so this fails:
match = re.search(r'^b\w+', 'foobar') # not found, match == None
# but without the ^ it succeeds:
match = re.search(r'b\w+', 'foobar') # found, match.group() == "bar"
| true
|
491454a81d8ee0e33fa142d93260c72e23345631
|
ammalik221/Python-Data-Structures
|
/Trees/Depth_first_traversal.py
| 2,866
| 4.25
| 4
|
"""
Depth First Search implementation on a binary Tree in Python 3.0
Working -
recursion calls associated with printing the tree are in the following order -
- print(1, "")
|- traversal = "1"
|- print(2, "1")
| |- traversal = "12"
| |- print(4, "12")
| | |- traversal = "124"
| | |- print(None, "124")
| | |- print(None, "124")
| |- print(5, "124")
| | |- traversal = "1245"
| | |- print(None, "1245")
| | |- print(None, "1245")
|- print(3, "1245")
| |- traversal = "12453"
| |- print(None, "12453")
| |- print(None, "12453")
recursion calls associated in searching are in the following order -
- search(1, 5) ----------------- True
|- search(2,5) ----------------- True
| |- search(4, 5) ----------------- False
| | |- search(None, 5) ----------------- False
| | |- search(None, 5) ----------------- False
| |- search(5,5) ----------------- True
|- search(3, 5) ----------------- False
| |-search(None, 5) ----------------- False
| |- search(None, 5) ----------------- False
"""
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_binary_tree(self):
return self.preorder_print(self.root, "")
def preorder_print(self, start, traversal):
if start:
traversal += str(start.value)
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def search_element(self, element):
return self.preorder_search(self.root, element)
def preorder_search(self, start, element):
if start:
if start.value == element:
return True
else:
return self.preorder_search(start.left, element) or self.preorder_search(start.right, element)
else:
return False
if __name__ == "__main__":
# test case
# add nodes to the tree
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
# 1
# / \
# 2 3
# / \
# 4 5
# output is True
print(tree.search(4))
# output is False
print(tree.search(6))
# output is 12453
print(tree.print_binary_tree())
| false
|
f01d7fab6569e318399eee144b7310d39433d061
|
ammalik221/Python-Data-Structures
|
/Collections/Queues_using_queue_module.py
| 411
| 4.1875
| 4
|
"""
Queues Implementation in Python 3.0 using deque module.
For implementations from scratch, check out the other files in this repository.
"""
from collections import deque
# test cases
# make a deque
q = deque()
# add elements
q.append(20)
q.append(30)
q.append(40)
# output is - 10 20 30 40
print(q)
# remove elements from queue
# output is 10 and 20 respectively
print(q.popleft())
print(q.popleft())
| true
|
73c2bcf27da231afe7d9af4425683c006799e7a9
|
razzanamani/pythonCalculator
|
/calculator.py
| 1,515
| 4.375
| 4
|
#!usr/bin/python
#Interpreter: Python3
#Program to create a functioning calculator
def welcome():
print('Welcome to the Calculator.')
def again():
again_input = input('''
Do you want to calculate again?
Press Y for YES and N for NO
''')
# if user types Y, run the calculate() function
if again_input == 'Y':
calculate()
#if user types N, say bye
elif again_input == 'N':
print('Thank You for using Calculator')
#if user types another key, run the same funtion again
else:
again()
def calculate():
operation = input('''
Please type the math operation you would like to complete:
+ for addition
- for substraction
* for multiplication
/ for division
% for modulo
''')
number_1 = int(input('Enter the first number :'))
number_2 = int(input('Enter the second number :'))
#Addition
if operation == '+':
print('{} + {} = '.format(number_1,number_2))
print(number_1 + number_2)
#Substraction
elif operation == '-':
print('{} - {} = '.format(number_1,number_2))
print(number_1 - number_2)
#Multiplication
elif operation == '*':
print('{} * {} ='.format(number_1,number_2))
print(number_1 * number_2)
#Division
elif operation == '/':
print('{} / {} = '.format(number_1,number_2))
print(number_1/number_2)
#else operation
else:
print('You have not typed a valid operator,please run the program again.')
#calling the again() function to repeat
again()
#calling the welcome funtion
welcome()
#calling the calculator function outside the function
calculate()
| true
|
5938614ce9d3181ed59c2e56e4df3adaa17ab91b
|
williamsyb/mycookbook
|
/algorithms/BAT-algorithms/Math/判断一个数是否为两个数的平方和.py
| 735
| 4.1875
| 4
|
"""
题目:
判断一个数是否是两个数的平方和
示例:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
思路: 双指针
本题是要判断一个数是否等于两个数的平方和 <=等价=> 在自然数数组中,是否存在两个数的平方和是否等于一个数。
所以本题的思路与 “/数组/Two sum - 有序数组”基本一致。
"""
def judge_square_sum(c):
start = 0
end = int(c ** 0.5)
while start <= end:
temp = start ** 2 + end ** 2
if temp == c:
return True
elif temp < c:
start += 1
else:
end -= 1
return False
if __name__ == '__main__':
print(judge_square_sum(3))
| false
|
ee1e7bff3095782f4886eeefc0558543c091ddc6
|
williamsyb/mycookbook
|
/thread_prac/different_way_kill_thread/de04.py
| 1,153
| 4.59375
| 5
|
# Python program killing
# a thread using multiprocessing
# module
"""
Though the interface of the two modules is similar, the two modules have very different implementations.
All the threads share global variables, whereas processes are completely separate from each other.
Hence, killing processes is much safer as compared to killing threads. The Process class is provided a method,
terminate(), to kill a process. Now, getting back to the initial problem. Suppose in the above code,
we want to kill all the processes after 0.03s have passed.
This functionality is achieved using the multiprocessing module in the following code.
"""
import multiprocessing
import time
def func(number):
for i in range(1, 10):
time.sleep(0.01)
print('Processing ' + str(number) + ': prints ' + str(number * i))
# list of all processes, so that they can be killed afterwards
all_processes = []
for i in range(0, 3):
process = multiprocessing.Process(target=func, args=(i,))
process.start()
all_processes.append(process)
# kill all processes after 0.03s
time.sleep(0.03)
for process in all_processes:
process.terminate()
| true
|
353a3606af9aa9b5c5065edaa2e35d88f9e8ec5f
|
Imsurajkr/Cod001
|
/challenge2.py
| 662
| 4.1875
| 4
|
#!/usr/bin/python3
import random
highestNumber = 10
answer = random.randint(1, highestNumber)
print("Enter the number betweeen 1 and {}".format(highestNumber))
guess = 0 #initialize to any number outside of the range
while guess != answer:
guess = int(input())
if guess > answer:
print("please Select Lower Number")
# guess = int(input())
elif guess < answer:
print("Please Select Higher Number ")
# guess = int(input())
elif guess == 0:
print("Thanks For playing")
break
else:
print("You guessed it Great")
break
else:
print("Great You successfully Guessed on 1st attemp")
| true
|
6ca787eac5185c966f539079a8d2b890d9dc6447
|
OldPanda/The-Analysis-of-Algorithms-Code
|
/Chapter_2/2.4.py
| 897
| 4.15625
| 4
|
"""
Random Hashing:
Data structure: a key array X with entries x_i for 0 <= i <= N-1 and a corresponding record array R.
Initial conditions: the number of entries, k, is zero and each key location, x_i, contains the value empty, a special value that is not the value of any key.
Input: a query, q.
Output: a location i such that q = x_i if there is such an i (i.e., q is in the table) or i such that x_i contains empty and the hash algorithm would look in location x_i when looking for q.
"""
import numpy as np
X = np.random.randint(10, size=10)
R = np.random.randint(100, size=10)
# A simple function
def f(h, q):
return (h*2 + q)%10
def random_hashing(q):
h = 0
while True:
h = h + 1
i = f(h, q)
if X[i] == 0:
return False
elif X[i] == q:
return True
if __name__ == "__main__":
print X
print "Query 5: ", random_hashing(5)
print "Query 6: ", random_hashing(6)
| true
|
2ca5b9fd677edf64a50c6687803c91b721bee140
|
basakmugdha/Python-Workout
|
/1. Numeric Types/Excercise 1 (Number Guessing Game)/Ex1c_word_GG.py
| 848
| 4.375
| 4
|
#Excercise 1 beyond 3: Word Guessing Game
from random_word import RandomWords
def guessing_game():
'''returns a random integer between 1 and 100'''
r = RandomWords()
return r.get_random_word()
if __name__ == '__main__':
print('Hmmmm.... let me pick a word')
word = guessing_game()
guess = input(f"Guess the word ({len(word)} characters) : ")
# only 6 guesses so the game is less tedious
#the for loop can be replaced with 'while True:' for the original trap style game
for _ in range(5):
if guess>word:
print("You're far ahead in the dictionary")
elif guess == word:
print("YOU GUESSED IT!")
break
else:
print("You're far behind in the dictionary")
word = input('Guess again :')
print(word+' is the word!')
| true
|
942d67e9bbad4dc5a890de12ef0317b6af4f571f
|
danebista/Python
|
/suzan/python3.py
| 2,143
| 4.1875
| 4
|
#!/usr/bin/env python
# coding: utf-8
# Print formatting
# In[1]:
print ("hurry makes a bad curry")
# In[3]:
print("{1} makes a bad {0}".format("curry","hurry"))
# In[7]:
print("The {e} rotates {a} a {s}".format(e="Earth",a="around",s="Sun"))
# In[8]:
result=9/5
print(result)
# In[9]:
result=100/3
print(result)
# In[82]:
print("the result is {r:1.4f}".format(r=result))
# In[13]:
celsius=((132-32)*5)/9
# In[14]:
print(celsius)
# boolean
# In[17]:
a=True
# In[18]:
a=False
# Operators
# In[20]:
5>=6
# In[21]:
not 5>=6
# looping
#
# In[23]:
a="hello";
if a.lower()=="hello":
print(a)
elif a.lower()=="hello":
print(a)
else:
print(a)
# In[24]:
a="hello"
for variable in a:
print(variable)
# In[28]:
a=["hello","world"]
for variable in a:
print (variable)
# In[29]:
for i in range (0,10,2):
print(i)
# In[30]:
for i in range(0,10):
print(i%2)
# In[31]:
abc=[(0,1),(2,3),(4,5),(5,6),(6,7)]
for i in abc:
print(i)
# In[33]:
abc=[(0,1),(2,3),(4,5),(5,6),(6,7)]
for first_number,second_number in abc:
print(second_number)
# In[34]:
abc=[(0,1),(2,3),(4,5),(5,6),(6,7)]
for first_number,second_number in abc:
print(first_number)
# In[35]:
abc="hello"
for i in enumerate(abc):
print(i)
# In[36]:
abc="hello"
for index,value in enumerate(abc):
print(value)
# In[39]:
abc="hello"
for index, value in enumerate(abc):
print(index)
# In[40]:
a=[1,2,3,4,5]
b=[6,7,8,9,10]
for i in zip(a,b):
print(i)
# In[67]:
a=[1,2,3,4,5]
b=[6,7,8,9,10]
c=[11,12,13,14,15]
for i in zip(a,b,c):
print(i)
# List Comprehension
# In[66]:
a="hello"
b=[ ]
for i in a:
b.append(i)
print(b)
# In[68]:
m="hello"
n=[x for x in m]
print (n)
# In[81]:
a=[]
b=[x for x in range (0,10,2)]
print(b)
# In[83]:
a="hello"
b=[x for x in enumerate(a)]
print(b)
# In[109]:
a="hello"
b=[y for (x,y) in enumerate(a) if x%2 == 0]
print(b)
# While loop
# In[111]:
x=0
while x<=5:
print(x)
x=x+1
else:
print(x)
# In[112]:
x=0
while x<=5:
print(x)
x=x+1
# In[ ]:
| false
|
c26c3fa52692454bd47cfab92253715ed461f4f2
|
DiegoRmsR/holbertonschool-higher_level_programming
|
/0x03-python-data_structures/3-print_reversed_list_integer.py
| 223
| 4.28125
| 4
|
#!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if not my_list:
pass
else:
for list_reverse in reversed(my_list):
str = "{:d}"
print(str.format(list_reverse))
| true
|
0254ed479c00b3f5140df3546c06612dca233557
|
Andriy63/-
|
/lesson 4-4.py
| 686
| 4.15625
| 4
|
'''
Представлен список чисел. Определить элементы списка, не имеющие повторений.
Сформировать итоговый массив чисел, соответствующих требованию.
Элементы вывести в порядке их следования в исходном списке.
Для выполнения задания обязательно использовать генератор.'''
from itertools import permutations
from itertools import repeat
from itertools import combinations
my_list = [1, 2, 2, 3, 4, 1, 2]
new = [el for el in my_list if my_list.count(el)==1]
print(new)
| false
|
440fb62ef8a3a4144b3082ca38c478fc78357c6b
|
mohitciet/CorePython
|
/LearnPython/PythonBasics/Dictionary.py
| 2,077
| 4.3125
| 4
|
"""DICTIONARY"""
dictionary={'key1' : 'india','key2' : 'USA'}
#Access Elements from Dictionary
print(dictionary['key1'])
print("===================")
#Adding Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA'}
dictionary['key3']='Pakistan'
print(dictionary)
print("===================")
#Modify Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary['key3']='Aus'
print(dictionary)
print("===================")
#Delete Elements from Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
del dictionary['key3']
print(dictionary)
print("===================")
#Looping to Iterate the Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
for x in dictionary:
print(x +" : "+dictionary[x])
print("===================")
#Length of a Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(len(dictionary))
print("===================")
#Equallity Test in Dictionary
dictionary1={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary2={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictionary3={'key1' : 'india','key2' : 'USA'}
print(dictionary1==dictionary2)
print(dictionary1==dictionary3)
print("===================")
#Functions in Dictionary
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(dictionary.popitem()) #Returns random element and removed from Dictionary
print(dictionary)
print("===================")
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
print(dictionary.keys()) #Returns all keys as tuple Format
print("<><><><>")
print(dictionary.values()) #Returns all values as tuple Format
print("<><><><>")
print(dictionary.get('key1')) #Returns value on the basis of key,if key invalid it returns None
print("<><><><>")
print(dictionary.pop('key5')) #Delete value on the basis of key,if key invalid it throws exception
print("<><><><>")
print(dictionary.clear()) #Delete Everything from Dictionary
print(dictionary)
print("<><><><>")
print("===================")
| false
|
8ba63fdd070ef490570285c17d8669b8d8ffb5b0
|
lukelu389/programming-class
|
/python_demo_programs/2020/prime_number.py
| 273
| 4.375
| 4
|
# write a python program to check if a number is prime or not
number = int(input('enter a number:'))
n = 1
counter = 0
while n <= number:
if number % n == 0:
counter += 1
n += 1
if counter > 2:
print('not prime number')
else:
print('prime number')
| true
|
3404c6cc7af2350bf12592921226a9f4a87da618
|
lukelu389/programming-class
|
/python_demo_programs/2021/example_20210319.py
| 1,529
| 4.1875
| 4
|
# s = 'abcdefgh'
# print(s[0:2])
# print(s[:2]) # implicitly start at 0
# print(s[3:]) # implicitly end at the end
#
# # slice from index 4 to the end
# print(s[4:])
# to achieve the conditional, need to use if keyword
# a = 6
# b = 5
# if b > a:
# print('inside if statement')
# print('b is bigger than a')
# # exit the if
# print('program finish')
# a = a + 1
# input = -9
# if input > 0:
# print('positive')
# else:
# print('not positive')
# a = 2
# b = 3
# using if, else statement, print the bigger number
# if a > b:
# print(a)
# else:
# print(b)
# a = 3
# b = 2
# # given two variables, print the positive variables
# if a > 0
# print(a)
#
# if b > 0:
# print(b)
# given a variable, print the variable if it is the even number
# hint: use % operator to find the even or odd
# a = 3
# if a % 2 == 0:
# print("a is an even number")
# else:
# print("a is an odd number")
# number = 0
# if number > 0:
# print("positive")
# elif number < 0:
# print("negative")
# else:
# print("zero")
# because input() takes all value as string, need convert to int
# by using int()
# a = int(input("enter the value for a:"))
# b = int(input("enter the value for b:"))
#
# if a > b:
# print("a is bigger")
# elif a < b:
# print("b is bigger")
# else:
# print("a is equal to b")
a = int(input("enter a value for a: "))
if a > 0:
print("a is positive")
if a % 2 == 0:
print("a is even")
else:
print("a is odd")
else:
print("a is negative")
| true
|
1d4bac21899ddd993ad41cdf80a0c2ad350b8104
|
lukelu389/programming-class
|
/python_demo_programs/2021/example_20210815.py
| 1,644
| 4.1875
| 4
|
# class Person:
# def __init__(self, name):
# self.name = name
# def method1(self):
# return 'hello'
# p1 = Person('jerry')
# print(p1.name)
# Person.method1()
# class = variables + methods
# variable: static variable vs instance variable
# method: static method vs instance method
# class is customized data structure
# class is the blueprint of object, we use class to create object
class Person:
# constructor
def __init__(self, name, age):
# instance variable is created in the constructor
self.name = name
self.age = age
# instance method
def say_hi(self):
return 'hi'
p1 = Person('jerry', 10)
p2 = Person('tom', 20)
print(p1.name)
print(p1.age)
print(p2.name)
print(p2.age)
p1.say_hi()
p2.say_hi()
class Student:
def __init__(self, student_name, student_id):
self.student_name = student_name
self.student_id = student_id
def get_info(self):
return self.student_name + ":" + str(self.student_id)
def __str__(self):
return self.student_name
peter = Student('peter', 1)
print(peter.get_info())
print(peter)
class Grade:
def __init__(self):
self.grades = []
'''
Give two dictionaries, create thrid dictionary with the unique key and value from both dictionaries
d1 = {'a': 1, 'b': 3, 'c': 2}
d2 = {'a': 2, 'b': 2, 'd': 3}
d3 = {'c': 2, 'd': 3}
'''
d1 = {'a': 1, 'b': 3, 'c': 2}
d2 = {'a': 2, 'b': 2, 'd': 3}
d3 = {}
for key1, value1 in d1.items():
if key1 not in d2:
d3[key1] = value1
for key2, value2 in d2.items():
if key2 not in d1:
d3[key2] = value2
print(d3)
| true
|
6d7f89a6f38bcb3765ff3e6f5a954bfed6b27f3c
|
lukelu389/programming-class
|
/python_demo_programs/2020/factorial.py
| 231
| 4.15625
| 4
|
# use a loop to calculate n*(n-1)*(n-2)*(n-3)*...2*1,
# and return the result
def factorial(n):
result = 1
while n > 0:
result = result * n
n -= 1
return result
print(factorial(5))
print(factorial(3))
| true
|
ea53f0ecbeee4c3c1a35d5a2d2569b8a70cf4ea2
|
lukelu389/programming-class
|
/python_demo_programs/2020/example_20201018.py
| 1,389
| 4.125
| 4
|
# homework
# write a python function takes two lists as input, check if one list contains another list
# [1, 2, 3] [1, 2] -> true
# [1] [1, 2, 3] -> true
# [1, 2] [1, 3] -> false
def contain(list1, list2):
# loop through list1 check if each element in list1 is also in list2
list2_contains_list1 = True
for i in list1:
if i not in list2:
list2_contains_list1 = False
# loop through list2 check if each element in list2 is also in list1
list1_contains_list2 = True
for i in list2:
if i not in list1:
list1_contains_list2 = False
return list1_contains_list2 or list2_contains_list1
# print(contains([1, 2, 3], [1, 2]))
# print(contains([1], [1, 2, 3]))
# print(contains([1, 2], [1, 3]))
# l = [[1, 2], 3]
# print(1 in l)
# print([1, 2] in l)
# write a python function that takes a list and a int, check if list contains two values that sum is the input int
# case1 [1, 2, 3], 4 -> True
# case2 [1, 2, 3], 10 -> False
# case3 [1, 3, 5], 4 -> True
# case4 [4, 2, 1], 5 ->
def pair_sum(list, sum):
i = 0
while i < len(list):
j = i + 1
while j < len(list):
if list[i] + list[j] == sum:
return True
j += 1
i += 1
return False
# write a python function that takes a list and a int, check if list contains two values that diff is the input int
| true
|
9e63c534debc5b8bb2adcfd7493ce18e8acd1bf7
|
lukelu389/programming-class
|
/python_demo_programs/2020/example_20201025.py
| 1,532
| 4.25
| 4
|
# # write a python function that takes a list and a int, check if list contains any two values that diff of the two values
# # is the input int
# # [1, 2, 3] 1 -> true
# # [1, 2, 3] 4 -> false
#
# def find_diff(list, target):
# for i in list:
# for j in list:
# if j - i == target:
# return True
#
# return False
#
#
# l = ["1", "2", "3"]
# print(l)
# l[0] = 100
# print(l)
#
# s = 'abc'
# # question: what's the similar part between list and string
# # 1. contains multiple items
# # [1, 2, 3] '123'
# # 2. index
# # 3. loop
# # 4. len()
# # different: list -> mutable(changeable), string -> immutable(unchangeable)
#
# list = [1, 2, 3]
#
# string = 'abc'
# # string[0] = 'w'
#
# string_new = string + 'w' # this does not change the string, it creates a new string
# print(string)
# print(string_new)
#
# print(list.count(3))
# a = [1, 2, 3]
b = 1, 2, 3
# print(type(a))
print(type(b))
x, y = b
# unpack
print(x)
print(y)
# print(z)
# # write a function takes a list and tuple, check if all values in tuple also in the list
# def contains(l, t):
# for i in t:
# if i not in l:
# return False
# return True
#
# # write a function that takes a tuple as input, return a list contains the same value as tuple
# def tuple_to_list(tuple):
# list = []
# for i in tuple:
# list.append(i)
# return list
# write a function that takes a list and a value, delete all the values from list which is equal to the given value
# [1, 2, 2, 3] 2 -> [1, 3]
| true
|
12720f4c953a952aaebf3737a248c5e61c947773
|
lukelu389/programming-class
|
/python_demo_programs/2020/nested_conditionals.py
| 1,370
| 4.15625
| 4
|
# a = 3
# b = 20
# c = 90
#
# # method 1
# if a > b:
# # compare a and c
# if a > c:
# print('a is the biggest')
# else:
# print('c is the biggest')
# else:
# # a is smaller than b, compare b and c
# if b > c:
# print('b is the biggest')
# else:
# print('c is the biggest')
#
# # method 2
# # and/or/not
# a = int(input('enter value a:'))
# b = int(input('enter value b:'))
# c = int(input('enter value c:'))
#
# if a > b and a > c:
# print('a is the biggest')
# elif b > a and b > c:
# print('b is the biggest')
# else:
# print('c is the biggest')
# print('Welcome come to the door choosing game')
# print('There are two door, 1 and 2, which one do you choose?')
#
# door = input('you choose:')
#
# if door == "1":
# print('There is a bear here, what do you do?')
# print('1. Run away')
# print('2. Scream at the bear')
# print('3. Give bear a cheese cake')
#
# bear = input('your choose:')
#
# if bear == "1":
# print('bear eats your legs off.')
# elif bear == "2":
# print('bear eats your face off')
# elif bear == "3":
# print('bear is happy, you are safe')
#
# elif door == "2":
# print('there is tiger.')
# a = int(input('enter a number:'))
# if a % 2 == 0:
# print(str(a) + " is even")
# else:
# print(str(a) + " is odd.")
| false
|
a0b7bbca5f8d4cbd1638a54e0e7c5d78302139f8
|
vijaykanth1729/Python-Programs-Interview-Purpose
|
/list_remove_duplicates.py
| 776
| 4.3125
| 4
|
'''
Write a program (function!) that takes a list and returns a new
list that contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and constructing a
list, and another using sets.
Go back and do Exercise 5 using sets, and write the solution for that in a
different function.
'''
original = []
def remove_duplicates(my_list):
print("Original data: ", my_list)
data = set(my_list)
original.append(data)
def using_loop(my_list):
y = []
for i in my_list:
if i not in y:
y.append(i)
print("Using loop to remove duplicates: ",y)
remove_duplicates([1,2,3,4,5,4,2])
using_loop([1,2,3,4,5,4,2])
print("Using set function to remove duplicates:", original)
| true
|
bb3c2b979426ab217b7cf3bbdadb12d4c8aa2e05
|
ThtGuyBro/Python-sample
|
/Dict.py
| 307
| 4.125
| 4
|
words = {"favorite dessert": "apple pie","never eat": "scallop","always have" : "parachute","don't have" :"accident","do this" : "fare","bug" : "flea"}
print(words['bug'])
words['parachute']= 'water'
words['oar']= 'girrafe'
del words['never eat']
for key, value in words.items():
print(key)
| true
|
a5c89600f1343b8059680634e0ca7caed0bcebe9
|
felipemlrt/begginer-python-exercises
|
/06_FuntionsI/Exercise.py
| 1,923
| 4.3125
| 4
|
#!/usr/bin/env python3
#1)
#Create a function that receives a operator ( + - * or / ), values X and Y, calculates the result and prints it.
#Crie uma função que receva um oprador ( + - * or / ), valores X e Y, e calcule o resultando apresentando este ao usuário.
#2)
#Create a function that tell if a number is odd or even.
#Crie uma função que retorne se um número é par ou ímpar.
#3)
#Create a function that receives a memory size in Bytes, converts it to Giga Bytes then prints the resulting size in GB. Example 1024MB = 1GB. Use binary not decimal.
#Crie uma funço que receba um tamanho de memória em Bytes e o converta no equivalente em Giga Bytes apresentando o resultado.
#4)
#Create a function that receives a series of prices and prints the subtotal after each one is given.
#Crie uma função que receba uma serie de preços e apresente o subtotal apos cada novo item inserido.
#5)
#Create a function that prints a given x number x times. Example: print 5, 5 times, 3, 3 times, 9, 9 times and so on.
#Crie uma função que apresente um núemro x, x vezes. Exemplo: apresentar 5, 5 vezes, 3, 3 vezes e assim por diante
#6)
#Create a function that generate a random number.
#Crie uma função que gere um numero randonico.
#7)
#Create a function that calculates the area of a circle of a given r radius.
#
#8)
#Create a function that converts a time in hours, minutes, seconds to a total in miliseconds. Tip 1h = 60m, 1m = 60s, 1s = 1000ms.
#
#9)
#Create a function that receives a list of login/password sets and compares it to another list printing those that are present in both.
#
#10)
#Create a function that counts seconds. Use a chronometer to compare with your code.
#Crie uma função que conte segundos. Use um cronometro para comparar com o seu código.
#11)
#Create a function that receives a data and a number, then calculates what day will be the date + the number given days.
#
| false
|
8320e270cc0ef7f8767336dfcb0dcf7ffe538e01
|
tocodeil/webinar-live-demos
|
/20200326-clojure/patterns/04_recursion.py
| 658
| 4.15625
| 4
|
"""
Iteration (looping) in functional languages is usually accomplished
via recursion.
Recursive functions invoke themselves,
letting an operation be repeated until it reaches the base case.
"""
import os.path
# Iterative code
def find_available_filename_iter(base):
i = 0
while os.path.exists(f"{base}_{i}"):
i += 1
return f"{base}_{i}"
print(find_available_filename_iter('hello'))
# ---
# Recursive code
def find_available_filename_rec(base, i=0):
name = f"{base}_{i}"
if not os.path.exists(name):
return name
return find_available_filename_rec(base, i + 1)
print(find_available_filename_rec('hello'))
| true
|
fc0d283efec47c1f9a4b19eeeff42ba58db258c7
|
EdmondTongyou/Rock-Paper-Scissors
|
/main.py
| 2,479
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
"""
Edmond Tongyou
CPSC 223P-01
Tues March 9 14:47:33 2021
tongyouedmond@fullerton.edu
"""
# Importing random for randint()
import random
computerScore = 0
ties = 0
userScore = 0
computerChoice = ""
userChoice = ""
# Loops until the exit condition (Q) is met otherwise keeps asking for
# one of three options (R, P, S), every loop the computer choice is
# decided via randint and then compares the user choice to the
# computer choice. If user wins, adds 1 to userScore same with computer
# win. If a tie is found adds 1 to the ties. If the inputted letter is
# not R P S or Q then the loop repeats until a valid option is inputted
while 'Q' not in userChoice:
computerChoice = random.randint(0, 2)
print ("Please input one: (R, P, S, Q) > ", end = " ")
userChoice = input()
userChoice = userChoice.upper()
if 'R' in userChoice or 'P' in userChoice or 'S' in userChoice:
if computerChoice == 0:
print("Computer chose Rock", end = '. ')
if 'R' in userChoice:
print("Call it a draw.")
ties += 1
elif 'P' in userChoice:
print("You win.")
userScore += 1
else:
print("Computer wins.")
computerScore += 1
elif computerChoice == 1:
print("Computer chose Paper", end = '. ')
if 'R' in userChoice:
print("Computer wins.")
computerScore += 1
elif 'P' in userChoice:
print("Call it a draw.")
ties += 1
else:
print("You win.")
userScore += 1
else:
print("Computer chose Scissors", end = '. ')
if 'R' in userChoice:
print("You win.")
userScore += 1
elif 'P' in userChoice:
print("Computer wins.")
computerScore += 1
else:
print("Call it a draw.")
ties += 1
elif 'Q' in userChoice:
continue
else:
print("Invalid option, input again.")
continue
# Prints out the results for each score then compares the scores to see who won
# or if a tie was found.
print("Computer: " , computerScore)
print("You: ", userScore)
print("Ties: ", ties)
if computerScore > userScore:
print("Computer Won!")
elif computerScore < userScore:
print("You Won!")
else:
print("It's a tie!")
| true
|
ccbbeda5e9f600eb58bec8894a1f2118eed329bb
|
chinaxiaobin/python_study
|
/练习Python/python-基础-01/08-打印一个名片.py
| 789
| 4.34375
| 4
|
# 先做啥再做啥,可以用注释搭框架
# 1.使用input获取必要信息
name = input("请输入你的名字:")
phone = input("请输入你的电话:")
wx = input("请输入你的微信:")
# 2.使用print来打印一个名片
print("=====================")
print("名字是:%s"%name)
print("电话是:%s"%phone)
print("微信好是:%s"%wx)
print("=====================")
"""
python2中input是将输入的内容当作代码了,而python3是把输入的内容当作一个字符串
name = input("请输入你的名字:")
如果输入1+4 然后打印name变量会得到结果5
如果输入laowang 会报错,这是因为
name = laowang 表示把laowang这个值赋给name,而laowang在内存中是没有的
Python2中使用 raw_input 才和python3中的input效果一样
"""
| false
|
89cb76c58b6814fb2a074d5be82b32d6775f9793
|
mileuc/100-days-of-python
|
/Day 22: Pong/ball.py
| 1,223
| 4.3125
| 4
|
# step 3: create and move the ball
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.color("white")
self.penup()
self.goto(x=0, y=0)
self.x_move = 10
self.y_move = 10
self.move_speed = 0.05
def move(self):
new_x = self.xcor() + self.x_move
new_y = self.ycor() + self.y_move
self.goto(new_x, new_y)
def bounce_y(self):
# when bounce occurs off top or bottom wall, y_move is changed so the ball moves in opposite way
self.y_move *= -1
def bounce_x_left_paddle(self):
self.x_move = (abs(self.x_move))
self.move_speed *= 0.9 # step 8: change ball speed every time ball hits paddle
def bounce_x_right_paddle(self):
self.x_move = -(abs(self.x_move))
self.move_speed *= 0.9
def left_paddle_miss(self):
self.goto(x=0, y=0)
self.move_speed = 0.05 # reset ball speed when it resets
self.bounce_x_left_paddle()
def right_paddle_miss(self):
self.goto(x=0, y=0)
self.move_speed = 0.05
self.bounce_x_right_paddle()
| false
|
ca9040e2f67a9ef6e1e15e9b5fa73c8df6295877
|
mileuc/100-days-of-python
|
/Day 10: Calculator/main.py
| 1,544
| 4.3125
| 4
|
from art import logo
from replit import clear
def calculate(operation, first_num, second_num):
"""Takes two input numbers, a chosen mathematical operation, and performs the operation on the two numbers and returns the output."""
if operation == '+':
output = first_num + second_num
return output
elif operation == '-':
output = first_num - second_num
return output
elif operation == '*':
output = first_num * second_num
return output
elif operation == '/':
output = first_num / second_num
return output
else:
return "Invalid operator chosen."
print(logo)
initial_calc = True
while initial_calc == True:
num1 = float(input("What's the first number? "))
subsequent_calc = True
print("+\n-\n*\n/")
while subsequent_calc == True:
operator = input("Pick an operation: ")
num2 = float(input("What's the second number? "))
result = calculate(operator, num1, num2)
print(f"{num1} {operator} {num2} = {result}")
if type(result) == float or type(result) == int:
y_or_n = input(f"Type 'y' to continue calculating with {result},\nor type 'n' to start a new calculation: ").lower()
if y_or_n == "n":
subsequent_calc = False
clear()
elif y_or_n == 'y':
num1 = result
else:
subsequent_calc = False
initial_calc = False
print("Sorry, you didn't enter 'y' or 'n'.")
else:
subsequent_calc = False
initial_calc = False
print("Sorry, you entered an invalid operator.")
| true
|
7e6caaea40c2ca56d00cf95dce934fb338a55ca1
|
dlingerfelt/DSC-510-Fall2019
|
/FRAKSO_MOHAMMED_DSC51/loops-week5.py
| 2,983
| 4.53125
| 5
|
'''
File: Loops.py
Name: Mohammed A. Frakso
Date: 12/01/2020
Course: DSC_510 - Introduction to Programming
Desc: This program will contain a variety of loops and functions:
The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user.
Define a function named performCalculation which takes one parameter. The parameter will be the operation being performed (+, -, *, /).
This function will perform the given prompt the user for two numbers then perform the expected operation depending on the parameter that's passed into the function.
This function will print the calculated value for the end user.
Define a function named calculateAverage which takes no parameters.
This function will ask the user how many numbers they wish to input.
This function will use the number of times to run the program within a for loop in order to calculate the total and average.
This function will print the calculated average.
'''
import operator
# Function to do math operations
def calc(number1: float, number2: float, op: str) -> float:
operands = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
return operands[op](number1, number2)
# Function to get the valid input number
def get_number(message: str) -> float:
number = 0
while number == 0:
try:
number: float = float(input(message))
break
except ValueError:
print('Invalid input please try again!')
continue
return number
# This function will perform math operations based on operation entered
def performCalculation(operation: str):
number1 = get_number('Enter first number: ')
number2 = get_number('Enter second number: ')
output = calc(number1, number2, operation)
print("the output is " + str(output), end="\n")
# This function will calculate total and average of numbers
def calculateAverage():
num = int(input('How many numbers you want to enter? '))
total_sum = 0
for n in range(num):
number = get_number('Please enter the number: ')
total_sum += number
avg = total_sum / num
print("the average is " + str(avg), end="\n")
# Display the welcome statement
def main():
print('Welcome to the math calculator:')
print("Enter '+', '-', '*', '/', 'avg' for math operations, and 'cancel' for quiting the program", end="\n")
while True:
operation: str = input("Enter your choice \n")
if operation == 'cancel':
break
if ("+" == operation) or ("-" == operation) or ("*" == operation) or ("/" == operation):
performCalculation(operation)
elif operation == 'avg':
calculateAverage()
else:
print("Invalid input entered please try again", end="\n")
if __name__ == '__main__':
main()
| true
|
88333bcf49ae0f01c6f7d4cca37c1dae5ddb64a2
|
dlingerfelt/DSC-510-Fall2019
|
/JALADI_DSC510/final/WeatherDisplay.py
| 1,791
| 4.34375
| 4
|
# File : WeatherDisplay.py
# Name : Pradeep Jaladi
# Date : 02/22/2020
# Course : DSC-510 - Introduction to Programming
# Desc : Weather Display class displays the weather details to output.
class WeatherDisplay:
def __init__(self, desc, city, country, temp, feels_like, min_temp, max_temp, lat, lon, wind):
""" Initialize the model variables """
self._desc = desc
self._city = city
self._country = country
self._temp = temp
self._feels_like = feels_like
self._min_temp = min_temp
self._max_temp = max_temp
self._lat = lat
self._lon = lon
self._wind = wind
def print_report(self):
""" Prints the details to the output screen """
print('---------------------------------------------------------------------------------------')
print('Current temperature is : %df' % self.__convert_temp(self._temp))
print('outside it looks like : {}'.format(self._desc))
print('Current it feels like : %df' % self.__convert_temp(self._feels_like))
print('Wind outside is : %d miles per hour' % self.__convert_wind(self._wind))
print('City : {}, {}'.format(self._city, self._country))
print('coordinates are : [{}, {}]'.format(self._lat, self._lon))
print('Today the temperatures are High as %df and low as %df' % (
self.__convert_temp(self._max_temp), self.__convert_temp(self._min_temp)))
print('---------------------------------------------------------------------------------------')
def __convert_temp(self, kelvin: float) -> float:
""" converts the temperature from kelvin to f """
return 9 / 5 * (kelvin - 273.15) + 32
def __convert_wind(self, meter: float) -> float:
""" converts the wind from meter to miles per hour """
return meter * 2.2369363
| true
|
433d5b3ed946f1f84893a9eed708b49e902af6c0
|
dlingerfelt/DSC-510-Fall2019
|
/NERALLA_DSC510/NERALLA_DSC510_WEEK11.py
| 2,521
| 4.15625
| 4
|
'''
File: NERALLA_DSC510_WEEK10.py
Name: Ravindra Neralla
Course:DSC510-T303
Date:02/23/2020
Description: This program is to create a simple cash register program.
The program will have one class called CashRegister.
The program will have an instance method called addItem which takes one parameter for price. The method should also keep track of the number of items in your cart.
The program should have two getter methods.
getTotal – returns totalPrice
getCount – returns the itemCount of the cart
The program must create an instance of the CashRegister class.
The program should have a loop which allows the user to continue to add items to the cart until they request to quit.
The program should print the total number of items in the cart.
The program should print the total $ amount of the cart.
The output should be formatted as currency.
'''
import locale
# Creating class of CashRegister to calculate the total cost
class CashRegister:
def __init__(self):
self.__totalItems = 0
self.__totalPrice = 0.0
# Creating a method to return total price of the shopping cart
def getTotal(self) -> float:
return self.__totalPrice
# creating a method to return total number of items in the shopping cart
def getCount(self) -> int:
return self.__totalItems
# Create a method to add items to the shopping cart
def addItem(self, price: float):
self.__totalPrice += price # Adding each item price in the shopping cart
self.__totalItems += 1 # Adding item count in shopping cart
def main():
print('Welcome to the cash register. To know your total purchase price please enter q ')
# creating an object using CashRegister() class
register = CashRegister()
locale.setlocale(locale.LC_ALL, 'en_US.utf-8')
while True:
try:
operation: str = input('Enter the price of your item : ')
# At the end of shopping, enter q to calcualte total price and total items in cart
if operation == 'q':
break
price = float(operation)
register.addItem(price)
except ValueError:
print('The price is not valid. Please try again')
total_price: float = register.getTotal()
total_count: int = register.getCount()
print('Total number of items added to your shopping cart : {}'.format(total_count))
print('Total price of items is : {}'.format(locale.currency(total_price, grouping=True)))
if __name__ == '__main__':
main()
| true
|
78eee39d5b2e07f640f8be3968acdec0b7c8e13f
|
dlingerfelt/DSC-510-Fall2019
|
/Safari_Edris_DSC510/Week4/Safari_DSC510_Cable_Cost.py
| 1,951
| 4.4375
| 4
|
# File : Safari_DSC510_Cable_Cost.py
# Name:Edris Safari
# Date:9/18/2019
# Course: DSC510 - Introduction To Programming
# Desc: Get name of company and length in feet of fiber cable. compute cost at $.87 per foot. display result in recipt format.
# Usage: Provide input when prompted.
def welcome_screen():
"""Print welcome screen"""
# Welcome Screen
print("Welcome to Fiber Optics One.")
# Get Company name
print("Please tell us the name of your company")
def compute_cost(Cable_Length,CableCostPerFoot):
"""Compute cable cost"""
# Compute Installation cost at CableCostPerFoot cents
return float(Cable_Length) * CableCostPerFoot
welcome_screen()
Company_Name = input('>>>')
print("Thank You.")
print("Now, please tell us the length in feet of cable you need. Enter 'q' to exit.")
Cable_Length = input('>>>')
# Use while to run program until user enters 'q'
while Cable_Length.lower() != 'q':
if not Cable_Length.isnumeric(): # Make sure value is numeric
print("PLease enter a valid number.")
else:
# Compute Installation
Installation_Cost = compute_cost(Cable_Length, 0.87)
Tax = Installation_Cost*.083 # Tax rate is 8.3%
Installation_Cost_PlusTax = Installation_Cost + Tax
# Print out the receipt
print("Thank You. Here's your receipt.")
print("Company Name: " + Company_Name)
print("Cable Length: " + Cable_Length)
print("Cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost, '.2f')) + ".")
print("Tax at 8.3% is $: " + str(format(Tax, '.2f')) + ".")
print("Total cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost_PlusTax, '.2f')) + ".")
print("Please enter another length in feet of cable you need. Enter 'q' to exit.")
Cable_Length = input('>>>')
# Exit the program
print("Thank You. Please come back.")
| true
|
d2587b87036af1d39d478e5db8c6d03b19c6da83
|
dlingerfelt/DSC-510-Fall2019
|
/SMILINSKAS_DSC510/Temperatures.py
| 1,290
| 4.21875
| 4
|
# File: Temperatures.py
# Name: Vilius Smilinskas
# Date: 1/18/2020
# Course: DSC510: Introduction to Programming
# Desc: Program will collect multiple temperature inputs, find the max and min values and present the total
# number of values in the list
# Usage: Input information when prompted, input go to retrieve the output
import sys
temperature = [] # list for temperatures to be stored
number = [] # list for input variable
count = 0 # int variable for keeping count of loops
while number != 'go': # go is set up as sentinel value to break the input
try: # to not add go or any ineligible value into the program, if error: the exception will run line 17
number = int(input('Enter a temperature or to run program enter go:'))
temperature.append(number) # append adds the parameter to the end of temperature
count = count + 1 # counts the loops
except ValueError: # if line 15 triggers error run the below block of code
print('The highest temperature is:' + str(max(temperature))) # max() determines the maximum value
print('The lowest temperature is:' + str(min(temperature))) # min() determines the minimum value
print('The number of values entered is:' + str(count))
sys.exit() # exits the program
| true
|
7faffa27e0944548717be676c521fcb8ed1653a8
|
dlingerfelt/DSC-510-Fall2019
|
/FRAKSO_MOHAMMED_DSC51/week6-lists.py
| 1,257
| 4.46875
| 4
|
'''
File: lists.py
Name: Mohammed A. Frakso
Date: 19/01/2020
Course: DSC_510 - Introduction to Programming
Desc: This program will work with lists:
The program will contains a list of temperatures, it will populate the list based upon user input.
The program will determine the number of temperatures in the program, determine the largest temperature, and the smallest temperature.
'''
# create an empty list
temperature_list = []
while True:
print('\n Please enter a temperature:')
#print('Enter "finished" once you are done with all temparatures: \n')
input_temperature = input('please type "finished" when you have entered all temperatures')
if input_temperature.lower() == 'finished':
break
try:
temperature_list.append(float(input_temperature))
except ValueError:
input_temperature = input('Oops... Please enter a numeric value!')
temperature_list.append(float(input_temperature))
# printing argest, smallest temperatures and how many temperatures are in the list.
print('The largest temperature is: ', max(temperature_list), 'degrees')
print('The smallest temperature is: ', min(temperature_list), 'degrees')
print('The total temperatures input is: ', len(temperature_list))
| true
|
42d37509986bc3233ab711cef2496ab4fa17602a
|
dlingerfelt/DSC-510-Fall2019
|
/Ndingwan_DSC510/week4.py
| 2,921
| 4.28125
| 4
|
# File: week4.py
# Name: Awah Ndingwan
# Date: 09/17/2019
# Desc: Program calculates total cost by multiplying length of feet by cost per feet
# Usage: This program receives input from the user and calculates total cost by multiplying the number of feet
# by the cost per feet. Finally the program returns a summary of the transaction to the user
cost_per_feet_above_100feet = 0.80
cost_per_feet_above_250feet = 0.70
cost_per_feet_above_500feet = 0.50
length_above_100 = 100.0
length_above_250 = 250.0
length_above_500 = 500.0
# calculate and return cost
def calculate_cost(cost, feet):
return cost * feet
class FiberCostCalculator:
def __init__(self, company_name="", num_of_feet=0, installation_cost=0, cost_per_feet=0.87):
self.company_name = company_name
self.number_of_feet = num_of_feet
self.installation_cost = installation_cost
self.cost_per_feet = cost_per_feet
self.get_input()
self.compute_total_cost()
self.show_receipt()
# Get amd validate input from user
def get_input(self):
# printing welcome message
message = "******** WELCOME ********"
print(message)
self.company_name = input("Enter Company name: ")
while True:
try:
self.number_of_feet = float(input("Enter number of feet for fiber optic cable(ft): "))
except ValueError:
print("Not Valid! length of feet cannot be a String. Please try again.")
continue
else:
break
# compute installation cost for user
def compute_total_cost(self):
if length_above_100 < self.number_of_feet < length_above_250:
self.cost_per_feet = cost_per_feet_above_100feet
self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet)
elif length_above_250 < self.number_of_feet < length_above_500:
self.cost_per_feet = cost_per_feet_above_250feet
self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet)
elif self.number_of_feet > length_above_500:
self.cost_per_feet = cost_per_feet_above_500feet
self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet)
else:
self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet)
# Print receipt details
def show_receipt(self):
print('********************')
print(' Receipt ')
print(' ****************** ')
print(f'Company Name: {self.company_name}')
print(f'Cost Per Feet: ${float(self.cost_per_feet)}')
print(f'Length of feet to be installed: {self.number_of_feet} feet')
print("Total cost: $" + format(round(float(self.installation_cost), 2), ',.2f'))
if __name__ == "__main__":
fiberCostCalculator = FiberCostCalculator()
| true
|
8c70251443a384255c610a8a96d4977c5da28947
|
dlingerfelt/DSC-510-Fall2019
|
/JALADI_DSC510/TEMPERATURE_OPERATIONS.py
| 1,536
| 4.53125
| 5
|
# File : MATH_OPERATIONS.py
# Name : Pradeep Jaladi
# Date : 01/11/2020
# Course : DSC-510 - Introduction to Programming
# Assignment :
# Program :
# Create an empty list called temperatures.
# Allow the user to input a series of temperatures along with a sentinel value which will stop the user input.
# Evaluate the temperature list to determine the largest and smallest temperature.
# Print the largest temperature.
# Print the smallest temperature.
# Print a message tells the user how many temperatures are in the list.
def print_values(temperatures):
length: int = len(temperatures)
# there are couple of ways to determine the min & max of the list -> using max & min function or sort the list and get 0, max length element
print('There are total %d temperature values ' % length)
print('The lowest temperature is %g and the highest temperature is %g' % (min(temperatures), max(temperatures)))
def main():
print("Welcome to temperature calculator program ....")
# Declaration of empty temperatures list
temperatures = [];
# Getting the temperature values
while True:
temperature: str = input("Enter the temperature [%d] : " % len(temperatures))
if temperature == 'q':
break
try:
temperatures.append(float(temperature))
except ValueError:
print("Oops! Invalid temperature. Try again...")
# printing the desired calucations
print_values(temperatures)
if __name__ == '__main__':
main()
| true
|
f5428333663e7da9d39bdff3e25f6a34c07ebd08
|
dlingerfelt/DSC-510-Fall2019
|
/Steen_DSC510/Assignment 3.1 - Jonathan Steen.py
| 1,186
| 4.34375
| 4
|
# File: Assignment 3.1 - Jonathan Steen.py
# Name: Jonathan Steen
# Date: 12/9/2019
# Course: DSC510 - Introduction to Programing
# Desc: Program calculates cost of fiber optic installation.
# Usage: The program gets company name,
# number of feet of fiber optic cable, calculate
# installation cost, bulk discount and print receipt.
#welcome statement and get user input
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
#if statement to calculate bulk discount
fiberOpticCost = 0
if float(fiberOpticLength) > 499:
fiberOpticCost = .50
elif float(fiberOpticLength) > 249:
fiberOpticCost = .70
elif float(fiberOpticLength) > 99:
fiberOpticCost = .80
elif float(fiberOpticLength) < 100:
fiberOpticCost = .87
#calculate cost
totalCost = float(fiberOpticLength) * float(fiberOpticCost)
#print receipt
print('\n')
print('Receipt')
print(companyName)
print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot')
print('Total: ' + '${:,.2f}'.format(totalCost))
| true
|
af093e824555df86dc56d2b1b581270fd1671d1c
|
dlingerfelt/DSC-510-Fall2019
|
/Stone_DSC510/Assignment2_1/Assignment2_1.py
| 751
| 4.21875
| 4
|
# 2.1 Programming Assignment Calculate Cost of Cabling
# Name: Zachary Stone
# File: Assignment 2.1.py
# Date: 09/08/2019
# Course: DSC510-Introduction to Programming
# Greeting
print('Welcome to the ABC Cabling Company')
# Get Company Name
companyName = input('What is the name of you company?\n')
# Get Num of feet
feet = float(input('How any feet of fiber optic cable do you need installed?\n'))
# calculate cost
cost = float(feet*0.87)
# print receipt
print("********Receipt********")
print('Thank you for choosing ABC Cable Company.\n')
print('Customer:', companyName)
print('Feet of fiber optic cable:', feet)
print('Cost per foot:', '$0.87')
print('The cost of your installation is', '${:,.2f}'.format(cost))
print('Thank you for your business!\n')
| true
|
edc28c6d0a7bd72d9a875d7716f8957874455fd0
|
dlingerfelt/DSC-510-Fall2019
|
/Steen_DSC510/Assignment 4.1 - Jonathan Steen.py
| 1,364
| 4.15625
| 4
|
# File: Assignment 4.1 - Jonathan Steen.py
# Name: Jonathan Steen
# Date: 12/17/2019
# Course: DSC510 - Introduction to Programing
# Desc: Program calculates cost of fiber optic installation.
# Usage: The program gets company name,
# number of feet of fiber optic cable, calculate
# installation cost, bulk discount and prints receipt.
#welcome statement and get user input
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
#if statement to calculate bulk discount
fiberOpticCost = 0
if float(fiberOpticLength) > 499:
fiberOpticCost = .50
elif float(fiberOpticLength) > 249:
fiberOpticCost = .70
elif float(fiberOpticLength) > 99:
fiberOpticCost = .80
elif float(fiberOpticLength) < 100:
fiberOpticCost = .87
#define function to calculate cost
def calculateCost(x, y):
global totalCost
totalCost = float(x) * float(y)
return totalCost
#call calcution function
calculateCost(fiberOpticLength, fiberOpticCost)
#print receipt
print('\n')
print('Receipt')
print(companyName)
print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot')
print('Total: ' + '${:,.2f}'.format(totalCost))
| true
|
f70f72b4d449726be0bb53878d32116d999756f5
|
dlingerfelt/DSC-510-Fall2019
|
/Steen_DSC510/Assignment 2.1 - Jonathan Steen.py
| 1,105
| 4.28125
| 4
|
# File: Assignment 2.1 - Jonathan Steen.py
# Name: Jonathan Steen
# Date: 12/2/2019
# Course: DSC510 - Introduction to Programing
# Desc: Program calculates cost of fiber optic installation.
# Usage: The program gets company name,
# number of feet of fiber optic cable, calculate
# installation cost and prints a receipt.
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
fiberOpticCost = .87 #define the varible to hold the cost per ft of fiber optic.
totalCost = float(fiberOpticLength) * float(fiberOpticCost) #convert user input to float and calculate price.
print('\n')
print('Receipt')
print(companyName)
print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '$' + str(fiberOpticCost) + ' Per Foot') #convert float varible to string
totalCost = totalCost - totalCost % 0.01 #format output to two decimal points without rounding up or down to get accurate amount.
print('Total: ' + '$' + str(totalCost))
| true
|
2155f32ff8af7f310124f09964e576fe5b464398
|
dlingerfelt/DSC-510-Fall2019
|
/DSC510- Week 5 Nguyen.py
| 2,139
| 4.3125
| 4
|
'''
File: DSC510-Week 5 Nguyen.py
Name: Chau Nguyen
Date: 1/12/2020
Course: DSC_510 Intro to Programming
Desc: This program helps implement variety of loops and functions.
The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user.
'''
def performCalculation(user_operation):
# Using list will allow multiple inputs
user_input = list(map(int, input("Enter multiple values: (no comma, just space) ").split()))
if user_operation =="*":
result = user_input[0] * user_input[1]
elif user_operation =="%":
try:
result = user_input[0] / user_input[1]
except:
print("Error: Cannot Divide %s/%s" %(user_input[0], user_input[1]))
return
elif user_operation =="-":
result = user_input[0] - user_input[1]
elif user_operation =="+":
result = user_input[0] + user_input[1]
else :
return float(result,2)
print("Your calcualtion result is",result)
def calculateAverage():
user_input2 = int(input('How many numbers they wish to input? '))
total_sum = 0
# Define store_input as list
store_input = []
for n in range(user_input2):
x = (int(input("Enter your value ")))
# Store user input into a list
store_input.append(x)
total_sum = sum(store_input)
average = total_sum / user_input2
print("The average is ", average)
def main():
# Welcome statement
print("Welcome. What program would you like to run today?")
user_operation =''
# Asking user to pick the program they want to run
while user_operation != 'exist':
user_operation = input("pick one of the choices: -,*,+,%,average, or exist ")
if user_operation == 'exist':
break
elif (user_operation == '-') or (user_operation == '+') or (user_operation == '*') or (user_operation == '%'):
performCalculation(user_operation)
elif (user_operation == 'average'):
calculateAverage()
else:
print("invalid choice try again")
if __name__ == '__main__':
main()
| true
|
7bd2456b0c77f97e11f16454bfa9890c28d93f35
|
mun5424/ProgrammingInterviewQuestions
|
/MergeTwoSortedLinkedLists.py
| 1,468
| 4.15625
| 4
|
# given two sorted linked lists, merge them into a new sorted linkedlist
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# set iterators
dummy = ListNode(0)
current = dummy
#traverse linked list, looking for lower value of each
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
#traverse rest of the linkedlist
if l1:
current.next = l1
else:
current.next = l2
return dummy.next
def printList(self, list1: ListNode):
# print a linked list
dummy = list1
res = ""
while dummy:
if dummy.next:
res += str(dummy.val) + ", "
else:
res += str(dummy.val)
dummy = dummy.next
print(res)
# sample test
node1 = ListNode(1)
node5 = ListNode(5)
node8 = ListNode(8)
node1.next = node5
node5.next = node8
node4 = ListNode(4)
node7 = ListNode(7)
node9 = ListNode(9)
node4.next = node7
node7.next = node9
s = Solution()
list1 = node1
s.printList(list1)
list2 = node4
s.printList(list2)
result = s.mergeTwoLists(list1, list2)
s.printList(result)
| true
|
ee04bfff8656142d1abd103c4994d257af6e64c9
|
JaydeepKachare/Python-Classwork
|
/Session11/05.py
| 838
| 4.21875
| 4
|
# Inheritance in Python
class Base1 :
def __init__(self):
self.i = 10
self.j = 20
print("Inside Base Constructor")
def fun(self) :
print("Inside Base1 fun")
class Base2 :
def __init__(self):
self.x = 30
self.y = 40
print("Inside Base Constructor")
def fun(self) :
print("Inside Base2 fun")
class Derived (Base1,Base2) :
def __init__(self):
Base2.__init__(self)
Base1.__init__(self)
self.a = 50
self.b = 60
print("Inside Derived Constructor")
def fun(self) :
Base2.fun(self)
def main() :
dobj = Derived()
print(dobj.i)
print(dobj.j)
print(dobj.x)
print(dobj.y)
print(dobj.a)
print(dobj.b)
dobj.fun()
if __name__ == "__main__" :
main()
| false
|
199da8145e506f6e08900a15431258286e8216dc
|
JaydeepKachare/Python-Classwork
|
/Recursion/7_7 PrimeFactors.py
| 718
| 4.1875
| 4
|
# find prime factors of given number
# using while loop
def primeFactors(num) :
i = 2
while (i <= num ) :
if num % i == 0 :
print(i,end=" ")
num = int(num/i)
i = 1
i+=1
print()
# using recursion
def primeFactorsR(num,i) :
if i >= num :
print(i)
return
if (num%i == 0) :
print(i,end=" ")
primeFactorsR(int(num/i),2)
else :
primeFactorsR(num,i+1)
return
def main() :
num = int(input("ENterany number : "))
print("Prime factors of {} are ".format(num), end=" ")
# primeFactors(num)
primeFactorsR(num,2)
if __name__ == "__main__" :
main()
| false
|
65fc4f293f441ff863eb83dc60cdf7e7935b5121
|
JaydeepKachare/Python-Classwork
|
/Session6/practice/01 isPrime.py
| 432
| 4.15625
| 4
|
# check whether given number is prime or not
def isPrime (num) :
for i in range(2,num) :
if num % i == 0 :
return False
return True
# main function
def main() :
num = int(input("Enter any number : "))
if isPrime(num) == True :
print("{} is prime number ".format(num))
else :
print("{} is not prime number ".format(num))
if __name__ == "__main__" :
main()
| false
|
a0033278eee5f2ce160875caa8bd5d270989d3ea
|
JaydeepKachare/Python-Classwork
|
/Recursion/7_9 nth term of fibo.py
| 278
| 4.1875
| 4
|
# calculate nth term of fibonacci series
def fibo(num) :
if num == 0 or num == 1 :
return 1
return fibo(num-1) + fibo(num-2)
def main() :
n = int(input("Enter term to find : "))
print(fibo(n))
if __name__ == "__main__" :
main()
| false
|
b9d16e4a06e0485a6e4e5c26bf4673d063c1eb7e
|
JaydeepKachare/Python-Classwork
|
/Session3/Arithematic6.py
| 429
| 4.125
| 4
|
# addition of two number
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2) # reusing same function (function call)
print("Addition : ",ans)
| true
|
e200d189bee58ad51f7ad8721ef54aaf2d5d63e0
|
JaydeepKachare/Python-Classwork
|
/Recursion/540.py
| 366
| 4.375
| 4
|
# check whether if string is palindrome or not
def isPalindrome(str) :
if len(str)==0 or len(str)==1 :
return True
if str[0] == str[-1] :
return isPalindrome(str[1:-1])
else :
return False
str = input("Enter string : " )
if isPalindrome(str) == True :
print("Palindrome")
else :
print("Not Palindrome")
| false
|
8bf5ca07b63351502911b50328ca0a6eac240187
|
AndrewGEvans95/foobar
|
/breedinglikerabbits.py
| 675
| 4.125
| 4
|
def BinSearch(a, b, target, parity):
#Standard binary search w/ recursion
if b <= a:
return None
n = a + ((b - a)/2)
n += parity != n & 1
S = Scan(n)
if S == target:
return n
if S > target:
b = n - 1
else:
a = n + 1
return BinSearch(a, b, target, parity)
dic = {}
def Scan(n):
if n < 3:
return [1 ,1, 2][n]
h = n/2
if n & 1:
dic[n] = Scan(h) + Scan(h - 1) + 1
else:
dic[n] = Scan(h) + Scan(h + 1) + h
set(dic)
return dic[n]
def answer(str_S):
str_S = int(str_S)
return BinSearch(0, str_S, str_S, 1) or BinSearch(0, str_S, str_S, 0)
print answer(7)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.